Skip to content
Conduit

mcp server

scars

Git-native regression guardrails and failure memory for AI coding agents and developers. Deterministic recall, token-budgeted prompt injection, and Model Context Protocol (MCP).

Pavanspoojary/scarscommunitylistedunreviewed

Set up

Runs on your computer. Pick your agent and operating system.

This project does not publish an install method we can turn into a config. Follow the README instead.

README

synced Oct 21, 2026

GitScars (git-scars)

Go Reference License Go Report Card CI

A Git-native failure memory and regression guardrail system for software engineers and AI coding assistants.

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

When developers edit code or coding agents (Claude Code, Cursor, Antigravity, Windsurf) tackle tasks, GitScars deterministically retrieves only the relevant failure memories before mistakes repeat.


Table of Contents


The Problem

Repository knowledge frequently disappears into old commits, closed pull requests, Slack threads, and transient agent conversation transcripts. As repositories expand:

  • 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.
  • Vector Memory & RAG introduce semantic hallucinations, noisy false-positive retrieval (see VibeMemBench arXiv:2609.23570), and vulnerability to indirect prompt injection (MemSecBench arXiv:2607.27080).
  • 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.

Architecture & Comparison

CapabilityMonolithic (AGENTS.md)Glob-Scoped (.cursor/rules)Vector Memory (RAG)GitScars (git-scars)
Prompt StrategyUnconditional full dumpDirectory glob pattern matchSemantic similarity searchSelective multi-signal anchor match
Average Prompt Tokens871 tokens (all rules)187 tokens avg (directory rules)Dynamic retrieval133 tokens avg (-28.9% vs Scoped)
Drift DetectionNone (silent obsolescence)None (silent failure on move)None (unanchored)Deterministic SHA-256 & AST symbol hashing
Verification GateUnverified text assertionsUnverified text assertionsNoneScrubbed fail-to-pass test execution
Human GovernanceAd-hoc editsAd-hoc editsNonePromotion gate (git-scars promote)
Host Security BoundaryStatic textStatic textCloud API / embeddingsHost argv execution (cleanEnv()) + trust-hash
Runtime DependenciesOffline textOffline textRemote embeddings / DBZero dependencies (pure Go single binary)

For scenario-by-scenario modeled token measurements and architectural case walkthroughs, see SCENARIO_ANALYSIS.md.


Why Not Just Scoped Rules (.cursor/rules / CLAUDE.md)?

Glob-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?

In our scenario walkthrough across 10 production regression patterns (SCENARIO_ANALYSIS.md), scoped rules fail in three critical production scenarios:

1. The Refactored Anchor (Silent Failure)

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

2. The Toxic Unverified Claim

  • 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.
  • GitScars Defense: Scars cannot transition to active without a runnable fail-to-pass verifier. Claims must be proven against code before entering prompt memory.

3. Prompt Inflation & Rule Contradiction

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

How It Works

flowchart TD
    A["Production Bug / Incident"] --> B["Capture Draft (git-scars add / from-commit)"]
    B --> C["Execute Scrubbed Verifier (git-scars verify)"]
    C --> D{"Fail-to-Pass Verified?"}
    D -- Yes --> E["Human Code Review in PR (git-scars promote)"]
    D -- No / Exception --> E
    E --> F["Active Scar (.gitscars/scars/)"]
    
    F --> G["Coding Task / Agent Session"]
    G --> H["Selective Retrieval (git-scars recall / MCP)"]
    H --> I["Code Drift Detected (git-scars check / hook)"]
    I --> J["Inspect Diff (git-scars diff)"]
    J --> K["Explicit Reaffirmation (git-scars reaffirm)"]
    K --> F

Installation & Build

Requires Go 1.22+:

# Clone the repository
git clone https://github.com/Pavanspoojary/scars.git
cd scars

# Build the single standalone static binary
go build -o git-scars ./cmd/git-scars

Optionally install git-scars into your system $PATH:

sudo mv git-scars /usr/local/bin/

Once installed, Git automatically discovers it: you can run either git-scars <command> or git scars <command>.


Quickstart Workflow

1. Initialize GitScars

git-scars init

Creates .gitscars/scars/ for versioned lessons and .gitscars/.local/ (automatically gitignored) for derived local state (indexes, trusted verifier hashes, feedback).

