# tigranu80-lang/gruntling architecture

> Architecture diagram of the GitHub repository tigranu80-lang/gruntling, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-09). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/tigranu80-lang/gruntling
- Repository: https://github.com/tigranu80-lang/gruntling

## Overview

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: [`src/gruntling/cli.py`](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/cli.py) (CLI), [`src/gruntling/prompts.py`](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts.py) (Prompts), [`src/gruntling/core.py`](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/core.py) (Core), [`src/gruntling/config.py`](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/config.py) (Config)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_grp_cli["CLI & orchestration"]
  node_cli["CLI<br/>entrypoint<br/>[cli.py]"]
  node_runner["Runner<br/>orchestrator<br/>[runner.py]"]
  node_core["Core<br/>[core.py]"]
end

subgraph group_grp_policy["Policy & safety"]
  node_config["Config<br/>policy resolver<br/>[config.py]"]
  node_guards{{"Guards<br/>safety gate<br/>[guards.py]"}}
  node_retrieval["Retrieval<br/>provider client<br/>[retrieval.py]"]
  node_providers["Providers<br/>provider matrix<br/>[providers.toml]"]
end

subgraph group_grp_generation["Task roles"]
  node_prompts["Prompts<br/>role contracts<br/>[prompts.py]"]
  node_ask_prompt["Ask<br/>prompt contract<br/>[ask.md]"]
  node_code_prompt["Code<br/>prompt contract<br/>[code.md]"]
  node_review_prompt["Review<br/>prompt contract<br/>[review.md]"]
end

subgraph group_grp_search["Semantic search"]
  node_search["Search<br/>retrieval pipeline<br/>[search.py]"]
  node_index["Index<br/>embedding pipeline<br/>[index.py]"]
  node_find["Find<br/>search command<br/>[search.py]"]
end

subgraph group_grp_integrations["Integrations"]
  node_hook["Hook<br/>adapter<br/>[hook.py]"]
  node_install["Install<br/>[install.py]"]
  node_templates["Templates"]
end

subgraph group_grp_state["Local state"]
  node_state[(".gruntling<br/>local runtime state")]
end

node_cli -->|"resolve policy"| node_config
node_cli -->|"dispatch role"| node_runner
node_runner -->|"assemble call"| node_core
node_core -->|"pre/post checks"| node_guards
node_core -->|"provider call"| node_retrieval
node_config -->|"select provider"| node_providers
node_config -->|"kill-switch"| node_guards
node_retrieval -->|"cache/log"| node_state
node_cli -->|"choose role"| node_prompts
node_prompts -->|"template"| node_ask_prompt
node_prompts -->|"template"| node_code_prompt
node_prompts -->|"template"| node_review_prompt
node_cli -->|"build index"| node_index
node_cli -->|"search repo"| node_find
node_index -->|"write index"| node_state
node_find -->|"query pipeline"| node_search
node_search -->|"read index"| node_state
node_cli -->|"install hooks"| node_hook
node_cli -->|"install integration"| node_install
node_install -->|"render files"| node_templates
node_hook -->|"compose hook"| node_templates

click node_cli "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/cli.py"
click node_runner "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/runner.py"
click node_core "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/core.py"
click node_config "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/config.py"
click node_guards "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/guards.py"
click node_retrieval "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/retrieval.py"
click node_providers "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/providers.toml"
click node_prompts "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts.py"
click node_ask_prompt "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts/ask.md"
click node_code_prompt "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts/code.md"
click node_review_prompt "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts/review.md"
click node_search "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/search.py"
click node_index "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/index.py"
click node_find "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/search.py"
click node_hook "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/hook.py"
click node_install "https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/install.py"
click node_templates "https://github.com/tigranu80-lang/gruntling/tree/main/src/gruntling/templates"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_cli,node_runner,node_core toneBlue
class node_config,node_guards,node_retrieval,node_providers toneAmber
class node_prompts,node_ask_prompt,node_code_prompt,node_review_prompt toneMint
class node_search,node_index,node_find toneRose
class node_hook,node_install,node_templates toneIndigo
class node_state toneTeal
```

## Components

### CLI & orchestration

User-facing command surface and shared execution flow for short-lived invocations.

- [CLI](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/cli.py): entrypoint · Parses subcommands and dispatches to task, search, and integration flows. · `src/gruntling/cli.py`
- [Runner](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/runner.py): orchestrator · Shared run path for role execution and output handling. · `src/gruntling/runner.py`
- [Core](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/core.py): execution core · Common model-call assembly and postprocessing boundary. · `src/gruntling/core.py`

### Policy & safety

Configuration resolution, provider selection, and guardrails before/after model calls.

- [Config](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/config.py): policy resolver · Resolves flags, environment, config files, provider mapping, and kill-switch behavior. · `src/gruntling/config.py`
- [Guards](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/guards.py): safety gate · Preflight secret scanning and output contract enforcement. · `src/gruntling/guards.py`
- [Retrieval](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/retrieval.py): provider client · Builds requests to OpenAI-compatible providers, handles retries, caching, and usage logging. · `src/gruntling/retrieval.py`
- [Providers](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/providers.toml): provider matrix · 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](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts.py): role contracts · Role-specific prompt templates and output-shape contracts. · `src/gruntling/prompts.py`
- [Ask](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts/ask.md): prompt contract · Prose answer role template. · `src/gruntling/prompts/ask.md`
- [Code](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts/code.md): prompt contract · Raw code generation role template. · `src/gruntling/prompts/code.md`
- [Review](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/prompts/review.md): prompt contract · Diff review role template and line-oriented findings contract. · `src/gruntling/prompts/review.md`

### Semantic search

Local indexing and retrieval pipeline for repository search.

- [Search](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/search.py): retrieval pipeline · Query-time semantic search and snippet ranking. · `src/gruntling/search.py`
- [Index](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/index.py): embedding pipeline · Repository chunking and local vector index builder. · `src/gruntling/index.py`
- [Find](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/search.py): search command · Search command that embeds a query and returns ranked matches. · `src/gruntling/search.py`

### Integrations

Installer and hook adapters for external agent harnesses.

- [Hook](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/hook.py): adapter · Harness integration and stop-hook wiring for external agents. · `src/gruntling/hook.py`
- [Install](https://github.com/tigranu80-lang/gruntling/blob/main/src/gruntling/install.py): installer · Installs harness-specific files and integration assets. · `src/gruntling/install.py`
- [Templates](https://github.com/tigranu80-lang/gruntling/tree/main/src/gruntling/templates): integration templates · Harness-specific instruction and snippet templates. · `src/gruntling/templates`

### Local state

File-backed runtime artifacts under the .gruntling boundary.

- **.gruntling**: local runtime state · File-backed cache, rate-limit, usage, and index artifacts across runs.

## Connections

- 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.
