@seanhogg/builderforce-memory 2026.10.31 → 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 (231) hide show
  1. package/dist/agent/SSMAgent.d.ts.map +1 -1
  2. package/dist/agent/SSMAgent.js.map +1 -1
  3. package/dist/bridges/AnthropicBridge.d.ts.map +1 -1
  4. package/dist/bridges/AnthropicBridge.js.map +1 -1
  5. package/dist/bridges/CachingBridge.d.ts.map +1 -1
  6. package/dist/bridges/CachingBridge.js.map +1 -1
  7. package/dist/bridges/FetchBridge.d.ts.map +1 -1
  8. package/dist/bridges/OpenAIBridge.d.ts.map +1 -1
  9. package/dist/bridges/OpenAIBridge.js.map +1 -1
  10. package/dist/bridges/ResponseCache.d.ts.map +1 -1
  11. package/dist/bridges/ResponseCache.js.map +1 -1
  12. package/dist/bridges/SemanticCachingBridge.d.ts.map +1 -1
  13. package/dist/bridges/SemanticCachingBridge.js.map +1 -1
  14. package/dist/bridges/VertexAIBridge.d.ts.map +1 -1
  15. package/dist/bridges/VertexAIBridge.js.map +1 -1
  16. package/dist/cache/FetchSemanticCacheBackend.d.ts.map +1 -1
  17. package/dist/cache/SemanticCache.d.ts.map +1 -1
  18. package/dist/cognition/EvermindCognition.d.ts.map +1 -1
  19. package/dist/cognition/EvermindCognition.js.map +1 -1
  20. package/dist/diagnostics/stack-diagnostic.js.map +1 -1
  21. package/dist/distillation/DistillationEngine.d.ts.map +1 -1
  22. package/dist/distillation/DistillationEngine.js.map +1 -1
  23. package/dist/errors/SSMError.d.ts +2 -2
  24. package/dist/errors/SSMError.d.ts.map +1 -1
  25. package/dist/errors/SSMError.js.map +1 -1
  26. package/dist/eval/EvalHarness.d.ts.map +1 -1
  27. package/dist/eval/EvalHarness.js.map +1 -1
  28. package/dist/evermind/runtime.js.map +1 -1
  29. package/dist/evermind/textCoherence.js.map +1 -1
  30. package/dist/evermind/toolCall.js.map +1 -1
  31. package/dist/handoff/pack.js.map +1 -1
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/ingest/IngestionPipeline.d.ts.map +1 -1
  34. package/dist/ingest/docsExtract.d.ts +9 -3
  35. package/dist/ingest/docsExtract.d.ts.map +1 -1
  36. package/dist/ingest/docsExtract.js +73 -20
  37. package/dist/ingest/docsExtract.js.map +1 -1
  38. package/dist/ingest/index.d.ts +1 -1
  39. package/dist/ingest/index.d.ts.map +1 -1
  40. package/dist/ingest/index.js +1 -1
  41. package/dist/ingest/index.js.map +1 -1
  42. package/dist/ingest/parserSupport.d.ts +16 -0
  43. package/dist/ingest/parserSupport.d.ts.map +1 -0
  44. package/dist/ingest/parserSupport.js +18 -0
  45. package/dist/ingest/parserSupport.js.map +1 -0
  46. package/dist/ingest/parsers.d.ts +3 -3
  47. package/dist/ingest/parsers.d.ts.map +1 -1
  48. package/dist/ingest/parsers.js +3 -92
  49. package/dist/ingest/parsers.js.map +1 -1
  50. package/dist/ingest/textParsers.d.ts +9 -0
  51. package/dist/ingest/textParsers.d.ts.map +1 -0
  52. package/dist/ingest/textParsers.js +99 -0
  53. package/dist/ingest/textParsers.js.map +1 -0
  54. package/dist/knowledge/build.d.ts +2 -0
  55. package/dist/knowledge/build.d.ts.map +1 -1
  56. package/dist/knowledge/build.js +46 -12
  57. package/dist/knowledge/build.js.map +1 -1
  58. package/dist/knowledge/cards.js.map +1 -1
  59. package/dist/knowledge/extractFile.d.ts +51 -0
  60. package/dist/knowledge/extractFile.d.ts.map +1 -0
  61. package/dist/knowledge/extractFile.js +59 -0
  62. package/dist/knowledge/extractFile.js.map +1 -0
  63. package/dist/knowledge/findings.d.ts +6 -0
  64. package/dist/knowledge/findings.d.ts.map +1 -1
  65. package/dist/knowledge/findings.js +9 -7
  66. package/dist/knowledge/findings.js.map +1 -1
  67. package/dist/knowledge/importance.js.map +1 -1
  68. package/dist/knowledge/index.d.ts +10 -7
  69. package/dist/knowledge/index.d.ts.map +1 -1
  70. package/dist/knowledge/index.js +8 -7
  71. package/dist/knowledge/index.js.map +1 -1
  72. package/dist/knowledge/judge.d.ts +34 -2
  73. package/dist/knowledge/judge.d.ts.map +1 -1
  74. package/dist/knowledge/judge.js +86 -16
  75. package/dist/knowledge/judge.js.map +1 -1
  76. package/dist/knowledge/model.d.ts +13 -62
  77. package/dist/knowledge/model.d.ts.map +1 -1
  78. package/dist/knowledge/owedFiles.d.ts +68 -0
  79. package/dist/knowledge/owedFiles.d.ts.map +1 -0
  80. package/dist/knowledge/owedFiles.js +86 -0
  81. package/dist/knowledge/owedFiles.js.map +1 -0
  82. package/dist/knowledge/packs/docs.d.ts +5 -2
  83. package/dist/knowledge/packs/docs.d.ts.map +1 -1
  84. package/dist/knowledge/packs/docs.js +33 -5
  85. package/dist/knowledge/packs/docs.js.map +1 -1
  86. package/dist/knowledge/plan.d.ts +37 -3
  87. package/dist/knowledge/plan.d.ts.map +1 -1
  88. package/dist/knowledge/plan.js +66 -19
  89. package/dist/knowledge/plan.js.map +1 -1
  90. package/dist/knowledge/refs.d.ts +22 -1
  91. package/dist/knowledge/refs.d.ts.map +1 -1
  92. package/dist/knowledge/refs.js +52 -0
  93. package/dist/knowledge/refs.js.map +1 -1
  94. package/dist/knowledge/review.d.ts +10 -4
  95. package/dist/knowledge/review.d.ts.map +1 -1
  96. package/dist/knowledge/review.js +125 -109
  97. package/dist/knowledge/review.js.map +1 -1
  98. package/dist/knowledge/reviewCompare.d.ts +39 -0
  99. package/dist/knowledge/reviewCompare.d.ts.map +1 -0
  100. package/dist/knowledge/reviewCompare.js +70 -0
  101. package/dist/knowledge/reviewCompare.js.map +1 -0
  102. package/dist/knowledge/reviewModel.d.ts +86 -0
  103. package/dist/knowledge/reviewModel.d.ts.map +1 -0
  104. package/dist/knowledge/reviewModel.js +6 -0
  105. package/dist/knowledge/reviewModel.js.map +1 -0
  106. package/dist/knowledge/reviewStored.d.ts +23 -0
  107. package/dist/knowledge/reviewStored.d.ts.map +1 -0
  108. package/dist/knowledge/reviewStored.js +62 -0
  109. package/dist/knowledge/reviewStored.js.map +1 -0
  110. package/dist/knowledge/sources.d.ts +34 -4
  111. package/dist/knowledge/sources.d.ts.map +1 -1
  112. package/dist/knowledge/sources.js +92 -26
  113. package/dist/knowledge/sources.js.map +1 -1
  114. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  115. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  116. package/dist/knowledge/trace.js.map +1 -1
  117. package/dist/knowledge/truncate.d.ts +4 -4
  118. package/dist/knowledge/truncate.d.ts.map +1 -1
  119. package/dist/knowledge/truncate.js +9 -13
  120. package/dist/knowledge/truncate.js.map +1 -1
  121. package/dist/limbic/LimbicSession.d.ts.map +1 -1
  122. package/dist/limbic/LimbicSession.js.map +1 -1
  123. package/dist/memory/MemoryStore.d.ts.map +1 -1
  124. package/dist/memory/MemoryStore.js.map +1 -1
  125. package/dist/memory/SemanticRecall.d.ts.map +1 -1
  126. package/dist/memory/SemanticRecall.js.map +1 -1
  127. package/dist/memory/ttlSweeper.d.ts.map +1 -1
  128. package/dist/orchestration/AgentGraph.d.ts.map +1 -1
  129. package/dist/orchestration/AgentGraph.js.map +1 -1
  130. package/dist/orchestration/checkpoint.d.ts.map +1 -1
  131. package/dist/orchestration/checkpoint.js.map +1 -1
  132. package/dist/publish/huggingface.js.map +1 -1
  133. package/dist/rag/EnterpriseRetriever.d.ts.map +1 -1
  134. package/dist/rag/EnterpriseRetriever.js.map +1 -1
  135. package/dist/retrieval/HybridRetriever.js.map +1 -1
  136. package/dist/retrieval/bm25.js.map +1 -1
  137. package/dist/retrieval/chunk.js.map +1 -1
  138. package/dist/retrieval/fusion.js.map +1 -1
  139. package/dist/retrieval/hnsw.d.ts.map +1 -1
  140. package/dist/retrieval/hnsw.js.map +1 -1
  141. package/dist/retrieval/knowledge-index/bytes.d.ts.map +1 -1
  142. package/dist/retrieval/knowledge-index/bytes.js.map +1 -1
  143. package/dist/retrieval/knowledge-index/cascade.js.map +1 -1
  144. package/dist/retrieval/knowledge-index/embeddings.d.ts.map +1 -1
  145. package/dist/retrieval/knowledge-index/embeddings.js.map +1 -1
  146. package/dist/retrieval/knowledge-index/expand.js.map +1 -1
  147. package/dist/retrieval/knowledge-index/index.js.map +1 -1
  148. package/dist/retrieval/knowledge-index/lexical.d.ts.map +1 -1
  149. package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
  150. package/dist/retrieval/order.js.map +1 -1
  151. package/dist/router/InferenceRouter.d.ts.map +1 -1
  152. package/dist/router/InferenceRouter.js.map +1 -1
  153. package/dist/runtime/SSMRuntime.d.ts.map +1 -1
  154. package/dist/runtime/SSMRuntime.js.map +1 -1
  155. package/dist/session/errors.d.ts +2 -2
  156. package/dist/session/errors.d.ts.map +1 -1
  157. package/dist/session/errors.js.map +1 -1
  158. package/dist/session/session.d.ts.map +1 -1
  159. package/dist/session/session.js.map +1 -1
  160. package/dist/session/streaming.js.map +1 -1
  161. package/dist/storage/ScopedFactRepository.d.ts.map +1 -1
  162. package/dist/storage/ScopedFactRepository.js.map +1 -1
  163. package/dist/storage/fileLock.d.ts.map +1 -1
  164. package/dist/storage/fileLock.js.map +1 -1
  165. package/dist/storage/fileTransaction.d.ts.map +1 -1
  166. package/dist/storage/fileTransaction.js.map +1 -1
  167. package/dist/storage/idbAdapter.d.ts +1 -1
  168. package/dist/storage/idbAdapter.d.ts.map +1 -1
  169. package/dist/storage/idbAdapter.js.map +1 -1
  170. package/dist/storage/nodeFileAdapter.d.ts +1 -1
  171. package/dist/storage/nodeFileAdapter.d.ts.map +1 -1
  172. package/dist/storage/nodeFileAdapter.js.map +1 -1
  173. package/dist/storage/types.d.ts.map +1 -1
  174. package/dist/telemetry/InstrumentedBridge.d.ts.map +1 -1
  175. package/dist/telemetry/InstrumentedBridge.js.map +1 -1
  176. package/dist/telemetry/MetricsRegistry.d.ts.map +1 -1
  177. package/dist/telemetry/MetricsRegistry.js.map +1 -1
  178. package/dist/telemetry/Tracer.d.ts.map +1 -1
  179. package/dist/telemetry/Tracer.js.map +1 -1
  180. package/dist/telemetry/exporters.d.ts.map +1 -1
  181. package/dist/telemetry/exporters.js.map +1 -1
  182. package/dist/telemetry/pricing.js.map +1 -1
  183. package/dist/vectorstore/MemoryVectorStore.d.ts.map +1 -1
  184. package/dist/vectorstore/MemoryVectorStore.js.map +1 -1
  185. package/dist/vectorstore/RestVectorStore.d.ts.map +1 -1
  186. package/dist/vectorstore/dialects.js.map +1 -1
  187. package/dist/vectorstore/filter.js.map +1 -1
  188. package/dist/wire/chatClient.d.ts +5 -0
  189. package/dist/wire/chatClient.d.ts.map +1 -1
  190. package/dist/wire/chatClient.js +6 -0
  191. package/dist/wire/chatClient.js.map +1 -1
  192. package/dist/wire/usage.d.ts.map +1 -1
  193. package/dist/workflow/registry.d.ts.map +1 -1
  194. package/dist/workflow/run.js.map +1 -1
  195. package/dist/workflow/templates.js.map +1 -1
  196. package/dist/working/codemapAreas.js.map +1 -1
  197. package/dist/working/consolidate.js.map +1 -1
  198. package/dist/working/workingMemory.d.ts.map +1 -1
  199. package/dist/working/workingMemory.js.map +1 -1
  200. package/package.json +8 -9
  201. package/src/ingest/docsExtract.ts +68 -18
  202. package/src/ingest/index.ts +1 -0
  203. package/src/ingest/parserSupport.ts +24 -0
  204. package/src/ingest/parsers.ts +4 -102
  205. package/src/ingest/textParsers.ts +107 -0
  206. package/src/knowledge/build.ts +43 -11
  207. package/src/knowledge/extractFile.ts +86 -0
  208. package/src/knowledge/findings.ts +12 -5
  209. package/src/knowledge/index.ts +15 -8
  210. package/src/knowledge/judge.clamp.test.ts +61 -0
  211. package/src/knowledge/judge.ts +88 -19
  212. package/src/knowledge/model.ts +15 -57
  213. package/src/knowledge/owedFiles.ts +108 -0
  214. package/src/knowledge/packs/docs.ts +34 -5
  215. package/src/knowledge/plan.ts +93 -19
  216. package/src/knowledge/refs.ts +49 -1
  217. package/src/knowledge/review.details.test.ts +93 -0
  218. package/src/knowledge/review.estimate.test.ts +112 -0
  219. package/src/knowledge/review.fixes.test.ts +235 -0
  220. package/src/knowledge/review.gaps.test.ts +167 -0
  221. package/src/knowledge/review.owed.test.ts +379 -0
  222. package/src/knowledge/review.test.ts +2 -15
  223. package/src/knowledge/review.ts +114 -117
  224. package/src/knowledge/review.upgrade.test.ts +257 -0
  225. package/src/knowledge/reviewCompare.ts +80 -0
  226. package/src/knowledge/reviewModel.ts +81 -0
  227. package/src/knowledge/reviewStored.ts +62 -0
  228. package/src/knowledge/sources.ts +97 -20
  229. package/src/knowledge/testkit.test-util.ts +39 -1
  230. package/src/knowledge/truncate.ts +8 -11
  231. package/src/wire/chatClient.ts +13 -0
