@seanhogg/builderforce-memory 2026.10.32 → 2026.10.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/knowledge/index.d.ts +2 -1
  2. package/dist/knowledge/index.d.ts.map +1 -1
  3. package/dist/knowledge/index.js +1 -1
  4. package/dist/knowledge/index.js.map +1 -1
  5. package/dist/knowledge/judge.d.ts +14 -1
  6. package/dist/knowledge/judge.d.ts.map +1 -1
  7. package/dist/knowledge/judge.js +26 -3
  8. package/dist/knowledge/judge.js.map +1 -1
  9. package/dist/knowledge/owedFiles.d.ts +68 -0
  10. package/dist/knowledge/owedFiles.d.ts.map +1 -0
  11. package/dist/knowledge/owedFiles.js +86 -0
  12. package/dist/knowledge/owedFiles.js.map +1 -0
  13. package/dist/knowledge/plan.d.ts +22 -3
  14. package/dist/knowledge/plan.d.ts.map +1 -1
  15. package/dist/knowledge/plan.js +43 -18
  16. package/dist/knowledge/plan.js.map +1 -1
  17. package/dist/knowledge/review.d.ts +3 -1
  18. package/dist/knowledge/review.d.ts.map +1 -1
  19. package/dist/knowledge/review.js +43 -13
  20. package/dist/knowledge/review.js.map +1 -1
  21. package/dist/knowledge/reviewCompare.d.ts +6 -5
  22. package/dist/knowledge/reviewCompare.d.ts.map +1 -1
  23. package/dist/knowledge/reviewCompare.js +27 -16
  24. package/dist/knowledge/reviewCompare.js.map +1 -1
  25. package/dist/knowledge/reviewModel.d.ts +8 -2
  26. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  27. package/dist/knowledge/sources.d.ts +5 -7
  28. package/dist/knowledge/sources.d.ts.map +1 -1
  29. package/dist/knowledge/sources.js +5 -12
  30. package/dist/knowledge/sources.js.map +1 -1
  31. package/package.json +3 -3
  32. package/src/knowledge/index.ts +3 -1
  33. package/src/knowledge/judge.clamp.test.ts +61 -0
  34. package/src/knowledge/judge.ts +27 -3
  35. package/src/knowledge/owedFiles.ts +108 -0
  36. package/src/knowledge/plan.ts +61 -19
  37. package/src/knowledge/review.estimate.test.ts +112 -0
  38. package/src/knowledge/review.owed.test.ts +379 -0
  39. package/src/knowledge/review.ts +39 -14
  40. package/src/knowledge/review.upgrade.test.ts +86 -21
  41. package/src/knowledge/reviewCompare.ts +26 -14
  42. package/src/knowledge/reviewModel.ts +8 -2
  43. package/src/knowledge/sources.ts +5 -14
  44. package/src/knowledge/testkit.test-util.ts +24 -1
@@ -27,15 +27,24 @@ const MAX_NAME = 120;
27
27
  export const MAX_QUOTE_CHARS = 300;
28
28
  export const MAX_QUOTE_LINES = 3;
29
29
 
30
- /** A quote as it may be stored: at most {@link MAX_QUOTE_LINES} lines and {@link MAX_QUOTE_CHARS} characters, trimmed. */
30
+ /** The first `n` lines of `text`, joined with `\n` (line endings normalised). */
31
+ const firstLines = (text: string, n: number): string => text.split(/\r?\n/).slice(0, n).join('\n');
32
+
33
+ /**
34
+ * A quote as it may be stored: at most {@link MAX_QUOTE_LINES} lines and {@link MAX_QUOTE_CHARS}
35
+ * characters, trimmed at both ends — also after the cut, so clamping a clamped quote changes nothing.
36
+ */
31
37
  export function clampQuote(text: string): string {
32
- return text.split(/\r?\n/).slice(0, MAX_QUOTE_LINES).join('\n').trim().slice(0, MAX_QUOTE_CHARS);
38
+ return firstLines(text, MAX_QUOTE_LINES).trim().slice(0, MAX_QUOTE_CHARS).trimEnd();
33
39
  }
34
40
 
35
41
  const QUOTE_SEPARATOR = ' — “';
