{"name":"derive-codebase-context","title":"Derive codebase context","description":"Write agent context for a repository from the repo itself: a CLAUDE.md / AGENTS.md that matches reality, the boundaries agents must not cross, and a map of where things live. Symptoms: write or fix our CLAUDE.md, the agent guidance is stale, the context files have multiplied (CLAUDE.md + AGENTS.md + Cursor rules), agents keep rediscovering the same layout, someone proposes a code knowledge graph / vector index / semantic search over the codebase.","compatibility":"Any repository an agent works in. The generators need Node 22+ (builtins only) and git. Layer 2 assumes a JavaScript/TypeScript import graph through dependency-cruiser; other ecosystems need their own edge linter, and the rest of the procedure is unchanged. The measurements behind this came from a TypeScript monorepo of roughly 2,500 files. No database server, no daemon, and no network at any layer.","allowedTools":"Read Write Edit Grep Glob Bash","license":"MIT","kind":"signals","useWhen":"the repository has no agent context file, or several that disagree","group":"workflow","lifecycle":"release","version":"1.0.0","author":"crissmoldovan","install":["npx skills add crissmoldovan/agent-skills --skill derive-codebase-context"],"asks":["Set up derived codebase context in this repo. Detect what already exists first\nand tell me which of the three layers are present before you write anything.","We have CLAUDE.md, AGENTS.md and Cursor rules that disagree. Do layer 1: show me\nthe drift between them as a diff first, then generate all three from one core\nand gate it in CI.","Turn the four architecture rules in our README into dependency-cruiser forbidden\nedges. Measure the current violation count with the tool before writing each\nrule, and mutation-test every one of them before you tell me it works."],"commands":[],"documents":[{"path":"references/gate-hardening.md","slug":"gate-hardening","title":"Gate hardening","body":"# Gate hardening\n\nEverything in this procedure is worthless if the gates do not gate. In the work\nthis skill came from, **four separate guards were born unarmed**: they passed\nevery run while verifying nothing, and nothing about a green run distinguished\nthem from the guards that worked.\n\nThis is how to tell the difference, and the four mechanisms that produced them.\n\n## The mutation test\n\nFor every gate, before you trust it, before you report it as done:\n\n1. **Back the file up with `cp`.**\n\n   ```bash\n   cp path/to/file path/to/file.bak\n   ```\n\n   Not with git. `git checkout -- <file>` **silently does nothing for an\n   untracked file**, so on a file you just created it neither restores nor\n   errors. Run it after a mutation on new work and you have thrown away the fix\n   and been told nothing.\n\n2. **Introduce exactly the thing the gate forbids.** Not something adjacent. If\n   the rule forbids an import of a package, add that import, in a file the rule's\n   scope covers.\n\n3. **Run the gate. Watch it fail.** Read the message. It must name the thing you\n   introduced. A failure whose message names something else is a different gate\n   firing, and yours is still unproven.\n\n4. **Restore from the backup**, and delete the backup.\n\n   ```bash\n   cp path/to/file.bak path/to/file && rm path/to/file.bak\n   ```\n\n5. **Run it again. Watch it pass.** A gate that stays red after restore was\n   measuring the wrong file, or the mutation was not fully reverted.\n\nA guard you cannot make fail is checking something other than what you think.\nTreat a new guard as broken until step 3 has happened.\n\n## The four unarmed guards\n\n### 1. The exclusion that deleted the edges the rule matched\n\nA dependency-cruiser config carried `exclude: node_modules`. Two rules existed to\nforbid direct imports of specific npm packages. But `exclude` removes those\nmodules from the graph **entirely**, so the edges the rules matched were not\nabsent from the code, they were absent from the graph. Both rules reported\nsuccess on every run while checking nothing.\n\nUse `doNotFollow` for npm packages instead. It keeps the edge and stops the\ntraversal, which is the actual intent: you want to know that the import exists,\nnot what the package imports next.\n\n### 2. The path prefix that is not guaranteed\n\nThe same two rules anchored their patterns on a leading `node_modules/`. The\nresolver runs through a TypeScript configuration, and a package whose `exports`\nmap that configuration cannot follow arrives with `couldNotResolve: true` and its\n`resolved` path set to the **bare specifier**. No `node_modules/` prefix ever\nappears, so the pattern never matches.\n\nAnchor npm patterns to accept both:\n\n```text\n(^|node_modules/)package-name\n```\n\nThe general lesson is larger than one tool: a rule that matches on a resolved\npath is making an assumption about resolution succeeding. Check what the tool\nactually emits for the case you care about, on this repository, before writing\nthe pattern.\n\n### 3. The branch that could not be reached\n\nA generator tracked whether it was inside a block comment so it could skip\ncommented-out declarations. The condition that entered the tracking branch could\nnever be true given how the lines were split upstream. The guard existed, was\ncovered by a test, and was dead.\n\nReachability is exactly what a mutation test checks. Adding a commented-out\ndeclaration to the input and watching the count not move is the two-minute\nversion of this discovery, and it happened only because somebody ran it.\n\n### 4. The guard masked by a filter after it\n\nAn atlas generator decided a route's method twice: once where the guard checked\nit, and again in a filter further down the pipeline. Anything the guard would\nhave rejected was removed by the later filter first, so the guard never fired on\nreal input.\n\nWhen a guard sits in a pipeline, mutate the input and confirm the failure comes\nfrom **your** guard, by its message. A pipeline that rejects bad input somewhere\nis not the same as a guard that works.\n\n## CI traps that make a green check meaningless\n\n### Shallow clones\n\n`actions/checkout` gives a depth-1 clone by default. Two consequences that both\npass locally and fail on every CI run:\n\n- `git log -1 -- <path>` returns the tip commit for **every** path, because\n  there is only one commit. Per-path provenance is uniform and meaningless.\n- `git rev-parse --short` abbreviates to 7 characters rather than 8, because the\n  abbreviation length scales with the object count.\n\nSo never build a provenance scheme that compares a per-path SHA. Stamp HEAD,\nrewrite a file only when its derived facts change, and compare bodies with the\nprovenance line blanked.\n\nIf you genuinely need history in CI, ask for it (`fetch-depth: 0`) and say in the\nworkflow why, because it is a real cost on a large repository.\n\n### Formatters\n\nA markdown formatter that realigns tables will rewrite generated files, and the\ngenerated-file gate then fails for a reason unrelated to its content. In the\noriginal work this was already breaking the context check before the atlas\nexisted, because the repository had no formatter ignore file at all.\n\nAdd the ignore entry in the same commit as the generator, covering every\ngenerated path.\n\n### A new test directory that contributes zero tests\n\nA test runner with a workspace or projects configuration only collects from the\ndirectories that configuration names. A new test directory outside it contributes\nzero tests, the suite stays green, and the summary count moves by nothing.\n\nAfter adding tests in a new location, check that the reported test count went up\nby the number you wrote.\n\n### Stale dependencies\n\nA declared, lockfile-present package that is not actually installed will fail a\nlarge fraction of a suite for a reason that looks like a code defect. Install\nbefore believing any suite result, especially after a big merge.\n\n## Ratcheting\n\nWhen a rule cannot start at zero:\n\n- Write the current count into the rule's comment, with the date.\n- Set severity to warn, not error, and say in the comment what turns it into an\n  error.\n- Never widen the rule to make a build green. Either fix the violation or record\n  an explicit exception with a written reason that survives review.\n\nA rule whose baseline drifts upward while nobody notices is a worse outcome than\nno rule, because it is a rule everybody believes in.\n","bodyHtml":"<h2 id=\"gate-hardening\">Gate hardening</h2>\n<p>Everything in this procedure is worthless if the gates do not gate. In the work\nthis skill came from, <strong>four separate guards were born unarmed</strong>: they passed\nevery run while verifying nothing, and nothing about a green run distinguished\nthem from the guards that worked.</p>\n<p>This is how to tell the difference, and the four mechanisms that produced them.</p>\n<h3 id=\"the-mutation-test\">The mutation test</h3>\n<p>For every gate, before you trust it, before you report it as done:</p>\n<ol>\n<li><p><strong>Back the file up with <code>cp</code>.</strong></p>\n<pre><code class=\"language-bash\">cp path/to/file path/to/file.bak\n</code></pre>\n<p>Not with git. <code>git checkout -- &lt;file&gt;</code> <strong>silently does nothing for an\nuntracked file</strong>, so on a file you just created it neither restores nor\nerrors. Run it after a mutation on new work and you have thrown away the fix\nand been told nothing.</p>\n</li>\n<li><p><strong>Introduce exactly the thing the gate forbids.</strong> Not something adjacent. If\nthe rule forbids an import of a package, add that import, in a file the rule&#39;s\nscope covers.</p>\n</li>\n<li><p><strong>Run the gate. Watch it fail.</strong> Read the message. It must name the thing you\nintroduced. A failure whose message names something else is a different gate\nfiring, and yours is still unproven.</p>\n</li>\n<li><p><strong>Restore from the backup</strong>, and delete the backup.</p>\n<pre><code class=\"language-bash\">cp path/to/file.bak path/to/file &amp;&amp; rm path/to/file.bak\n</code></pre>\n</li>\n<li><p><strong>Run it again. Watch it pass.</strong> A gate that stays red after restore was\nmeasuring the wrong file, or the mutation was not fully reverted.</p>\n</li>\n</ol>\n<p>A guard you cannot make fail is checking something other than what you think.\nTreat a new guard as broken until step 3 has happened.</p>\n<h3 id=\"the-four-unarmed-guards\">The four unarmed guards</h3>\n<h4 id=\"1-the-exclusion-that-deleted-the-edges-the-rule-matched\">1. The exclusion that deleted the edges the rule matched</h4>\n<p>A dependency-cruiser config carried <code>exclude: node_modules</code>. Two rules existed to\nforbid direct imports of specific npm packages. But <code>exclude</code> removes those\nmodules from the graph <strong>entirely</strong>, so the edges the rules matched were not\nabsent from the code, they were absent from the graph. Both rules reported\nsuccess on every run while checking nothing.</p>\n<p>Use <code>doNotFollow</code> for npm packages instead. It keeps the edge and stops the\ntraversal, which is the actual intent: you want to know that the import exists,\nnot what the package imports next.</p>\n<h4 id=\"2-the-path-prefix-that-is-not-guaranteed\">2. The path prefix that is not guaranteed</h4>\n<p>The same two rules anchored their patterns on a leading <code>node_modules/</code>. The\nresolver runs through a TypeScript configuration, and a package whose <code>exports</code>\nmap that configuration cannot follow arrives with <code>couldNotResolve: true</code> and its\n<code>resolved</code> path set to the <strong>bare specifier</strong>. No <code>node_modules/</code> prefix ever\nappears, so the pattern never matches.</p>\n<p>Anchor npm patterns to accept both:</p>\n<pre><code class=\"language-text\">(^|node_modules/)package-name\n</code></pre>\n<p>The general lesson is larger than one tool: a rule that matches on a resolved\npath is making an assumption about resolution succeeding. Check what the tool\nactually emits for the case you care about, on this repository, before writing\nthe pattern.</p>\n<h4 id=\"3-the-branch-that-could-not-be-reached\">3. The branch that could not be reached</h4>\n<p>A generator tracked whether it was inside a block comment so it could skip\ncommented-out declarations. The condition that entered the tracking branch could\nnever be true given how the lines were split upstream. The guard existed, was\ncovered by a test, and was dead.</p>\n<p>Reachability is exactly what a mutation test checks. Adding a commented-out\ndeclaration to the input and watching the count not move is the two-minute\nversion of this discovery, and it happened only because somebody ran it.</p>\n<h4 id=\"4-the-guard-masked-by-a-filter-after-it\">4. The guard masked by a filter after it</h4>\n<p>An atlas generator decided a route&#39;s method twice: once where the guard checked\nit, and again in a filter further down the pipeline. Anything the guard would\nhave rejected was removed by the later filter first, so the guard never fired on\nreal input.</p>\n<p>When a guard sits in a pipeline, mutate the input and confirm the failure comes\nfrom <strong>your</strong> guard, by its message. A pipeline that rejects bad input somewhere\nis not the same as a guard that works.</p>\n<h3 id=\"ci-traps-that-make-a-green-check-meaningless\">CI traps that make a green check meaningless</h3>\n<h4 id=\"shallow-clones\">Shallow clones</h4>\n<p><code>actions/checkout</code> gives a depth-1 clone by default. Two consequences that both\npass locally and fail on every CI run:</p>\n<ul>\n<li><code>git log -1 -- &lt;path&gt;</code> returns the tip commit for <strong>every</strong> path, because\nthere is only one commit. Per-path provenance is uniform and meaningless.</li>\n<li><code>git rev-parse --short</code> abbreviates to 7 characters rather than 8, because the\nabbreviation length scales with the object count.</li>\n</ul>\n<p>So never build a provenance scheme that compares a per-path SHA. Stamp HEAD,\nrewrite a file only when its derived facts change, and compare bodies with the\nprovenance line blanked.</p>\n<p>If you genuinely need history in CI, ask for it (<code>fetch-depth: 0</code>) and say in the\nworkflow why, because it is a real cost on a large repository.</p>\n<h4 id=\"formatters\">Formatters</h4>\n<p>A markdown formatter that realigns tables will rewrite generated files, and the\ngenerated-file gate then fails for a reason unrelated to its content. In the\noriginal work this was already breaking the context check before the atlas\nexisted, because the repository had no formatter ignore file at all.</p>\n<p>Add the ignore entry in the same commit as the generator, covering every\ngenerated path.</p>\n<h4 id=\"a-new-test-directory-that-contributes-zero-tests\">A new test directory that contributes zero tests</h4>\n<p>A test runner with a workspace or projects configuration only collects from the\ndirectories that configuration names. A new test directory outside it contributes\nzero tests, the suite stays green, and the summary count moves by nothing.</p>\n<p>After adding tests in a new location, check that the reported test count went up\nby the number you wrote.</p>\n<h4 id=\"stale-dependencies\">Stale dependencies</h4>\n<p>A declared, lockfile-present package that is not actually installed will fail a\nlarge fraction of a suite for a reason that looks like a code defect. Install\nbefore believing any suite result, especially after a big merge.</p>\n<h3 id=\"ratcheting\">Ratcheting</h3>\n<p>When a rule cannot start at zero:</p>\n<ul>\n<li>Write the current count into the rule&#39;s comment, with the date.</li>\n<li>Set severity to warn, not error, and say in the comment what turns it into an\nerror.</li>\n<li>Never widen the rule to make a build green. Either fix the violation or record\nan explicit exception with a written reason that survives review.</li>\n</ul>\n<p>A rule whose baseline drifts upward while nobody notices is a worse outcome than\nno rule, because it is a rule everybody believes in.</p>\n","words":1057},{"path":"references/onboarding.md","slug":"onboarding","title":"Onboarding runbook","body":"# Onboarding runbook\n\nThe per-layer procedure in full. Read the skill body first: it carries the order,\nthe detection step, and the discipline. This carries the mechanics.\n\n## Preconditions\n\n- Git, and a Node 22+ runtime for the generators. The generators use builtins\n  only, so there is nothing to install and nothing to keep up to date.\n- A CI system that can run a command and fail the build on a non-zero exit.\n- Write access to the repository's formatter configuration.\n\n**Stack assumptions, and how to adapt.** Layers 1 and 3 are stack-agnostic: they\nread the tree and write markdown. Layer 2 is the only one with an ecosystem\ndependency, because it needs something that can resolve an import graph. The\nmeasurements behind this procedure came from a TypeScript monorepo, so\ndependency-cruiser is what the examples name. Substitute the equivalent for your\necosystem and nothing else in the procedure changes:\n\n| Ecosystem | Import-edge enforcement |\n|---|---|\n| JavaScript / TypeScript | dependency-cruiser, or an eslint import boundary plugin |\n| Python | import-linter contracts |\n| Go | the language's own package visibility, plus a depguard-style linter |\n| Java / Kotlin | ArchUnit rules |\n| Rust | crate boundaries, plus a workspace dependency lint |\n\nWhat matters is not the tool. It is that a violated rule fails a build, and that\nthe rule was measured before it was written.\n\n## Step 0: detection probes\n\nRun these before writing anything. Adjust the paths to the repository's own\nconventions; the point is the question each one answers, not the exact path.\n\n```bash\n# Which agent context files exist at all?\ngit ls-files | grep -Ei 'CLAUDE\\.md|AGENTS\\.md|GEMINI\\.md|copilot-instructions|clinerules|windsurfrules|\\.cursor/rules/'\n\n# Are any of them generated? A generated file says so in its first lines.\ngit ls-files | grep -Ei 'CLAUDE\\.md|AGENTS\\.md' | xargs -I{} sh -c 'echo \"== {}\"; head -4 \"{}\"'\n\n# Is there a generator, and does it have a --check mode?\ngit grep -lE 'generated.*do not edit|--check' -- '*.mjs' '*.js' '*.ts' | head\n\n# Is there an import-boundary config, and does it carry this repo's own rules?\ngit ls-files | grep -Ei 'dependency-cruiser|importlinter|\\.importlinter|archunit'\n\n# Is there a committed atlas, and is it stamped?\ngit ls-files | grep -Ei 'atlas|agent-context' | head\n\n# Will a format run rewrite the generated files?\ncat .prettierignore 2>/dev/null || echo 'no formatter ignore file'\n```\n\nReport what you found, and which of the three branches you are taking, before\nyou edit a file. The three branches are in the skill body.\n\n## Layer 1: one source for the agent context files\n\n### 1. Measure the drift\n\nDiff every context file against every other one and produce a list of rules that\nexist in one place and not another. Do not resolve contradictions yourself: they\nare decisions, and the list is what you take to whoever owns them.\n\nThis step is the reason the layer is worth doing. Generation without it copies\none file's mistakes into six harnesses at once.\n\n### 2. Author the core\n\nA directory of topic files, one topic per file, plus a manifest saying which\ntopics each harness output composes. Topics, not harnesses: a rule about\nmigrations belongs in the migrations topic whether or not Cursor reads it.\n\nKeep harness-specific material in small per-harness files. If a harness needs a\ntool syntax or a directory convention nobody else understands, that belongs to\nthe harness file, not to the core.\n\n### 3. Write the generator\n\nBuiltins only. It reads the core plus the manifest and writes each output file\nwith a header of exactly this shape:\n\n```text\n<!-- Generated from docs/agent-context/. Do not edit.\n     Regenerate: node tools/agent-context/generate.mjs -->\n```\n\nThe header states three things: that it is generated, where the source is, and\nthe exact command. Somebody who edits the file by hand will read the header\nbefore their change is reverted, and that is the only chance to teach them.\n\n### 4. Add `--check`\n\n`--check` regenerates into memory, compares to what is on disk, and exits\nnon-zero on any difference. It must **name the file that drifted** and print the\nregenerate command. A check that says only \"drift detected\" costs the reader a\nround trip.\n\n### 5. Gate it, and ignore it in the formatter\n\nAdd the `--check` invocation to CI, and in the same commit add every generated\npath to the formatter's ignore file. Not in a follow-up: a markdown formatter\nthat realigns tables will rewrite generated output the first time anybody runs\nit, and the gate then fails for a reason that has nothing to do with the\ncontent.\n\nMutation-test the gate before you believe it. See the gate hardening reference.\n\n## Layer 2: architecture rules as enforced import edges\n\n### 1. Take rules that already exist\n\nRead the repository's own documentation and pull out the rules it already states\nabout what may import what. Every rule you enforce should be quotable back to a\nsentence somebody wrote deliberately.\n\nRules invented inside a lint config are the ones that get switched off in the\nfirst PR that trips them.\n\n### 2. Measure with the enforcing tool\n\nBefore writing a rule, run the tool in reporting mode and count the current\nviolations. Not with grep. A pathspec is not an import graph, and the two\ndisagree in ways that are invisible until the rule ships. See the pitfalls in\nthe skill body for the exact case.\n\nRecord the number. It is the rule's baseline and it belongs in the rule's\ncomment.\n\n### 3. Write the rule\n\n- Count is zero: severity `error`. It cannot regress.\n- Count is not zero: severity `warn`, with the count and the intended direction\n  in the comment, and a plan to ratchet.\n\nNever widen a rule to make a red build green. Either fix the violation or record\nan explicit, reviewed exception with a written reason.\n\n### 4. Mutation test it\n\nEvery rule, individually. This is where two of the rules in the original work\nturned out to be verifying nothing. The procedure and the two configuration\ntraps behind those failures are in the gate hardening reference.\n\n### 5. Run it in CI\n\nAlongside the other checks, with the same exit-code contract.\n\nOptionally add a graph render (`dot`) as a local-only command. It is useful in\nreview and CI must never depend on it.\n\n## Layer 3: the generated operational atlas\n\n### What to derive\n\nThe registries an agent would otherwise reconstruct by grep every session.\nTypical candidates:\n\n- Background jobs, their identifiers, and where each is registered. If the\n  repository has a registry file, the atlas is the place the mismatch between\n  the two becomes visible.\n- Tool or plugin definitions and their executors.\n- HTTP routes, their methods, and their handler files.\n- Schema migrations and their applied-state convention.\n\nThe test for a good atlas page: an agent currently answers this question by\nrunning three greps and getting it slightly wrong.\n\n### How to derive it\n\nParse the tree. Never ask a model to summarise the codebase into the artifact:\nthe whole value is that it is exactly as true as the code, and a summary is not.\n\nEvery row carries the file path of the thing it describes. The atlas is an index\ninto the source, not a replacement for reading it.\n\n### Provenance\n\nStamp each file with the generator, the commit the tree was at, and the\nregenerate command. Then obey two rules that are less obvious than they look:\n\n1. **Rewrite a file only when its derived facts change.** Otherwise every commit\n   rewrites every atlas file and the diffs become noise.\n2. **Compare bodies with the provenance line blanked** in `--check`. Otherwise\n   the stamp itself is a difference and the check fails on every commit.\n\nDo not build a scheme that compares a per-path commit SHA. It cannot work in CI.\nThe reason is in the gate hardening reference, and it is the kind of thing that\npasses every local run.\n\n## Layer 4: defer it\n\nDo not start here, and do not let it block layers 1 to 3.\n\nWhen the earlier layers have run long enough to show what is still missing, and\nthe missing thing is genuinely blast radius across duplicate exported names,\nbuild it: a SCIP indexer for the language, loaded into an embedded SQLite or\nDuckDB file, gitignored and rebuilt on demand. Budget a week.\n\nA language server over MCP is the cheap partial substitute and can be added at\nany point. It answers \"where is this symbol defined and used\" with no committed\nartifact and nothing to keep in sync, which means nothing to keep honest.\n\n## Stopping rules\n\nEach layer is useful alone. Stop wherever it stops paying, and say so:\n\n- If layer 1's drift list turns out to be empty, the repository does not have\n  this problem. Generating anyway adds a build step and buys nothing.\n- If layer 2's candidate rules all have non-zero violation counts nobody intends\n  to fix, you are proposing policy, not enforcement. Take it back to the owner.\n- If nobody can name a question layer 3 would answer, do not build an atlas of\n  whatever is easiest to parse. An unread generated file is still a file that\n  breaks a gate.\n","bodyHtml":"<h2 id=\"onboarding-runbook\">Onboarding runbook</h2>\n<p>The per-layer procedure in full. Read the skill body first: it carries the order,\nthe detection step, and the discipline. This carries the mechanics.</p>\n<h3 id=\"preconditions\">Preconditions</h3>\n<ul>\n<li>Git, and a Node 22+ runtime for the generators. The generators use builtins\nonly, so there is nothing to install and nothing to keep up to date.</li>\n<li>A CI system that can run a command and fail the build on a non-zero exit.</li>\n<li>Write access to the repository&#39;s formatter configuration.</li>\n</ul>\n<p><strong>Stack assumptions, and how to adapt.</strong> Layers 1 and 3 are stack-agnostic: they\nread the tree and write markdown. Layer 2 is the only one with an ecosystem\ndependency, because it needs something that can resolve an import graph. The\nmeasurements behind this procedure came from a TypeScript monorepo, so\ndependency-cruiser is what the examples name. Substitute the equivalent for your\necosystem and nothing else in the procedure changes:</p>\n<table>\n<thead>\n<tr>\n<th>Ecosystem</th>\n<th>Import-edge enforcement</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>JavaScript / TypeScript</td>\n<td>dependency-cruiser, or an eslint import boundary plugin</td>\n</tr>\n<tr>\n<td>Python</td>\n<td>import-linter contracts</td>\n</tr>\n<tr>\n<td>Go</td>\n<td>the language&#39;s own package visibility, plus a depguard-style linter</td>\n</tr>\n<tr>\n<td>Java / Kotlin</td>\n<td>ArchUnit rules</td>\n</tr>\n<tr>\n<td>Rust</td>\n<td>crate boundaries, plus a workspace dependency lint</td>\n</tr>\n</tbody></table>\n<p>What matters is not the tool. It is that a violated rule fails a build, and that\nthe rule was measured before it was written.</p>\n<h3 id=\"step-0-detection-probes\">Step 0: detection probes</h3>\n<p>Run these before writing anything. Adjust the paths to the repository&#39;s own\nconventions; the point is the question each one answers, not the exact path.</p>\n<pre><code class=\"language-bash\"># Which agent context files exist at all?\ngit ls-files | grep -Ei &#39;CLAUDE\\.md|AGENTS\\.md|GEMINI\\.md|copilot-instructions|clinerules|windsurfrules|\\.cursor/rules/&#39;\n\n# Are any of them generated? A generated file says so in its first lines.\ngit ls-files | grep -Ei &#39;CLAUDE\\.md|AGENTS\\.md&#39; | xargs -I{} sh -c &#39;echo &quot;== {}&quot;; head -4 &quot;{}&quot;&#39;\n\n# Is there a generator, and does it have a --check mode?\ngit grep -lE &#39;generated.*do not edit|--check&#39; -- &#39;*.mjs&#39; &#39;*.js&#39; &#39;*.ts&#39; | head\n\n# Is there an import-boundary config, and does it carry this repo&#39;s own rules?\ngit ls-files | grep -Ei &#39;dependency-cruiser|importlinter|\\.importlinter|archunit&#39;\n\n# Is there a committed atlas, and is it stamped?\ngit ls-files | grep -Ei &#39;atlas|agent-context&#39; | head\n\n# Will a format run rewrite the generated files?\ncat .prettierignore 2&gt;/dev/null || echo &#39;no formatter ignore file&#39;\n</code></pre>\n<p>Report what you found, and which of the three branches you are taking, before\nyou edit a file. The three branches are in the skill body.</p>\n<h3 id=\"layer-1-one-source-for-the-agent-context-files\">Layer 1: one source for the agent context files</h3>\n<h4 id=\"1-measure-the-drift\">1. Measure the drift</h4>\n<p>Diff every context file against every other one and produce a list of rules that\nexist in one place and not another. Do not resolve contradictions yourself: they\nare decisions, and the list is what you take to whoever owns them.</p>\n<p>This step is the reason the layer is worth doing. Generation without it copies\none file&#39;s mistakes into six harnesses at once.</p>\n<h4 id=\"2-author-the-core\">2. Author the core</h4>\n<p>A directory of topic files, one topic per file, plus a manifest saying which\ntopics each harness output composes. Topics, not harnesses: a rule about\nmigrations belongs in the migrations topic whether or not Cursor reads it.</p>\n<p>Keep harness-specific material in small per-harness files. If a harness needs a\ntool syntax or a directory convention nobody else understands, that belongs to\nthe harness file, not to the core.</p>\n<h4 id=\"3-write-the-generator\">3. Write the generator</h4>\n<p>Builtins only. It reads the core plus the manifest and writes each output file\nwith a header of exactly this shape:</p>\n<pre><code class=\"language-text\">&lt;!-- Generated from docs/agent-context/. Do not edit.\n     Regenerate: node tools/agent-context/generate.mjs --&gt;\n</code></pre>\n<p>The header states three things: that it is generated, where the source is, and\nthe exact command. Somebody who edits the file by hand will read the header\nbefore their change is reverted, and that is the only chance to teach them.</p>\n<h4 id=\"4-add---check\">4. Add <code>--check</code></h4>\n<p><code>--check</code> regenerates into memory, compares to what is on disk, and exits\nnon-zero on any difference. It must <strong>name the file that drifted</strong> and print the\nregenerate command. A check that says only &quot;drift detected&quot; costs the reader a\nround trip.</p>\n<h4 id=\"5-gate-it-and-ignore-it-in-the-formatter\">5. Gate it, and ignore it in the formatter</h4>\n<p>Add the <code>--check</code> invocation to CI, and in the same commit add every generated\npath to the formatter&#39;s ignore file. Not in a follow-up: a markdown formatter\nthat realigns tables will rewrite generated output the first time anybody runs\nit, and the gate then fails for a reason that has nothing to do with the\ncontent.</p>\n<p>Mutation-test the gate before you believe it. See the gate hardening reference.</p>\n<h3 id=\"layer-2-architecture-rules-as-enforced-import-edges\">Layer 2: architecture rules as enforced import edges</h3>\n<h4 id=\"1-take-rules-that-already-exist\">1. Take rules that already exist</h4>\n<p>Read the repository&#39;s own documentation and pull out the rules it already states\nabout what may import what. Every rule you enforce should be quotable back to a\nsentence somebody wrote deliberately.</p>\n<p>Rules invented inside a lint config are the ones that get switched off in the\nfirst PR that trips them.</p>\n<h4 id=\"2-measure-with-the-enforcing-tool\">2. Measure with the enforcing tool</h4>\n<p>Before writing a rule, run the tool in reporting mode and count the current\nviolations. Not with grep. A pathspec is not an import graph, and the two\ndisagree in ways that are invisible until the rule ships. See the pitfalls in\nthe skill body for the exact case.</p>\n<p>Record the number. It is the rule&#39;s baseline and it belongs in the rule&#39;s\ncomment.</p>\n<h4 id=\"3-write-the-rule\">3. Write the rule</h4>\n<ul>\n<li>Count is zero: severity <code>error</code>. It cannot regress.</li>\n<li>Count is not zero: severity <code>warn</code>, with the count and the intended direction\nin the comment, and a plan to ratchet.</li>\n</ul>\n<p>Never widen a rule to make a red build green. Either fix the violation or record\nan explicit, reviewed exception with a written reason.</p>\n<h4 id=\"4-mutation-test-it\">4. Mutation test it</h4>\n<p>Every rule, individually. This is where two of the rules in the original work\nturned out to be verifying nothing. The procedure and the two configuration\ntraps behind those failures are in the gate hardening reference.</p>\n<h4 id=\"5-run-it-in-ci\">5. Run it in CI</h4>\n<p>Alongside the other checks, with the same exit-code contract.</p>\n<p>Optionally add a graph render (<code>dot</code>) as a local-only command. It is useful in\nreview and CI must never depend on it.</p>\n<h3 id=\"layer-3-the-generated-operational-atlas\">Layer 3: the generated operational atlas</h3>\n<h4 id=\"what-to-derive\">What to derive</h4>\n<p>The registries an agent would otherwise reconstruct by grep every session.\nTypical candidates:</p>\n<ul>\n<li>Background jobs, their identifiers, and where each is registered. If the\nrepository has a registry file, the atlas is the place the mismatch between\nthe two becomes visible.</li>\n<li>Tool or plugin definitions and their executors.</li>\n<li>HTTP routes, their methods, and their handler files.</li>\n<li>Schema migrations and their applied-state convention.</li>\n</ul>\n<p>The test for a good atlas page: an agent currently answers this question by\nrunning three greps and getting it slightly wrong.</p>\n<h4 id=\"how-to-derive-it\">How to derive it</h4>\n<p>Parse the tree. Never ask a model to summarise the codebase into the artifact:\nthe whole value is that it is exactly as true as the code, and a summary is not.</p>\n<p>Every row carries the file path of the thing it describes. The atlas is an index\ninto the source, not a replacement for reading it.</p>\n<h4 id=\"provenance\">Provenance</h4>\n<p>Stamp each file with the generator, the commit the tree was at, and the\nregenerate command. Then obey two rules that are less obvious than they look:</p>\n<ol>\n<li><strong>Rewrite a file only when its derived facts change.</strong> Otherwise every commit\nrewrites every atlas file and the diffs become noise.</li>\n<li><strong>Compare bodies with the provenance line blanked</strong> in <code>--check</code>. Otherwise\nthe stamp itself is a difference and the check fails on every commit.</li>\n</ol>\n<p>Do not build a scheme that compares a per-path commit SHA. It cannot work in CI.\nThe reason is in the gate hardening reference, and it is the kind of thing that\npasses every local run.</p>\n<h3 id=\"layer-4-defer-it\">Layer 4: defer it</h3>\n<p>Do not start here, and do not let it block layers 1 to 3.</p>\n<p>When the earlier layers have run long enough to show what is still missing, and\nthe missing thing is genuinely blast radius across duplicate exported names,\nbuild it: a SCIP indexer for the language, loaded into an embedded SQLite or\nDuckDB file, gitignored and rebuilt on demand. Budget a week.</p>\n<p>A language server over MCP is the cheap partial substitute and can be added at\nany point. It answers &quot;where is this symbol defined and used&quot; with no committed\nartifact and nothing to keep in sync, which means nothing to keep honest.</p>\n<h3 id=\"stopping-rules\">Stopping rules</h3>\n<p>Each layer is useful alone. Stop wherever it stops paying, and say so:</p>\n<ul>\n<li>If layer 1&#39;s drift list turns out to be empty, the repository does not have\nthis problem. Generating anyway adds a build step and buys nothing.</li>\n<li>If layer 2&#39;s candidate rules all have non-zero violation counts nobody intends\nto fix, you are proposing policy, not enforcement. Take it back to the owner.</li>\n<li>If nobody can name a question layer 3 would answer, do not build an atlas of\nwhatever is easiest to parse. An unread generated file is still a file that\nbreaks a gate.</li>\n</ul>\n","words":1537}],"body":"# Derive codebase context\n\nAn agent working in a repository of a few thousand files cannot hold its shape.\nThe reflex is to build a code knowledge graph. The measurements say do something\ncheaper and more durable: derive three artifacts from the tree itself, commit\nthem, and gate each one in CI so it cannot rot.\n\nThis skill is the order to build them in, how to tell whether a repository\nalready has them, and the one discipline that decides whether any of it works.\n\n## What the evidence says\n\nRead this before proposing a graph, because the graph is the thing people keep\nproposing.\n\n- **A tree-sitter code graph is not a win across the board.** Measured over 31\n  repositories it gives roughly 10x fewer tokens and 2.1x fewer tool calls, at\n  **83% answer quality against 92%** for an agent that simply reads files\n  (arXiv 2603.27277). It wins on hub detection and caller ranking and loses\n  elsewhere. So route *structural* questions to derived artifacts, and never\n  take agents off grep.\n- **Anthropic removed a local vector index from Claude Code** in favour of\n  agentic search, over staleness, privacy and reliability. Anything built here\n  must be **derived and regenerated**, never hand-maintained.\n- **Name-keyed graphs collapse on real repositories.** In the codebase this came\n  from, 184 exported names were defined in more than one file, and the worst\n  offenders were its own conventions: `POST` 271 times, `GET` 209, `KEY` 143. A\n  graph keyed on bare symbol names merges those into one node, and every\n  blast-radius answer becomes \"the whole app\". Only compiler-resolved indexing\n  survives that, and it is layer 4, which you defer.\n\n## When to Use\n\n- A repository is large enough that agents guess at its structure, and you are\n  deciding what to build about it.\n- Someone proposes a code knowledge graph, a vector index, or a semantic search\n  layer over the codebase.\n- The context files have multiplied: `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`,\n  Copilot instructions, Cursor rules, `.clinerules`, Windsurf rules, all\n  hand-maintained and no longer saying the same thing.\n- Architecture rules live in prose that nothing enforces.\n- A repository already has some of this and you need to know whether to finish\n  it, upgrade it, or leave it alone.\n\nDo not use it to answer a question about the code. That is what grep, the\nlanguage server, and reading files are for, and they are better at it. This\nbuilds the artifacts; it does not replace how agents read.\n\n## Required tooling\n\n| Need | Tool | Where it runs | Notes |\n|---|---|---|---|\n| Context and atlas generation | Node 22+, builtins only | local and CI | No dependencies at all. |\n| Boundary enforcement | `dependency-cruiser` ^18 | local and CI | One dev dependency at the root. |\n| Boundary graph image | `graphviz` (`dot`) | local only | Optional. CI never needs it. |\n| Symbol navigation (companion) | `uv` / `uvx` plus Serena | local only | Spawns a language server; the server itself indexes nothing you commit. Its memory files usually ARE tracked — see below. |\n| Symbol index (layer 4) | `scip-typescript` or your language's SCIP indexer | local, and CI only if you keep it | Emits a protobuf index. Gitignored, rebuilt on demand. |\n| Index storage (layer 4) | SQLite or DuckDB **as a library** | local | An embedded file, not a server. |\n\n**No database server at any layer.** No daemon, no container, no hosted index,\nno network call. Everything travels through git because every artifact is a pure\nfunction of the tree at HEAD, so a stale copy is fixed by regenerating it, not by\npulling. Do not register the repository with a hosted indexing service unless the\nowner has decided the source may leave the machine.\n\n## Step 0: find out what is already there\n\n**Do this first, every time.** Blindly scaffolding over a working setup is the\nfailure this step exists to prevent, and a half-built setup is more common than\neither extreme.\n\nProbe for six signals:\n\n| Signal | Look for | What it proves |\n|---|---|---|\n| Shared core | A directory holding the context source that several harness files are built from. | Layer 1 has a single source. |\n| Generator | A script that writes those harness files, with a `--check` mode. | Layer 1 is derived, not hand-copied. |\n| Gate | A CI step running that `--check`. | Layer 1 is enforced. |\n| Boundary config | A dependency-cruiser config whose `forbidden` rules name *this* repository's architecture. | Layer 2 has started. |\n| Atlas | A committed directory of generated registry markdown carrying a provenance line. | Layer 3 exists. |\n| Formatter ignore | The generated paths listed in the formatter's ignore file. | Layers 1 and 3 survive a format run. |\n\nTwo ways to be fooled:\n\n- **A file that feeds several harnesses is not generated.** Open it and look for\n  a \"generated, do not edit\" header and a provenance stamp. No header means\n  hand-maintained, however many harnesses read it.\n- **A dependency-cruiser config carrying only the tool's own starter rules**\n  (`no-circular`, `no-orphans`, `not-to-dev-dep`) encodes none of this\n  repository's architecture. Layer 2 has not started.\n\nThen branch:\n\n- **Nothing found: onboard.** Build layers 1, 2, 3 in that order. Each is useful\n  alone. Stop wherever it stops paying.\n- **Some found: finish the layer that exists before adding the next one.** The\n  usual half-state is a generator with no CI gate, which is the least useful\n  shape there is: it drifts exactly as fast as hand-maintenance, and looks\n  solved. Arm it first.\n- **All found: verify and report. Change nothing.** Run each `--check` and the\n  boundary check, report drift and its cause, and stop. Do not regenerate and\n  commit unless the owner asks.\n\n## Layer 1: one source for the agent context files\n\n**The failure.** Every harness wants its own file, so the repository accumulates\n`CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `.github/copilot-instructions.md`,\n`.cursor/rules/*`, `.clinerules`, `.windsurfrules`. Hand-maintained, they drift,\nthen contradict each other, and an agent obeys whichever one its harness happens\nto load. Nobody can tell which rule is current.\n\n1. **Measure the drift before writing anything.** List every context file, diff\n   them, and write down which rules exist in one and not another. That list is\n   the review artifact, and it is the only chance to settle contradictions with\n   a human.\n2. **Author a shared core**, split by topic so each harness file can compose a\n   subset rather than take everything.\n3. **Write the generator** with language builtins only. It reads the core and\n   writes every harness file with a \"generated, do not edit, regenerate with X\"\n   header.\n4. **Add `--check`**: regenerate to memory, compare against what is on disk,\n   exit non-zero on drift. Naming the file that drifted is the whole product of\n   a failed run.\n5. **Gate it in CI, and add the generated paths to the formatter's ignore file\n   in the same commit.** See the pitfalls: a formatter will rewrite generated\n   markdown and break the gate before you have finished building it.\n\n## Layer 2: architectural rules as enforced import edges\n\n**The failure.** The repository already writes rules in prose: this package may\nnot import that one, background jobs may not reach the web app, nothing calls\nthe provider SDK directly. Prose is followed until somebody is in a hurry.\n\n1. **Take rules that are already written down.** Do not invent architecture\n   policy inside a lint config. A rule nobody agreed to gets disabled.\n2. **Measure the current violations with the tool that will enforce them**, not\n   by hand. See the pitfalls: a hand count found 4 where the rule engine found\n   6, and a rule that starts red gets switched off rather than fixed.\n3. **Write each rule as a forbidden edge**, at error severity where the count is\n   zero and warn where it is not, with the target count in the rule's own\n   comment so the next person knows what it is ratcheting towards.\n4. **Mutation test it.** Every rule. No exceptions. See the discipline below.\n5. **Run it in CI** alongside the other checks.\n\nTwo traps that made real rules pass while checking nothing are in\n[the gate hardening reference](references/gate-hardening.md). Read it before\nwriting a rule that mentions an npm package.\n\n## Layer 3: the generated operational atlas\n\n**The failure.** Agents re-derive the same cross-cutting registries by grep,\nevery session, and get them subtly wrong. Background jobs to their keys to where\nthey are registered. Plugin or MCP tools to their executors. HTTP routes to\nmethods to handlers. Whatever your repository has several dozen of and no list\nof.\n\nDerive them into committed markdown:\n\n- **Parse the tree.** Never ask a model to summarise it. The value here is that\n  the artifact is exactly as true as the code.\n- **One row per real thing, carrying its file path**, so the agent can open the\n  source instead of trusting the summary.\n- **Stamp provenance**: which generator wrote it, the commit the tree was at, and\n  the command to regenerate it.\n- **Add `--check`**, as in layer 1.\n- **Rewrite a file only when its derived facts change**, and compare bodies with\n  the provenance line blanked. Otherwise every commit rewrites every atlas file\n  and the diff becomes noise nobody reads.\n\nThe provenance scheme is where this goes wrong in CI specifically. Read the\n[gate hardening reference](references/gate-hardening.md) before designing it.\n\n## Layer 4: a compiler-accurate symbol index. Defer it.\n\nThis is the only thing that answers blast radius correctly in a repository with\nduplicate exported names, and it is roughly a week of work. Run layers 1 to 3 for\na month first, because the cheap layers often remove the need.\n\nWhen you do build it: a SCIP indexer for your language, loaded into an **embedded**\nSQLite or DuckDB file. Gitignore the index. It is tens of megabytes of protobuf\nthat changes every commit, and committing it is putting `node_modules` in git.\n\nA language server exposed over MCP (Serena, run through `uvx`) is a useful\ncompanion at any point and is not a layer: it answers \"who calls this\" from the\ntree as it is, with no index to build and nothing to rebuild after a pull.\n\nTwo things to settle before turning it on.\n\n**Its memory system is a second store, and it drifts like any other.** Serena\nreuses project memories across sessions and its memory directory is normally\ntracked, so they reach the whole team through git. That puts them squarely under\nlayer 1's rule: memories must **point at** the generated context files, never\nrestate the facts in them. A memory that copies a hard rule is the exact drift\nthis skill exists to prevent, rebuilt inside the tool meant to help. Write them\nfor what the generated files cannot carry — commands, local traps, the\nverification standard — and say so in the entry-point memory so the next reader\ndoes not add a copy. Run its onboarding once and review what it writes; do not\naccept a generated memory that duplicates your context files.\n\n**An empty reference result is not zero references.** For a very-high-fan-out\nsymbol the reference query returns an empty object, because the answer exceeds\nits size cap rather than because nothing calls it. Read it as \"too many to\nserialize\" and reach for the atlas or a grep count instead. Measured on a symbol\nimported by roughly a thousand files.\n\n## The discipline: a gate you have not watched fail is not a gate\n\nIn the work this came from, **four separate guards were born unarmed**. They\npassed every run while verifying nothing: two boundary rules whose configuration\nhad deleted the edges they matched, and two atlas guards that were structurally\nunreachable. Nothing about a green run distinguishes a guard that passed from a\nguard that checked nothing.\n\nSo for every gate, before you trust it:\n\n1. **Back it up with `cp`.** Not with git. `git checkout -- <file>` silently does\n   nothing for an untracked file, so it will not revert a mutation test on a\n   file you just created, and you will lose the fix instead.\n2. **Introduce exactly the thing the gate forbids.**\n3. **Run the gate. Watch it fail**, and read the message. It must name the thing\n   you introduced. A failure with a message that names something else is a\n   different gate firing.\n4. **Restore from the backup.**\n5. **Run it again. Watch it pass.**\n\nA guard you cannot make fail is checking something other than what you think it\nis checking. Treat a new guard as broken until it has been watched to fail.\n\n## Pitfalls\n\n- **Measure with the tool that will enforce, not with a hand grep.** A pathspec\n  like `dir/**/*.ts` does not match files sitting directly in `dir/`. The hand\n  count said 4; the rule engine found 6. A baseline that is an undercount turns\n  into a rule that starts red, and a rule that starts red gets disabled.\n- **CI clones are shallow.** `actions/checkout` gives depth 1, so\n  `git log -1 -- <path>` returns the tip commit for *every* path and\n  `git rev-parse --short` abbreviates to 7 characters instead of 8. Any\n  provenance scheme that compares a per-path SHA passes on a laptop and fails on\n  every CI run.\n- **Formatters rewrite generated files.** A markdown formatter realigning tables\n  broke the generated-file gate before the atlas it was meant to protect even\n  existed. The ignore entry belongs in the same commit as the generator.\n- **A new test directory needs a workspace or project entry**, or its first test\n  file contributes zero tests while the summary stays green.\n- **Dependencies go stale after a big pull.** A declared, lockfile-present\n  package that is not actually installed will fail most of a suite. Install\n  before believing any suite result.\n\n## Usage Examples\n\n```text\nSet up derived codebase context in this repo. Detect what already exists first\nand tell me which of the three layers are present before you write anything.\n```\n\n```text\nWe have CLAUDE.md, AGENTS.md and Cursor rules that disagree. Do layer 1: show me\nthe drift between them as a diff first, then generate all three from one core\nand gate it in CI.\n```\n\n```text\nTurn the four architecture rules in our README into dependency-cruiser forbidden\nedges. Measure the current violation count with the tool before writing each\nrule, and mutation-test every one of them before you tell me it works.\n```\n\n## Verification\n\n- [ ] Step 0 ran, and the branch taken (onboard, finish, verify-only) was stated.\n- [ ] Nothing was scaffolded over an existing setup without being reported first.\n- [ ] Every generated file carries a \"do not edit\" header and a regenerate command.\n- [ ] Every generator has a `--check` mode that names the file that drifted.\n- [ ] Every `--check` runs in CI.\n- [ ] Generated paths are in the formatter's ignore file.\n- [ ] Each boundary rule was measured with the enforcing tool before it was written.\n- [ ] Every gate was watched to fail on a mutation and then to pass on restore.\n- [ ] Mutation backups were `cp` copies, and the restore was verified.\n- [ ] Provenance survives a depth-1 clone.\n- [ ] No index, cache, or generated binary artifact was committed.\n- [ ] Layer 4 was deferred, or the owner explicitly chose to pay for it.\n\n## Deeper reading\n\n- [Onboarding runbook](references/onboarding.md): the per-layer procedure in\n  full, including generator design, `--check` semantics, provenance stamping,\n  and how to adapt each layer to a non-JavaScript stack.\n- [Gate hardening](references/gate-hardening.md): the mutation-test procedure,\n  the four unarmed guards and the exact mechanism of each, and the CI traps that\n  make a green check meaningless.\n","bodyHtml":"<h2 id=\"derive-codebase-context\">Derive codebase context</h2>\n<p>An agent working in a repository of a few thousand files cannot hold its shape.\nThe reflex is to build a code knowledge graph. The measurements say do something\ncheaper and more durable: derive three artifacts from the tree itself, commit\nthem, and gate each one in CI so it cannot rot.</p>\n<p>This skill is the order to build them in, how to tell whether a repository\nalready has them, and the one discipline that decides whether any of it works.</p>\n<h3 id=\"what-the-evidence-says\">What the evidence says</h3>\n<p>Read this before proposing a graph, because the graph is the thing people keep\nproposing.</p>\n<ul>\n<li><strong>A tree-sitter code graph is not a win across the board.</strong> Measured over 31\nrepositories it gives roughly 10x fewer tokens and 2.1x fewer tool calls, at\n<strong>83% answer quality against 92%</strong> for an agent that simply reads files\n(arXiv 2603.27277). It wins on hub detection and caller ranking and loses\nelsewhere. So route <em>structural</em> questions to derived artifacts, and never\ntake agents off grep.</li>\n<li><strong>Anthropic removed a local vector index from Claude Code</strong> in favour of\nagentic search, over staleness, privacy and reliability. Anything built here\nmust be <strong>derived and regenerated</strong>, never hand-maintained.</li>\n<li><strong>Name-keyed graphs collapse on real repositories.</strong> In the codebase this came\nfrom, 184 exported names were defined in more than one file, and the worst\noffenders were its own conventions: <code>POST</code> 271 times, <code>GET</code> 209, <code>KEY</code> 143. A\ngraph keyed on bare symbol names merges those into one node, and every\nblast-radius answer becomes &quot;the whole app&quot;. Only compiler-resolved indexing\nsurvives that, and it is layer 4, which you defer.</li>\n</ul>\n<h3 id=\"when-to-use\">When to Use</h3>\n<ul>\n<li>A repository is large enough that agents guess at its structure, and you are\ndeciding what to build about it.</li>\n<li>Someone proposes a code knowledge graph, a vector index, or a semantic search\nlayer over the codebase.</li>\n<li>The context files have multiplied: <code>CLAUDE.md</code>, <code>AGENTS.md</code>, <code>GEMINI.md</code>,\nCopilot instructions, Cursor rules, <code>.clinerules</code>, Windsurf rules, all\nhand-maintained and no longer saying the same thing.</li>\n<li>Architecture rules live in prose that nothing enforces.</li>\n<li>A repository already has some of this and you need to know whether to finish\nit, upgrade it, or leave it alone.</li>\n</ul>\n<p>Do not use it to answer a question about the code. That is what grep, the\nlanguage server, and reading files are for, and they are better at it. This\nbuilds the artifacts; it does not replace how agents read.</p>\n<h3 id=\"required-tooling\">Required tooling</h3>\n<table>\n<thead>\n<tr>\n<th>Need</th>\n<th>Tool</th>\n<th>Where it runs</th>\n<th>Notes</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Context and atlas generation</td>\n<td>Node 22+, builtins only</td>\n<td>local and CI</td>\n<td>No dependencies at all.</td>\n</tr>\n<tr>\n<td>Boundary enforcement</td>\n<td><code>dependency-cruiser</code> ^18</td>\n<td>local and CI</td>\n<td>One dev dependency at the root.</td>\n</tr>\n<tr>\n<td>Boundary graph image</td>\n<td><code>graphviz</code> (<code>dot</code>)</td>\n<td>local only</td>\n<td>Optional. CI never needs it.</td>\n</tr>\n<tr>\n<td>Symbol navigation (companion)</td>\n<td><code>uv</code> / <code>uvx</code> plus Serena</td>\n<td>local only</td>\n<td>Spawns a language server; the server itself indexes nothing you commit. Its memory files usually ARE tracked — see below.</td>\n</tr>\n<tr>\n<td>Symbol index (layer 4)</td>\n<td><code>scip-typescript</code> or your language&#39;s SCIP indexer</td>\n<td>local, and CI only if you keep it</td>\n<td>Emits a protobuf index. Gitignored, rebuilt on demand.</td>\n</tr>\n<tr>\n<td>Index storage (layer 4)</td>\n<td>SQLite or DuckDB <strong>as a library</strong></td>\n<td>local</td>\n<td>An embedded file, not a server.</td>\n</tr>\n</tbody></table>\n<p><strong>No database server at any layer.</strong> No daemon, no container, no hosted index,\nno network call. Everything travels through git because every artifact is a pure\nfunction of the tree at HEAD, so a stale copy is fixed by regenerating it, not by\npulling. Do not register the repository with a hosted indexing service unless the\nowner has decided the source may leave the machine.</p>\n<h3 id=\"step-0-find-out-what-is-already-there\">Step 0: find out what is already there</h3>\n<p><strong>Do this first, every time.</strong> Blindly scaffolding over a working setup is the\nfailure this step exists to prevent, and a half-built setup is more common than\neither extreme.</p>\n<p>Probe for six signals:</p>\n<table>\n<thead>\n<tr>\n<th>Signal</th>\n<th>Look for</th>\n<th>What it proves</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Shared core</td>\n<td>A directory holding the context source that several harness files are built from.</td>\n<td>Layer 1 has a single source.</td>\n</tr>\n<tr>\n<td>Generator</td>\n<td>A script that writes those harness files, with a <code>--check</code> mode.</td>\n<td>Layer 1 is derived, not hand-copied.</td>\n</tr>\n<tr>\n<td>Gate</td>\n<td>A CI step running that <code>--check</code>.</td>\n<td>Layer 1 is enforced.</td>\n</tr>\n<tr>\n<td>Boundary config</td>\n<td>A dependency-cruiser config whose <code>forbidden</code> rules name <em>this</em> repository&#39;s architecture.</td>\n<td>Layer 2 has started.</td>\n</tr>\n<tr>\n<td>Atlas</td>\n<td>A committed directory of generated registry markdown carrying a provenance line.</td>\n<td>Layer 3 exists.</td>\n</tr>\n<tr>\n<td>Formatter ignore</td>\n<td>The generated paths listed in the formatter&#39;s ignore file.</td>\n<td>Layers 1 and 3 survive a format run.</td>\n</tr>\n</tbody></table>\n<p>Two ways to be fooled:</p>\n<ul>\n<li><strong>A file that feeds several harnesses is not generated.</strong> Open it and look for\na &quot;generated, do not edit&quot; header and a provenance stamp. No header means\nhand-maintained, however many harnesses read it.</li>\n<li><strong>A dependency-cruiser config carrying only the tool&#39;s own starter rules</strong>\n(<code>no-circular</code>, <code>no-orphans</code>, <code>not-to-dev-dep</code>) encodes none of this\nrepository&#39;s architecture. Layer 2 has not started.</li>\n</ul>\n<p>Then branch:</p>\n<ul>\n<li><strong>Nothing found: onboard.</strong> Build layers 1, 2, 3 in that order. Each is useful\nalone. Stop wherever it stops paying.</li>\n<li><strong>Some found: finish the layer that exists before adding the next one.</strong> The\nusual half-state is a generator with no CI gate, which is the least useful\nshape there is: it drifts exactly as fast as hand-maintenance, and looks\nsolved. Arm it first.</li>\n<li><strong>All found: verify and report. Change nothing.</strong> Run each <code>--check</code> and the\nboundary check, report drift and its cause, and stop. Do not regenerate and\ncommit unless the owner asks.</li>\n</ul>\n<h3 id=\"layer-1-one-source-for-the-agent-context-files\">Layer 1: one source for the agent context files</h3>\n<p><strong>The failure.</strong> Every harness wants its own file, so the repository accumulates\n<code>CLAUDE.md</code>, <code>AGENTS.md</code>, <code>GEMINI.md</code>, <code>.github/copilot-instructions.md</code>,\n<code>.cursor/rules/*</code>, <code>.clinerules</code>, <code>.windsurfrules</code>. Hand-maintained, they drift,\nthen contradict each other, and an agent obeys whichever one its harness happens\nto load. Nobody can tell which rule is current.</p>\n<ol>\n<li><strong>Measure the drift before writing anything.</strong> List every context file, diff\nthem, and write down which rules exist in one and not another. That list is\nthe review artifact, and it is the only chance to settle contradictions with\na human.</li>\n<li><strong>Author a shared core</strong>, split by topic so each harness file can compose a\nsubset rather than take everything.</li>\n<li><strong>Write the generator</strong> with language builtins only. It reads the core and\nwrites every harness file with a &quot;generated, do not edit, regenerate with X&quot;\nheader.</li>\n<li><strong>Add <code>--check</code></strong>: regenerate to memory, compare against what is on disk,\nexit non-zero on drift. Naming the file that drifted is the whole product of\na failed run.</li>\n<li><strong>Gate it in CI, and add the generated paths to the formatter&#39;s ignore file\nin the same commit.</strong> See the pitfalls: a formatter will rewrite generated\nmarkdown and break the gate before you have finished building it.</li>\n</ol>\n<h3 id=\"layer-2-architectural-rules-as-enforced-import-edges\">Layer 2: architectural rules as enforced import edges</h3>\n<p><strong>The failure.</strong> The repository already writes rules in prose: this package may\nnot import that one, background jobs may not reach the web app, nothing calls\nthe provider SDK directly. Prose is followed until somebody is in a hurry.</p>\n<ol>\n<li><strong>Take rules that are already written down.</strong> Do not invent architecture\npolicy inside a lint config. A rule nobody agreed to gets disabled.</li>\n<li><strong>Measure the current violations with the tool that will enforce them</strong>, not\nby hand. See the pitfalls: a hand count found 4 where the rule engine found\n6, and a rule that starts red gets switched off rather than fixed.</li>\n<li><strong>Write each rule as a forbidden edge</strong>, at error severity where the count is\nzero and warn where it is not, with the target count in the rule&#39;s own\ncomment so the next person knows what it is ratcheting towards.</li>\n<li><strong>Mutation test it.</strong> Every rule. No exceptions. See the discipline below.</li>\n<li><strong>Run it in CI</strong> alongside the other checks.</li>\n</ol>\n<p>Two traps that made real rules pass while checking nothing are in\n<a href=\"references/gate-hardening.md\">the gate hardening reference</a>. Read it before\nwriting a rule that mentions an npm package.</p>\n<h3 id=\"layer-3-the-generated-operational-atlas\">Layer 3: the generated operational atlas</h3>\n<p><strong>The failure.</strong> Agents re-derive the same cross-cutting registries by grep,\nevery session, and get them subtly wrong. Background jobs to their keys to where\nthey are registered. Plugin or MCP tools to their executors. HTTP routes to\nmethods to handlers. Whatever your repository has several dozen of and no list\nof.</p>\n<p>Derive them into committed markdown:</p>\n<ul>\n<li><strong>Parse the tree.</strong> Never ask a model to summarise it. The value here is that\nthe artifact is exactly as true as the code.</li>\n<li><strong>One row per real thing, carrying its file path</strong>, so the agent can open the\nsource instead of trusting the summary.</li>\n<li><strong>Stamp provenance</strong>: which generator wrote it, the commit the tree was at, and\nthe command to regenerate it.</li>\n<li><strong>Add <code>--check</code></strong>, as in layer 1.</li>\n<li><strong>Rewrite a file only when its derived facts change</strong>, and compare bodies with\nthe provenance line blanked. Otherwise every commit rewrites every atlas file\nand the diff becomes noise nobody reads.</li>\n</ul>\n<p>The provenance scheme is where this goes wrong in CI specifically. Read the\n<a href=\"references/gate-hardening.md\">gate hardening reference</a> before designing it.</p>\n<h3 id=\"layer-4-a-compiler-accurate-symbol-index-defer-it\">Layer 4: a compiler-accurate symbol index. Defer it.</h3>\n<p>This is the only thing that answers blast radius correctly in a repository with\nduplicate exported names, and it is roughly a week of work. Run layers 1 to 3 for\na month first, because the cheap layers often remove the need.</p>\n<p>When you do build it: a SCIP indexer for your language, loaded into an <strong>embedded</strong>\nSQLite or DuckDB file. Gitignore the index. It is tens of megabytes of protobuf\nthat changes every commit, and committing it is putting <code>node_modules</code> in git.</p>\n<p>A language server exposed over MCP (Serena, run through <code>uvx</code>) is a useful\ncompanion at any point and is not a layer: it answers &quot;who calls this&quot; from the\ntree as it is, with no index to build and nothing to rebuild after a pull.</p>\n<p>Two things to settle before turning it on.</p>\n<p><strong>Its memory system is a second store, and it drifts like any other.</strong> Serena\nreuses project memories across sessions and its memory directory is normally\ntracked, so they reach the whole team through git. That puts them squarely under\nlayer 1&#39;s rule: memories must <strong>point at</strong> the generated context files, never\nrestate the facts in them. A memory that copies a hard rule is the exact drift\nthis skill exists to prevent, rebuilt inside the tool meant to help. Write them\nfor what the generated files cannot carry — commands, local traps, the\nverification standard — and say so in the entry-point memory so the next reader\ndoes not add a copy. Run its onboarding once and review what it writes; do not\naccept a generated memory that duplicates your context files.</p>\n<p><strong>An empty reference result is not zero references.</strong> For a very-high-fan-out\nsymbol the reference query returns an empty object, because the answer exceeds\nits size cap rather than because nothing calls it. Read it as &quot;too many to\nserialize&quot; and reach for the atlas or a grep count instead. Measured on a symbol\nimported by roughly a thousand files.</p>\n<h3 id=\"the-discipline-a-gate-you-have-not-watched-fail-is-not-a-gate\">The discipline: a gate you have not watched fail is not a gate</h3>\n<p>In the work this came from, <strong>four separate guards were born unarmed</strong>. They\npassed every run while verifying nothing: two boundary rules whose configuration\nhad deleted the edges they matched, and two atlas guards that were structurally\nunreachable. Nothing about a green run distinguishes a guard that passed from a\nguard that checked nothing.</p>\n<p>So for every gate, before you trust it:</p>\n<ol>\n<li><strong>Back it up with <code>cp</code>.</strong> Not with git. <code>git checkout -- &lt;file&gt;</code> silently does\nnothing for an untracked file, so it will not revert a mutation test on a\nfile you just created, and you will lose the fix instead.</li>\n<li><strong>Introduce exactly the thing the gate forbids.</strong></li>\n<li><strong>Run the gate. Watch it fail</strong>, and read the message. It must name the thing\nyou introduced. A failure with a message that names something else is a\ndifferent gate firing.</li>\n<li><strong>Restore from the backup.</strong></li>\n<li><strong>Run it again. Watch it pass.</strong></li>\n</ol>\n<p>A guard you cannot make fail is checking something other than what you think it\nis checking. Treat a new guard as broken until it has been watched to fail.</p>\n<h3 id=\"pitfalls\">Pitfalls</h3>\n<ul>\n<li><strong>Measure with the tool that will enforce, not with a hand grep.</strong> A pathspec\nlike <code>dir/**/*.ts</code> does not match files sitting directly in <code>dir/</code>. The hand\ncount said 4; the rule engine found 6. A baseline that is an undercount turns\ninto a rule that starts red, and a rule that starts red gets disabled.</li>\n<li><strong>CI clones are shallow.</strong> <code>actions/checkout</code> gives depth 1, so\n<code>git log -1 -- &lt;path&gt;</code> returns the tip commit for <em>every</em> path and\n<code>git rev-parse --short</code> abbreviates to 7 characters instead of 8. Any\nprovenance scheme that compares a per-path SHA passes on a laptop and fails on\nevery CI run.</li>\n<li><strong>Formatters rewrite generated files.</strong> A markdown formatter realigning tables\nbroke the generated-file gate before the atlas it was meant to protect even\nexisted. The ignore entry belongs in the same commit as the generator.</li>\n<li><strong>A new test directory needs a workspace or project entry</strong>, or its first test\nfile contributes zero tests while the summary stays green.</li>\n<li><strong>Dependencies go stale after a big pull.</strong> A declared, lockfile-present\npackage that is not actually installed will fail most of a suite. Install\nbefore believing any suite result.</li>\n</ul>\n<h3 id=\"usage-examples\">Usage Examples</h3>\n<pre><code class=\"language-text\">Set up derived codebase context in this repo. Detect what already exists first\nand tell me which of the three layers are present before you write anything.\n</code></pre>\n<pre><code class=\"language-text\">We have CLAUDE.md, AGENTS.md and Cursor rules that disagree. Do layer 1: show me\nthe drift between them as a diff first, then generate all three from one core\nand gate it in CI.\n</code></pre>\n<pre><code class=\"language-text\">Turn the four architecture rules in our README into dependency-cruiser forbidden\nedges. Measure the current violation count with the tool before writing each\nrule, and mutation-test every one of them before you tell me it works.\n</code></pre>\n<h3 id=\"verification\">Verification</h3>\n<ul>\n<li><input disabled=\"\" type=\"checkbox\"> Step 0 ran, and the branch taken (onboard, finish, verify-only) was stated.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Nothing was scaffolded over an existing setup without being reported first.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every generated file carries a &quot;do not edit&quot; header and a regenerate command.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every generator has a <code>--check</code> mode that names the file that drifted.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every <code>--check</code> runs in CI.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Generated paths are in the formatter&#39;s ignore file.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Each boundary rule was measured with the enforcing tool before it was written.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every gate was watched to fail on a mutation and then to pass on restore.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Mutation backups were <code>cp</code> copies, and the restore was verified.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Provenance survives a depth-1 clone.</li>\n<li><input disabled=\"\" type=\"checkbox\"> No index, cache, or generated binary artifact was committed.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Layer 4 was deferred, or the owner explicitly chose to pay for it.</li>\n</ul>\n<h3 id=\"deeper-reading\">Deeper reading</h3>\n<ul>\n<li><a href=\"references/onboarding.md\">Onboarding runbook</a>: the per-layer procedure in\nfull, including generator design, <code>--check</code> semantics, provenance stamping,\nand how to adapt each layer to a non-JavaScript stack.</li>\n<li><a href=\"references/gate-hardening.md\">Gate hardening</a>: the mutation-test procedure,\nthe four unarmed guards and the exact mechanism of each, and the CI traps that\nmake a green check meaningless.</li>\n</ul>\n","outline":["What the evidence says","When to Use","Required tooling","Step 0: find out what is already there","Layer 1: one source for the agent context files","Layer 2: architectural rules as enforced import edges","Layer 3: the generated operational atlas","Layer 4: a compiler-accurate symbol index. Defer it.","The discipline: a gate you have not watched fail is not a gate","Pitfalls","Usage Examples","Verification","Deeper reading"],"words":2629}