@@ -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
+ }
@@ -3,16 +3,17 @@
3
3
  *
4
4
  * Parsers are the ONE builtin ingest parsers (markdown, HTML, plain text); their `extract`
5
5
  * lives in `ingest/docsExtract.ts`. Partitions: one plane per top-level folder, no `allow`
6
- * (so no verdicts). Findings: broken links and orphan documents. Judgement: claims,
7
- * entities and contradictions per section.
6
+ * (so no verdicts). Findings: broken links, orphan documents and contradictions (the
7
+ * generic rules add near-duplicate sections and stale claims). Judgement: claims, entities
8
+ * and contradictions per section.
8
9
  */
9
10
 
10
11
  import { htmlParser, markdownParser, plainTextParser } from '../../ingest/parsers.js';
11
12
  import { DOCS_PACK_ID } from '../../ingest/docsExtract.js';
12
13
  import type { Finding, FindingRule, KnowledgeGraph, KnowledgePack, NodeRef } from '../model.js';
13
- import { findingId, MAX_FINDING_NODES, requestKeyFor } from '../findings.js';
14
+ import { finding, findingId, MAX_FINDING_NODES, requestKeyFor } from '../findings.js';
14
15
  import { TOP_LEVEL_FOLDER } from '../partitions.js';
15
- import { basenameOf, compareStr, fileRefOf, pathOfRef } from '../refs.js';
16
+ import { aboutTargets, basenameOf, compareStr, fileRefOf, pathOfRef } from '../refs.js';
16
17
 