42
+ const QUOTE_CLOSE = '”';
43
+ /** The longest a claim's own text may be: subject, predicate and object at {@link MAX_TERM} characters each, joined by two spaces. */
44
+ export const MAX_CLAIM_TEXT_CHARS = 3 * MAX_TERM + 2;
36
45
 
37
46
  /** A claim's stored `content`: its text, then its quote when it has one. */
38
- export const claimContent = (text: string, quote: string): string => (quote ? `${text}${QUOTE_SEPARATOR}${quote}”` : text);
47
+ export const claimContent = (text: string, quote: string): string => (quote ? `${text}${QUOTE_SEPARATOR}${quote}${QUOTE_CLOSE}` : text);
39
48
 
40
49
  /**
41
50
  * The text a claim is compared by: `subject predicate object`, the form a first run hands the
@@ -47,6 +56,21 @@ export function claimTextOf(content: string): string {
47
56
  return i < 0 ? content : content.slice(0, i);
48
57
  }
49
58
 
59
+ /**
60
+ * A claim's `content` as a host may store it (privacy: a judgement, never a document): the
61
+ * text bounded to {@link MAX_CLAIM_TEXT_CHARS} characters (its terms may span lines, as the
62
+ * judge validates them), the quote it rests on by {@link clampQuote} — so a long claim is not
63
+ * cut mid-quote. Content the judge produced passes unchanged; an empty quote is dropped (the
64
+ * canonical {@link claimContent} form); clamping a clamped claim changes nothing.
65
+ */
66
+ export function clampClaim(content: string): string {
67
+ const text = claimTextOf(content).slice(0, MAX_CLAIM_TEXT_CHARS);
68
+ const at = content.indexOf(QUOTE_SEPARATOR);
69
+ if (at < 0) return text;
70
+ const rest = content.slice(at + QUOTE_SEPARATOR.length);
71
+ return claimContent(text, clampQuote(rest.endsWith(QUOTE_CLOSE) ? rest.slice(0, -QUOTE_CLOSE.length) : rest));
72
+ }
73
+
50
74
  export interface JudgeBudget {
51
75
  modelCalls: number;
52
76
  deadline: number;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * knowledge/owedFiles.ts — the extractor entry of a root's manifest (PRD 38 §4.3): the
3
+ * extractor version the files were last reviewed with, and the files still OWED a
4
+ * re-extraction under it. Planning reads it, every run writes it — aborted or not.
5
+ *
6
+ * A file is owed when the stored version is not {@link EXTRACTOR_VERSION} (every file, once),
7
+ * or when an earlier run left it unfinished (a read error, an abort before it, the budget, a
8
+ * failed judge call). Owed is independent of the file's content: a content-changed file left
9
+ * unfinished is recorded too — under any version — so its debt survives the bytes reverting
10
+ * to the manifest hash. A path the plan no longer lists (ignored, claimed by no pack, a run
11
+ * that aborted before retiring it) stays owed while the files manifest still holds it; once
12
+ * retired it drops out.
13
+ *
14
+ * Stored under {@link extractorManifestKey} as fingerprints: `{ id: 'version', hash: '<version>' }`
15
+ * plus one `{ id: 'owed:<path>', hash: '<calls>' }` per owed file, where `<calls>` is the
16
+ * decimal number of model calls the file is still expected to cost (the plan's estimate):
17
+ * • a file the run reached but did not finish: the sections the budget or a failed call left
18
+ * unjudged; for a content-changed file, every section it had to judge plus what it was
19
+ * already owed (a revert to the manifest bytes re-judges them all);
20
+ * • a file not reached (an abort) or unreadable: what it was already owed at, {@link owedCalls}
21
+ * — the recorded count, plus the one new section a re-extraction may add while the stored
22
+ * version is not today's. A read error learns nothing about the file, so a permanently
23
+ * unreadable file is the only file re-read and its known debt is neither erased nor invented.
24
+ * An old `[{ id: 'version', … }]` value is `{ version, owed: none }`; a missing or empty value
25
+ * is an upgrade — every file owed one call.
26
+ */
27
+
28
+ import type { IngestManifest } from '../ingest/types.js';
29
+ import { compareStr } from './refs.js';
30
+ import { EXTRACTOR_VERSION, extractorManifestKey } from './sources.js';
31
+
32
+ const VERSION_ID = 'version';
33
+ const OWED_PREFIX = 'owed:';
34
+ /** What a version upgrade costs per file: the one new section a re-extraction may add (an upper bound). */
35
+ const UPGRADE_CALLS = 1;
36
+
37
+ export interface ExtractorState {
38
+ /** The version the files were last reviewed with; undefined when never recorded. */
39
+ version: number | undefined;
40
+ /** Paths a previous run left unfinished under that version → model calls each still costs. */
41
+ owed: ReadonlyMap<string, number>;
42
+ }
43
+
44
+ export async function loadExtractorState(manifest: IngestManifest, rootId: string): Promise<ExtractorState> {
45
+ let version: number | undefined;
46
+ const owed = new Map<string, number>();
47
+ for (const { id, hash } of (await manifest.get(extractorManifestKey(rootId))) ?? []) {
48
+ if (id === VERSION_ID) {
49
+ const v = Number(hash);
50
+ if (Number.isFinite(v)) version = v;
51
+ } else if (id.startsWith(OWED_PREFIX)) {
52
+ const calls = Number(hash);
53
+ owed.set(id.slice(OWED_PREFIX.length), Number.isFinite(calls) && calls >= 0 ? calls : UPGRADE_CALLS);
54
+ }
55
+ }
56
+ return { version, owed };
57
+ }
58
+
59
+ /** True when `path` is owed a re-extraction: another extractor version than today's, or left unfinished before. */
60
+ export const isOwed = (state: ExtractorState, path: string): boolean =>
61
+ state.version !== EXTRACTOR_VERSION || state.owed.has(path);
62
+
63
+ /** Model calls an owed `path` is expected to cost: its recorded count, plus one while an upgrade is pending. */
64
+ export const owedCalls = (state: ExtractorState, path: string): number =>
65
+ (state.version !== EXTRACTOR_VERSION ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
66
+
67
+ /**
68
+ * Paths in the files manifest that the plan does not list yet are owed: ignored, claimed by
69
+ * no pack, or missing from an older plan handed to *Continue*. A removed path is among them
70
+ * until the run retires it; the run saves only those still in the manifest.
71
+ */
72
+ export function carriedOwed(state: ExtractorState, prior: ReadonlyMap<string, string>, planned: Iterable<string>): string[] {
73
+ const listed = new Set(planned);
74
+ return [...prior.keys()].filter((p) => !listed.has(p) && isOwed(state, p)).sort(compareStr);
75
+ }
76
+
77
+ /**
78
+ * The owed record a run leaves: its unfinished files that are owed or content-changed (at the
79
+ * cost it measured, else the one it was owed at), and the carried paths the files manifest
80
+ * still holds (`live`). A forced run's unchanged, not-owed files are neither, so it never
81
+ * widens the set.
82
+ */
83
+ export function owedAfterRun(a: {
84
+ state: ExtractorState;
85
+ changed: ReadonlyArray<{ path: string; hash: string; owed: boolean }>;
86
+ /** The files manifest as the plan read it: a hash that differs from the file's is a content change. */
87
+ prior: ReadonlyMap<string, string>;
88
+ finished: ReadonlySet<string>;
89
+ carried: readonly string[];
90
+ live: ReadonlyMap<string, string>;
91
+ /** Calls a file this run reached but did not finish still costs. */
92
+ measured: ReadonlyMap<string, number>;
93
+ }): Map<string, number> {
94
+ const out = new Map<string, number>();
95
+ for (const f of a.changed) {
96
+ if ((f.owed || a.prior.get(f.path) !== f.hash) && !a.finished.has(f.path)) out.set(f.path, a.measured.get(f.path) ?? owedCalls(a.state, f.path));
97
+ }
98
+ for (const p of a.carried) if (a.live.has(p)) out.set(p, owedCalls(a.state, p));
99
+ return out;
100
+ }
101
+
102
+ /** Records today's version and exactly the files still owed after this run. */
103
+ export async function saveExtractorState(manifest: IngestManifest, rootId: string, owed: ReadonlyMap<string, number>): Promise<void> {
104
+ await manifest.set(extractorManifestKey(rootId), [
105
+ { id: VERSION_ID, hash: String(EXTRACTOR_VERSION) },
106
+ ...[...owed].sort((a, b) => compareStr(a[0], b[0])).map(([path, calls]) => ({ id: `${OWED_PREFIX}${path}`, hash: String(calls) })),
107
+ ]);
108
+ }
@@ -10,9 +10,10 @@
10
10
 
11
11
  import type { IngestManifest } from '../ingest/types.js';
12
12
  import type { DirectorySource, KnowledgePack, ReviewPlan } from './model.js';
13
+ import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls } from './owedFiles.js';
13
14
  import {
14
- composePacks, DEFAULT_MAX_FILE_BYTES, EXTRACTOR_VERSION, filesManifestKey, ignoreMatcher, ignoreSourcesOf, isBinaryPath,
15
- isDocumentPath, manifestMap, resolveDocument, storedExtractorVersion, stubSource,
15
+ compareManifestKey, composePacks, DEFAULT_MAX_FILE_BYTES, filesManifestKey, ignoreMatcher, ignoreSourcesOf, isBinaryPath,
16
+ isDocumentPath, manifestMap, resolveDocument, stubSource,
16
17
  } from './sources.js';
17
18
  import { compareStr, sortBy } from './refs.js';
18
19
 
@@ -27,11 +28,20 @@ export interface PlanOptions {
27
28
  /**
28
29
  * *Re-review all*: every file is `changed`, whatever its hash — but `removed` still comes
29
30
  * from the real prior manifest, and the estimate still counts only files whose content
30
- * changed (sections whose text was judged before are re-anchored, not judged again).
31
+ * changed (sections whose text was judged before are re-anchored, not judged again), plus
32
+ * one call per file owed a re-extraction.
31
33
  * A forced run cut short is forced again, not continued: *Continue* re-derives what is
32
34
  * left from content hashes.
33
35
  */
34
36
  force?: boolean;
37
+ /**
38
+ * Whether the run will compare near-duplicate claims, which needs a `similar` port (and a
39
+ * judgement port). Default true. A host that will not pass `similar` MUST pass `false`:
40
+ * otherwise the estimate counts compare calls — including the awaiting backlog a run
41
+ * without ports keeps, up to 2000 claims — that it will never spend. (*Continue* keeps the
42
+ * estimate of the plan it continues; it is not recomputed.)
43
+ */
44
+ compare?: boolean;
35
45
  }
36
46
 
37
47
  export interface PlannedFile {
@@ -40,6 +50,11 @@ export interface PlannedFile {
40
50
  size: number;
41
51
  pack: string;
42
52
  changed: boolean;
53
+ /**
54
+ * Owed a re-extraction (another extractor version, or left unfinished by an earlier run),
55
+ * whether or not its content moved. See owedFiles.ts.
56
+ */
57
+ owed: boolean;
43
58
  }
44
59
 
45
60
  export interface PlanDetail {
@@ -48,6 +63,17 @@ export interface PlanDetail {
48
63
  files: PlannedFile[];
49
64
  /** The manifest's prior `path → hash`. */
50
65
  prior: Map<string, string>;
66
+ /** The extractor entry the plan was made against. */
67
+ extractor: ExtractorState;
68
+ /** Owed paths the manifest holds that `files` does not list (ignored, no pack, an older plan, removed). */
69
+ carried: string[];
70
+ }
71
+
72
+ /** The ONE classification of a listed file: did its content move, is it owed, is it re-processed. */
73
+ function classify(extractor: ExtractorState, prior: ReadonlyMap<string, string>, path: string, hash: string, force = false) {
74
+ const contentChanged = prior.get(path) !== hash;
75
+ const owed = isOwed(extractor, path);
76
+ return { contentChanged, owed, changed: force || contentChanged || owed };
51
77
  }
52
78
 
53
79
  export async function planReview(
@@ -78,9 +104,9 @@ export async function planDetail(
78
104
  const ignored = ignoreMatcher(ignoreTexts);
79
105
  const composed = composePacks(packs);
80
106
  const prior = await manifestMap(manifest, filesManifestKey(source.rootId));
81
- // Another extractor version than the one that reviewed these files: all are re-extracted
82
- // once, but `prior` stays the real manifest (removals) and the estimate counts content changes only.
83
- const everything = opts.force === true || (await storedExtractorVersion(manifest, source.rootId)) !== EXTRACTOR_VERSION;
107
+ // Another extractor version than the one that reviewed these files, or files an earlier run
108
+ // left unfinished: those are owed a re-extraction. `prior` stays the real manifest (removals).
109
+ const extractor = await loadExtractorState(manifest, source.rootId);
84
110
  const packById = new Map(packs.map((p) => [p.id, p] as const));
85
111
 
86
112
  const files: PlannedFile[] = [];
@@ -95,21 +121,31 @@ export async function planDetail(
95
121
  if (e.size > maxBytes) { skipped.push({ path: e.path, reason: 'too-large' }); continue; }
96
122
  const hit = document ?? composed.resolve(stubSource(e.path));
97
123
  if (!hit) { skipped.push({ path: e.path, reason: 'no-pack' }); continue; }
98
- const contentChanged = prior.get(e.path) !== e.hash;
99
- const changed = everything || contentChanged;
100
- files.push({ path: e.path, hash: e.hash, size: e.size, pack: hit.pack.id, changed });
124
+ const { contentChanged, owed, changed } = classify(extractor, prior, e.path, e.hash, opts.force === true);
125
+ files.push({ path: e.path, hash: e.hash, size: e.size, pack: hit.pack.id, changed, owed });
101
126
  byPack[hit.pack.id] = (byPack[hit.pack.id] ?? 0) + 1;
102
127
  const spec = packById.get(hit.pack.id)?.judgement;
103
- if (contentChanged && spec && (spec.claims || spec.entities)) {
104
- const sections = Math.max(1, Math.ceil(e.size / AVG_SECTION_BYTES));
105
- estimatedSections += sections;
106
- if (spec.contradictions) compareSections += sections;
128
+ if (spec && (spec.claims || spec.entities)) {
129
+ if (contentChanged) {
130
+ const sections = Math.max(1, Math.ceil(e.size / AVG_SECTION_BYTES));
131
+ estimatedSections += sections;
132
+ if (spec.contradictions) compareSections += sections;
133
+ } else if (owed) {
134
+ // An unchanged file costs what it is owed — and the claims of those sections reach the compare phase too.
135
+ const calls = owedCalls(extractor, e.path);
136
+ estimatedSections += calls;
137
+ if (spec.contradictions) compareSections += calls;
138
+ }
107
139
  }
108
140
  }
109
141
 
110
142
  const present = new Set(entries.map((e) => e.path));
111
143
  const removed = [...prior.keys()].filter((p) => !present.has(p)).sort(compareStr);
112
144
  const changed = files.filter((f) => f.changed).map((f) => f.path);
145
+ // The compare phase: this run's claims, plus those a run without ports left awaiting for the first run that has them.
146
+ const compares = opts.compare !== false && packs.some((p) => p.judgement?.contradictions);
147
+ const awaiting = compares ? (await manifestMap(manifest, compareManifestKey(source.rootId))).size : 0;
148
+ const compareCalls = compares ? Math.ceil((compareSections + awaiting) / SECTIONS_PER_COMPARE) : 0;
113
149
  const sortedByPack = Object.fromEntries(Object.keys(byPack).sort(compareStr).map((k) => [k, byPack[k]!]));
114
150
  return {
115
151
  plan: {
@@ -120,28 +156,34 @@ export async function planDetail(
120
156
  changed,
121
157
  removed,
122
158
  skipped,
123
- estimatedModelCalls: estimatedSections + Math.ceil(compareSections / SECTIONS_PER_COMPARE),
159
+ estimatedModelCalls: estimatedSections + compareCalls,
124
160
  },
125
161
  files,
126
162
  prior,
163
+ extractor,
164
+ carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
127
165
  };
128
166
  }
129
167
 
130
168
  /**
131
169
  * *Continue*: the confirmed plan without a re-walk. Only `changed` is re-read — against the
132
- * manifest as the last run left it — so files finished since are not reviewed again. (While
133
- * the stored extractor version is not today's, every file still counts as changed.)
170
+ * manifest and owed list as the last run left them — so files finished since are not reviewed
171
+ * again, and files it left owed (an upgrade cut short, a failed read) are picked up.
134
172
  */
135
173
  export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest): Promise<PlanDetail> {
136
174
  const prior = await manifestMap(manifest, filesManifestKey(detail.plan.rootId));
137
- // The version entry is written only by a run that finished, so an upgrade cut short stays "everything".
138
- const everything = (await storedExtractorVersion(manifest, detail.plan.rootId)) !== EXTRACTOR_VERSION;
139
- const files = detail.files.map((f) => ({ ...f, changed: everything || prior.get(f.path) !== f.hash }));
175
+ const extractor = await loadExtractorState(manifest, detail.plan.rootId);
176
+ const files = detail.files.map((f) => {
177
+ const { owed, changed } = classify(extractor, prior, f.path, f.hash);
178
+ return { ...f, changed, owed };
179
+ });
140
180
  const changed = files.filter((f) => f.changed).map((f) => f.path);
141
181
  const removed = detail.plan.removed.filter((p) => prior.has(p));
142
182
  return {
143
183
  plan: { ...detail.plan, unchanged: files.length - changed.length, changed, removed },
144
184
  files,
145
185
  prior,
186
+ extractor,
187
+ carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
146
188
  };
147
189
  }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * src/knowledge/review.estimate.test.ts
3
+ * The confirm chip's estimate against the calls a run makes — owed files and the awaiting
4
+ * backlog count — and the awaiting set keeping its age order across a save/load.
5
+ */
6
+
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import type { StoredFact } from './model.js';
9
+ import { DOCS_PACK } from './packs/docs.js';
10
+ import { planDetail } from './plan.js';
11
+ import { reviewDirectory } from './review.js';
12
+ import { MAX_AWAITING_CLAIMS, pendingClaims, saveAwaiting, type PendingClaims } from './reviewCompare.js';
13
+ import { compareManifestKey, extractorManifestKey, manifestMap } from './sources.js';
14
+ import { args, fakeJudge, FILES, memSource, memStore, quietPack, ROOT, similar } from './testkit.test-util.js';
15
+ import { compareStr } from './refs.js';
16
+
17
+ const estimateOf = async (source: ReturnType<typeof memSource>, manifest: InMemoryIngestManifest, packs = [DOCS_PACK]) =>
18
+ (await planDetail(source, manifest, packs)).plan.estimatedModelCalls;
19
+
20
+ describe('the estimate', () => {
21
+ it('counts the awaiting backlog a run without ports left, and equals the compare calls the first run with ports makes', async () => {
22
+ const source = memSource({ ...FILES });
23
+ const store = memStore();
24
+ const manifest = new InMemoryIngestManifest();
25
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
26
+ expect((await manifestMap(manifest, compareManifestKey(ROOT))).size).toBe(3); // one claim per file, never compared
27
+
28
+ const estimate = await estimateOf(source, manifest); // nothing changed: just ceil(3 awaiting / 10 per call)
29
+ const judge = fakeJudge();
30
+ await reviewDirectory(args(source, store, manifest, { judgement: judge, similar }));
31
+ expect(judge.requests.map((r) => r.kind)).toEqual(['compare']);
32
+ expect(estimate).toBe(judge.requests.length);
33
+ });
34
+
35
+ it('adds the compare term only when the run will compare: the same backlog is free with compare:false', async () => {
36
+ const source = memSource({ ...FILES });
37
+ const manifest = new InMemoryIngestManifest();
38
+ await reviewDirectory(args(source, memStore(), manifest, { judgement: fakeJudge() }));
39
+ expect((await manifestMap(manifest, compareManifestKey(ROOT))).size).toBe(3);
40
+
41
+ expect(await estimateOf(source, manifest)).toBe(1); // default: ceil(3 awaiting / 10)
42
+ const noCompare = (await planDetail(source, manifest, [DOCS_PACK], { compare: false })).plan;
43
+ expect(noCompare.estimatedModelCalls).toBe(0);
44
+
45
+ // A content-changed file's compare sections drop out too; its own section stays.
46
+ source.files['c.md'] = '# C\ngamma changed\n';
47
+ const changed = await planDetail(source, manifest, [DOCS_PACK], { compare: false });
48
+ expect(changed.plan.estimatedModelCalls).toBe(1);
49
+ expect((await planDetail(source, manifest, [DOCS_PACK])).plan.estimatedModelCalls).toBe(1 + 1);
50
+ });
51
+
52
+ it('an upgrade that adds no section is estimated at one call per file, an upper bound that spends nothing', async () => {
53
+ const source = memSource({ ...FILES });
54
+ const store = memStore();
55
+ const manifest = new InMemoryIngestManifest();
56
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), packs: [quietPack] }));
57
+ expect(await estimateOf(source, manifest, [quietPack])).toBe(0);
58
+
59
+ await manifest.delete(extractorManifestKey(ROOT));
60
+ expect(await estimateOf(source, manifest, [quietPack])).toBe(3);
61
+ const judge = fakeJudge();
62
+ await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack] }));
63
+ expect(judge.requests).toHaveLength(0); // every section is re-anchored: the estimate is a ceiling
64
+ });
65
+
66
+ it('keeps the content-changed count beside the owed files', async () => {
67
+ const source = memSource({ ...FILES });
68
+ const manifest = new InMemoryIngestManifest();
69
+ await reviewDirectory(args(source, memStore(), manifest, { judgement: fakeJudge() }));
70
+ await manifest.delete(extractorManifestKey(ROOT));
71
+ // 3 owed files, one call each; their 3 owed sections and the 3 claims already awaiting share compare
72
+ // calls of ten: ceil((3 + 3) / 10) = 1.
73
+ expect(await estimateOf(source, manifest)).toBe(3 + 1);
74
+
75
+ // c.md also changed: a.md and b.md stay owed (2) and c.md's changed section replaces its owed call (1);
76
+ // compare: ceil((2 owed + 1 changed section + 3 awaiting) / 10) = 1.
77
+ source.files['c.md'] = '# C\ngamma changed\n';
78
+ expect(await estimateOf(source, manifest)).toBe(2 + 1 + 1);
79
+ });
80
+ });
81
+
82
+ describe('the awaiting set keeps its age order across a reload', () => {
83
+ it('drops the oldest claims even though the manifest hands entries back in id order', async () => {
84
+ const manifest = new InMemoryIngestManifest();
85
+ // Ref order is the reverse of age order, so a reload that sorts by ref would get the age wrong.
86
+ const refOf = (n: number) => `fact:claim:${String(99999 - n).padStart(5, '0')}`;
87
+ const facts = new Map<string, StoredFact>();
88
+ const fact = (r: string): StoredFact => ({
89
+ key: r.slice(5), content: 'Lease ends x', source: 'review', importance: 0.5, origin: 'model',
90
+ fileAnchors: [{ path: 'a.md', contentHash: 'h' }],
91
+ });
92
+ const first: PendingClaims = new Map();
93
+ for (let n = 0; n < MAX_AWAITING_CLAIMS - 100; n++) {
94
+ first.set(refOf(n), { text: 'Lease ends x', hash: 'h' });
95
+ const f = fact(refOf(n));
96
+ facts.set(f.key, f);
97
+ }
98
+ await saveAwaiting(manifest, ROOT, first, undefined);
99
+ const stored = (await manifest.get(compareManifestKey(ROOT)))!;
100
+ await manifest.set(compareManifestKey(ROOT), [...stored].sort((a, b) => compareStr(a.id, b.id)));
101
+
102
+ const reloaded = await pendingClaims(manifest, ROOT, facts);
103
+ expect([...reloaded.keys()]).toEqual([...first.keys()]);
104
+
105
+ for (let n = 0; n < 300; n++) reloaded.set(refOf(MAX_AWAITING_CLAIMS + n), { text: 'Lease ends x', hash: 'h' });
106
+ await saveAwaiting(manifest, ROOT, reloaded, undefined);
107
+ const kept = [...(await manifestMap(manifest, compareManifestKey(ROOT))).keys()];
108
+ expect(kept).toHaveLength(MAX_AWAITING_CLAIMS);
109
+ // 2200 pending, 200 over the cap: the 200 oldest of the first run go, nothing newer.
110
+ expect(kept).toEqual([...reloaded.keys()].slice(200));
111
+ });
112
+ });