From c98ee136a3e6ff2e19a88065c0a3b7d77bbf9f8c Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Wed, 18 Nov 2026 10:24:09 +0000 Subject: [PATCH 1/2] docs(plan): close M19 on PetClinic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #6's criteria are met on main (M19a/b/c, PRs #26-#46), so PLAN says so. §20.4 ticks the live run (M20: 68 calls, 79 records, 70 with words, 3 glossaries) and the docs box (docs/vocabulary.md, #45). The Definition of Done is restated for what was tested: M19a/b on Broadleaf, M19c on Spring PetClinic in Broadleaf's place, with the side-car (prompt "2", 139 records) importing and exporting cmp-equal, and the v1 migration. The §22 rows for M19a/b/c give the merge dates of #26-#30 and #46. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PKCVgyytH9LKzUTsUaKxeH --- PLAN.md | 71 +++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 46 insertions(+), 25 deletions(-) diff --git a/PLAN.md b/PLAN.md index 94a599e..c68f0f8 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5535,7 +5535,8 @@ and `confidence` are generated columns over it. The decisions: word estimates (28 206 records, 131 190 entries): the import takes 1.5 s and the export is byte-identical. The projection is 22 MB of a 91 MB store, `WHERE word = 'order'` takes 0.5 ms, and the migration's backfill 0.6 s. The - real Broadleaf side-car is owed. + real file is PetClinic's (139 records, `cmp`-identical; §20.4's definition + of done), not Broadleaf's. **As built — the store's readers (2026-10-27).** `codegraph insights --word`, `--glossary`, `--polysemy` and `--concerns`, over `glossary.ts` in @@ -5806,36 +5807,56 @@ The decisions: - [x] The store at version 2: migration 1 creating `insight_word`, written per record in the unit's transaction and rebuilt on `--import`; the migration tests of §20.3; the round-trip property unchanged and green - on every existing side-car. *(The real Broadleaf side-car is owed; - measured on a synthetic one at its scale.)* -- [ ] `--terms N`; `--dry-run`/`--estimate` reflecting the longer + on every existing side-car. *(Scale measured on a synthetic side-car + at Broadleaf's counts; the real file is PetClinic's — the definition + of done.)* +- [x] `--terms N`; `--dry-run`/`--estimate` reflecting the longer completions (`COMPLETION_TOKENS_PER_BLOCK` re-measured); a reader's answer for a record explained under prompt `"1"`; on the fake client and live on the Java fixture; the §20.3 estimate replaced by the - Broadleaf measurement. *(In: `--terms`, the estimate's per-word - figures, the fake-client run, the prompt-1 answer; the measurement, - from a live run on Spring PetClinic in Broadleaf's place, 2026-10-29, - §20.3 "Measured". Owed: the live run on the Java fixture.)* + PetClinic measurement. *(The measurement: a live run on Spring + PetClinic in Broadleaf's place, 2026-10-29, §20.3 "Measured". The live + run on the Java fixture: M20's, 2026-11-10 (§21.4), Claude Code with + Sonnet under prompt `"2"` — 68 calls, 79 records, the 70 a model wrote + every one with `words`, the 3 modules with `glossary`; the 9 templated + operations carry none, as built.)* - [x] Readers: `insights --word`, `--glossary`, `--polysemy`, `--concerns`; `vocabulary --drift-insights`; `/glossary.json`; the entries in the Vocabulary tab and in the Navigate panel as inferences. -- [ ] `docs/vocabulary.md` (the idioms per profile, the classes, the +- [x] `docs/vocabulary.md` (the idioms per profile, the classes, the weights, the artifact, the three layers, the readers, the drift reports); README names the feature; `docs/cli.md` the command and the flags; `docs/insights.md` the `words` and `glossary` fields and the - version bump. - -Definition of done: the five `vocabulary.json` snapshots byte-identical to -the package's output; `codegraph vocabulary` on Broadleaf prints a commerce -vocabulary under `domain`; the tab and the coloured city reviewed as -screenshots; `explain` on the Java fixture, live and on the fake client, -writes a side-car whose every record carries `words` and whose module -records carry `glossary`; the Broadleaf side-car (28 206 records, prompt -`"1"`) imports into a version-2 store with its counts intact and exports -`cmp`-equal, and `--estimate` under prompt `"2"` prices the re-explanation -before it runs; `insights --word order` on the re-explained Broadleaf store -answers in under a second; `pnpm -r test`, typecheck and `./test.sh --ts` -green; the coverage table and the cost filled in this section. + version bump. *(`docs/vocabulary.md` is the design record VO-1…VO-16, + merged 2026-11-05 with #45.)* + +Definition of done — M19a and M19b on Broadleaf, where the demo images were +made; M19c on Spring PetClinic, the user's choice (2026-10-29): small enough +to read every answer, where re-explaining Broadleaf's 28 206 records was +not. The five `vocabulary.json` snapshots byte-identical to the package's +output; `codegraph vocabulary` on Broadleaf prints a commerce vocabulary +under `domain`; the tab and the coloured city reviewed as screenshots; +`explain` on the Java fixture, live and on the fake client, writes a +side-car whose every record a model wrote carries `words` and whose module +records carry `glossary`; `--estimate` prices a PetClinic run before it runs +and the live run's measurement replaces its per-block figures; the PetClinic +side-car (prompt `"2"`, 139 records) imports into a fresh version-2 store +with its counts intact and exports `cmp`-equal, a version-1 store migrates +(`store-v1.sql`, and the synthetic side-car at Broadleaf's scale); `insights +--word pet` on the PetClinic store answers in under a second; `pnpm -r test`, +typecheck and `./test.sh --ts` green; the coverage table and the cost filled +in this section. + +**Met (2026-11-12, main `4e3aa82`).** The Java-fixture live run is M20's +(above). PetClinic, on a copy of the paid store: 139 records imported (109 +operations, 76 by a model, every one with `words`; 25 types; 5 modules, each +with `glossary`: 301 word and 52 glossary entries), exported `cmp`-identical; +`insights --word pet` 0.14 s, 81 MB. `--estimate` had said 66 570 completion +tokens, the run took 96 356; refitted (§20.3 "Measured"), it now prices the +53 calls the function-word change made stale (#42) — 121 067 in, 55 665 out, +~$0.08 at the run's fitted prices — before any is sent. CI green on that +commit: the workspace's build, typecheck and tests, and the TypeScript +extractor's `cmp` gate that `./test.sh --ts` runs. ### 20.5 Deferred, explicitly @@ -6115,9 +6136,9 @@ builds `claudeCodeClient`; the seam's `clientFor` takes the whole resolution. | M18a | Ruby extractor — profile + skeleton | ✅ (2026-10-13, worktree `ruby-extractor`) `rb` profile in core (the eleventh: the module is the file, `class` and `module` are types below it, mixins are `traitUsage`, no interface — §19.2); `extractors/ruby/` in Rust on Prism 1.9.0 (`ruby-prism`, pinned), no Ruby to build or run; the core table distilled from RBS 4.2.0 `core/` with RBS's own parser (915 constants: 304 classes, 26 modules, 585 values); walking skeleton — files, classes and modules (the wrapper rule, one entity per declaring file, reopenings `attachedTo` their primary, a `String` patch attached to `/String`), methods and parameters, `require`/`require_relative` by path and by load root, superclasses and mixins resolved lexically, the `derived` import, stubs — → `fixtures/ruby/expected/model.jsonl` (24 files, 102 entities / 38 edges) byte-identical to core's encoder and profile-valid with zero issues; 60 cargo tests (50 unit, 10 contract: snapshot, CRLF + reversed creation order, the CLI contract) + 16 core gate tests; `codegraph validate` OK; `bin/codegraph-ruby`; `build.sh --ruby` (a 1.2 MB binary) / `test.sh --ruby` with the release-binary `cmp`; `ruby-test` written in CI, not yet run there | | M18b | Ruby extractor — model | ✅ (2026-10-13, worktree `ruby-extractor`) `field` (an instance variable, its `attr_*`, a Struct member: one entity `@x`) and `constant` (keyed by full path, with its literal `value`); `Struct.new` / `Data.define` / `Class.new` / `Module.new` assigned to a constant as types, a `Struct.new` superclass as a `generated` inheritance; constant references resolved lexically then through the ancestors; the core table extended with superclasses, mixins and methods (RBS 4.2.0: 915 constants, 23 mixins, 2428 methods) so lookup crosses from the corpus into the VM's classes; the invocation tiers of §19.4 — `declared` where the receiver's class is written, `derived` for typed locals, typed instance variables and the sole-library-ancestor attribution, the language resolved with no edge, untyped receivers dropped and counted; `access` with read/write, `throws`, comments, `sloc` + `cyclomatic`, literals; the Ruby 1.8 require idioms, `load`, `autoload`, shebang scripts; `--explain-dropped`, every drop with its line → `fixtures/ruby/expected/model.jsonl` (27 files, 154 entities / 136 edges; 152 sites, 77.0 % resolved) byte-identical to core's encoder and profile-valid with zero issues; `ruby` in the metrics pass and the fifth `model.metrics.jsonl` (86 of 88 joined, `sloc = ploc` on all 86); 101 cargo tests (90 unit, 11 contract) + 24 core gate tests; the fixture in the analyzer, city, navigator, CLI `validate` and metrics suites; `validate`, `analyze`, `navigator`, `city --layout` and `serve` run on it, City and Navigate screenshots reviewed | | M18c | Ruby extractor — audit + oracles + distribution | ✅ (2026-10-13, worktree `ruby-extractor`; CI not yet run) rake 13.2.1, rubygems 3.6.2, Mastodon 4.3.0 and rails 8.0.2 audited `validate`-clean (100 / 794 / 2 541 / 3 334 files; 77.8 / 54.4 / 31.2 / 57.0 % of sites resolved, Mastodon's `app/`+`lib/` 62.1 %; rails in 4.7 s). Seven defects found and fixed test-first: a library namespace the corpus reopens below dropped as `namespace-only` (592 `Rails.*` in Mastodon); class methods given by an `included` hook unseen (now read where literal — plain Ruby and ActiveSupport::Concern — and `derived`); a library mixin ignored as a class-side candidate (`validates` charged to ActiveRecord::Base); a per-type `dynamic` flag clouding both sides; a compact declaration's qualifier not read; a constant qualified by a subclass stubbed below ``; `--explain-dropped` not saying what decided a drop. Oracles: Packwerk 3.3.1 over Mastodon — 4 289 of its 4 335 cross-file references in the model (98.9 %), the rest the wrapper rule; rake booted under its own tests — 1 006 of 1 012 declared methods held by the VM on the same line, 1 533 of 2 829 observed calls already edges. The trace tool (`trace/codegraph_trace.rb`, one file) and `--trace`: `generated` `traitUsage`, `dynamic-candidate` invocations with `candidates`, no entity added — exercised end to end in a container and `validate`-clean. `fixtures/ruby` → 31 files, 181 entities / 153 edges, 177 sites, 76.3 %; metrics 106 of 109 joined. 119 cargo tests (107 unit, 12 contract) + 27 core gate tests. Distribution wired: `ruby-native` on four Unix runners, the release loop, `Formula/codegraph-ruby.rb`, the catalogue row; `docs/ruby-extractor.md` | -| M19a | Vocabulary — lexicon, split, artifact | ✅ (2026-10-26, five stacked PRs from #26, not yet merged; Broadleaf 76 310 entities → 3 381 terms in 0.29 s, 2.9 MB, its top ten a commerce vocabulary after 13 words joined the shared list) `Profile.lexicon` on the eleven profiles (keywords, conventional names, affixes, separators — the profile half of #19), METAMODEL §5 row, printed by `profiles --lang`; `@codegraph/vocabulary`: one idiom-parametrized splitter with the acronym rule on Unicode categories, four term classes as tags (never filters), role weights recorded in the artifact, scopes = the fold's containers; `codegraph vocabulary` report, `--level`/`--scope`/`--class`/`--drift FILE`; five `vocabulary.json` snapshots byte-identical, closure and determinism properties; the coverage table of §20.1 filled on fixtures, Broadleaf, codegraph, Mastodon, Plausible | -| M19b | Vocabulary — cloud, tab, city channel | ✅ (2026-10-26, three stacked PRs from #31, not yet merged; Broadleaf's cloud and its city raised by `order` are the demo images) deterministic spiral layout with an injected measurer and the no-overlap property; `--svg` with the fixture snapshot; `serve` builds `/vocabulary.json` and answers `/carriers.json?scope=&term=`; the sixth navigator tab (scope follows the selection, chips, table, carriers → reveal), literals pinned, types-only import; `vocabulary:` metric source through the CLI hook, city unchanged; the two demo images under `docs/` and the README section — the issue's fourth criterion | -| M19c | Vocabulary — glossary in the explanation | `words` on every insight block — the words of the unit's name, its parameters' and (for a type) its fields', each with `in`, `concern` (domain / technical / ambiguous), `sense`, `meaning`, in that entity's context, asked in the SAME call that explains it; `glossary` on the module block reconciling its types' entries with `polysemous`; `PROMPT_VERSION` 2, the words `.optional()` in the record schema so every existing side-car round-trips byte-identical — no new record type, no format change; the store at version 2 with the `insight_word` projection (rebuilt on `--import`); readers `insights --word/--glossary/--polysemy/--concerns`, `vocabulary --drift-insights`, `/glossary.json`, the entries shown as inferences in both panels; the Broadleaf re-explanation priced by `--estimate` and measured; `docs/vocabulary.md` | +| M19a | Vocabulary — lexicon, split, artifact | ✅ (2026-10-26, five stacked PRs from #26 — #26 merged to main 2026-10-27, #27–#30 with #46 on 2026-11-05; Broadleaf 76 310 entities → 3 381 terms in 0.29 s, 2.9 MB, its top ten a commerce vocabulary after 13 words joined the shared list) `Profile.lexicon` on the eleven profiles (keywords, conventional names, affixes, separators — the profile half of #19), METAMODEL §5 row, printed by `profiles --lang`; `@codegraph/vocabulary`: one idiom-parametrized splitter with the acronym rule on Unicode categories, four term classes as tags (never filters), role weights recorded in the artifact, scopes = the fold's containers; `codegraph vocabulary` report, `--level`/`--scope`/`--class`/`--drift FILE`; five `vocabulary.json` snapshots byte-identical, closure and determinism properties; the coverage table of §20.1 filled on fixtures, Broadleaf, codegraph, Mastodon, Plausible | +| M19b | Vocabulary — cloud, tab, city channel | ✅ (2026-10-26, three stacked PRs from #31, merged to main with #46 on 2026-11-05; Broadleaf's cloud and its city raised by `order` are the demo images) deterministic spiral layout with an injected measurer and the no-overlap property; `--svg` with the fixture snapshot; `serve` builds `/vocabulary.json` and answers `/carriers.json?scope=&term=`; the sixth navigator tab (scope follows the selection, chips, table, carriers → reveal), literals pinned, types-only import; `vocabulary:` metric source through the CLI hook, city unchanged; the two demo images under `docs/` and the README section — the issue's fourth criterion | +| M19c | Vocabulary — glossary in the explanation | ✅ (2026-11-12; merged 2026-11-05 with #46 and #42–#45; tested on Spring PetClinic in Broadleaf's place, §20.4) `words` on every insight block — the words of the unit's name, its parameters' and (for a type) its fields', each with `in`, `concern` (domain / technical / ambiguous), `sense`, `meaning`, in that entity's context, asked in the SAME call that explains it; `glossary` on the module block reconciling its types' entries with `polysemous`; `PROMPT_VERSION` 2, the words `.optional()` in the record schema so every existing side-car round-trips byte-identical — no new record type, no format change; the store at version 2 with the `insight_word` projection (rebuilt on `--import`); readers `insights --word/--glossary/--polysemy/--concerns`, `vocabulary --drift-insights`, `/glossary.json`, the entries shown as inferences in both panels; the PetClinic run priced by `--estimate` and measured; `docs/vocabulary.md` | | M20a | Model providers — the Claude Code adapter | ✅ (2026-11-10, 94 `@codegraph/llm` tests) `claudeCodeClient` in `@codegraph/llm` (§21.1): `claude -p --output-format json --json-schema --system-prompt --tools "" --safe-mode --no-session-persistence`, the user prompt on stdin, `structured_output` / `usage` / `total_cost_usd` / `modelUsage` read into the port's response, every failure classified into the port's one error type; `findClaudeCode` (option → `CLAUDE_CODE_PATH` → PATH → known install locations, pure) and `resolveProvider` with the fixed precedence; fake-process tests, the boundary test unchanged | | M20b | Model providers — wired and documented | ✅ (2026-11-10, live on Claude Code 2.1.322, Java fixture: 68 calls, 0 failed, 79 records — 70 explained, stamped `claude-sonnet-5-5`, 9 templated — decode-clean, eof `$1.03` for 307 896 + 54 688 tokens; the prompt side came in ≈ 2.7× the bare estimate — Claude Code's per-call scaffolding and schema, which the estimate now counts (§21.4): 280 481 estimated for the 307 896 billed) `--provider claude-code`, `--claude-path`, `--model` default per provider resolved before the plan (`sonnet`), the usage error naming the fix and the `--max-tokens` note; a live run on the Java fixture; `docs/cli.md`, `docs/insights.md`, README, CLAUDE.md and the website's explain pages name the port, the three adapters and the Anthropic API slot (§21.6) | From 5263bf94c1713282afef6656c5f655d1137339f0 Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Wed, 18 Nov 2026 10:24:09 +0000 Subject: [PATCH 2/2] feat(insights): keep words out of the chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dependent hashed its dependencies' whole fingerprints, words included, though no caller's prompt shows a callee's words. A correction to the word lists therefore re-explained everything above the units it touched: 53 calls on Spring PetClinic for 9 units whose words moved. Each unit now has two hashes. The fingerprint is stored on its records as before. The chain (chainOf) is every input but the words, over the dependencies' chains, and is never stored. A dependent hashes a dependency's chain, except a module, which reconciles its types' word entries into its glossary and so hashes their whole fingerprints (readsWordsOf). Source, comments, signatures, facts, model, depth and missing dependencies are all in the chain and still cascade. No store is re-explained for the switch: a record whose stamp matches the fold from before (stampedBeforeSplit) is reused. That stamp is compared, never written. A match means every transitive input is unchanged, words included. Measured on a copy of the PetClinic store: the old fold reproduces all 106 stamps (0 calls); today's words cost 53 calls as stamped and 10 on a store stamped under the split (~$0.08 against ~$0.02). An existing store still pays the 53 once. 9 new tests; six mutants of the rule are each killed. docs/insights.md IN-5, docs/vocabulary.md, the website's explanation and cost pages and PLAN §20.3/§23 follow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PKCVgyytH9LKzUTsUaKxeH --- PLAN.md | 46 ++++++- docs/insights.md | 28 +++-- docs/vocabulary.md | 15 ++- packages/insights/src/fingerprint.ts | 17 ++- packages/insights/src/plan.ts | 102 ++++++++++++---- packages/insights/src/run.ts | 4 +- packages/insights/test/fingerprint.test.ts | 25 +++- packages/insights/test/prompt.test.ts | 4 +- packages/insights/test/run.test.ts | 114 +++++++++++++++++- .../docs/explanation/explaining-bottom-up.md | 10 ++ website/content/docs/how-to/explain-cost.md | 4 +- 11 files changed, 322 insertions(+), 47 deletions(-) diff --git a/PLAN.md b/PLAN.md index c68f0f8..748a09f 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5682,7 +5682,9 @@ Their senses were grammar ("lookup criterion", "boolean predicate", prompt, ~56 k completion tokens, about $0.08 at the run's prices): 9 units directly (7 operations, 2 controllers with an `…_OR_…` view field), 44 through their dependencies. Nothing is lost before a run: the old records - stay, and the readers show their entries until they are replaced. + stay, and the readers show their entries until they are replaced. *(The 44 + are gone for stores stamped since: "As built — the words leave the + chain".)* - **The Java fixture's plan** is now 114 474 prompt and 52 415 completion tokens (was 114 483 and 52 900). @@ -5742,6 +5744,47 @@ The decisions: - **On PetClinic** `--polysemy` lists 14 words, was 16 (`owners` and `or` gone; `or` is no longer asked at all since the function words). +**As built — the words leave the chain (2026-11-15).** The function words +made 9 PetClinic units stale and 44 more only because a dependent hashed its +dependencies' whole fingerprints, words included — though no caller's prompt +shows a callee's words (`DependencySummary`: summary and concept). The user's +choice among four (keep the cascade; split the hash; a words-only re-ask; no +words in the fingerprint): split it. The decisions: + +- **Two hashes per unit.** `unitHashes` in `plan.ts` gives the fingerprint + (stored, as before) and the *chain* — `chainOf` in `fingerprint.ts`, every + input but the words, over the dependencies' chains; never stored. A + dependent hashes a dependency's chain unless its prompt reads that + dependency's words: `readsWordsOf(unit, dependency)`, true for a module and + its types only, since it reconciles their entries (`context.ts`). Its own + candidates are hashed as before; its types' whole fingerprints cover an + entry that changed under a candidate that did not. +- **What still cascades:** source, comments, signatures, facts, model, + depth, prompt version, a missing dependency — all in the chain. A words-only + change re-explains the units whose words moved and the modules above those + types. +- **No store re-explained for the switch.** A record stamped under the fold + before is reused while that stamp matches (`stampedBeforeSplit`, computed + beside the fingerprint, read for `reuse` only): a match means every + transitive input is unchanged, words included, so the split would reuse it + too. A leaf's two stamps are one. What is re-explained gets the new stamp; + nothing is rewritten on reuse. The cost: an old stamp cannot tell a + dependency's words from its source, so a store stamped before still pays + the 53 once. +- **Measured on PetClinic** (the paid store, on a copy; stamps restated under + the words as they were before the function words): the old fold's 106 + stamps reproduced exactly (0 calls); the function words then cost 53 calls + as stamped (121 067 in, 55 665 out, ~$0.08) and **10** stamped under the + split (7 operations, 2 types, 1 module; 26 758 in, 12 925 out, ~$0.02). +- **Tests:** a callee's words leave its callers and its type reused; a type's + words re-explain its module even when the module's candidates did not move; + a type depending on it and a module importing its module stay reused; a + source change still reaches every dependent; old stamps reused while + nothing changed, followed once more on a dependency's words, refused on a + source change. Six mutants (no module rule, the old fold, old stamps + refused, words in the chain, whole fingerprints in the chain, the run + stamping the chain) each fail at least one. + ### 20.4 Milestone split **M19a — the lexicon, the split, the artifact** (closes the profile half of #19) @@ -6261,6 +6304,7 @@ builds `claudeCodeClient`; the seam's `clientFor` takes the whole resolution. | Glossary tied to the entity (M19c) | each explained unit's block carries `words`: the words its name (and its parameters' or fields' names) is made of, with sense and concern in that entity's context, asked in the explanation call itself; the module block reconciles its types' words into `glossary`; scopes and the corpus roll up from the records | a meaning belongs to the entity that uses the word, and the context pack of that entity is the one place the pipeline has its source, facts and dependencies' explanations together; a scope has a vocabulary, not a meaning — the two earlier drafts (a standalone command over a term table; a second request per scope) asked at the wrong altitude | | Glossary storage (M19c) | the insights store, version 2: an `insight_word (id, word, in, concern, sense, confidence)` projection written with the record and rebuilt on `--import`, indexed on `word`; the side-car stays the one source of truth | bought, so it shares the insights' lifecycle (migrated, never regenerated); a projection makes `--word` an index lookup without a second authoritative copy — the M16b rule (what is queried is a column over the JSON, what is fetched is the block) | | Glossary wire format (M19c) | no new record type: `words`/`glossary` live inside `block`, `.optional()` in the record schema and required on the wire by `strictify`; `PROMPT_VERSION` 2 | M11 put the prompt version in every fingerprint so a better prompt re-explains what it improves — the designed case; a version-1 record decodes and re-encodes to its own bytes, so every existing side-car round-trips, and nothing is deleted by the bump | +| Words out of the chain (M19c) | every unit has two hashes: its fingerprint (stored) and its chain (the fingerprint without the words, over its dependencies' chains; never stored); a dependent hashes a dependency's chain, a module its types' whole fingerprints; a record stamped before is reused while that stamp matches | no caller's prompt shows a callee's words, only a module reads its types' — so a lexicon correction re-explains 10 PetClinic units instead of 53; a match on the old stamp implies one on the new, so no paid store is re-explained for the switch | | Port and adapters (M20) | `LlmClient` is the port; OpenRouter, Cloudflare AI Gateway and Claude Code are adapters behind it, each holding its transport behind one function; the Anthropic API is a named empty slot (§21.6), not a stub | the walk, the store and the CLI never learn a provider; a fourth adapter is one file and one entry in `providers.ts` | | Claude Code as a subprocess (M20) | the user's own `claude` binary in headless mode — `--safe-mode` (not `--bare`, which drops OAuth), tools off, no session, the system prompt replaced, the user prompt on stdin | the installation, login and version are the user's; no second SDK enters the workspace; argv has a 128 KB per-argument limit | | Provider precedence (M20) | `auto` takes the single configured provider; with several, OpenRouter, then Cloudflare, then Claude Code, the reason naming the flag for the others; `--model` defaults per provider (`sonnet` on Claude Code) | an exported key is a deliberate act, an installed CLI is ambient; `openai/gpt-5.6-luna` means nothing to Claude Code | diff --git a/docs/insights.md b/docs/insights.md index b7de0a8..131ad7d 100644 --- a/docs/insights.md +++ b/docs/insights.md @@ -385,13 +385,27 @@ Every record carries a sha256 over what it was computed from: the prompt version, the model slug, the level, the source slices, the comments, the signatures, a digest of the facts shown, the words its prompt asks to define and a module's glossary candidates (so a lexicon correction re-explains the -units whose words it changed, and through the next input what depends on them, -and another `--terms` exactly the modules whose cut moved; which candidates a -type defined is not hashed), the **fingerprints of the units it depended on**, -and the ids of dependencies that had no record. Merkle-style: -change one leaf's source and exactly its transitive dependents and containers -change; nothing else does. The explanation text is deliberately **not** -hashed — a non-deterministic answer must never cascade re-runs. +units whose words it changed, and another `--terms` exactly the modules whose +cut moved; which candidates a type defined is not hashed), **its +dependencies' hashes**, and the ids of dependencies that had no record. +Merkle-style: change one leaf's source and exactly its transitive dependents +and containers change; nothing else does. The explanation text is +deliberately **not** hashed — a non-deterministic answer must never cascade +re-runs. + +**Two hashes per unit.** A unit's *chain* is its fingerprint without the +words, over its dependencies' chains; it is never stored. A dependent hashes a +dependency's chain — except a module, which hashes its types' whole +fingerprints, because its prompt reconciles their word entries into its +glossary. A caller sees a callee's summary and concept, a type its +operations', never their words, so a words-only change re-explains the units +whose words moved and the modules above those types, and nothing else. On +Spring PetClinic, the function-word correction would cost 10 calls stamped +this way, against 53 when every dependent hashed its dependencies' whole +fingerprints (the fold before 2026-11). A record stamped under that fold is +still reused while its stamp matches — a match there means every transitive +input is unchanged, words included — so no store is re-explained for the +switch; it moves to the new stamp when it is next re-explained. A re-run plans `reuse` for every unit whose members' records match; `--force` overrides. Because a missing dependency is part of the fingerprint, a diff --git a/docs/vocabulary.md b/docs/vocabulary.md index 4c100d4..c5bcd0e 100644 --- a/docs/vocabulary.md +++ b/docs/vocabulary.md @@ -623,12 +623,15 @@ module's glossary *candidates* — never what a type said of them, and not which candidates a type defined — join the fingerprint inputs. So a lexicon correction re-explains exactly the units whose words it changed, and the same `--terms` reuses every module while another redoes exactly the modules whose -cut moved. Because a dependent hashes its dependencies' fingerprints (IN-5), -a words-only change cascades: adding the function words made 9 of -PetClinic's units stale directly and 53 of its 106 calls in all (about -$0.08). Whether a words-only change *should* cascade is an open design -question (PLAN.md §20.3); nothing is lost before a run, since the old records -stay and the readers show them until they are replaced. +cut moved. A words-only change does not cascade: a dependent hashes a +dependency's *chain*, its fingerprint without the words, since no caller's +prompt shows a callee's words — except a module, which hashes its types' +whole fingerprints because it reconciles their entries (IN-5). On PetClinic +the function words cost 10 calls on a store stamped this way, against 53 of +its 106 when every dependent hashed its dependencies' whole fingerprints. A +store stamped before the split is reused as stamped, so it still pays the 53 +once; nothing is lost before a run, since the old records stay and the +readers show them until they are replaced. **Cost, measured.** No new call; a completion grows by what it defines. The estimate's figures were fitted on a live prompt-2 run over Spring PetClinic diff --git a/packages/insights/src/fingerprint.ts b/packages/insights/src/fingerprint.ts index b056512..b6e20c3 100644 --- a/packages/insights/src/fingerprint.ts +++ b/packages/insights/src/fingerprint.ts @@ -12,6 +12,12 @@ import { PROMPT_VERSION, type Level } from "./schema.js"; * DELIBERATELY EXCLUDED: the explanation text itself. Two runs of the same * prompt can return different words, and if those words fed the fingerprint a * single non-deterministic answer would cascade re-runs up the whole graph. + * + * TWO HASHES PER UNIT. The fingerprint is stored on its records; the CHAIN is + * the same hash without the words asked, and is what a dependent hashes of a + * dependency whose words its prompt never shows (plan.ts `readsWordsOf`). So a + * lexicon correction re-explains the units whose words moved and the modules + * that reconcile them — not every caller above them. Never stored. */ export interface FingerprintInputs { @@ -25,7 +31,7 @@ export interface FingerprintInputs { readonly signatures: readonly string[]; /** A digest of the facts shown (calls, accesses, throws, fields, imports…). */ readonly factsDigest: string; - /** Fingerprints of the units this one depends on, sorted. */ + /** Per dependency, sorted: its fingerprint where this unit's prompt reads its words, else its chain. */ readonly dependencyFingerprints: readonly string[]; /** Dependencies that had NO record when this unit was explained, sorted — once one exists, redo. */ readonly missingDependencies: readonly string[]; @@ -34,8 +40,8 @@ export interface FingerprintInputs { /** * Per member, the words its prompt asks to define and a module's glossary * words: a function of the names and the lexicon, hashed so a lexicon - * correction re-explains the units whose words it changed — and, through - * `dependencyFingerprints`, everything that depends on them. + * correction re-explains the units whose words it changed. Left out of the + * chain: only a module's fingerprint carries its types' (theirs, whole). */ readonly words: readonly { readonly names: readonly { readonly identifier: string; readonly words: readonly string[] }[]; readonly glossary: readonly string[] }[]; } @@ -68,3 +74,8 @@ export function digestOf(value: unknown): string { export function fingerprintOf(inputs: FingerprintInputs): string { return digestOf({ promptVersion: PROMPT_VERSION, ...inputs }); } + +/** A unit as its word-blind dependents see it: every input but the words, over its dependencies' chains. */ +export function chainOf(inputs: Omit): string { + return digestOf({ promptVersion: PROMPT_VERSION, chain: true, ...inputs }); +} diff --git a/packages/insights/src/plan.ts b/packages/insights/src/plan.ts index c41de83..a4da404 100644 --- a/packages/insights/src/plan.ts +++ b/packages/insights/src/plan.ts @@ -1,5 +1,5 @@ import { contextPackFor, type ContextEnv, type ContextPack } from "./context.js"; -import { fingerprintOf } from "./fingerprint.js"; +import { chainOf, fingerprintOf } from "./fingerprint.js"; import type { Unit, WalkPlan } from "./order.js"; import { estimateCompletionTokens, estimateTokens, renderPrompts, type Prompt } from "./prompt.js"; import { sourceOf, type RecordSource } from "./records.js"; @@ -12,6 +12,7 @@ import type { TemplateKind } from "./units.js"; * * template a trivial member; the block is computed, no model call * reuse every member already has a record with THIS fingerprint + * (or with the stamp from before the split, `stampedBeforeSplit`) * skip-scope outside `--scope` and not reusable; dependents see it as * NOT EXPLAINED * skip-budget `--max-calls` is spent; this and every later call is skipped, @@ -22,7 +23,7 @@ import type { TemplateKind } from "./units.js"; * a plain map of records, which is copied into one. * * Fingerprints are exact here — they depend on inputs and on dependency - * fingerprints, never on explanation text — so `reuse` is decided correctly + * hashes, never on explanation text — so `reuse` is decided correctly * before any call. Token counts are ESTIMATES: prompts are rendered against * the records that exist now, and a dependency explained later in this run * will make the real prompt a little longer. @@ -53,7 +54,8 @@ export interface LevelEstimate { export interface RunPlan { readonly steps: readonly PlanStep[]; - readonly fingerprints: ReadonlyMap; + /** Per unit id, its plan-time hashes: what the run's records and dependents hash. */ + readonly hashes: ReadonlyMap; readonly estimates: { readonly calls: number; readonly promptTokens: number; @@ -95,15 +97,30 @@ export function modelFor(level: Level, models: PlanOptions["models"]): string { return level === "operation" ? models.leaf : models.rollup; } -/** The fingerprint of a unit from its pack and its dependencies' fingerprints. */ -export function unitFingerprint( - pack: ContextPack, - model: string, - depth: number, - dependencyFingerprints: readonly string[], - missingDependencies: readonly string[], -): string { - return fingerprintOf({ +/** A planned unit's two hashes (fingerprint.ts): the one its records carry, and the one a word-blind dependent takes. */ +export interface UnitHashes { + readonly level: Level; + readonly fingerprint: string; + readonly chain: string; +} + +/** + * Whether a unit's prompt shows a dependency's words — then it hashes that + * dependency's whole fingerprint, else its chain. Only a module does, of its + * types: it reconciles their entries into its glossary (context.ts). A caller + * sees a callee's summary and concept, a type its operations', never words. + */ +export function readsWordsOf(unit: Level, dependency: Level): boolean { + return unit === "module" && dependency === "type"; +} + +/** A unit's dependencies as already hashed, in `unit.deps` order. */ +export function dependenciesOf(unit: Unit, hashes: ReadonlyMap): readonly UnitHashes[] { + return unit.deps.map((d) => hashes.get(d) ?? { level: unit.level, fingerprint: "", chain: "" }); +} + +function inputsOf(pack: ContextPack, model: string, depth: number, missingDependencies: readonly string[]) { + return { level: pack.level, members: pack.unit.members, model, @@ -111,22 +128,56 @@ export function unitFingerprint( comments: pack.comments, signatures: pack.signatures, factsDigest: pack.factsDigest, - dependencyFingerprints: [...dependencyFingerprints].sort(), // A dependency unit that had no record when this unit was explained is // part of what it was explained WITHOUT; once it exists, redo the unit. // At plan time that is a skipped dependency; at run time (run.ts) it is // also a failed one — the record carries the run-time value. missingDependencies: [...missingDependencies].sort(), depth, - words: pack.words, - }); + }; +} + +/** A unit's hashes from its pack and its dependencies' hashes. */ +export function unitHashes( + pack: ContextPack, + model: string, + depth: number, + dependencies: readonly UnitHashes[], + missingDependencies: readonly string[], +): UnitHashes { + const inputs = inputsOf(pack, model, depth, missingDependencies); + return { + level: pack.level, + fingerprint: fingerprintOf({ + ...inputs, + dependencyFingerprints: dependencies.map((d) => (readsWordsOf(pack.level, d.level) ? d.fingerprint : d.chain)).sort(), + words: pack.words, + }), + chain: chainOf({ ...inputs, dependencyFingerprints: dependencies.map((d) => d.chain).sort() }), + }; +} + +/** + * The fingerprint as stamped before the split (2026-11): a unit hashed its + * dependencies' whole fingerprints. Read for `reuse` only, never written: a + * match means every transitive input is unchanged, words included, so the + * split would reuse the record too. A leaf's is its fingerprint. + */ +export function stampedBeforeSplit( + pack: ContextPack, + model: string, + depth: number, + dependencyFingerprints: readonly string[], + missingDependencies: readonly string[], +): string { + return fingerprintOf({ ...inputsOf(pack, model, depth, missingDependencies), dependencyFingerprints: [...dependencyFingerprints].sort(), words: pack.words }); } /** * The scope of a RETRY: the units a side-car recorded as failed, plus their * DIRECT dependents — explained without them, so stale the moment they exist. * Nothing further up moves: a unit hashes its dependencies' plan-time - * fingerprints, which a failure never changed. Matching is by member, so a + * hashes, which a failure never changed. Matching is by member, so a * failure still finds its unit after a re-extraction regrouped a cycle. */ export function retryScope(failures: readonly FailureRecord[], walk: WalkPlan): (unit: Unit) => boolean { @@ -153,7 +204,8 @@ export function planRun( ): RunPlan { const records = sourceOf(existing); const contextEnv: ContextEnv = { ...env, records, depth: options.depth, maxLines: options.maxLines, terms: options.terms }; - const fingerprints = new Map(); + const hashes = new Map(); + const before = new Map(); const steps: PlanStep[] = []; const byLevel: Record = { operation: { calls: 0, promptTokens: 0, completionTokens: 0, units: 0 }, @@ -177,20 +229,26 @@ export function planRun( for (const unit of walk.units) { const model = modelFor(unit.level, options.models); const pack = contextPackFor(unit, contextEnv); - const depFingerprints = unit.deps.map((d) => fingerprints.get(d) ?? ""); const missing = unit.deps.filter((d) => { const status = statusOf.get(d); return status === "skip-scope" || status === "skip-budget"; }); - const fingerprint = unitFingerprint(pack, model, options.depth, depFingerprints, missing); - fingerprints.set(unit.id, fingerprint); + const own = unitHashes(pack, model, options.depth, dependenciesOf(unit, hashes), missing); + const { fingerprint } = own; + hashes.set(unit.id, own); + const stamped = + unit.deps.length === 0 ? fingerprint : stampedBeforeSplit(pack, model, options.depth, unit.deps.map((d) => before.get(d) ?? ""), missing); + before.set(unit.id, stamped); byLevel[unit.level].units += 1; const template = templateOf(env, unit); const reusable = !options.force && // Fingerprints alone: a plan that reuses everything reads no block (M16b). - unit.members.every((id) => records.fingerprint(id) === fingerprint); + unit.members.every((id) => { + const held = records.fingerprint(id); + return held === fingerprint || held === stamped; + }); let status: StepStatus; let prompts: readonly Prompt[] = []; @@ -220,7 +278,7 @@ export function planRun( return { steps, - fingerprints, + hashes, estimates: { calls: steps.reduce((n, s) => n + s.calls, 0), promptTokens: steps.reduce((n, s) => n + s.promptTokens, 0), diff --git a/packages/insights/src/run.ts b/packages/insights/src/run.ts index c2832f7..877edee 100644 --- a/packages/insights/src/run.ts +++ b/packages/insights/src/run.ts @@ -1,7 +1,7 @@ import type { z } from "zod"; import { contextPackFor, glossaryAsked, type ContextEnv, type MemberPack } from "./context.js"; import type { Unit } from "./order.js"; -import { unitFingerprint, type PlanEnv, type PlanStep, type RunPlan } from "./plan.js"; +import { dependenciesOf, unitHashes, type PlanEnv, type PlanStep, type RunPlan } from "./plan.js"; import { renderPrompts, type Prompt } from "./prompt.js"; import { bookOf, type RecordBook } from "./records.js"; import { @@ -339,7 +339,7 @@ export async function executeRun( const dep = env.unitOf.get(d); return dep === undefined || dep.members.some((member) => !explained(member)); }); - const fingerprint = unitFingerprint(pack, step.model, options.depth, unit.deps.map((d) => plan.fingerprints.get(d) ?? ""), missing); + const { fingerprint } = unitHashes(pack, step.model, options.depth, dependenciesOf(unit, plan.hashes), missing); const produced: InsightRecord[] = []; let calls = 0; try { diff --git a/packages/insights/test/fingerprint.test.ts b/packages/insights/test/fingerprint.test.ts index 20c8175..8511877 100644 --- a/packages/insights/test/fingerprint.test.ts +++ b/packages/insights/test/fingerprint.test.ts @@ -1,6 +1,6 @@ import fc from "fast-check"; import { describe, expect, it } from "vitest"; -import { canonicalJson, digestOf, fingerprintOf, type FingerprintInputs } from "../src/fingerprint.js"; +import { canonicalJson, chainOf, digestOf, fingerprintOf, type FingerprintInputs } from "../src/fingerprint.js"; const BASE: FingerprintInputs = { level: "operation", @@ -55,6 +55,29 @@ describe("fingerprintOf", () => { } }); + it("chainOf hashes every input but the words: no other change escapes it", () => { + const { words: _, ...rest } = BASE; + const variants: Omit[] = [ + { ...rest, sources: ["int f() { return 2; }"] }, + { ...rest, comments: ["doc"] }, + { ...rest, signatures: ["f(int)"] }, + { ...rest, factsDigest: digestOf({ calls: ["g"] }) }, + { ...rest, dependencyFingerprints: ["a".repeat(64)] }, + { ...rest, missingDependencies: ["java:p/B.g()"] }, + { ...rest, model: "other" }, + { ...rest, depth: 2 }, + { ...rest, level: "type" }, + ]; + const seen = new Set([chainOf(rest), fingerprintOf(BASE)]); + expect(seen.size).toBe(2); + for (const v of variants) { + const chain = chainOf(v); + expect(chain).toMatch(/^[0-9a-f]{64}$/); + expect(seen.has(chain)).toBe(false); + seen.add(chain); + } + }); + it("Merkle: changing a leaf changes exactly its transitive dependents", () => { // chain c → b → a (c depends on b, b on a); d independent const fp = (id: string, source: string, deps: string[]) => diff --git a/packages/insights/test/prompt.test.ts b/packages/insights/test/prompt.test.ts index db657e5..14cdf4d 100644 --- a/packages/insights/test/prompt.test.ts +++ b/packages/insights/test/prompt.test.ts @@ -3,7 +3,7 @@ import { contextPackFor, type ContextEnv } from "../src/context.js"; import { buildWalk } from "../src/order.js"; import { estimateTokens, renderPrompts } from "../src/prompt.js"; import { memoryBook } from "../src/records.js"; -import { unitFingerprint } from "../src/plan.js"; +import { unitHashes } from "../src/plan.js"; import type { InsightRecord, OperationBlock, TypeBlock, WordEntry } from "../src/schema.js"; import { createSourceReader, mapReader } from "../src/source.js"; import { edge, field, graphOf, method, pkg, prepared, toySpeller, type } from "./fixture.js"; @@ -298,7 +298,7 @@ describe("words to define (PLAN.md §20.3)", () => { }); it("fingerprints the words asked and the glossary cut, never what the types said", () => { - const fp = (pack: ReturnType["pack"]>) => unitFingerprint(pack, "m", 1, [], []); + const fp = (pack: ReturnType["pack"]>) => unitHashes(pack, "m", 1, [], []).fingerprint; const base = fp(shop().pack(SHOP)); const said = fp(shop([typeRecord(LINE, [entry("order", "a purchase", "Bought.")])]).pack(SHOP)); expect(said).toBe(base); diff --git a/packages/insights/test/run.test.ts b/packages/insights/test/run.test.ts index eb92ef1..a52d95b 100644 --- a/packages/insights/test/run.test.ts +++ b/packages/insights/test/run.test.ts @@ -1,13 +1,15 @@ import { describe, expect, it } from "vitest"; import type { Edge, Entity } from "@codegraph/core"; +import { contextPackFor, type Speller } from "../src/context.js"; +import { fingerprintOf } from "../src/fingerprint.js"; import { buildWalk } from "../src/order.js"; -import { planRun, retryScope, type PlanEnv, type PlanOptions } from "../src/plan.js"; +import { planRun, retryScope, type PlanEnv, type PlanOptions, type RunPlan } from "../src/plan.js"; import { COMPLETION_TOKENS_PER_BLOCK, COMPLETION_TOKENS_PER_GLOSSARY_ENTRY, COMPLETION_TOKENS_PER_WORD, estimateTokens } from "../src/prompt.js"; import { memoryBook, type RecordBook } from "../src/records.js"; import { executeRun, type Completer, type CompletionRequest } from "../src/run.js"; import { responseJsonSchema, type Block, type FailureRecord, type InsightRecord, type ModuleBlock, type OperationBlock, type TypeBlock } from "../src/schema.js"; import { createSourceReader, mapReader } from "../src/source.js"; -import { edge, field, graphOf, method, pkg, prepared, toySpeller, type } from "./fixture.js"; +import { edge, field, graphOf, method, packageCorpus, pkg, prepared, toySpeller, type } from "./fixture.js"; const P = "java:p"; const T = "java:p/T"; @@ -284,6 +286,114 @@ describe("planRun", () => { }); }); +/** A lexicon correction in miniature: one entity's name now spells one more word, every other entity's the same. */ +function respelled(speller: Speller, id: string, word: string): Speller { + return { ...speller, words: (entity) => (entity === id ? [...speller.words(entity), word] : speller.words(entity)) }; +} + +const statusOf = (plan: RunPlan): Map => new Map(plan.steps.map((s) => [s.unit.id, s.status])); + +describe("a words-only change (PLAN §20.3): stale where a prompt reads the words, nowhere else", () => { + it("re-explains the operation whose words moved, not its callers nor its type, which see its summary only", async () => { + const first = await run(new Map()); + const existing = new Map(first.result.records.map((r) => [r.id, r])); + const { walk, env } = corpus(); + const status = statusOf(planRun(walk, existing, { ...env, speller: respelled(env.speller, m("h"), "extra") }, OPTIONS)); + expect(status.get(m("h"))).toBe("llm"); + expect(status.get(m("g"))).toBe("reuse"); + expect(status.get(m("f"))).toBe("reuse"); + expect(status.get(T)).toBe("reuse"); + expect(status.get(P)).toBe("reuse"); + }); + + it("re-explains a type whose words moved and its module, which reconciles its types' words — even when its own candidates did not move", async () => { + const first = await run(new Map()); + const existing = new Map(first.result.records.map((r) => [r.id, r])); + const { walk, env } = corpus(); + // `total` is already the module's one candidate (the field's word): only the type's own entry changes. + const status = statusOf(planRun(walk, existing, { ...env, speller: respelled(env.speller, T, "total") }, OPTIONS)); + expect(status.get(T)).toBe("llm"); + expect(status.get(P)).toBe("llm"); + for (const op of [m("f"), m("g"), m("h")]) expect(status.get(op)).toBe("reuse"); + }); + + it("a type that depends on it and a module that imports its module stay reused", async () => { + const graph = packageCorpus(2, [[1, 0]]); + const { facts, units } = prepared(graph); + const walk = buildWalk(units, graph); + const env: PlanEnv = { graph, facts, units, reader: createSourceReader(mapReader(new Map())), unitOf: walk.unitOf, speller: toySpeller(graph) }; + const C0 = "java:p0/C"; + const C1 = "java:p1/C"; + expect(walk.unitOf.get(C1)?.deps).toContain(C0); + expect(walk.unitOf.get("java:p1")?.deps).toContain("java:p0"); + const cold = planRun(walk, new Map(), env, OPTIONS); + const first = await executeRun(cold, env, new Map(), fakeCompleter(), { maxScc: 12, depth: 1, maxLines: 100, terms: 60 }, { concurrency: 1 }); + const existing = new Map(first.records.map((r) => [r.id, r])); + const status = statusOf(planRun(walk, existing, { ...env, speller: respelled(env.speller, C0, "extra") }, OPTIONS)); + expect(status.get(C0)).toBe("llm"); + expect(status.get("java:p0")).toBe("llm"); + expect(status.get(C1)).toBe("reuse"); + expect(status.get("java:p1")).toBe("reuse"); + }); + + it("a source change still reaches every transitive dependent", async () => { + const first = await run(new Map()); + const existing = new Map(first.result.records.map((r) => [r.id, r])); + const { walk, env } = corpus(); + const edited = SOURCE.replace("return 1;", "return 2;"); + const status = statusOf(planRun(walk, existing, { ...env, reader: createSourceReader(mapReader(new Map([["T.java", edited]]))) }, OPTIONS)); + for (const id of [m("h"), m("g"), m("f"), T, P]) expect(status.get(id)).toBe("llm"); + }); +}); + +describe("records stamped before the split (every dependent hashed its dependencies' whole fingerprints)", () => { + /** The previous fold, restated here rather than read from the plan: a unit hashed its dependencies' fingerprints, words included. */ + function stampedBefore(records: ReadonlyMap): Map { + const { walk, env } = corpus(); + const contextEnv = { ...env, records: memoryBook([]), depth: 1, maxLines: 100, terms: 60 }; + const before = new Map(); + for (const unit of walk.units) { + const pack = contextPackFor(unit, contextEnv); + const { sources, comments, signatures, factsDigest, words } = pack; + const model = unit.level === "operation" ? OPTIONS.models.leaf : OPTIONS.models.rollup; + const dependencyFingerprints = unit.deps.map((d) => before.get(d) ?? "").sort(); + before.set(unit.id, fingerprintOf({ level: unit.level, members: unit.members, model, sources, comments, signatures, factsDigest, dependencyFingerprints, missingDependencies: [], depth: 1, words })); + } + return new Map([...records].map(([id, r]) => [id, { ...r, fingerprint: before.get(walk.unitOf.get(id)?.id ?? "") ?? "" }])); + } + + it("are reused while nothing changed: a store paid for before the split is not re-explained for it", async () => { + const first = await run(new Map()); + const records = new Map(first.result.records.map((r) => [r.id, r])); + const stamped = stampedBefore(records); + // Not vacuous: every unit with a dependency is stamped differently from now on. + expect([...stamped.values()].filter((r) => r.fingerprint !== records.get(r.id)?.fingerprint).map((r) => r.id).sort()).toEqual([m("f"), m("g"), P, T].sort()); + const second = await run(stamped); + expect(second.completer.requests).toHaveLength(0); + expect(second.plan.estimates.byStatus.reuse).toBe(5); + }); + + it("follow a dependency's words once more, since that stamp cannot tell them apart; what is re-explained moves to the split", async () => { + const first = await run(new Map()); + const stamped = stampedBefore(new Map(first.result.records.map((r) => [r.id, r]))); + const { walk, env } = corpus(); + const status = statusOf(planRun(walk, stamped, { ...env, speller: respelled(env.speller, m("h"), "extra") }, OPTIONS)); + expect(status.get(m("h"))).toBe("llm"); + expect(status.get(m("g"))).toBe("llm"); + expect(status.get(m("f"))).toBe("llm"); + expect(status.get(m("getTotal"))).toBe("template"); + }); + + it("a stale stamp from before is not reused: a source change still re-explains", async () => { + const first = await run(new Map()); + const stamped = stampedBefore(new Map(first.result.records.map((r) => [r.id, r]))); + const { walk, env } = corpus(); + const edited = SOURCE.replace("return 1;", "return 2;"); + const status = statusOf(planRun(walk, stamped, { ...env, reader: createSourceReader(mapReader(new Map([["T.java", edited]]))) }, OPTIONS)); + for (const id of [m("h"), m("g"), m("f"), T, P]) expect(status.get(id)).toBe("llm"); + }); +}); + describe("executeRun", () => { it("produces one record per unit member in walk order, layer hooks in order, and carries usage", async () => { const { result, emitted, layers, completer } = await run(new Map()); diff --git a/website/content/docs/explanation/explaining-bottom-up.md b/website/content/docs/explanation/explaining-bottom-up.md index 7fe52b9..90f8f5d 100644 --- a/website/content/docs/explanation/explaining-bottom-up.md +++ b/website/content/docs/explanation/explaining-bottom-up.md @@ -177,6 +177,16 @@ Including the *missing* dependencies in the fingerprint is the other half. A uni explained while its callee had failed, or was out of scope, is redone once the callee exists — automatically, because its inputs genuinely changed. +The words a prompt asks the model to define are hashed too, but a dependent +does not inherit them. Each unit has a second hash, its *chain* — the +fingerprint without the words — and that is what a caller hashes of its +callee, since no caller's prompt shows a callee's words. A module is the +exception: it reconciles its types' word entries into its glossary, so it +hashes their whole fingerprints. A correction to the word lists therefore +re-explains the units whose words moved and the modules above those types — +10 calls on Spring PetClinic, where hashing whole fingerprints all the way up +would have cost 53. + ## IN-6 · Budget controls, because this one costs money This is the only command that opens a socket and the only one that costs diff --git a/website/content/docs/how-to/explain-cost.md b/website/content/docs/how-to/explain-cost.md index 08aff47..2f8b0cb 100644 --- a/website/content/docs/how-to/explain-cost.md +++ b/website/content/docs/how-to/explain-cost.md @@ -149,7 +149,9 @@ A re-run reuses every unit whose fingerprint still matches. Because the fingerprint covers the unit's inputs *and* its dependencies' fingerprints, changing one method's source re-explains exactly its transitive dependents and containers. Explanation text is deliberately not hashed, so a differently-worded -answer never cascades. +answer never cascades. Nor does a change to the words a unit is asked to define: +it re-explains that unit, and the module above it when it is a type, never its +callers. ```bash codegraph explain model.jsonl --src src/main/java --force