Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 91 additions & 26 deletions PLAN.md

Large diffs are not rendered by default.

28 changes: 21 additions & 7 deletions docs/insights.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 9 additions & 6 deletions docs/vocabulary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 14 additions & 3 deletions packages/insights/src/fingerprint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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[];
Expand All @@ -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[] }[];
}
Expand Down Expand Up @@ -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<FingerprintInputs, "words">): string {
return digestOf({ promptVersion: PROMPT_VERSION, chain: true, ...inputs });
}
102 changes: 80 additions & 22 deletions packages/insights/src/plan.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -53,7 +54,8 @@ export interface LevelEstimate {

export interface RunPlan {
readonly steps: readonly PlanStep[];
readonly fingerprints: ReadonlyMap<string, string>;
/** Per unit id, its plan-time hashes: what the run's records and dependents hash. */
readonly hashes: ReadonlyMap<string, UnitHashes>;
readonly estimates: {
readonly calls: number;
readonly promptTokens: number;
Expand Down Expand Up @@ -95,38 +97,87 @@ 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<string, UnitHashes>): 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,
sources: pack.sources,
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 {
Expand All @@ -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<string, string>();
const hashes = new Map<string, UnitHashes>();
const before = new Map<string, string>();
const steps: PlanStep[] = [];
const byLevel: Record<Level, LevelEstimate> = {
operation: { calls: 0, promptTokens: 0, completionTokens: 0, units: 0 },
Expand All @@ -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[] = [];
Expand Down Expand Up @@ -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),
Expand Down
4 changes: 2 additions & 2 deletions packages/insights/src/run.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
25 changes: 24 additions & 1 deletion packages/insights/test/fingerprint.test.ts
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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<FingerprintInputs, "words">[] = [
{ ...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[]) =>
Expand Down
4 changes: 2 additions & 2 deletions packages/insights/test/prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<ReturnType<typeof shop>["pack"]>) => unitFingerprint(pack, "m", 1, [], []);
const fp = (pack: ReturnType<ReturnType<typeof shop>["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);
Expand Down
Loading
Loading