2. Capture a Failure Lesson

Create a new draft using the interactive terminal wizard:

git-scars add -i

Or pass flags directly:

git-scars add \
  --title "Nil pointer dereference in auth context" \
  --lesson "Always use comma-ok idiom when reading user profile from request context" \
  --files "pkg/auth/context.go"

Or capture automatically from an existing fix commit without requiring an LLM:

git-scars add from-commit 8a1b3f9

Prefills changed files, parent base commit, fix commit, and inferred test commands into a new draft.

3. Record Verification Evidence

Execute the verifier safely against the codebase:

git-scars verify nil-pointer-dereference-8a1b3f --interactive

Computes deterministic command hashes, scrubs the environment, redacts secrets, and tests the worktree.

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

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

4. Review and Promote

Human review is required before a Scar can become active:

git-scars promote nil-pointer-dereference-8a1b3f \
  --status active \
  --reviewer "alice" \
  --rationale "Reviewed test reproduction in PR #42"

5. Selective Retrieval

Retrieve relevant lessons during coding tasks:

# By target file
git-scars recall --files pkg/auth/context.go

# Diff-aware retrieval (against a branch or commit)
git-scars recall --diff origin/main

# Failure-aware retrieval from failing test stderr
go test ./... 2>&1 | git-scars recall --stdin

# Machine-readable JSON output for coding agents
git-scars recall --files pkg/auth/context.go --json

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

6. Token-Budgeted Agent Prompt Injection

Generate an ultra-dense, token-budget-capped guardrail block for AI coding agents before file editing:

# Generate compact XML block capped to 300 estimated tokens
git-scars inject --files "pkg/auth/context.go" --budget 300

# Generate Markdown guardrails for prompt templates
git-scars inject --files "pkg/auth/context.go" --budget 200 --format markdown

7. Autonomous Instruction File Sync

Automatically synchronize active failure memories into AI agent instruction files (AGENTS.md, CLAUDE.md, .cursorrules, .windsurfrules):

# Auto-discover and update existing agent instruction files
git-scars sync

# Or explicitly target specific instruction files
git-scars sync --targets AGENTS.md,CLAUDE.md

Manages a deterministic markdown table between <!-- GIT-SCARS:START --> and <!-- GIT-SCARS:END --> markers, preserving all external prompt rules.

8. Instant Failure & Test Triage

Diagnose raw compiler errors, panic stack traces, or test failures directly against recorded regression wisdom across multiple languages:

  • Go: panic:, fatal error: all goroutines asleep - deadlock, --- FAIL:, race detector warnings, and runtime file/line locations.
  • Python: Traceback (most recent call last), File "...", line N, in func, AssertionError.
  • JavaScript & TypeScript: V8 stack traces at func (file:line:col), Error:, TypeError.
  • Rust: thread '...' panicked at '...', source locations src/file.rs:N.
  • Generic / Runners: Memory faults (Segmentation fault), test framework failures, and race reports.
# Pipe failing test output directly to triage
go test ./... 2>&1 | git-scars triage

# Or diagnose a specific error signature
git-scars triage --error "fatal error: all goroutines are asleep - deadlock"

# Machine-readable JSON for agent automated healing loops
git-scars triage --error "panic: nil pointer" --json

9. Read-Only Freshness Check in CI

Add to your CI workflow to ensure no active Scars have stale anchors:

git-scars check

Stable Exit Codes:

  • 0: All Scars valid and current.
  • 1: Invalid format or invariant violation. Records that fail to parse or that break a lifecycle invariant are reported, never skipped.
  • 2: Stale anchor detected (code modified since baseline, requires reaffirmation).
  • 3: Operational error.

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

10. Git Pre-Commit Hook Guardrail

Install the Git pre-commit hook to catch stale active scars before staging and committing:

# Install hook into .git/hooks/pre-commit
git-scars hook install

# Inspect hook status (warns when git-scars is not on PATH)
git-scars hook status

# Uninstall hook
git-scars hook uninstall

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

11. Inspect Drift & Reaffirm

When git-scars check or pre-commit hooks report modified anchors, inspect the exact unified diff before reaffirming:

# View unified line diff against recorded anchor baseline
git-scars diff map-write-crash-391945

