{"id":"ad3bc7d2-11a6-4158-8a6f-3e72bb637086","slug":"scars","kind":"mcp","name":"scars","summary":"Git-native regression guardrails and failure memory for AI coding agents and developers. Deterministic recall, token-budgeted prompt injection, and Model Context Protocol (MCP).","owner":"Pavanspoojary","repoUrl":"https://github.com/Pavanspoojary/scars","license":"Apache-2.0","licenseTier":"permissive","trust":"community","stars":1,"match":null,"fewStars":true,"format":"mcp","createdAt":"2026-10-10T18:59:17.000Z","addedAt":"2026-10-21T06:56:09.234Z","logoUrl":"https://avatars.githubusercontent.com/u/114323262?u=3ec4be1229d40fd8e9ff9891c92bdf2eed59c178&v=4","linkOnly":false,"collection":null,"skillPath":null,"categories":["developer-tools","memory-knowledge"],"tags":["ai-agents","autonomous-agents","claude-code","codex","coding-assistant","developer-tools","failure-prevention","git"],"runtime":"go","local":true,"cloudCapable":false,"cloudCapability":"unknown","cloudReadyOnPlatform":false,"needsApiKey":false,"reviewed":false,"syncedAt":"2026-10-21T07:01:09.875Z","sample":false,"url":"https://conduits.dev/tools/scars","language":"Go","transports":["stdio"],"install":{},"requirements":{"env":[],"upstreamMayCharge":false},"tools":null,"readme":"# GitScars (`git-scars`)\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/Pavanspoojary/scars.svg)](https://pkg.go.dev/github.com/Pavanspoojary/scars)\n[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)\n[![Go Report Card](https://goreportcard.com/badge/github.com/Pavanspoojary/scars)](https://goreportcard.com/report/github.com/Pavanspoojary/scars)\n[![CI](https://github.com/Pavanspoojary/scars/actions/workflows/ci.yml/badge.svg)](https://github.com/Pavanspoojary/scars/actions/workflows/ci.yml)\n\n> **A Git-native failure memory and regression guardrail system for software engineers and AI coding assistants.**\n\nGitScars captures lessons learned from production incidents, subtle concurrency bugs, and breaking regressions as versioned, human-reviewable Markdown documents anchored directly to repository files, symbols, error signatures, and dependency versions.\n\nWhen developers edit code or coding agents (Claude Code, Cursor, Antigravity, Windsurf) tackle tasks, GitScars deterministically retrieves only the relevant failure memories before mistakes repeat.\n\n---\n\n## Table of Contents\n\n- [The Problem](#the-problem)\n- [Architecture & Comparison](#architecture--comparison)\n- [Why Not Just Scoped Rules?](#why-not-just-scoped-rules-cursorrules--claudemd)\n- [How It Works](#how-it-works)\n- [Installation & Build](#installation--build)\n- [Quickstart Workflow](#quickstart-workflow)\n  - [Automated Regression Harvesting (`harvest`)](#16-automated-historical-regression-mining-git-scars-harvest)\n  - [Portable Memory Bundles (`bundle`)](#17-portable-memory-bundles-git-scars-bundle)\n  - [Self-Healing Execution Loop (`heal`)](#18-self-healing-execution-loop-git-scars-heal)\n  - [CI/CD & SARIF Annotations (`check --format sarif`)](#19-cicd--github-code-scanning-sarif-git-scars-check---format-sarif)\n  - [Multi-Language AST Freshness](#20-multi-language-ast-aware-freshness-go-python-typescript)\n- [File Format & Schema](#file-format--schema)\n- [AI Agent Integration & MCP Server](#ai-agent-integration--mcp-server)\n- [Dependency Manifest & Lockfile Anchors](#dependency-manifest--lockfile-anchors)\n- [CLI Command Reference](#cli-command-reference)\n- [Security, Threat Model & Privacy](#security-threat-model--privacy)\n- [Documentation & ADRs](#documentation--adrs)\n- [Contributing](#contributing)\n\n---\n\n## The Problem\n\nRepository knowledge frequently disappears into old commits, closed pull requests, Slack threads, and transient agent conversation transcripts. As repositories expand:\n\n- **Monolithic Instruction Files (`AGENTS.md`, `CLAUDE.md`)** suffer from prompt bloat, attention dilution (\"lost in the middle\"), and cannot bind rules to specific file versions or symbol anchors.\n- **Vector Memory & RAG** introduce semantic hallucinations, noisy false-positive retrieval (see [VibeMemBench arXiv:2609.23570](https://arxiv.org/abs/2609.23570)), and vulnerability to indirect prompt injection ([MemSecBench arXiv:2607.27080](https://arxiv.org/abs/2607.27080)).\n- **Silent Code Drift**: Code changes over time. When files change, lessons written months ago become stale or invalid, but flat files provide no way to detect staleness.\n\n---\n\n## Architecture & Comparison\n\n| Capability | Monolithic (`AGENTS.md`) | Glob-Scoped (`.cursor/rules`) | Vector Memory (RAG) | **GitScars (`git-scars`)** |\n| :--- | :--- | :--- | :--- | :--- |\n| **Prompt Strategy** | Unconditional full dump | Directory glob pattern match | Semantic similarity search | Selective multi-signal anchor match |\n| **Average Prompt Tokens** | `871` tokens (all rules) | `187` tokens avg (directory rules) | Dynamic retrieval | **`133` tokens avg (-28.9% vs Scoped)** |\n| **Drift Detection** | None (silent obsolescence) | None (silent failure on move) | None (unanchored) | **Deterministic SHA-256 & AST symbol hashing** |\n| **Verification Gate** | Unverified text assertions | Unverified text assertions | None | **Scrubbed fail-to-pass test execution** |\n| **Human Governance** | Ad-hoc edits | Ad-hoc edits | None | **Promotion gate (`git-scars promote`)** |\n| **Host Security Boundary** | Static text | Static text | Cloud API / embeddings | **Host `argv` execution (`cleanEnv()`) + trust-hash** |\n| **Runtime Dependencies** | Offline text | Offline text | Remote embeddings / DB | **Zero dependencies (pure Go single binary)** |\n\n*For scenario-by-scenario modeled token measurements and architectural case walkthroughs, see [SCENARIO_ANALYSIS.md](SCENARIO_ANALYSIS.md).*\n\n---\n\n## Why Not Just Scoped Rules (`.cursor/rules` / `CLAUDE.md`)?\n\nGlob-scoped rules (such as Cursor `.cursor/rules/*.mdc` or nested directory `CLAUDE.md` files) provide path-scoping out of the box. Why is GitScars necessary when path-scoping already exists?\n\nIn our scenario walkthrough across 10 production regression patterns ([SCENARIO_ANALYSIS.md](SCENARIO_ANALYSIS.md)), scoped rules fail in three critical production scenarios:\n\n### 1. The Refactored Anchor (Silent Failure)\n- **Failure**: When code is moved or refactored (e.g., `services/billing/calc.py` becomes `core/pricing/calc.py`), glob rules silently stop firing. If obsolete files remain, they fire on dead code. Scoped rules have **0% drift detection**.\n- **GitScars Defense**: Anchors track both file SHA and symbol AST hashes. If anchors move, `git-scars check` fails in CI with exit code 2. Teams maintain an unbroken chain of memory using `git-scars supersede`.\n\n### 2. The Toxic Unverified Claim\n- **Failure**: A developer or AI agent writes an untested rule (e.g., `\"Set DisableKeepAlives = true on http.Transport\"`). In production, disabling keep-alives forces TLS renegotiation on every connection, crashing API latency and exhausting local ports. Scoped rules accept any markdown without execution proof.\n- **GitScars Defense**: Scars cannot transition to `active` without a runnable fail-to-pass verifier. Claims must be proven against code before entering prompt memory.\n\n### 3. Prompt Inflation & Rule Contradiction\n- **Failure**: In shared directories (`pkg/**` or `services/**`), glob-scoped rules dump every rule into the prompt simultaneously. In our benchmark, editing a client file pulled 4 unrelated concurrency rules (334 tokens of attention dilution).\n- **GitScars Defense**: Token-budgeted injection (`git-scars inject --budget 400`) scores multi-signal anchors (symbols, error signatures, dependency versions) and injects only the exact relevant guardrail with structured `<dont>` and `<do>` instructions.\n\n---\n\n## How It Works\n\n```mermaid\nflowchart TD\n    A[\"Production Bug / Incident\"] --> B[\"Capture Draft (git-scars add / from-commit)\"]\n    B --> C[\"Execute Scrubbed Verifier (git-scars verify)\"]\n    C --> D{\"Fail-to-Pass Verified?\"}\n    D -- Yes --> E[\"Human Code Review in PR (git-scars promote)\"]\n    D -- No / Exception --> E\n    E --> F[\"Active Scar (.gitscars/scars/)\"]\n    \n    F --> G[\"Coding Task / Agent Session\"]\n    G --> H[\"Selective Retrieval (git-scars recall / MCP)\"]\n    H --> I[\"Code Drift Detected (git-scars check / hook)\"]\n    I --> J[\"Inspect Diff (git-scars diff)\"]\n    J --> K[\"Explicit Reaffirmation (git-scars reaffirm)\"]\n    K --> F\n```\n\n---\n\n## Installation & Build\n\nRequires Go 1.22+:\n\n```bash\n# Clone the repository\ngit clone https://github.com/Pavanspoojary/scars.git\ncd scars\n\n# Build the single standalone static binary\ngo build -o git-scars ./cmd/git-scars\n```\n\nOptionally install `git-scars` into your system `$PATH`:\n```bash\nsudo mv git-scars /usr/local/bin/\n```\nOnce installed, Git automatically discovers it: you can run either `git-scars <command>` or `git scars <command>`.\n\n---\n\n## Quickstart Workflow\n\n### 1. Initialize GitScars\n```bash\ngit-scars init\n```\nCreates `.gitscars/scars/` for versioned lessons and `.gitscars/.local/` (automatically gitignored) for derived local state (indexes, trusted verifier hashes, feedback).\n\n### 2. Capture a Failure Lesson\nCreate a new draft using the interactive terminal wizard:\n```bash\ngit-scars add -i\n```\n\nOr pass flags directly:\n```bash\ngit-scars add \\\n  --title \"Nil pointer dereference in auth context\" \\\n  --lesson \"Always use comma-ok idiom when reading user profile from request context\" \\\n  --files \"pkg/auth/context.go\"\n```\n\nOr capture automatically from an existing fix commit without requiring an LLM:\n```bash\ngit-scars add from-commit 8a1b3f9\n```\n*Prefills changed files, parent base commit, fix commit, and inferred test commands into a new draft.*\n\n### 3. Record Verification Evidence\nExecute the verifier safely against the codebase:\n```bash\ngit-scars verify nil-pointer-dereference-8a1b3f --interactive\n```\nComputes deterministic command hashes, scrubs the environment, redacts secrets, and tests the worktree.\n\nThe procedure verifies the worktree in both directions. It runs the verifier on the current tree, then creates a detached worktree at the recorded base commit, overlays the test files of the fix commit onto it, and runs the verifier there. The scar is recorded as `fail_to_pass` only when the verifier passes on the current tree and fails at the base. A base that also passes is reported as a failure to reproduce, and an inconclusive result is reported honestly as an exception.\n\nThe command exits `1` when verification does not produce a passable result, so CI pipelines can gate on it. Recorded evidence never promotes a scar on its own: a human reviewer must still run `git-scars promote`.\n\n### 4. Review and Promote\nHuman review is required before a Scar can become active:\n```bash\ngit-scars promote nil-pointer-dereference-8a1b3f \\\n  --status active \\\n  --reviewer \"alice\" \\\n  --rationale \"Reviewed test reproduction in PR #42\"\n```\n\n### 5. Selective Retrieval\nRetrieve relevant lessons during coding tasks:\n```bash\n# By target file\ngit-scars recall --files pkg/auth/context.go\n\n# Diff-aware retrieval (against a branch or commit)\ngit-scars recall --diff origin/main\n\n# Failure-aware retrieval from failing test stderr\ngo test ./... 2>&1 | git-scars recall --stdin\n\n# Machine-readable JSON output for coding agents\ngit-scars recall --files pkg/auth/context.go --json\n```\n\nRecall reads through a per-process cache: parsed records, anchor digests, the decoded index, and the parsed dependency manifests are reused while their files keep the same size and modification time, and every cached value is invalidated when this process writes the file. A one-shot command starts with an empty cache and always reflects the disk; a long-lived MCP server pays the full read once and then recalls on a directory read, one stat per scar file, and a copy of each returned candidate. Retrieval weights, thresholds, and the fail-closed invariant gate are unaffected — only the cost of reaching the same answer changed (see [ADR-0021](DECISIONS.md)).\n\n### 6. Token-Budgeted Agent Prompt Injection\nGenerate an ultra-dense, token-budget-capped guardrail block for AI coding agents before file editing:\n```bash\n# Generate compact XML block capped to 300 estimated tokens\ngit-scars inject --files \"pkg/auth/context.go\" --budget 300\n\n# Generate Markdown guardrails for prompt templates\ngit-scars inject --files \"pkg/auth/context.go\" --budget 200 --format markdown\n```\n\n### 7. Autonomous Instruction File Sync\nAutomatically synchronize active failure memories into AI agent instruction files (`AGENTS.md`, `CLAUDE.md`, `.cursorrules`, `.windsurfrules`):\n```bash\n# Auto-discover and update existing agent instruction files\ngit-scars sync\n\n# Or explicitly target specific instruction files\ngit-scars sync --targets AGENTS.md,CLAUDE.md\n```\n*Manages a deterministic markdown table between `<!-- GIT-SCARS:START -->` and `<!-- GIT-SCARS:END -->` markers, preserving all external prompt rules.*\n\n### 8. Instant Failure & Test Triage\nDiagnose raw compiler errors, panic stack traces, or test failures directly against recorded regression wisdom across multiple languages:\n- **Go**: `panic:`, `fatal error: all goroutines asleep - deadlock`, `--- FAIL:`, race detector warnings, and runtime file/line locations.\n- **Python**: `Traceback (most recent call last)`, `File \"...\", line N, in func`, `AssertionError`.\n- **JavaScript & TypeScript**: V8 stack traces `at func (file:line:col)`, `Error:`, `TypeError`.\n- **Rust**: `thread '...' panicked at '...'`, source locations `src/file.rs:N`.\n- **Generic / Runners**: Memory faults (`Segmentation fault`), test framework failures, and race reports.\n\n```bash\n# Pipe failing test output directly to triage\ngo test ./... 2>&1 | git-scars triage\n\n# Or diagnose a specific error signature\ngit-scars triage --error \"fatal error: all goroutines are asleep - deadlock\"\n\n# Machine-readable JSON for agent automated healing loops\ngit-scars triage --error \"panic: nil pointer\" --json\n```\n\n### 9. Read-Only Freshness Check in CI\nAdd to your CI workflow to ensure no active Scars have stale anchors:\n```bash\ngit-scars check\n```\n**Stable Exit Codes**:\n- `0`: All Scars valid and current.\n- `1`: Invalid format or invariant violation. Records that fail to parse or that break a lifecycle invariant are reported, never skipped.\n- `2`: Stale anchor detected (code modified since baseline, requires reaffirmation).\n- `3`: Operational error.\n\nAn active scar that claims `fail_to_pass` verification must record a `command_hash` derived from its own `argv`. A record whose hash does not match its command is rejected as an invariant violation and is never injected into an agent prompt.\n\n### 10. Git Pre-Commit Hook Guardrail\nInstall the Git pre-commit hook to catch stale active scars before staging and committing:\n```bash\n# Install hook into .git/hooks/pre-commit\ngit-scars hook install\n\n# Inspect hook status (warns when git-scars is not on PATH)\ngit-scars hook status\n\n# Uninstall hook\ngit-scars hook uninstall\n```\n\nThe generated hook guards every check behind `command -v git-scars`, so a hook whose binary cannot be resolved skips silently instead of failing — every commit would pass with no guardrail running. `git-scars hook status` and the `Pre-Commit Hook` probe in `git-scars doctor` both report a warning in that state.\n\n### 11. Inspect Drift & Reaffirm\nWhen `git-scars check` or pre-commit hooks report modified anchors, inspect the exact unified diff before reaffirming:\n```bash\n# View unified line diff against recorded anchor baseline\ngit-scars diff map-write-crash-391945\n\n# Reaffirm anchor baseline after human review\ngit-scars reaffirm map-write-crash-391945 \\\n  --reviewer \"alice\" \\\n  --rationale \"Verified logic holds after refactoring exporter package\"\n```\n\n### 12. Repository Health & Metrics\nInspect overall repository scar metrics, monitored anchors, and recorded feedback:\n```bash\n# Human-readable summary\ngit-scars stats\n\n# Machine-readable JSON metrics\ngit-scars stats --json\n```\n\n### 13. Run Full Diagnostics & Automated Repair\nAudit Git worktree health, scar file loadability, schema validity, invariants, anchor drift, and hook readiness (including whether an installed hook can resolve `git-scars` on PATH):\n```bash\n# Interactive diagnostic checklist\ngit-scars doctor\n\n# Machine-readable JSON report for CI pipelines\ngit-scars doctor --json\n\n# Automatically repair recoverable cache, local directory, and hook configurations\ngit-scars doctor --fix\n```\n\n### 14. Lifecycle Contradiction & Supersession\nManage evolution of failure memories as codebase architectures and best practices evolve:\n```bash\n# Contradict an outdated scar with documented rationale and conflict reference\ngit-scars contradict scar-001 --by scar-005 --rationale \"Worker pool refactored to context cancellation\"\n\n# Supersede an obsolete scar by a successor scar\ngit-scars supersede scar-001 --by scar-005\n```\n\n### 15. Near-Duplicate Scar Detection\nInspect active repository scars for semantic and lexical duplication using token-level Jaccard similarity:\n```bash\n# Dry-run near-duplicate audit (default threshold: 0.85)\ngit-scars dedupe --dry-run\n\n# Custom similarity threshold and machine-readable JSON\ngit-scars dedupe --min 0.75 --json\n```\n\n### 16. Automated Historical Regression Mining (`git-scars harvest`)\nBootstrap repository memory by walking Git history to identify past bug-fixing commits and generating draft scars with built-in quality filtering to eliminate draft noise:\n- **Diff-Size Cap (`--max-files 5`)**: Automatically ignores commits touching `> 5` files to avoid noisy reformatting, mass migrations, and large multi-package refactors.\n- **Co-Located Test Requirement**: Skips commits without co-located test updates by default to guarantee verified test behavior (override with `--allow-untested`).\n- **Confidence Scoring (`--min-confidence 7`)**: Computes a 1-10 quality confidence score; drafts scoring below 7 are rejected to prevent human review fatigue. The score is a base of 2, plus 3 for an issue reference cited in the subject or body, plus 3 for a co-located regression test, plus 2 when the diff is within the `--max-files` cap the harvest filter itself applies — so a capped fix with co-located tests reaches the review bar without an external issue reference, while an uncapped or untested commit needs the reference.\n\nEach mined draft records the fix commit and its first parent, so the draft can be verified as a genuine fail-to-pass regression rather than an exception.\n\n```bash\n# Preview high-confidence candidate bug fixes in recent commit history (dry run)\ngit-scars harvest --max 50 --dry-run\n\n# Automatically generate quality-filtered draft scars for review and promotion\ngit-scars harvest --max 100 --min-confidence 7\n\n# Inspect findings as structured JSON\ngit-scars harvest --json\n```\n\n### 17. Portable Memory Bundles (`git-scars bundle`)\nShare, export, and import curated sets of verified failure memories across teams and services without sharing entire Git histories:\n```bash\n# Export active scars into a portable verified JSON memory bundle\ngit-scars bundle export --out ./shared-scars.json\n\n# Export with severity filtering\ngit-scars bundle export --severity critical --out ./critical-scars.json\n\n# Import memory bundle into repository as reviewable drafts (with optional ID prefix)\ngit-scars bundle import ./shared-scars.json --prefix org-\n```\n*Note: All imported scars are ingested as unreviewed drafts (`status: unreviewed`) to guarantee local verifier execution and team code review before activation.*\n\n### 18. Self-Healing Execution Loop (`git-scars heal`)\nRun test suites or build commands under automated surveillance. When failures occur, `heal` intercepts output, matches relevant regression scars, and generates structured remediation guidance:\n```bash\n# Run tests under self-healing observation\ngit-scars heal -- go test -race ./...\n\n# Machine-readable output for autonomous agent loops\ngit-scars heal --json -- npm test\n```\n\nThe observed command's own exit code is reported in the heal output. `git-scars heal` itself exits `4` when the observed command failed and `0` when it succeeded, so that the failure of the observed command is never confused with an operational error of `git-scars` itself.\n\n### 19. CI/CD & GitHub Code Scanning SARIF (`git-scars check --format sarif`)\nIntegrate GitScars directly into pull request checks and security dashboards using the OASIS SARIF 2.1.0 standard:\n```bash\n# Scaffold production-ready GitHub Actions workflow (.github/workflows/git-scars.yml)\ngit-scars init --ci github\n\n# Emit SARIF report for GitHub Code Scanning annotations\ngit-scars check --format sarif > git-scars.sarif\n\n# Pre-edit enforcement blocking check in SARIF format\ngit-scars enforce --files \"pkg/auth.go\" --format sarif\n```\n\nBoth reports can be uploaded to GitHub Code Scanning under separate categories, so anchor drift and guardrail matches appear as annotations on the changed lines of a pull request. The `--files` argument accepts a comma or newline separated list, so a file list can be piped directly from a git command:\n\n```bash\ngit-scars enforce --files \"$(git diff --name-only origin/main...HEAD)\" --fail-on high --format sarif\n```\n\n### 20. Multi-Language AST-Aware Freshness (Go, Python, TypeScript)\nGitScars includes built-in syntactic symbol hashing across multiple languages to eliminate reaffirm fatigue:\n- **Go**: Full AST symbol declaration extraction via `go/parser` and `go/ast`.\n- **Python**: Function (`def`, `async def`) and class (`class`) definition hashing.\n- **TypeScript & JavaScript**: Functions, classes, interfaces, types, and exported symbols.\n\nWhen anchor source files are modified:\n- If anchored symbols remain syntactically identical (e.g. comments, whitespace, imports, or unrelated helper functions changed), freshness remains **`current`**, eliminating rubber-stamp reaffirmations on hot files.\n- If anchored symbol declarations are altered or removed, freshness transitions to **`changed`** (stale), signaling the need for review and reaffirmation.\n\n---\n\n## File Format & Schema\n\nEach Scar is stored as a single, human-readable, Git-diffable Markdown file in `.gitscars/scars/<slug>-<shortid>.md` with strict YAML frontmatter:\n\n```markdown\n---\nschema_version: \"1\"\nid: \"map-write-crash-391945\"\nslug: \"concurrent-map-write-in-telemetry-exporter\"\ntitle: \"Concurrent map write in telemetry exporter\"\nlesson: \"Metrics map must be protected by sync.RWMutex during RecordMetric calls.\"\nseverity: \"high\"\nfix_hint: \"Wrap map mutations in mu.Lock() or replace with sync.Map\"\nbad_pattern: \"m[key] = val\"\ngood_pattern: \"mu.Lock(); m[key] = val; mu.Unlock()\"\napplicability: \"Telemetry exporters handling concurrent metrics emissions.\"\nanchors:\n  files:\n    - \"pkg/telemetry/exporter.go\"\n  symbols:\n    - \"RecordMetric\"\n  commands:\n    - \"go test -race ./pkg/telemetry/...\"\n  error_signatures:\n    - \"fatal error: concurrent map writes\"\nverifier:\n  result: \"fail_to_pass\"\n  argv:\n    - \"go\"\n    - \"test\"\n    - \"-race\"\n    - \"./pkg/telemetry/...\"\n  command_hash: \"2d4b1ee683d6be106b1633c27fedb692d3f757a5aa049397e28ef1cbd6d52736\"\nbaseline:\n  recorded_at: \"2026-10-11T08:00:00Z\"\n  pkg/telemetry/exporter.go: \"a3b98f12c4...\"\nreview:\n  status: \"approved\"\n  reviewer: \"bob\"\n  date: \"2026-10-11T08:05:00Z\"\n  rationale: \"Reproduced with race detector in PR #104\"\nlifecycle:\n  state: \"active\"\n---\n\n### Symptom & Root Cause\nUnder heavy concurrent load, multiple goroutines called RecordMetric simultaneously without synchronization.\n\n### Footgun / Guardrail\nReplaced raw map with sync.Map or guarded reads and writes with sync.RWMutex.\n```\n\n---\n\n## Anchor Semantics\n\nA guardrail is only useful while its anchors still describe the code it protects. `git-scars lint` and `git-scars check` therefore verify anchor semantics rather than trusting them:\n\n| Rule | Severity | Meaning |\n| :--- | :--- | :--- |\n| `anchor_symbol_missing` | `ERROR` | The anchored symbol no longer exists in any anchored file. |\n| `bad_pattern_present` | `ERROR` | The recorded footgun is still present in the anchored code. |\n| `good_pattern_absent` | `WARNING` | The recorded fix cannot be found, so the anchor likely no longer covers the fixed code. |\n| `missing_severity` | `WARNING` | An active guardrail does not declare a severity, so it cannot be compared against a blocking threshold. |\n\nA symbol anchor is satisfied by a declaration or by any occurrence of the name in the anchored file, so anchors to variables and fields are accepted.\n\n`bad_pattern` and `good_pattern` must be **literal snippets of code**, so that presence and absence can be checked deterministically:\n\n- `good_pattern` is a snippet of the fixed code and must be present in an anchored file.\n- `bad_pattern` is a snippet of the footgun and must be absent from every anchored file.\n\nA pseudo-code pattern such as `m[key] = val` cannot be verified and will always be reported as absent.\n\n---\n\n## Repository Configuration\n\n`.gitscars/config.yaml` holds the repository-scoped retrieval limits and is created by `git-scars init`:\n\n```yaml\n# GitScars Configuration\nschema_version: \"1\"\nabstain_threshold: 3\ntop_k: 3\n```\n\n| Key | Meaning |\n| :--- | :--- |\n| `abstain_threshold` | Minimum score a candidate must reach to be retrieved. Below it, GitScars abstains. |\n| `top_k` | Maximum number of scars returned by a single recall. |\n\n`git-scars recall --threshold` and `--top-k` override the configured values for one invocation. A value of `0` means \"use the configured value\". The MCP `recall_scars` tool defers its limits to this file the same way. A missing, unreadable, or malformed configuration file falls back to the defaults, and an individual value that cannot be interpreted is ignored, so a configuration mistake never blocks retrieval; the mistake itself is reported by `git-scars doctor`.\n\n`git-scars doctor` carries a Configuration probe that names every entry of the file that was present but could not be used — a key outside the recognized set (a misspelling such as `abstain_treshold`), a value that is not a positive integer, a repeated key, or a declared `schema_version` the reader does not understand. A file that declares an unsupported schema version is set aside whole rather than partially applied, because the keys of a newer contract may carry different meanings. The reader strips an unquoted trailing comment and one layer of quotes, so `top_k: 5 # note` is honoured.\n\nInjection, triage, and enforcement deliberately use a more sensitive threshold than the abstain threshold, because a guardrail that is worth injecting is worth surfacing before it reaches the abstain threshold. `plan_task` plans with recall at a threshold of 2 for the same reason: planning surfaces candidates for consideration before work begins, it does not block.\n\n---\n\n## AI Agent Integration & MCP Server\n\n### 1. Model Context Protocol (MCP) Server\n\nGitScars provides a built-in stdio Model Context Protocol (MCP) server for native integration with coding assistants:\n\nThe server reports the current release version in its `initialize` response, so client-visible metadata stays aligned with the CLI banner and SARIF tool metadata. It never executes verifiers and never modifies an existing scar. The `draft_scar` tool writes a new draft record, which is a creation rather than a change to recorded failure memory.\n\n```bash\ngit-scars mcp\n```\n\nThe MCP server exposes rich two-way tools and resources for AI coding agents:\n\n#### Standard Tools:\n- `list_scars`: List all repository scars with their lifecycle and dynamic freshness status.\n- `get_scar`: Retrieve full frontmatter, anchors, severity, verifier results, and markdown body by scar ID.\n- `recall_scars`: Deterministically retrieve matching scars for target files, symbols, error messages, commands, and task descriptions. Its limits defer to the repository configuration.\n- `inject_guardrails`: Generate an ultra-compact, token-budget-capped prompt guardrail block for specific files, symbols, and task terms.\n- `triage_error`: Diagnose raw compiler errors, panic stack traces, or test outputs against recorded scars, optionally narrowed to known files.\n- `draft_scar`: Autonomously record a new failure memory draft into repository Git memory, including symbol anchors and a calibrated severity.\n\n#### Composite Tools (Single-Roundtrip Workflow):\n- `pre_edit_check`: Pre-edit blocking guardrail check. Inspects target files and symbols before file modifications and returns blocking scars with actionable do/don't patterns and verification commands.\n- `plan_task`: Combines selective recall (files, symbols, commands, an error signature, and task terms) and token-budget prompt injection into a single roundtrip for task planning. Planning recall is deliberately more sensitive than enforcement so candidates surface before work begins.\n- `post_failure_learn`: Multi-language failure triage and diagnostic learning in a single roundtrip, returning prevention lessons for test errors or stack traces.\n\n#### Resources:\n- `scar://<id>`: Read individual scar frontmatter and prevention lessons directly as MCP resources.\n- `scars://active`: Read the auto-generated markdown summary table of active repository guardrails.\n\n#### Client Configuration\n\n##### Claude Desktop (`claude_desktop_config.json`) / Cursor (`.cursor/mcp.json`) / Antigravity\n```json\n{\n  \"mcpServers\": {\n    \"git-scars\": {\n      \"command\": \"git-scars\",\n      \"args\": [\"mcp\"]\n    }\n  }\n}\n```\n\n##### Zed (`settings.json`)\n```json\n{\n  \"context_servers\": [\n    {\n      \"id\": \"git-scars\",\n      \"command\": {\n        \"path\": \"git-scars\",\n        \"args\": [\"mcp\"]\n      }\n    }\n  ]\n}\n```\n\n### 2. CLI JSON Recall (`reposcars.recall.v1`)\n\nAgents can also invoke the CLI directly:\n```bash\ngit scars recall --files \"$MODIFIED_FILES\" --json\n```\n\nOutput:\n```json\n{\n  \"schema_version\": \"reposcars.recall.v1\",\n  \"timestamp\": \"2026-10-11T08:00:00Z\",\n  \"query\": { \"files\": [\"pkg/telemetry/exporter.go\"], \"threshold\": 3, \"top_k\": 3 },\n  \"count\": 1,\n  \"results\": [\n    {\n      \"id\": \"map-write-crash-391945\",\n      \"title\": \"Concurrent map write in telemetry exporter\",\n      \"lesson\": \"Metrics map must be protected by sync.RWMutex during RecordMetric calls.\",\n      \"score\": 5,\n      \"confidence\": 0.26,\n      \"freshness\": \"current\",\n      \"matches\": [\"file(+5)\"],\n      \"explanation\": \"file(+5)\",\n      \"anchors\": { \"files\": [\"pkg/telemetry/exporter.go\"] }\n    }\n  ]\n}\n```\n\n### 3. Pre-Edit Guardrail Enforcement (`git-scars enforce`)\n\nPrevent AI coding agents and developers from re-introducing known regressions before files are modified:\n\n```bash\n# Check files before editing; returns exit code 2 if a high-severity guardrail matches\ngit-scars enforce --files \"pkg/worker.go\" --fail-on high\n```\n\nExit Codes:\n- `0`: Clean (no blocking guardrails detected).\n- `2`: Blocked (blocking guardrail detected; outputs actionable `<dont>`, `<do>`, and verification instructions to stderr).\n\nA guardrail that does not declare a severity is treated as `high`, so an uncalibrated guardrail is never silently downgraded below the blocking threshold.\n\nMachine JSON Output:\n```bash\ngit-scars enforce --files \"pkg/worker.go\" --json\n```\n\n### 4. Zero-Friction Agent Onboarding (`git-scars init --agent`)\n\nConfigure coding assistants with a single setup command:\n```bash\ngit-scars init --agent claude,cursor,zed,antigravity\n```\nAutomatically scaffolds `.claude/mcp.json`, `.cursor/rules/git-scars.mdc`, `.zed/settings.json`, and `.gemini/config/rules/git-scars.md`.\n\n---\n\n## Dependency Manifest & Lockfile Anchors\n\nGitScars automatically inspects repository dependency manifests and lockfiles to anchor lessons to exact package versions without manual configuration:\n\n- **Go**: Direct module dependencies and versions from `go.mod`.\n- **Node.js**: Package dependencies and versions from `package-lock.json` (v1, v2, and v3).\n- **Rust**: Package versions from `Cargo.lock`.\n- **Python**: Dependencies and versions from `poetry.lock` and `requirements.txt`.\n\nWhen dependencies are upgraded or downgraded, Scars anchored to vulnerable or breaking versions automatically trigger match signals during recall.\n\nDependency anchors are authored with the `name@version` form:\n\n```bash\ngit-scars add \\\n  --title \"Redis pipeline breaks on client upgrade\" \\\n  --lesson \"Upgrade the redis client only after reviewing the pipeline change\" \\\n  --files \"pkg/cache/redis.go\" \\\n  --deps \"github.com/redis/go-redis/v9@9.5.1\"\n```\n\nThey are persisted in the scar frontmatter and re-read on every subsequent load, so the anchor survives verification, reaffirmation, and synchronization cycles:\n\n```yaml\nanchors:\n  dependencies:\n    - name: \"github.com/redis/go-redis/v9\"\n      version: \"9.5.1\"\n```\n\n---\n\n## CLI Command Reference\n\n| Command | Arguments | Description |\n| :--- | :--- | :--- |\n| `init` | `[--agent <targets>, --ci <target>]` | Initialize `.gitscars/` repository, agent configs, and CI workflows (`--ci github`) |\n| `add` | `[-i], [--title, --lesson, --files, --deps]` | Create a new scar draft (interactive wizard or flags) |\n| `add from-commit` | `<sha>` | Automatically prefill a draft from a Git commit diff |\n| `list` | none | List recorded scars with lifecycle, review, and freshness |\n| `show` | `<id>` | Display full metadata, anchors, and body of a scar |\n| `diff` | `<id>` | Inspect unified line diff of anchor files against baseline |\n| `promote` | `<id> --status active` | Promote a scar to active state (enforces review & verifier invariants) |\n| `verify` | `<id> [--interactive]` | Safely execute verifier in scrubbed env and record evidence (exit `1` when verification does not pass) |\n| `reaffirm` | `<id> --reviewer --rationale` | Reaffirm a scar after anchor code drift |\n| `contradict` | `<id> --by <new-id> --rationale` | Transition scar to contradicted state with conflict reference |\n| `supersede` | `<id> --by <new-id>` | Supersede an obsolete scar by a successor scar |\n| `retire` | `<id>` | Retire a scar that is no longer applicable |\n| `recall` | `--files`, `--diff`, `--stdin`, `--json`, `--threshold`, `--top-k` | Retrieve relevant scars with deterministic multi-signal scoring |\n| `enforce` | `--files`, `[--fail-on, --format, --staged, --json]` | Pre-edit blocking guardrail check (`--format sarif`, exit `0` clean, exit `2` blocked) |\n| `inject` | `[--files, --task, --budget, --format]` | Generate token-budgeted prompt guardrails with `<dont>` and `<do>` patterns |\n| `sync` | `[--targets <files>]` | Synchronize active scars into AGENTS.md / CLAUDE.md |\n| `triage` | `[--error <text>, --json]` | Diagnose test failures and panic traces against recorded scars |\n| `dedupe` | `[--min <sim>, --dry-run, --json]` | Detect duplicate and near-duplicate scars (token Jaccard similarity) |\n| `harvest` | `[--max <n>, --since <ref>, --dry-run, --json, --max-files <n>, --min-confidence <n>, --allow-untested]` | Automatically mine bug-fixing commits from Git history into scar drafts |\n| `bundle` | `export [options], import <file> [options]` | Export and import portable, verified memory bundles (`gitscars.bundle.v1`) |\n| `heal` | `[--json] -- <command...>` | Run test command, intercept failures, and automatically triage regressions (exit `4` when the observed command failed) |\n| `check` | `[--diff <ref>, --format sarif]` | Read-only verification of scar freshness and invariants (`--format sarif`) |\n| `lint` | none | Security, schema, and anchor-semantics audit (checks traversal, injections, unloadable files, anchor drift, noisy scars) |\n| `doctor` | `[--json, --fix]` | Run repository diagnostics and automatically repair caches/hooks |\n| `stats` | `[--json]` | Display repository metrics, monitored anchors, and feedback stats |\n| `eval-agents` | `--report <file>` | Analyse a recorded multi-agent corpus under the preregistered non-inferiority protocol (EVAL_PLAN 5.2) |\n| `eval-authoring` | `--log <file>` | Summarise a human authoring log against the five minute median target (EVAL_PLAN 5.1) |\n| `index` | none | Rebuild `.gitscars/.local/index.json` fast cache |\n| `hook` | `install`, `status`, `uninstall` | Manage Git pre-commit hook guardrail |\n| `mcp` | none | Run stdio Model Context Protocol (MCP) server |\n| `feedback` | `<id> --rating --notes` | Record retrieval utility feedback (`helpful`, `irrelevant`, `incorrect`) |\n| `version` | none | Print `git-scars` version |\n\n---\n\n## Security, Threat Model & Privacy\n\n### Scrubbed Environment, Not Container Isolation\n`git-scars verify` executes verifiers directly on the host machine. While environment variables are scrubbed (`cleanEnv()`) and shell interpolation is prevented via direct `exec.Command` argv arrays, **verifiers run with the permissions of the host process and have full filesystem and network access**. Scrubbing is not OS container isolation.\n\n### Threat Model & Trust Boundaries\n1. **Never Auto-Run Untrusted Verifiers**: Verifiers from external pull requests or untrusted memory bundles must be reviewed before execution.\n2. **Deterministic Command Trust-Hash**: Verification commands are hashed (`sha256`) and recorded in `verifier.command_hash`. Invariant checks reject verifiers whose hashes do not match.\n3. **Mandatory Human Review Gate**: Scars cannot become `active` without explicit human sign-off (`git-scars promote --reviewer`). Untrusted drafts cannot inject guardrails into agent prompts.\n4. **Secret Redaction**: Automated regex scrubbing redacts Bearer tokens, private keys, API keys, and passwords before recording execution outputs.\n5. **Zero Cloud Telemetry**: All feedback, index caches, and command trust lists are stored locally in gitignored `.gitscars/.local/`. No data leaves your machine.\n\n---\n\n## Documentation & ADRs\n\n- [SCENARIO_ANALYSIS.md](SCENARIO_ANALYSIS.md): Design estimates and illustrative scenario walkthrough across 10 regression patterns comparing prompt token footprints and architectural failure modes.\n- [EVAL_PLAN.md](EVAL_PLAN.md): Preregistered benchmark evaluation plan, scoring baseline weights, and power calculations.\n- [PRIOR_ART.md](PRIOR_ART.md): Primary-source comparative analysis (`Daily-Nerd/Scar`, `fscars`, `gitmem`, arXiv:2609.23570).\n- [DECISIONS.md](DECISIONS.md): Architecture Decision Records (ADR-0001 through ADR-0014).\n\n---\n\n## Contributing\n\nContributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) and [AGENTS.md](AGENTS.md) for repository standards, code quality gates, and branching rules.\n\nThis project follows the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). The accessibility commitment, supported environments, known limitations, and the process for reporting a barrier are described in [ACCESSIBILITY.md](ACCESSIBILITY.md). Where to ask a question or report a problem is described in [SUPPORT.md](SUPPORT.md).\n\nRetrieval performance is guarded by benchmarks over a synthetic 200-scar corpus. Run them before and after touching `Recall`, `LoadScar`, freshness, or the process cache, and report the before/after numbers with the change:\n\n```bash\ngo test -run '^$' -bench 'BenchmarkRecall|BenchmarkInjectGuardrails|BenchmarkScoreScarItem' -benchmem ./pkg/scar/\n```\n\n---\n\n## License\n\nApache License 2.0. See [LICENSE](LICENSE) for details.\n"}