17
18
  export { DOCS_PACK_ID };
18
19
 
@@ -77,6 +78,34 @@ export const orphanDocumentRule: FindingRule = {
77
78
  },
78
79
  };
79
80
 
81
+ /** Two claims a model judged `contradicts`: one finding per pair, naming both sources to reconcile. */
82
+ export const contradictionRule: FindingRule = {
83
+ id: 'docs.contradiction',
84
+ find(g) {
85
+ const label = new Map(g.nodes.map((n) => [n.ref, n.label] as const));
86
+ // The section (else file) a claim is `about`: the most specific source it was judged from.
87
+ const source = aboutTargets(g.edges, { preferSection: true });
88
+ const where = (claim: NodeRef) => {
89
+ const at = source.get(claim);
90
+ const file = at ? fileRefOf(at) : undefined;
91
+ return {
92
+ file: (file && pathOfRef(file)) ?? '',
93
+ section: at && at !== file ? label.get(at) ?? '' : '',
94
+ };
95
+ };
96
+ return g.edges
97
+ .filter((e) => e.kind === 'contradicts')
98
+ .map((e): Finding => {
99
+ const a = where(e.from), b = where(e.to);
100
+ const sources = [source.get(e.from), source.get(e.to)].filter((r): r is NodeRef => !!r);
101
+ return finding('contradiction', DOCS_PACK_ID, [e.from, e.to, ...sources], e.stale ? 'info' : 'warn', {
102
+ fileA: a.file, sectionA: a.section, fileB: b.file, sectionB: b.section,
103
+ confidence: Math.round((e.confidence ?? e.weight) * 100),
104
+ }, [e.from, e.to]);
105
+ });
106
+ },
107
+ };
108
+
80
109
  export const DOCS_PACK: KnowledgePack = {
81
110
  id: DOCS_PACK_ID,
82
111
  parsers: [markdownParser, htmlParser, plainTextParser],
@@ -86,6 +115,6 @@ export const DOCS_PACK: KnowledgePack = {
86
115
  { id: '(root)', order: 0, match: ['*'] },
87
116
  ],
88
117
  },