# Reaffirm anchor baseline after human review
git-scars reaffirm map-write-crash-391945 \
  --reviewer "alice" \
  --rationale "Verified logic holds after refactoring exporter package"

12. Repository Health & Metrics

Inspect overall repository scar metrics, monitored anchors, and recorded feedback:

# Human-readable summary
git-scars stats

# Machine-readable JSON metrics
git-scars stats --json

13. Run Full Diagnostics & Automated Repair

Audit 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):

# Interactive diagnostic checklist
git-scars doctor

# Machine-readable JSON report for CI pipelines
git-scars doctor --json

# Automatically repair recoverable cache, local directory, and hook configurations
git-scars doctor --fix

14. Lifecycle Contradiction & Supersession

Manage evolution of failure memories as codebase architectures and best practices evolve:

# Contradict an outdated scar with documented rationale and conflict reference
git-scars contradict scar-001 --by scar-005 --rationale "Worker pool refactored to context cancellation"

# Supersede an obsolete scar by a successor scar
git-scars supersede scar-001 --by scar-005

15. Near-Duplicate Scar Detection

Inspect active repository scars for semantic and lexical duplication using token-level Jaccard similarity:

# Dry-run near-duplicate audit (default threshold: 0.85)
git-scars dedupe --dry-run

# Custom similarity threshold and machine-readable JSON
git-scars dedupe --min 0.75 --json

16. Automated Historical Regression Mining (git-scars harvest)

Bootstrap 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:

  • Diff-Size Cap (--max-files 5): Automatically ignores commits touching > 5 files to avoid noisy reformatting, mass migrations, and large multi-package refactors.
  • Co-Located Test Requirement: Skips commits without co-located test updates by default to guarantee verified test behavior (override with --allow-untested).
  • 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.

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

# Preview high-confidence candidate bug fixes in recent commit history (dry run)
git-scars harvest --max 50 --dry-run

# Automatically generate quality-filtered draft scars for review and promotion
git-scars harvest --max 100 --min-confidence 7

# Inspect findings as structured JSON
git-scars harvest --json

17. Portable Memory Bundles (git-scars bundle)

Share, export, and import curated sets of verified failure memories across teams and services without sharing entire Git histories:

# Export active scars into a portable verified JSON memory bundle
git-scars bundle export --out ./shared-scars.json

# Export with severity filtering
git-scars bundle export --severity critical --out ./critical-scars.json

# Import memory bundle into repository as reviewable drafts (with optional ID prefix)
git-scars bundle import ./shared-scars.json --prefix org-

Note: All imported scars are ingested as unreviewed drafts (status: unreviewed) to guarantee local verifier execution and team code review before activation.

18. Self-Healing Execution Loop (git-scars heal)

Run test suites or build commands under automated surveillance. When failures occur, heal intercepts output, matches relevant regression scars, and generates structured remediation guidance:

# Run tests under self-healing observation
git-scars heal -- go test -race ./...

# Machine-readable output for autonomous agent loops
git-scars heal --json -- npm test

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

19. CI/CD & GitHub Code Scanning SARIF (git-scars check --format sarif)

Integrate GitScars directly into pull request checks and security dashboards using the OASIS SARIF 2.1.0 standard:

# Scaffold production-ready GitHub Actions workflow (.github/workflows/git-scars.yml)
git-scars init --ci github

# Emit SARIF report for GitHub Code Scanning annotations
git-scars check --format sarif > git-scars.sarif

# Pre-edit enforcement blocking check in SARIF format
git-scars enforce --files "pkg/auth.go" --format sarif

Both 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:

git-scars enforce --files "$(git diff --name-only origin/main...HEAD)" --fail-on high --format sarif

20. Multi-Language AST-Aware Freshness (Go, Python, TypeScript)

GitScars includes built-in syntactic symbol hashing across multiple languages to eliminate reaffirm fatigue:

  • Go: Full AST symbol declaration extraction via go/parser and go/ast.
  • Python: Function (def, async def) and class (class) definition hashing.
  • TypeScript & JavaScript: Functions, classes, interfaces, types, and exported symbols.

When anchor source files are modified:

  • 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.
  • If anchored symbol declarations are altered or removed, freshness transitions to changed (stale), signaling the need for review and reaffirmation.

