This document describes how GuardDog is structured and the invariants we preserve as the tool evolves. It is the architectural contract for this repository — not a template for target codebases under review (those have their own DESIGN.md).
GuardDog reviews other systems for evolutionary architecture risk. To stay credible, GuardDog itself must be bounded, inspectable, and safe to change incrementally.
GuardDog is a standalone Node.js CLI (guarddog) that:
- Reads declared architecture intent from a design file (typically
DESIGN.mdin the target repo). - Builds a factual repo map (structure, languages, CI, packages, C4 docs) without sending full source upfront.
- Selects review context via a two-stage pipeline: rank important files, then pack into token budgets.
- Prompts an LLM to produce structured findings (severity, evidence, blast radius, incremental remediation).
- Optionally renders Markdown/JSON output and opens GitHub issues.
GuardDog is not a linter, style checker, or C4 generator. It consumes AutoDoc output when present; it does not invoke AutoDoc.
Primary user workflow:
auto-doc … # optional: generate C4 docs in target repo
guarddog review … # rank → pack → review → report
GuardDog follows a thin CLI over a deterministic core pipeline. Dependencies flow inward; LLM calls sit at explicit boundaries.
┌─────────────────────────────────────────────────────────────┐
│ cli/ argv parsing, exit codes, user-facing errors │
├─────────────────────────────────────────────────────────────┤
│ core/ review pipeline (orchestration, no I/O fmt) │
│ reviewer single entry: runReview() │
│ repoScanner factual scan → IRepoMap │
│ contextSelector rank → pack → IContextSelectionResult │
│ contextRanker LLM ranker + heuristic fallback │
│ tokenBudgetPacker greedy budget packing + manifest │
│ c4ArchitectureDocs discovery, sort, cap │
│ findingParser validate LLM JSON → IReviewResult │
│ findingFilter severity/impact/maxFindings │
│ markdownRenderer human-readable output │
│ llmProvider ArchitectureReview via PromptRepository│
│ promptFactory Prompts.json → IPromptRepository │
├─────────────────────────────────────────────────────────────┤
│ schemas/ shared types, JSON schemas, defaults │
│ utils/ filesystem, tokens, logging, errors │
│ github/ optional issue creation (side effects) │
├─────────────────────────────────────────────────────────────┤
│ Prompts.json prompt templates (copied to dist/) │
│ PromptIds.ts stable UUID constants │
└─────────────────────────────────────────────────────────────┘
│ │
▼ ▼
@jonverrier/prompt-repository tiktoken (token counting)
| Layer | May depend on | Must not depend on |
|---|---|---|
cli/ |
core/, schemas/, utils/, github/ |
PromptRepository directly |
core/ |
schemas/, utils/, PromptRepository, tiktoken |
cli/, github/ (except via reviewer wiring) |
schemas/ |
nothing upstream | core/, cli/ |
utils/ |
Node built-ins, minimatch | core/, LLM drivers |
github/ |
schemas/, utils/ |
LLM, context selection |
- PromptRepository — all LLM access goes through
IChatDriver+IPromptRepository. No raw OpenAI SDK calls in GuardDog. - AutoDoc — integration is file-based only. GuardDog detects C4 markdown by basename/suffix; no subprocess or npm import of AutoDoc.
- Target repositories — read-only scan except for configured outputs (
.guarddog/, review files, optional GitHub issues).
The review pipeline in runReview() must preserve this order:
load config → load DESIGN.md → generateRepoMap()
→ selectContextFiles() [rank → pack DESIGN + C4 + sources]
→ attach contextSelection to repoMap
→ ArchitectureReview LLM → validate → filter → render → write
Context selection is layered and budgeted:
| Layer | Default budget | Selection rule |
|---|---|---|
| Design file | 4,000 tokens (designTokenBudget) |
packed first; subject to per-file cap |
| C4 docs (review) | 12,000 tokens (c4TokenBudget) |
depth order (rollups first), max 24 files, greedy pack |
| C4 docs (ranker) | 12,000 tokens (rankerC4TokenBudget) |
same depth order via packC4DocsForPrompt |
| Source files | 32,000 tokens (contextTokenBudget) |
greedy pack by rank |
| Per file | 4,096 token cap (maxFileTokens) |
skip with manifest reason |
Token counting uses tiktoken via utils/tokenCounter.ts. Files are read and counted lazily. contextSelection.budgetUtilization records budget, used, and fillRatio per layer.
Ranker selection:
- C4 docs present →
ContextRankerLLM (file index + C4 bodies + design intent). - No C4 docs, LLM failure, or empty rank → heuristic fallback (config, CI, manifests, sampled source dirs).
- Ranker mode is recorded in
contextSelection.ranker(c4-llm|heuristic).
When files are skipped due to budget, the review is flagged sampledReview: true.
All LLM prompts are in src/Prompts.json, loaded through PromptInMemoryRepository. Do not embed prompt prose in TypeScript.
| Prompt | Role | Structured output schema |
|---|---|---|
ContextRanker |
Rank source paths | schemas/contextRank.ts |
ArchitectureReview |
Produce findings | schemas/finding.ts |
Prompt UUIDs in PromptIds.ts must stay stable across releases unless intentionally versioning a new prompt.
Prompt changes ≠ code changes. Wording and reviewer constitution evolve in Prompts.json; quality is validated by evals (when added), not unit tests.
IReviewResult / IFinding and REVIEW_RESULT_JSON_SCHEMA are consumed by:
- Markdown renderer
- JSON output files
- GitHub issue renderer
- Downstream automation (CI, dashboards)
Breaking field renames or enum changes require a schema version bump and migration notes. Prefer additive fields.
Evidence items (LLM vs parsed): OpenAI strict JSON requires file, directory, and observation on every evidence object. The LLM must use an empty string for file or directory when not applicable. After parsing, GuardDog stores IEvidenceItem with optional file/directory (omitted when empty). Helpers in schemas/finding.ts (evidenceItemToLlmShape, isLlmEvidenceItem) and test/unit/findingContract.test.ts keep the contract aligned.
contextSelection on the repo map includes:
summary—totalCandidates,rankedByRanker,unrankedByRanker, and packer skip countstruncation—rankerCapped(ranker returned fewer paths than candidates) vsbudgetExhausted(packer skipped files)manifest— per-file rank, tokens, included/skipped, and reason for ranked and packed paths
sampledReview on the review result is true only when budgetExhausted is true (token budget or per-file cap prevented inclusion). Ranker focus alone does not set sampledReview; the prompt may still note ranker focus via rankerCapped.
- Package:
@jonverrier/guard-dogon GitHub Packages. - Binary:
guarddog→dist/cli/index.js. - Runtime: Node 20+, CommonJS, TypeScript compiled to
dist/. - Config:
.guarddog/guarddog.config.jsonin the target repo (created byguarddog init). - Secrets:
OPENAI_API_KEYrequired at review time; GitHub token only when creating issues. - Publish artefact:
dist/**/*+README.mdonly (package.jsonfilesfield).
GuardDog runs locally or in CI against a checkout. It is stateless between runs except for files it writes.
These rules must not break during evolution:
-
Deterministic pre-LLM stages. Repo scan, C4 detection, heuristic ranking, and token packing must be reproducible given the same filesystem and config. No hidden randomness before the LLM call.
-
Bounded context. Every review run has explicit token budgets, a
contextSelection.summarywith candidate/ranked/unranked counts, and a manifest explaining what was included, skipped, and why. Never silently drop the manifest. -
Fail safe on ranker failure. If the C4 LLM ranker errors or returns invalid paths, fall back to heuristics — do not abort the review solely because ranking failed.
-
Fail loud on review failure. If the ArchitectureReview LLM returns empty/unparseable JSON, save debug output and throw — do not emit a fake “all clear” report.
-
Sampled reviews are visible. Set
sampledReview: trueonly when the source layer skips ranked files (truncation.source). C4 or design discards are reported incontextCoverageandlayerPackwithout marking a sampled review. Always log and render whether ranking was C4-guided vs heuristic separately from discards. -
Read-only target scan. Do not modify source files in the repository under review. Side effects are limited to report files inside the repository and GitHub issues requested on the CLI.
-
Repository path confinement. Design files, context reads, and Markdown/JSON reports stay inside the repository root. Reject absolute paths, parent traversal, and symlinks. Redact private-key blocks and other obvious secrets before that text is sent to an LLM.
-
Untrusted repo config cannot publish.
github.enabledandgithub.repoin the target config do not create issues or choose a repository. Cloud review forwardsNODE_AUTH_TOKENonly when that variable is set, and--dry-rundoes not launch cloud agents. -
Gitignore respected. Repository walks honour
.gitignorepatterns viautils/fileSystem.ts. -
No monorepo coupling. GuardDog must remain installable and runnable without the StrongAI workspace. Peer relationship to AutoDoc is documented, not wired.
When adding capability, prefer these seams rather than new cross-cutting imports:
| Need | Extend here | Avoid |
|---|---|---|
| New prompt | Prompts.json + PromptIds.ts |
String literals in core/ |
| New config flag | schemas/config.ts, CLI in cli/commands/review.ts, configLoader.ts |
Ad hoc process.env reads scattered in core |
| New file type in context | isContextCandidate() in contextRanker.ts |
Hard-coded extension lists in multiple files |
| New C4 filename convention | c4ArchitectureDocs.ts |
Path checks duplicated in ranker/packer |
| New output format | New renderer module; keep IReviewResult stable |
Forking finding shape per format |
| New LLM provider behaviour | llmProvider.ts, inject via tests |
Direct ChatDriverFactory calls outside ranker/reviewer |
| GitHub behaviour | github/ only |
Issue logic in reviewer.ts beyond a single call |
Use these checks before merging substantive changes:
npm run build— compiles and copiesPrompts.jsontodist/.npm run test:ci— unit tests with mocked LLM/filesystem; noOPENAI_API_KEYrequired.- Tests must cover: token packing math, manifest reasons, C4 detection/sort/cap, heuristic fallback, finding filter thresholds, config merge, finding evidence LLM contract (
findingContract.test.ts), context selection summary/truncation.
- Prompt wording changes → run targeted reviews on fixture repos; add eval suite when ready.
- After ContextRanker changes → verify ranker mode and manifest on repos with and without C4 docs.
- Work on
develop; merge tomainfor release. - Publish only from
mainafter build + test:ci. - Bump
@jonverrier/guard-dogsemver when output schema or CLI contract changes.
- Does a new feature respect token budgets?
- Is there a manifest entry for every skipped/included file?
- Does ranker failure still produce a review (heuristic path)?
- Are prompts still in
Prompts.json? - Are magic numbers named constants at file top?
- Are errors from
utils/errors.ts, not rawError? - Is
IReviewResultbackward compatible or versioned?
This DESIGN.md is the architectural contract for the GuardDog repository itself. When you change behaviour that affects invariants, context selection, or output contracts:
- Update the implementation and unit tests first.
- Update this
DESIGN.mdsection that documents the invariant or contract. - Update
README.mduser-facing sections (context manifest example, sampled-review semantics). - Regenerate C4 docs when module boundaries or public seams change:
npm run generate-docs. - Optionally re-run
guarddog review . --design DESIGN.mdto catch drift between declared intent and code.
Target repos under review have their own DESIGN.md; do not confuse this file with those.
Document these when changing related code:
- Eval suite not yet present. Prompt quality relies on manual review until evals land.
- Single LLM provider path. Model selection is via PromptRepository defaults;
--modelconfig exists but provider abstraction is minimal.
README.md— user-facing origin story, workflow, and prompt reference.AGENTS.md— instructions for AI assistants working in this repo.- AutoDoc — generates architecture docs GuardDog consumes.
- PromptRepository — LLM drivers and prompt expansion.