89
- findings: [brokenLinkRule, orphanDocumentRule],
118
+ findings: [brokenLinkRule, orphanDocumentRule, contradictionRule],
90
119
  judgement: { nodeKinds: ['section'], claims: true, entities: true, contradictions: true },
91
120
  };
@@ -2,16 +2,18 @@
2
2
  * knowledge/plan.ts — `planReview`: the confirm chip's numbers (PRD 38 §4.3).
3
3
  *
4
4
  * A walk plus a manifest diff by hash, nothing more: a file whose hash is unchanged is
5
- * never read. The only reads are the ignore files (`.gitignore`, `.builderforce/ignore`)
6
- * when the listing has them. Binary files (by extension), oversized files and files no
7
- * pack accepts are skipped with a reason.
5
+ * never read. The only reads are the ignore files (`.builderforce/ignore` and every
6
+ * `.gitignore`, a nested one scoped to its folder) when the listing has them. Binary files
7
+ * (by extension — pdf/office only when a host parser claims their media type), oversized
8
+ * files and files no pack accepts are skipped with a reason.
8
9
  */
9
10
 
10
11
  import type { IngestManifest } from '../ingest/types.js';
11
12
  import type { DirectorySource, KnowledgePack, ReviewPlan } from './model.js';
13
+ import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls } from './owedFiles.js';
12
14
  import {
13
- composePacks, DEFAULT_MAX_FILE_BYTES, filesManifestKey, IGNORE_FILES, ignoreMatcher, isBinaryPath,
14
- manifestMap, stubSource,
15
+ compareManifestKey, composePacks, DEFAULT_MAX_FILE_BYTES, filesManifestKey, ignoreMatcher, ignoreSourcesOf, isBinaryPath,
16
+ isDocumentPath, manifestMap, resolveDocument, stubSource,
15
17
  } from './sources.js';