File Format & Schema

Each Scar is stored as a single, human-readable, Git-diffable Markdown file in .gitscars/scars/<slug>-<shortid>.md with strict YAML frontmatter:

---
schema_version: "1"
id: "map-write-crash-391945"
slug: "concurrent-map-write-in-telemetry-exporter"
title: "Concurrent map write in telemetry exporter"
lesson: "Metrics map must be protected by sync.RWMutex during RecordMetric calls."
severity: "high"
fix_hint: "Wrap map mutations in mu.Lock() or replace with sync.Map"
bad_pattern: "m[key] = val"
good_pattern: "mu.Lock(); m[key] = val; mu.Unlock()"
applicability: "Telemetry exporters handling concurrent metrics emissions."
anchors:
  files:
    - "pkg/telemetry/exporter.go"
  symbols:
    - "RecordMetric"
  commands:
    - "go test -race ./pkg/telemetry/..."
  error_signatures:
    - "fatal error: concurrent map writes"
verifier:
  result: "fail_to_pass"
  argv:
    - "go"
    - "test"
    - "-race"
    - "./pkg/telemetry/..."
  command_hash: "2d4b1ee683d6be106b1633c27fedb692d3f757a5aa049397e28ef1cbd6d52736"
baseline:
  recorded_at: "2026-10-11T08:00:00Z"
  pkg/telemetry/exporter.go: "a3b98f12c4..."
review:
  status: "approved"
  reviewer: "bob"
  date: "2026-10-11T08:05:00Z"
  rationale: "Reproduced with race detector in PR #104"
lifecycle:
  state: "active"
---

### Symptom & Root Cause
Under heavy concurrent load, multiple goroutines called RecordMetric simultaneously without synchronization.

### Footgun / Guardrail
Replaced raw map with sync.Map or guarded reads and writes with sync.RWMutex.

Anchor Semantics

A 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:

RuleSeverityMeaning
anchor_symbol_missingERRORThe anchored symbol no longer exists in any anchored file.
bad_pattern_presentERRORThe recorded footgun is still present in the anchored code.
good_pattern_absentWARNINGThe recorded fix cannot be found, so the anchor likely no longer covers the fixed code.
missing_severityWARNINGAn active guardrail does not declare a severity, so it cannot be compared against a blocking threshold.

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

bad_pattern and good_pattern must be literal snippets of code, so that presence and absence can be checked deterministically:

  • good_pattern is a snippet of the fixed code and must be present in an anchored file.
  • bad_pattern is a snippet of the footgun and must be absent from every anchored file.

A pseudo-code pattern such as m[key] = val cannot be verified and will always be reported as absent.


Repository Configuration

.gitscars/config.yaml holds the repository-scoped retrieval limits and is created by git-scars init:

# GitScars Configuration
schema_version: "1"
abstain_threshold: 3
top_k: 3
KeyMeaning
abstain_thresholdMinimum score a candidate must reach to be retrieved. Below it, GitScars abstains.
top_kMaximum number of scars returned by a single recall.

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.

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.

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


AI Agent Integration & MCP Server

1. Model Context Protocol (MCP) Server

GitScars provides a built-in stdio Model Context Protocol (MCP) server for native integration with coding assistants:

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

git-scars mcp

The MCP server exposes rich two-way tools and resources for AI coding agents:

Standard Tools:

  • list_scars: List all repository scars with their lifecycle and dynamic freshness status.
  • get_scar: Retrieve full frontmatter, anchors, severity, verifier results, and markdown body by scar ID.
  • recall_scars: Deterministically retrieve matching scars for target files, symbols, error messages, commands, and task descriptions. Its limits defer to the repository configuration.
  • inject_guardrails: Generate an ultra-compact, token-budget-capped prompt guardrail block for specific files, symbols, and task terms.
  • triage_error: Diagnose raw compiler errors, panic stack traces, or test outputs against recorded scars, optionally narrowed to known files.
  • draft_scar: Autonomously record a new failure memory draft into repository Git memory, including symbol anchors and a calibrated severity.

Composite Tools (Single-Roundtrip Workflow):

  • 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.
  • 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.
  • post_failure_learn: Multi-language failure triage and diagnostic learning in a single roundtrip, returning prevention lessons for test errors or stack traces.

