How tigranu80-lang/gruntling works
1. What this repository is
gruntling is a Python CLI package that routes small, bounded tasks from a larger AI agent to cheaper OpenAI-compatible model providers. It is not a server or daemon: every invocation is a short-lived command that reads stdin/args, optionally calls a provider API, postprocesses the result, and exits.
2. Primary entrypoint and command surface
The top-level CLI lives in src/gruntling/cli.py. It exposes the user-facing subcommands: ask, code, review, distill, translate, judge, plus the semantic search pair index and find, and installer/hook commands under install and hook. The CLI is the orchestration layer that selects a role, resolves config, and dispatches to the role-specific pipeline.
3. Core orchestration layer
src/gruntling/core.py, runner.py, and review.py appear to hold the shared execution path for model calls: build the system/user prompt, choose the provider/model, enforce fail-open vs strict behavior, apply postprocessing, and record usage. runner.py likely centralizes the generic “run a role” flow, while review.py likely handles review-specific normalization and line-contract parsing.
4. Configuration and provider routing
config.py and providers.toml define the configuration boundary. Provider choice follows a precedence chain from CLI flags to environment variables to project/user config to built-ins. This layer also resolves role-specific model mappings, API key source, rate limits, and the kill switch. Architecturally, this is the “policy” layer that decides where work goes, without performing the work itself.
5. Prompt templates and role contracts
prompts.py and the markdown files under src/gruntling/prompts/ encode the six task roles as distinct prompt contracts. Each role has a different output shape:
- prose answer (ask)
- raw code (code)
- diff findings (review)
- bullet compression (distill)
- translation preserving structure (translate)
- strict JSON verdict (judge)
The prompts are a major boundary because downstream postprocessing depends on their output shape being machine-checkable.
6. Safety and guardrail subsystem
guards.py implements the preflight checks and behavioral constraints described in the README: secret scanning before any external API call, GRUNTLING_DISABLE kill-switch behavior, and likely the “think block” stripping / output contract validation. This subsystem sits before network I/O and after model output, ensuring unsafe input never leaves the machine and malformed output is rejected instead of passed through.
7. Provider request/retry/cache layer
src/gruntling/retrieval.py and search.py are the integration points to model providers. For text-generation roles, the flow is: resolve provider → build request → send to the selected OpenAI-compatible endpoint → capture response/usage → cache the completion under .gruntling/cache/ → append a usage log line. Rate limiting is shared across processes through .gruntling/ratelimit.json plus lock-file coordination, so this is not just in-memory throttling.
8. Semantic search as a separate subsystem
index.py and find.py/search.py implement a local repository search pipeline distinct from the text-generation roles. The repo is embedded chunk-by-chunk into .gruntling/index/ (chunks.jsonl, vectors.npy, meta.json), respecting .gitignore and skipping secrets/binaries. Queries are embedded, nearest chunks are retrieved, then optionally reranked if the provider supports it. This subsystem has a hard local-storage boundary and is designed to let agents ask “where does X happen?” without reading whole files.
9. Persistent local state and filesystem boundaries
Runtime state is intentionally file-based under .gruntling/:
- cached completions
- rate-limit window state
- usage logs
- semantic index artifacts
This makes the tool stateless at the process level but stateful across runs. The architecture diagram should show these as local persistence owned by the CLI, not as a separate service.
10. Hook and integration architecture
hook.py plus install.py implement integration points for external agent harnesses. The Claude Code adapter is the most elaborate: it installs a skill file, merges a stop hook, and can optionally run a bounded review pass over git diff HEAD. Other harness adapters for Codex, Cursor, and Gemini generate or write harness-specific instruction files. These integrations are thin adaptation layers around the same core roles and prompt guidance.
11. External dependencies and provider model matrix
The system talks to external model APIs through five built-in provider profiles: NVIDIA, Groq, Cerebras, OpenRouter, and local Ollama. Only the provider profiles materially affect architecture because they determine base URL, key source, model defaults, and whether embeddings/reranking are available. The default path is NVIDIA, while Ollama provides the local, keyless fallback.
12. Data flow for a typical generation call
For a role like review or code, the flow is: CLI parses inputs → config resolves provider/model → secret scan runs → optional cache lookup → request is sent to the provider → response is normalized/validated → result is either printed, written to --out, or rejected if it violates the role contract. Fail-open behavior means provider/config failures return no-op success unless --strict is set; contract violations still fail.
13. Data flow for semantic search
For index build/update, the flow is: walk repo files → filter by ignore rules and safety checks → chunk text → embed chunks → store vectors, chunk text, and metadata locally. For find, the flow is: embed query → retrieve nearest chunks → rerank if possible → print ranked snippets or JSON. This is a read-only local pipeline that never needs the agent to open whole files unless it chooses to.
14. Testing and packaging boundary
pyproject.toml, uv.lock, and the test suite under tests/ indicate a conventional Python package built and exercised with uv and pytest. The tests cover the major seams: config, CLI behavior, guards, hooks, installation, indexing, retrieval, and runner logic. That suggests the architecture is intentionally modular, with each subsystem testable in isolation.
15. How to draw the diagram
A good diagram would show one central CLI/orchestrator box, with branches to:
- config/provider resolution
- safety guards
- generation roles
- semantic search/indexing
- caching/rate-limiting/usage logging
- external provider APIs
- local .gruntling/ state
- harness integrations/installers
The key architectural message is that gruntling is a thin, file-backed, fail-open delegate wrapper around model APIs, plus a local embedding-based code search subsystem and a set of agent-harness adapters.
Main entry points: cli.py CLI · prompts.py Prompts · core.py Core · config.py Config
Components 18
CLI & orchestration
User-facing command surface and shared execution flow for short-lived invocations.
Policy & safety
Configuration resolution, provider selection, and guardrails before/after model calls.
- Config · Resolves flags, environment, config files, provider mapping, and kill-switch behavior.
src/gruntling/config.py - Guards · Preflight secret scanning and output contract enforcement.
src/gruntling/guards.py - Retrieval · Builds requests to OpenAI-compatible providers, handles retries, caching, and usage logging.
src/gruntling/retrieval.py - Providers · Built-in provider profiles and default model/base-url definitions.
src/gruntling/providers.toml
Task roles
Role-specific prompt contracts and response handling for text-generation commands.
- Prompts · Role-specific prompt templates and output-shape contracts.
src/gruntling/prompts.py - Ask · Prose answer role template.
src/gruntling/prompts/ask.md - Code · Raw code generation role template.
src/gruntling/prompts/code.md - Review · Diff review role template and line-oriented findings contract.
src/gruntling/prompts/review.md
Semantic search
Local indexing and retrieval pipeline for repository search.
Integrations
Installer and hook adapters for external agent harnesses.
Local state
File-backed runtime artifacts under the .gruntling boundary.
- .gruntling · File-backed cache, rate-limit, usage, and index artifacts across runs.
Connections 21
- CLI → Config: resolve policy · CLI resolves command options, provider choice, and strictness from layered config.
- CLI → Runner: dispatch role · CLI sends role commands into the shared execution path.
- Runner → Core: assemble call · Runner delegates prompt/model orchestration to the core execution layer.
- Core → Guards: pre/post checks · Core applies safety checks before network I/O and validates returned output contracts.
- Core → Retrieval: provider call · Core sends the prepared request to the selected provider client.
- Config → Providers: select provider · Configuration maps roles and flags onto built-in provider profiles.
- Config → Guards: kill-switch · Configuration exposes the disable switch and other safety policy inputs.
- Retrieval → .gruntling: cache/log · Provider responses, rate-limit state, and usage logs are persisted locally.
- CLI → Prompts: choose role · CLI selects the role contract for ask, code, review, and related tasks.
- Prompts → Ask: template · Representative prose-answer contract.
- Prompts → Code: template · Representative code-generation contract.
- Prompts → Review: template · Representative review contract.
- CLI → Index: build index · Index command walks the repository and writes embedding artifacts.
- CLI → Find: search repo · Find command performs semantic retrieval over the local index.
- Index → .gruntling: write index · Chunk text, vectors, and metadata are stored under the local runtime boundary.
- Find → Search: query pipeline · Find uses the search pipeline for retrieval and optional reranking.
- Search → .gruntling: read index · Search reads the local vector store and metadata artifacts.
- CLI → Hook: install hooks · CLI exposes hook-related setup for external harness integration.
- CLI → Install: install integration · CLI installs harness-specific files and adapter assets.
- Install → Templates: render files · Installer uses template fragments to generate integration files.
- Hook → Templates: compose hook · Hook logic reuses shared and harness-specific template snippets.