16
18
  import { compareStr, sortBy } from './refs.js';
17
19
 
@@ -23,6 +25,23 @@ const SECTIONS_PER_COMPARE = 10;
23
25
  export interface PlanOptions {
24
26
  /** Per-file size cap in bytes. Default 2 MB. */
25
27
  maxFileBytes?: number;
28
+ /**
29
+ * *Re-review all*: every file is `changed`, whatever its hash — but `removed` still comes
30
+ * from the real prior manifest, and the estimate still counts only files whose content
31
+ * changed (sections whose text was judged before are re-anchored, not judged again), plus
32
+ * one call per file owed a re-extraction.
33
+ * A forced run cut short is forced again, not continued: *Continue* re-derives what is
34
+ * left from content hashes.
35
+ */
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;
26
45
  }
27
46
 
28
47
  export interface PlannedFile {
@@ -31,6 +50,11 @@ export interface PlannedFile {
31
50
  size: number;
32
51
  pack: string;
33
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;
34
58
  }
35
59
 
36
60
  export interface PlanDetail {
@@ -39,6 +63,17 @@ export interface PlanDetail {
39
63
  files: PlannedFile[];
40
64
  /** The manifest's prior `path → hash`. */
41
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 };
42
77
  }
43
78
 
44
79
  export async function planReview(
@@ -61,15 +96,17 @@ export async function planDetail(
61
96
  for await (const entry of source.list()) listed.push({ ...entry, path: entry.path.replace(/\\/g, '/').replace(/^\.?\//, '') });
62
97
  const entries = sortBy(listed, (e) => e.path);
63
98
 
64
- const ignoreTexts: string[] = [];
65
- for (const name of IGNORE_FILES) {
66
- if (!entries.some((e) => e.path === name)) continue;
67
- const doc = await source.read(name);
68
- if (doc.content.kind === 'text') ignoreTexts.push(doc.content.text);
99
+ const ignoreTexts: Array<{ text: string; base: string }> = [];
100
+ for (const { path, base } of ignoreSourcesOf(entries.map((e) => e.path))) {
101
+ const doc = await source.read(path);
102
+ if (doc.content.kind === 'text') ignoreTexts.push({ text: doc.content.text, base });
69
103
  }
70
104
  const ignored = ignoreMatcher(ignoreTexts);
71
105
  const composed = composePacks(packs);
72
106
  const prior = await manifestMap(manifest, filesManifestKey(source.rootId));
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);
73
110
  const packById = new Map(packs.map((p) => [p.id, p] as const));
74
111
 
75
112
  const files: PlannedFile[] = [];
@@ -79,24 +116,36 @@ export async function planDetail(
79
116
  let compareSections = 0;
80
117
  for (const e of entries) {
81
118
  if (ignored(e.path)) { skipped.push({ path: e.path, reason: 'ignored' }); continue; }
82
- if (isBinaryPath(e.path)) { skipped.push({ path: e.path, reason: 'binary' }); continue; }
119
+ const document = isDocumentPath(e.path) ? resolveDocument(composed, e.path) : undefined;
120
+ if (isBinaryPath(e.path) && !document) { skipped.push({ path: e.path, reason: 'binary' }); continue; }
83
121
  if (e.size > maxBytes) { skipped.push({ path: e.path, reason: 'too-large' }); continue; }
84
- const hit = composed.resolve(stubSource(e.path));
122
+ const hit = document ?? composed.resolve(stubSource(e.path));
85
123
  if (!hit) { skipped.push({ path: e.path, reason: 'no-pack' }); continue; }
86
- const changed = prior.get(e.path) !== e.hash;
87
- 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 });
88
126
  byPack[hit.pack.id] = (byPack[hit.pack.id] ?? 0) + 1;
89
127
  const spec = packById.get(hit.pack.id)?.judgement;
90
- if (changed && spec && (spec.claims || spec.entities)) {
91
- const sections = Math.max(1, Math.ceil(e.size / AVG_SECTION_BYTES));
92
- estimatedSections += sections;
93
- 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
+ }
94
139
  }
95
140
  }
96
141
 
97
142
  const present = new Set(entries.map((e) => e.path));
98
143
  const removed = [...prior.keys()].filter((p) => !present.has(p)).sort(compareStr);
99
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;
100
149
  const sortedByPack = Object.fromEntries(Object.keys(byPack).sort(compareStr).map((k) => [k, byPack[k]!]));
101
150
  return {
102
151
  plan: {
@@ -107,9 +156,34 @@ export async function planDetail(
107
156
  changed,
108
157
  removed,
109
158
  skipped,
110
- estimatedModelCalls: estimatedSections + Math.ceil(compareSections / SECTIONS_PER_COMPARE),
159
+ estimatedModelCalls: estimatedSections + compareCalls,
111
160
  },
112
161
  files,
113
162
  prior,
163
+ extractor,
164
+ carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
165
+ };
166
+ }
167
+
168
+ /**
169
+ * *Continue*: the confirmed plan without a re-walk. Only `changed` is re-read — against the
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.
172
+ */
173
+ export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest): Promise<PlanDetail> {
174
+ const prior = await manifestMap(manifest, filesManifestKey(detail.plan.rootId));
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
+ });
180
+ const changed = files.filter((f) => f.changed).map((f) => f.path);
181
+ const removed = detail.plan.removed.filter((p) => prior.has(p));
182
+ return {
183
+ plan: { ...detail.plan, unchanged: files.length - changed.length, changed, removed },
184
+ files,
185
+ prior,
186
+ extractor,
187
+ carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
114
188
  };
115
189
  }
@@ -11,7 +11,7 @@
11
11
  * fact:${key} any other fact (claims: fact:claim:${hash})
12
12
  */
13
13
 
14
- import type { NodeRef } from './model.js';
14
+ import type { KEdge, NodeRef } from './model.js';
15
15
 
16
16
  /** Code-unit ordering — never `localeCompare`, whose result depends on the host's ICU. */
17
17
  export function compareStr(a: string, b: string): number {
@@ -106,3 +106,51 @@ export function sortBy<T>(items: readonly T[], ...keys: Array<(t: T) => string>)
106
106
  return 0;
107
107
  });