Resources:

  • scar://<id>: Read individual scar frontmatter and prevention lessons directly as MCP resources.
  • scars://active: Read the auto-generated markdown summary table of active repository guardrails.

Client Configuration

Claude Desktop (claude_desktop_config.json) / Cursor (.cursor/mcp.json) / Antigravity
{
  "mcpServers": {
    "git-scars": {
      "command": "git-scars",
      "args": ["mcp"]
    }
  }
}
Zed (settings.json)
{
  "context_servers": [
    {
      "id": "git-scars",
      "command": {
        "path": "git-scars",
        "args": ["mcp"]
      }
    }
  ]
}

2. CLI JSON Recall (reposcars.recall.v1)

Agents can also invoke the CLI directly:

git scars recall --files "$MODIFIED_FILES" --json

Output:

{
  "schema_version": "reposcars.recall.v1",
  "timestamp": "2026-10-11T08:00:00Z",
  "query": { "files": ["pkg/telemetry/exporter.go"], "threshold": 3, "top_k": 3 },
  "count": 1,
  "results": [
    {
      "id": "map-write-crash-391945",
      "title": "Concurrent map write in telemetry exporter",
      "lesson": "Metrics map must be protected by sync.RWMutex during RecordMetric calls.",
      "score": 5,
      "confidence": 0.26,
      "freshness": "current",
      "matches": ["file(+5)"],
      "explanation": "file(+5)",
      "anchors": { "files": ["pkg/telemetry/exporter.go"] }
    }
  ]
}

3. Pre-Edit Guardrail Enforcement (git-scars enforce)

Prevent AI coding agents and developers from re-introducing known regressions before files are modified:

# Check files before editing; returns exit code 2 if a high-severity guardrail matches
git-scars enforce --files "pkg/worker.go" --fail-on high

Exit Codes:

  • 0: Clean (no blocking guardrails detected).
  • 2: Blocked (blocking guardrail detected; outputs actionable <dont>, <do>, and verification instructions to stderr).

A guardrail that does not declare a severity is treated as high, so an uncalibrated guardrail is never silently downgraded below the blocking threshold.

Machine JSON Output:

git-scars enforce --files "pkg/worker.go" --json

4. Zero-Friction Agent Onboarding (git-scars init --agent)

Configure coding assistants with a single setup command:

git-scars init --agent claude,cursor,zed,antigravity

Automatically scaffolds .claude/mcp.json, .cursor/rules/git-scars.mdc, .zed/settings.json, and .gemini/config/rules/git-scars.md.


Dependency Manifest & Lockfile Anchors

GitScars automatically inspects repository dependency manifests and lockfiles to anchor lessons to exact package versions without manual configuration:

  • Go: Direct module dependencies and versions from go.mod.
  • Node.js: Package dependencies and versions from package-lock.json (v1, v2, and v3).
  • Rust: Package versions from Cargo.lock.
  • Python: Dependencies and versions from poetry.lock and requirements.txt.

When dependencies are upgraded or downgraded, Scars anchored to vulnerable or breaking versions automatically trigger match signals during recall.

Dependency anchors are authored with the name@version form:

git-scars add \
  --title "Redis pipeline breaks on client upgrade" \
  --lesson "Upgrade the redis client only after reviewing the pipeline change" \
  --files "pkg/cache/redis.go" \
  --deps "github.com/redis/go-redis/v9@9.5.1"

They are persisted in the scar frontmatter and re-read on every subsequent load, so the anchor survives verification, reaffirmation, and synchronization cycles:

anchors:
  dependencies:
    - name: "github.com/redis/go-redis/v9"
      version: "9.5.1"

CLI Command Reference