108
108
  }
109
+
110
+ /**
111
+ * A relative target walked from the linking file's folder (a leading `/` is the root):
112
+ * `segments` is where it lands under the root, `ups` how many levels it climbed ABOVE the
113
+ * root. Pure path arithmetic — the one place that decides "inside", "root itself" and "escapes".
114
+ */
115
+ export function walkRelative(fromPath: string, target: string): { ups: number; segments: string[] } {
116
+ const t = target.replace(/\\/g, '/');
117
+ const segments = t.startsWith('/') ? [] : fromPath.split('/').slice(0, -1);
118
+ let ups = 0;
119
+ for (const seg of t.split('/')) {
120
+ if (seg === '' || seg === '.') continue;
121
+ if (seg === '..') {
122
+ if (segments.length) segments.pop();
123
+ else ups += 1;
124
+ } else segments.push(seg);
125
+ }
126
+ return { ups, segments };
127
+ }
128
+
129
+ /**
130
+ * `[[Name]]` → the one listed file named `Name` (or `Name.md`), case-insensitively, anywhere
131
+ * in the root. Ambiguous names resolve to none, so the link keeps its beside-the-file fallback.
132
+ */
133
+ export function nameResolver(paths: readonly string[]): (name: string) => string | undefined {
134
+ const byName = new Map<string, string | null>();
135
+ for (const p of [...paths].sort(compareStr)) {
136
+ const base = basenameOf(p).toLowerCase();
137
+ for (const key of new Set([base, base.replace(/\.md$/, '')])) {
138
+ byName.set(key, byName.has(key) && byName.get(key) !== p ? null : p);
139
+ }
140
+ }
141
+ return (name) => byName.get(name.trim().toLowerCase()) ?? undefined;
142
+ }
143
+
144
+ /**
145
+ * The `about` target of each node, from edges in graph order. By default the first; with
146
+ * `preferSection` a section wins over the file it belongs to (the most specific source).
147
+ */
148
+ export function aboutTargets(edges: readonly KEdge[], opts: { preferSection?: boolean } = {}): Map<NodeRef, NodeRef> {
149
+ const out = new Map<NodeRef, NodeRef>();
150
+ for (const e of edges) {
151
+ if (e.kind !== 'about') continue;
152
+ const prior = out.get(e.from);
153
+ if (!prior || (opts.preferSection && prior === fileRefOf(prior) && e.to !== fileRefOf(e.to))) out.set(e.from, e.to);
154
+ }
155
+ return out;
156
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * src/knowledge/review.details.test.ts
3
+ * A file found binary on read goes stale, a throwing judgement port leaves the file to be
4
+ * retried, a contradiction names its sections, and `extractFile` is the one single-file extraction.
5
+ */
6
+
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { hashText } from '../ingest/hash.js';
9
+ import { buildGraph } from './build.js';
10
+ import { extractFile } from './extractFile.js';
11
+ import type { NodeRef, ReviewArgs, StoredFact } from './model.js';
12
+ import { DOCS_PACK } from './packs/docs.js';
13
+ import { planReview } from './plan.js';
14
+ import { reviewDirectory } from './review.js';
15
+ import { EXTRACTOR_VERSION } from './sources.js';
16
+ import { extractedOf, fakeJudge, fileNode, memSource, memStore, ref, ROOT, type SpySource } from './testkit.test-util.js';
17
+
18
+ const args = (source: SpySource, store = memStore(), manifest = new InMemoryIngestManifest(), extra: Partial<ReviewArgs> = {}): ReviewArgs =>
19
+ ({ source, store, manifest, packs: [DOCS_PACK], budget: { modelCalls: 200, ms: 60_000 }, ...extra });
20
+
21
+ describe('judgement and findings details', () => {
22
+ it('a file found binary on read has its old relations marked stale', async () => {
23
+ const source = memSource({ 'a.md': '# A\nalpha\n' });
24
+ const store = memStore();
25
+ const manifest = new InMemoryIngestManifest();
26
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
27
+ source.files['a.md'] = 'bin\u0000ary';
28
+ await reviewDirectory(args(source, store, manifest));
29
+ const about = (await store.relations({ rootId: ROOT })).filter((r) => r.kind === 'about');
30
+ expect(about.length).toBeGreaterThan(0);
31
+ expect(about.every((r) => r.staleAt)).toBe(true);
32
+ });
33
+
34
+ it('a judgement call that throws is unjudged, and the file is retried', async () => {
35
+ const source = memSource({ 'a.md': '# A\nalpha\n' });
36
+ const store = memStore();
37
+ const manifest = new InMemoryIngestManifest();
38
+ const broken = { async judge(): Promise<never> { throw new Error('port down'); } };
39
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: broken }));
40
+ expect(report).toMatchObject({ judged: 0, unjudged: 1 });
41
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual(['a.md']);
42
+
43
+ const judge = fakeJudge();
44
+ const again = await reviewDirectory(args(source, store, manifest, { judgement: judge }));
45
+ expect(judge.requests.filter((r) => r.kind === 'extract')).toHaveLength(1);
46
+ expect(again.judged).toBe(1);
47
+ });
48
+
49
+ it('a contradiction names the sections its claims are about', () => {
50
+ const section = (path: string, slug: string, label: string) => ({
51
+ ...fileNode(path), ref: `${ref(path)}#${slug}` as NodeRef, kind: 'section', label,
52
+ });
53
+ const claim = (key: string, path: string): StoredFact => ({
54
+ key, content: key, source: 'review', importance: 0.5, origin: 'model', fileAnchors: [{ path, contentHash: `h:${path}` }],
55
+ });
56
+ const g = buildGraph({
57
+ rootId: ROOT, packs: [DOCS_PACK],
58
+ extracted: [
59
+ { ...extractedOf(fileNode('a.md')), nodes: [fileNode('a.md'), section('a.md', 'rent', 'Rent')] },
60
+ { ...extractedOf(fileNode('b.md')), nodes: [fileNode('b.md'), section('b.md', 'term', 'Term')] },
61
+ ],
62
+ facts: [claim('claim:a', 'a.md'), claim('claim:b', 'b.md')],
63
+ relations: [
64
+ { from: 'fact:claim:a', to: `${ref('a.md')}#rent` as NodeRef, kind: 'about', weight: 1, origin: 'model' },
65
+ { from: 'fact:claim:b', to: `${ref('b.md')}#term` as NodeRef, kind: 'about', weight: 1, origin: 'model' },
66
+ { from: 'fact:claim:a', to: 'fact:claim:b', kind: 'contradicts', weight: 1, origin: 'model', confidence: 0.8 },
67
+ ],
68
+ });
69
+ const f = g.findings.find((x) => x.kind === 'contradiction');
70
+ expect(f?.params).toMatchObject({ fileA: 'a.md', sectionA: 'Rent', fileB: 'b.md', sectionB: 'Term' });
71
+ });
72
+ });
73
+
74
+ describe('extractFile', () => {
75
+ it('extracts one file with the cache, the version and the stored entity keys', async () => {
76
+ const store = memStore();
77
+ const lease = { key: 'ent:docs:lease', content: 'Lease', source: 's', importance: 0.5, origin: 'model' as const, fileAnchors: [] };
78
+ await store.write({ scope: { rootId: ROOT, title: 't', packs: [] }, facts: [lease], relations: [] });
79
+ const text = '# A\nThe Lease ends.\n';
80
+ const hash = hashText(text);
81
+ const input = {
82
+ rootId: ROOT, path: 'a.md', hash, packs: [DOCS_PACK], store,
83
+ doc: { id: 'a.md', tenantId: 't', content: { kind: 'text' as const, text } },
84
+ };
85
+ const ex = await extractFile(input);
86
+ expect(ex).toMatchObject({ sourceRef: ref('a.md'), sourceHash: hash, extractorVersion: EXTRACTOR_VERSION });
87
+ expect(ex!.edges.some((e) => e.kind === 'mentions' && e.to === 'ent:docs:lease')).toBe(true);
88
+ expect(await store.getExtracted(hash)).toEqual([ex]);
89
+ expect(await extractFile(input)).toEqual(ex);
90
+ const pdf = { ...input, path: 'a.pdf', doc: { ...input.doc, content: { kind: 'text' as const, text, mediaType: 'application/pdf' } } };
91
+ expect(await extractFile(pdf)).toBeUndefined();
92
+ });
93
+ });
@@ -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
+ });