CommandArgumentsDescription
init[--agent <targets>, --ci <target>]Initialize .gitscars/ repository, agent configs, and CI workflows (--ci github)
add[-i], [--title, --lesson, --files, --deps]Create a new scar draft (interactive wizard or flags)
add from-commit<sha>Automatically prefill a draft from a Git commit diff
listnoneList recorded scars with lifecycle, review, and freshness
show<id>Display full metadata, anchors, and body of a scar
diff<id>Inspect unified line diff of anchor files against baseline
promote<id> --status activePromote a scar to active state (enforces review & verifier invariants)
verify<id> [--interactive]Safely execute verifier in scrubbed env and record evidence (exit 1 when verification does not pass)
reaffirm<id> --reviewer --rationaleReaffirm a scar after anchor code drift
contradict<id> --by <new-id> --rationaleTransition scar to contradicted state with conflict reference
supersede<id> --by <new-id>Supersede an obsolete scar by a successor scar
retire<id>Retire a scar that is no longer applicable
recall--files, --diff, --stdin, --json, --threshold, --top-kRetrieve relevant scars with deterministic multi-signal scoring
enforce--files, [--fail-on, --format, --staged, --json]Pre-edit blocking guardrail check (--format sarif, exit 0 clean, exit 2 blocked)
inject[--files, --task, --budget, --format]Generate token-budgeted prompt guardrails with <dont> and <do> patterns
sync[--targets <files>]Synchronize active scars into AGENTS.md / CLAUDE.md
triage[--error <text>, --json]Diagnose test failures and panic traces against recorded scars
dedupe[--min <sim>, --dry-run, --json]Detect duplicate and near-duplicate scars (token Jaccard similarity)
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
bundleexport [options], import <file> [options]Export and import portable, verified memory bundles (gitscars.bundle.v1)
heal[--json] -- <command...>Run test command, intercept failures, and automatically triage regressions (exit 4 when the observed command failed)
check[--diff <ref>, --format sarif]Read-only verification of scar freshness and invariants (--format sarif)
lintnoneSecurity, schema, and anchor-semantics audit (checks traversal, injections, unloadable files, anchor drift, noisy scars)
doctor[--json, --fix]Run repository diagnostics and automatically repair caches/hooks
stats[--json]Display repository metrics, monitored anchors, and feedback stats
eval-agents--report <file>Analyse a recorded multi-agent corpus under the preregistered non-inferiority protocol (EVAL_PLAN 5.2)
eval-authoring--log <file>Summarise a human authoring log against the five minute median target (EVAL_PLAN 5.1)
indexnoneRebuild .gitscars/.local/index.json fast cache
hookinstall, status, uninstallManage Git pre-commit hook guardrail
mcpnoneRun stdio Model Context Protocol (MCP) server
feedback<id> --rating --notesRecord retrieval utility feedback (helpful, irrelevant, incorrect)
versionnonePrint git-scars version

Security, Threat Model & Privacy

Scrubbed Environment, Not Container Isolation

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.

Threat Model & Trust Boundaries

  1. Never Auto-Run Untrusted Verifiers: Verifiers from external pull requests or untrusted memory bundles must be reviewed before execution.
  2. Deterministic Command Trust-Hash: Verification commands are hashed (sha256) and recorded in verifier.command_hash. Invariant checks reject verifiers whose hashes do not match.
  3. 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.
  4. Secret Redaction: Automated regex scrubbing redacts Bearer tokens, private keys, API keys, and passwords before recording execution outputs.
  5. Zero Cloud Telemetry: All feedback, index caches, and command trust lists are stored locally in gitignored .gitscars/.local/. No data leaves your machine.

Documentation & ADRs

  • SCENARIO_ANALYSIS.md: Design estimates and illustrative scenario walkthrough across 10 regression patterns comparing prompt token footprints and architectural failure modes.
  • EVAL_PLAN.md: Preregistered benchmark evaluation plan, scoring baseline weights, and power calculations.
  • PRIOR_ART.md: Primary-source comparative analysis (Daily-Nerd/Scar, fscars, gitmem, arXiv:2609.23570).
  • DECISIONS.md: Architecture Decision Records (ADR-0001 through ADR-0014).

Contributing

Contributions are welcome! Please read CONTRIBUTING.md and AGENTS.md for repository standards, code quality gates, and branching rules.

This project follows the Contributor Covenant Code of Conduct. The accessibility commitment, supported environments, known limitations, and the process for reporting a barrier are described in ACCESSIBILITY.md. Where to ask a question or report a problem is described in SUPPORT.md.

Retrieval 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:

go test -run '^$' -bench 'BenchmarkRecall|BenchmarkInjectGuardrails|BenchmarkScoreScarItem' -benchmem ./pkg/scar/

License

Apache License 2.0. See LICENSE for details.

↑↓ navigate openesc close