@seanhogg/builderforce-memory 2026.10.30 → 2026.10.32

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 (223) 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 +9 -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 +21 -2
  73. package/dist/knowledge/judge.d.ts.map +1 -1
  74. package/dist/knowledge/judge.js +63 -16
  75. package/dist/knowledge/judge.js.map +1 -1
  76. package/dist/knowledge/model.d.ts +14 -63
  77. package/dist/knowledge/model.d.ts.map +1 -1
  78. package/dist/knowledge/packs/docs.d.ts +5 -2
  79. package/dist/knowledge/packs/docs.d.ts.map +1 -1
  80. package/dist/knowledge/packs/docs.js +33 -5
  81. package/dist/knowledge/packs/docs.js.map +1 -1
  82. package/dist/knowledge/plan.d.ts +18 -3
  83. package/dist/knowledge/plan.d.ts.map +1 -1
  84. package/dist/knowledge/plan.js +35 -13
  85. package/dist/knowledge/plan.js.map +1 -1
  86. package/dist/knowledge/refs.d.ts +22 -1
  87. package/dist/knowledge/refs.d.ts.map +1 -1
  88. package/dist/knowledge/refs.js +52 -0
  89. package/dist/knowledge/refs.js.map +1 -1
  90. package/dist/knowledge/review.d.ts +8 -4
  91. package/dist/knowledge/review.d.ts.map +1 -1
  92. package/dist/knowledge/review.js +92 -106
  93. package/dist/knowledge/review.js.map +1 -1
  94. package/dist/knowledge/reviewCompare.d.ts +38 -0
  95. package/dist/knowledge/reviewCompare.d.ts.map +1 -0
  96. package/dist/knowledge/reviewCompare.js +59 -0
  97. package/dist/knowledge/reviewCompare.js.map +1 -0
  98. package/dist/knowledge/reviewModel.d.ts +80 -0
  99. package/dist/knowledge/reviewModel.d.ts.map +1 -0
  100. package/dist/knowledge/reviewModel.js +6 -0
  101. package/dist/knowledge/reviewModel.js.map +1 -0
  102. package/dist/knowledge/reviewStored.d.ts +23 -0
  103. package/dist/knowledge/reviewStored.d.ts.map +1 -0
  104. package/dist/knowledge/reviewStored.js +62 -0
  105. package/dist/knowledge/reviewStored.js.map +1 -0
  106. package/dist/knowledge/sources.d.ts +36 -4
  107. package/dist/knowledge/sources.d.ts.map +1 -1
  108. package/dist/knowledge/sources.js +99 -26
  109. package/dist/knowledge/sources.js.map +1 -1
  110. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  111. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  112. package/dist/knowledge/trace.js.map +1 -1
  113. package/dist/knowledge/truncate.d.ts +4 -4
  114. package/dist/knowledge/truncate.d.ts.map +1 -1
  115. package/dist/knowledge/truncate.js +9 -13
  116. package/dist/knowledge/truncate.js.map +1 -1
  117. package/dist/limbic/LimbicSession.d.ts.map +1 -1
  118. package/dist/limbic/LimbicSession.js.map +1 -1
  119. package/dist/memory/MemoryStore.d.ts.map +1 -1
  120. package/dist/memory/MemoryStore.js.map +1 -1
  121. package/dist/memory/SemanticRecall.d.ts.map +1 -1
  122. package/dist/memory/SemanticRecall.js.map +1 -1
  123. package/dist/memory/ttlSweeper.d.ts.map +1 -1
  124. package/dist/orchestration/AgentGraph.d.ts.map +1 -1
  125. package/dist/orchestration/AgentGraph.js.map +1 -1
  126. package/dist/orchestration/checkpoint.d.ts.map +1 -1
  127. package/dist/orchestration/checkpoint.js.map +1 -1
  128. package/dist/publish/huggingface.js.map +1 -1
  129. package/dist/rag/EnterpriseRetriever.d.ts.map +1 -1
  130. package/dist/rag/EnterpriseRetriever.js.map +1 -1
  131. package/dist/retrieval/HybridRetriever.js.map +1 -1
  132. package/dist/retrieval/bm25.js.map +1 -1
  133. package/dist/retrieval/chunk.js.map +1 -1
  134. package/dist/retrieval/fusion.js.map +1 -1
  135. package/dist/retrieval/hnsw.d.ts.map +1 -1
  136. package/dist/retrieval/hnsw.js.map +1 -1
  137. package/dist/retrieval/knowledge-index/bytes.d.ts.map +1 -1
  138. package/dist/retrieval/knowledge-index/bytes.js.map +1 -1
  139. package/dist/retrieval/knowledge-index/cascade.js.map +1 -1
  140. package/dist/retrieval/knowledge-index/embeddings.d.ts.map +1 -1
  141. package/dist/retrieval/knowledge-index/embeddings.js.map +1 -1
  142. package/dist/retrieval/knowledge-index/expand.js.map +1 -1
  143. package/dist/retrieval/knowledge-index/index.js.map +1 -1
  144. package/dist/retrieval/knowledge-index/lexical.d.ts.map +1 -1
  145. package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
  146. package/dist/retrieval/order.js.map +1 -1
  147. package/dist/router/InferenceRouter.d.ts.map +1 -1
  148. package/dist/router/InferenceRouter.js.map +1 -1
  149. package/dist/runtime/SSMRuntime.d.ts.map +1 -1
  150. package/dist/runtime/SSMRuntime.js.map +1 -1
  151. package/dist/session/errors.d.ts +2 -2
  152. package/dist/session/errors.d.ts.map +1 -1
  153. package/dist/session/errors.js.map +1 -1
  154. package/dist/session/session.d.ts.map +1 -1
  155. package/dist/session/session.js.map +1 -1
  156. package/dist/session/streaming.js.map +1 -1
  157. package/dist/storage/ScopedFactRepository.d.ts.map +1 -1
  158. package/dist/storage/ScopedFactRepository.js.map +1 -1
  159. package/dist/storage/fileLock.d.ts.map +1 -1
  160. package/dist/storage/fileLock.js.map +1 -1
  161. package/dist/storage/fileTransaction.d.ts.map +1 -1
  162. package/dist/storage/fileTransaction.js.map +1 -1
  163. package/dist/storage/idbAdapter.d.ts +1 -1
  164. package/dist/storage/idbAdapter.d.ts.map +1 -1
  165. package/dist/storage/idbAdapter.js.map +1 -1
  166. package/dist/storage/nodeFileAdapter.d.ts +1 -1
  167. package/dist/storage/nodeFileAdapter.d.ts.map +1 -1
  168. package/dist/storage/nodeFileAdapter.js.map +1 -1
  169. package/dist/storage/types.d.ts.map +1 -1
  170. package/dist/telemetry/InstrumentedBridge.d.ts.map +1 -1
  171. package/dist/telemetry/InstrumentedBridge.js.map +1 -1
  172. package/dist/telemetry/MetricsRegistry.d.ts.map +1 -1
  173. package/dist/telemetry/MetricsRegistry.js.map +1 -1
  174. package/dist/telemetry/Tracer.d.ts.map +1 -1
  175. package/dist/telemetry/Tracer.js.map +1 -1
  176. package/dist/telemetry/exporters.d.ts.map +1 -1
  177. package/dist/telemetry/exporters.js.map +1 -1
  178. package/dist/telemetry/pricing.js.map +1 -1
  179. package/dist/vectorstore/MemoryVectorStore.d.ts.map +1 -1
  180. package/dist/vectorstore/MemoryVectorStore.js.map +1 -1
  181. package/dist/vectorstore/RestVectorStore.d.ts.map +1 -1
  182. package/dist/vectorstore/dialects.js.map +1 -1
  183. package/dist/vectorstore/filter.js.map +1 -1
  184. package/dist/wire/chatClient.d.ts +5 -0
  185. package/dist/wire/chatClient.d.ts.map +1 -1
  186. package/dist/wire/chatClient.js +6 -0
  187. package/dist/wire/chatClient.js.map +1 -1
  188. package/dist/wire/usage.d.ts.map +1 -1
  189. package/dist/workflow/registry.d.ts.map +1 -1
  190. package/dist/workflow/run.js.map +1 -1
  191. package/dist/workflow/templates.js.map +1 -1
  192. package/dist/working/codemapAreas.js.map +1 -1
  193. package/dist/working/consolidate.js.map +1 -1
  194. package/dist/working/workingMemory.d.ts.map +1 -1
  195. package/dist/working/workingMemory.js.map +1 -1
  196. package/package.json +8 -9
  197. package/src/ingest/docsExtract.ts +68 -18
  198. package/src/ingest/index.ts +1 -0
  199. package/src/ingest/parserSupport.ts +24 -0
  200. package/src/ingest/parsers.ts +4 -102
  201. package/src/ingest/textParsers.ts +107 -0
  202. package/src/knowledge/build.ts +43 -11
  203. package/src/knowledge/extractFile.ts +86 -0
  204. package/src/knowledge/findings.ts +12 -5
  205. package/src/knowledge/index.ts +13 -8
  206. package/src/knowledge/judge.ts +64 -19
  207. package/src/knowledge/model.ts +16 -58
  208. package/src/knowledge/packs/docs.ts +34 -5
  209. package/src/knowledge/plan.ts +46 -14
  210. package/src/knowledge/refs.ts +49 -1
  211. package/src/knowledge/review.details.test.ts +93 -0
  212. package/src/knowledge/review.fixes.test.ts +235 -0
  213. package/src/knowledge/review.gaps.test.ts +167 -0
  214. package/src/knowledge/review.test.ts +2 -15
  215. package/src/knowledge/review.ts +85 -113
  216. package/src/knowledge/review.upgrade.test.ts +192 -0
  217. package/src/knowledge/reviewCompare.ts +68 -0
  218. package/src/knowledge/reviewModel.ts +75 -0
  219. package/src/knowledge/reviewStored.ts +62 -0
  220. package/src/knowledge/sources.ts +106 -20
  221. package/src/knowledge/testkit.test-util.ts +16 -1
  222. package/src/knowledge/truncate.ts +8 -11
  223. package/src/wire/chatClient.ts +13 -0
@@ -0,0 +1,192 @@
1
+ /**
2
+ * src/knowledge/review.upgrade.test.ts
3
+ * Upgrade and robustness follow-ups: the extractor version lives in its own manifest entry
4
+ * (the files manifest keeps its key), *Re-review all*, a failed read retires nothing, the
5
+ * compare phase without its ports, the reserved preamble ref, claim text and byName determinism.
6
+ */
7
+
8
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
9
+ import { hashText } from '../ingest/hash.js';
10
+ import { markdownParser } from '../ingest/parsers.js';
11
+ import { buildGraph, graphDigest } from './build.js';
12
+ import type { ExtractContext, ReviewArgs } from './model.js';
13
+ import { DOCS_PACK } from './packs/docs.js';
14
+ import { planReview } from './plan.js';
15
+ import { reviewDirectory } from './review.js';
16
+ import { MAX_AWAITING_CLAIMS, saveAwaiting, type PendingClaims } from './reviewCompare.js';
17
+ import {
18
+ asPathSource, compareManifestKey, EXTRACTOR_VERSION, extractorManifestKey, filesManifestKey, judgedManifestKey, manifestMap,
19
+ resolveRelativePath, storedExtractorVersion,
20
+ } from './sources.js';
21
+ import {
22
+ edge, extractedOf, fakeJudge, fileNode, memSource, memStore, ref, ROOT, type SpySource,
23
+ } from './testkit.test-util.js';
24
+ import { canonicalJson, srcRef } from './refs.js';
25
+
26
+ const args = (source: SpySource, store = memStore(), manifest = new InMemoryIngestManifest(), extra: Partial<ReviewArgs> = {}): ReviewArgs =>
27
+ ({ source, store, manifest, packs: [DOCS_PACK], budget: { modelCalls: 200, ms: 60_000 }, ...extra });
28
+
29
+ const FILES = { 'a.md': '# A\nalpha\n', 'b.md': '# B\nbeta\n', 'c.md': '# C\ngamma\n' };
30
+
31
+ describe('the extractor version has its own manifest entry', () => {
32
+ it('the files manifest keeps the key consumers read', () => {
33
+ expect(filesManifestKey(ROOT)).toBe(`knowledge:${ROOT}`);
34
+ expect(extractorManifestKey(ROOT)).toBe(`knowledge:${ROOT}:extractor`);
35
+ });
36
+
37
+ it('an old manifest (files, no version entry) re-extracts once, still detects removals, and counts only content changes', async () => {
38
+ const source = memSource({ ...FILES });
39
+ const store = memStore();
40
+ const manifest = new InMemoryIngestManifest();
41
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
42
+ expect(await storedExtractorVersion(manifest, ROOT)).toBe(EXTRACTOR_VERSION);
43
+ expect((await manifest.get(filesManifestKey(ROOT)))!.map((f) => f.id)).toEqual(['a.md', 'b.md', 'c.md']);
44
+
45
+ delete source.files['b.md'];
46
+ source.files['c.md'] = '# C\ngamma changed\n';
47
+ const withVersion = await planReview(source, manifest, [DOCS_PACK]);
48
+ expect(withVersion.changed).toEqual(['c.md']);
49
+
50
+ await manifest.set(extractorManifestKey(ROOT), []); // what a v2026.10.31 manifest looks like
51
+ const old = await planReview(source, manifest, [DOCS_PACK]);
52
+ expect(old.removed).toEqual(['b.md']);
53
+ expect(old.changed).toEqual(['a.md', 'c.md']);
54
+ expect(old.estimatedModelCalls).toBe(withVersion.estimatedModelCalls);
55
+
56
+ const judge = fakeJudge();
57
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: judge }));
58
+ expect(report.extracted).toBe(2);
59
+ expect(judge.requests.filter((r) => r.kind === 'extract')).toHaveLength(1); // c.md only; a.md is re-anchored
60
+ expect([...(await manifestMap(manifest, filesManifestKey(ROOT))).keys()]).toEqual(['a.md', 'c.md']);
61
+ expect(await storedExtractorVersion(manifest, ROOT)).toBe(EXTRACTOR_VERSION);
62
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual([]);
63
+ });
64
+
65
+ it('an aborted run does not record the version', async () => {
66
+ const controller = new AbortController();
67
+ controller.abort();
68
+ const manifest = new InMemoryIngestManifest();
69
+ const report = await reviewDirectory(args(memSource({ ...FILES }), memStore(), manifest, { signal: controller.signal }));
70
+ expect(report.aborted).toBe(true);
71
+ expect(await storedExtractorVersion(manifest, ROOT)).toBeUndefined();
72
+ });
73
+ });
74
+
75
+ describe('re-review all', () => {
76
+ it('marks every file changed, still finds removals and does not inflate the estimate', async () => {
77
+ const source = memSource({ ...FILES });
78
+ const manifest = new InMemoryIngestManifest();
79
+ const store = memStore();
80
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
81
+ delete source.files['b.md'];
82
+
83
+ const plain = await planReview(source, manifest, [DOCS_PACK]);
84
+ const forced = await planReview(source, manifest, [DOCS_PACK], { force: true });
85
+ expect(plain.changed).toEqual([]);
86
+ expect(forced.changed).toEqual(['a.md', 'c.md']);
87
+ expect(forced.removed).toEqual(['b.md']);
88
+ expect(forced.estimatedModelCalls).toBe(plain.estimatedModelCalls);
89
+
90
+ const judge = fakeJudge();
91
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: judge, force: true }));
92
+ expect(report.extracted).toBe(2);
93
+ expect(judge.requests).toHaveLength(0);
94
+ expect([...(await manifestMap(manifest, filesManifestKey(ROOT))).keys()]).toEqual(['a.md', 'c.md']);
95
+ });
96
+ });
97
+
98
+ describe('a file that cannot be read', () => {
99
+ it('keeps its facts, anchors and manifest hash, and is counted', async () => {
100
+ const source = memSource({ 'a.md': '# A\nalpha\n' });
101
+ const store = memStore();
102
+ const manifest = new InMemoryIngestManifest();
103
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
104
+ const before = { facts: await store.facts({ rootId: ROOT }), relations: await store.relations({ rootId: ROOT }) };
105
+ const hash = hashText('# A\nalpha\n');
106
+
107
+ source.files['a.md'] = '# A\nalpha edited\n';
108
+ source.read = async () => { throw Object.assign(new Error('permission denied'), { code: 'EACCES' }); };
109
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
110
+ expect(report).toMatchObject({ readErrors: 1, extracted: 0, aborted: false });
111
+ expect(await store.facts({ rootId: ROOT })).toEqual(before.facts);
112
+ expect((await store.relations({ rootId: ROOT })).every((r) => !r.staleAt)).toBe(true);
113
+ expect((await manifestMap(manifest, filesManifestKey(ROOT))).get('a.md')).toBe(hash);
114
+ // Still changed for the next review.
115
+ expect((await planReview(source, manifest, [DOCS_PACK])).changed).toEqual(['a.md']);
116
+ });
117
+ });
118
+
119
+ describe('bookkeeping of removed and binary files', () => {
120
+ it('counts them stale, prunes their judged sections and drops their anchor from shared entities', async () => {
121
+ const source = memSource({ ...FILES });
122
+ const store = memStore();
123
+ const manifest = new InMemoryIngestManifest();
124
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
125
+ expect([...(await manifestMap(manifest, judgedManifestKey(ROOT))).keys()].some((k) => k.startsWith(`${srcRef(ROOT, 'b.md')}#`))).toBe(true);
126
+
127
+ delete source.files['b.md'];
128
+ delete source.files['c.md'];
129
+ const removed = await reviewDirectory(args(source, store, manifest));
130
+ expect(removed.staleMarked).toBe(2);
131
+ const judged = [...(await manifestMap(manifest, judgedManifestKey(ROOT))).keys()];
132
+ expect(judged.every((k) => k.startsWith(`${srcRef(ROOT, 'a.md')}#`))).toBe(true);
133
+ const lease = (await store.facts({ rootId: ROOT })).find((f) => f.key === 'ent:docs:lease')!;
134
+ expect(lease.fileAnchors.map((a) => a.path)).toEqual(['a.md']);
135
+
136
+ source.files['a.md'] = 'bin\u0000ary';
137
+ expect((await reviewDirectory(args(source, store, manifest))).staleMarked).toBe(1);
138
+ });
139
+ });
140
+
141
+ describe('the compare phase', () => {
142
+ it('keeps nothing awaiting when the host has no similar port', async () => {
143
+ const manifest = new InMemoryIngestManifest();
144
+ await reviewDirectory(args(memSource({ ...FILES }), memStore(), manifest, { judgement: fakeJudge() }));
145
+ expect((await manifestMap(manifest, compareManifestKey(ROOT))).size).toBe(0);
146
+ });
147
+
148
+ it('bounds the awaiting set to the most recent claims', async () => {
149
+ const manifest = new InMemoryIngestManifest();
150
+ const pending: PendingClaims = new Map();
151
+ for (let i = 0; i < MAX_AWAITING_CLAIMS + 50; i++) pending.set(`fact:claim:${String(i).padStart(5, '0')}`, { text: 't', hash: 'h' });
152
+ await saveAwaiting(manifest, ROOT, pending, undefined, true);
153
+ const kept = [...(await manifestMap(manifest, compareManifestKey(ROOT))).keys()];
154
+ expect(kept).toHaveLength(MAX_AWAITING_CLAIMS);
155
+ expect(kept).toContain(`fact:claim:${String(MAX_AWAITING_CLAIMS + 49).padStart(5, '0')}`);
156
+ expect(kept).not.toContain('fact:claim:00000');
157
+ });
158
+
159
+ it('compares a claim left awaiting by its claim text, the form a first run uses', async () => {
160
+ const source = memSource({ 'a.md': '# A\nalpha\n', 'b.md': '# B\nbeta\n' });
161
+ const store = memStore();
162
+ const manifest = new InMemoryIngestManifest();
163
+ const similar = async (ids: string[]) => (ids.length >= 2 ? [{ a: ids[0]!, b: ids[1]!, similarity: 0.95 }] : []);
164
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), similar, budget: { modelCalls: 2, ms: 60_000 } }));
165
+ const judge = fakeJudge();
166
+ await reviewDirectory(args(source, store, manifest, { judgement: judge, similar }));
167
+ const compare = judge.requests.find((r) => r.kind === 'compare')!;
168
+ expect(compare.items.map((i) => i.text).sort()).toEqual(['Lease ends alpha', 'Lease ends beta']);
169
+ });
170
+ });
171
+
172
+ describe('docs extract determinism and refs', () => {
173
+ const ctx: ExtractContext = { rootId: ROOT, knownKeys: new Map(), resolvePath: resolveRelativePath };
174
+
175
+ it('a preamble and a top-level "# Body" heading keep distinct refs', () => {
176
+ const text = 'Intro text.\n# Body\nunder the heading\n';
177
+ const src = asPathSource({ id: 'p.md', tenantId: 't', content: { kind: 'text', text } }, 'p.md', 'h:p');
178
+ const ex = markdownParser.extract!(src, markdownParser.parse(src), ctx);
179
+ const sections = ex.nodes.filter((n) => n.kind === 'section');
180
+ expect(sections.map((n) => n.ref).sort()).toEqual([`${ref('p.md')}#body`, `${ref('p.md')}#~preamble`].sort());
181
+ expect(sections.find((n) => n.ref.endsWith('#body'))!.label).toBe('Body');
182
+ });
183
+
184
+ it('edges that differ only by byName digest and build the same in any input order', () => {
185
+ const edges = [edge('a.md', 'x.md', 'links', { byName: 'X' }), edge('a.md', 'x.md', 'links', { byName: 'Y' })];
186
+ const input = (es: typeof edges) => ({
187
+ rootId: ROOT, packs: [DOCS_PACK], facts: [], relations: [], extracted: [extractedOf(fileNode('a.md'), es)],
188
+ });
189
+ expect(graphDigest(input(edges))).toBe(graphDigest(input([...edges].reverse())));
190
+ expect(canonicalJson(buildGraph(input(edges)))).toBe(canonicalJson(buildGraph(input([...edges].reverse()))));
191
+ });
192
+ });
@@ -0,0 +1,68 @@
1
+ /**
2
+ * knowledge/reviewCompare.ts — the compare phase of a review (PRD 38 §4.3): near-duplicate
3
+ * claim pairs → `contradicts` / `agrees`. Claims whose pairs could not all be compared
4
+ * (budget, a failed call, an abort) are kept in the compare manifest, so *Continue* picks
5
+ * them up at the next run instead of losing them.
6
+ */
7
+
8
+ import type { IngestManifest } from '../ingest/types.js';
9
+ import { claimTextOf, compareClaims, type CompareOutcome, type JudgeBudget, type JudgedBatch } from './judge.js';
10
+ import type { NodeRef, ReviewArgs, StoredFact } from './model.js';
11
+ import { compareManifestKey, manifestMap, saveManifestMap } from './sources.js';
12
+ import { compareStr, factKeyOf } from './refs.js';
13
+
14
+ /** At most this many claims wait for *Continue*; beyond it the oldest are dropped (the set stays bounded). */
15
+ export const MAX_AWAITING_CLAIMS = 2000;
16
+
17
+ /** A claim awaiting comparison: its text and the content hash it was judged from. */
18
+ export type PendingClaims = Map<string, { text: string; hash: string }>;
19
+
20
+ /** Claims a previous run left awaiting comparison, read back from their stored facts (a gone fact drops out). */
21
+ export async function pendingClaims(manifest: IngestManifest, rootId: string, facts: ReadonlyMap<string, StoredFact>): Promise<PendingClaims> {
22
+ const out: PendingClaims = new Map();
23
+ for (const ref of (await manifestMap(manifest, compareManifestKey(rootId))).keys()) {
24
+ const fact = facts.get(factKeyOf(ref as NodeRef) ?? '');
25
+ if (fact?.key.startsWith('claim:')) out.set(ref, { text: claimTextOf(fact.content), hash: fact.fileAnchors[0]?.contentHash ?? '' });
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /**
31
+ * Compares `pending` against its near-duplicates, within the budget. Undefined when the
32
+ * phase cannot run (no judgement port, no index, nothing pending).
33
+ */
34
+ export async function compareNew(a: {
35
+ args: ReviewArgs; pending: PendingClaims; known: ReadonlyMap<string, StoredFact>; budget: JudgeBudget; batch: JudgedBatch;
36
+ onPairs(total: number): void;
37
+ }): Promise<CompareOutcome | undefined> {
38
+ const { args, pending } = a;
39
+ if (!args.judgement || !args.similar || pending.size === 0) return undefined;
40
+ const pairs = await args.similar([...pending.keys()].sort(compareStr));
41
+ const claims: PendingClaims = new Map(pending);
42
+ for (const p of pairs) {
43
+ for (const id of [p.a, p.b]) {
44
+ const fact = !claims.has(id) ? a.known.get(factKeyOf(id as NodeRef) ?? '') : undefined;
45
+ if (fact?.key.startsWith('claim:')) claims.set(id, { text: claimTextOf(fact.content), hash: fact.fileAnchors[0]?.contentHash ?? '' });
46
+ }
47
+ }
48
+ a.onPairs(pairs.length);
49
+ // Run even with the budget spent: compareClaims counts every pair it skips as unjudged.
50
+ return compareClaims({ port: args.judgement, pairs, claims, budget: a.budget, batch: a.batch, ...(args.signal ? { signal: args.signal } : {}) });
51
+ }
52
+
53
+ /**
54
+ * Persists the claims still awaiting comparison, capped at {@link MAX_AWAITING_CLAIMS} (the
55
+ * most recent: a previous run's first, this run's last). With `canCompare` false — no
56
+ * judgement port, no `similar` port, or no pack asking for contradictions — the phase cannot
57
+ * run at all, so nothing waits: it is not the same as an abort, which keeps every claim.
58
+ */
59
+ export async function saveAwaiting(
60
+ manifest: IngestManifest, rootId: string, pending: PendingClaims, outcome: CompareOutcome | undefined, canCompare: boolean,
61
+ ): Promise<void> {
62
+ const awaiting = new Map<string, string>();
63
+ if (canCompare) {
64
+ for (const [ref, c] of pending) if (!outcome || outcome.skipped.has(ref)) awaiting.set(ref, c.hash);
65
+ }
66
+ const kept = awaiting.size > MAX_AWAITING_CLAIMS ? new Map([...awaiting].slice(-MAX_AWAITING_CLAIMS)) : awaiting;
67
+ await saveManifestMap(manifest, compareManifestKey(rootId), kept);
68
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * knowledge/reviewModel.ts — the review's port and reports (PRD 38 §4.1, §4.3): where files
3
+ * come from, the confirm chip's plan, progress and the final report.
4
+ */
5
+
6
+ import type { IngestManifest, SourceDocument } from '../ingest/types.js';
7
+ import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
8
+ import type { JudgementPort, KnowledgePack, KnowledgeStore } from './model.js';
9
+ import type { PlanDetail } from './plan.js';
10
+
11
+ /** Where files come from: one adapter per host. */
12
+ export interface DirectorySource {
13
+ rootId: string;
14
+ title: string;
15
+ list(): AsyncIterable<{ path: string; hash: string; size: number }>;
16
+ read(path: string): Promise<SourceDocument>;
17
+ watch?(cb: (paths: string[]) => void): () => void;
18
+ }
19
+
20
+ export interface ReviewPlan {
21
+ rootId: string;
22
+ files: number;
23
+ byPack: Record<string, number>;
24
+ unchanged: number;
25
+ changed: string[];
26
+ removed: string[];
27
+ skipped: Array<{ path: string; reason: 'ignored' | 'binary' | 'too-large' | 'no-pack' }>;
28
+ /** ≈ judgement calls for changed files (sections of judged kinds). */
29
+ estimatedModelCalls: number;
30
+ }
31
+
32
+ export interface ReviewProgress {
33
+ phase: 'plan' | 'extract' | 'resolve' | 'judge' | 'write' | 'index' | 'done';
34
+ done: number;
35
+ total: number;
36
+ path?: string;
37
+ }
38
+
39
+ export interface ReviewReport {
40
+ rootId: string;
41
+ digest: string;
42
+ extracted: number;
43
+ judged: number;
44
+ /** Sections and compare pairs left for *Continue* (budget ran out, or a model call failed). */
45
+ unjudged: number;
46
+ invalidJudgements: number;
47
+ factsWritten: number;
48
+ relationsWritten: number;
49
+ staleMarked: number;
50
+ /**
51
+ * Files whose read threw: skipped, not retired — their facts, anchors and manifest hash are
52
+ * untouched, so the next review tries them again. A file that is truly gone shows up in
53
+ * the next fresh plan's `removed`.
54
+ */
55
+ readErrors: number;
56
+ aborted: boolean;
57
+ durationMs: number;
58
+ }
59
+
60
+ export interface ReviewArgs {
61
+ source: DirectorySource;
62
+ store: KnowledgeStore;
63
+ packs: KnowledgePack[];
64
+ manifest: IngestManifest;
65
+ judgement?: JudgementPort;
66
+ /** Near-duplicate claim pairs to compare / possible-same entities; from the knowledge index. */
67
+ similar?: (ids: string[]) => Promise<SimilarPair[]>;
68
+ budget: { modelCalls: number; ms: number };
69
+ /** *Continue*: the plan the person confirmed. Reused without a re-walk; `changed` is re-read from the manifest. */
70
+ plan?: PlanDetail;
71
+ /** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
72
+ force?: boolean;
73
+ signal?: AbortSignal;
74
+ onProgress?(p: ReviewProgress): void;
75
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * knowledge/reviewStored.ts — what a review reads back from the store: the stored model
3
+ * knowledge indexed for re-anchoring unchanged sections without a model call, and the
4
+ * rewrite that lets a fact outlive one of its deleted sources.
5
+ */
6
+
7
+ import type { NodeRef, StoredFact, StoredRelation } from './model.js';
8
+ import type { JudgedBatch } from './judge.js';
9
+ import { factKeyOf } from './refs.js';
10
+
11
+ /** Stored knowledge, indexed for re-anchoring unchanged sections without a model call. */
12
+ export class StoredIndex {
13
+ readonly facts: Map<string, StoredFact>;
14
+ private readonly from = new Map<string, StoredRelation[]>();
15
+ private readonly to = new Map<string, StoredRelation[]>();
16
+
17
+ constructor(facts: StoredFact[], relations: StoredRelation[]) {
18
+ this.facts = new Map(facts.map((f) => [f.key, f] as const));
19
+ for (const r of relations) {
20
+ if (r.origin !== 'model') continue;
21
+ (this.from.get(r.from) ?? this.from.set(r.from, []).get(r.from)!).push(r);
22
+ (this.to.get(r.to) ?? this.to.set(r.to, []).get(r.to)!).push(r);
23
+ }
24
+ }
25
+
26
+ /** An unchanged section keeps its claims and mentions; they are re-anchored to the file's new hash. */
27
+ refresh(section: NodeRef, path: string, hash: string, batch: JudgedBatch, entities: Map<string, StoredFact>): void {
28
+ const reanchor = (f: StoredFact): StoredFact => ({
29
+ ...f, fileAnchors: f.fileAnchors.map((a) => (a.path === path ? { ...a, contentHash: hash } : a)),
30
+ });
31
+ const relation = (r: StoredRelation) => batch.relation({ ...r, sourceHash: hash, staleAt: null });
32
+ for (const r of this.to.get(section) ?? []) {
33
+ if (r.kind !== 'about') continue;
34
+ relation(r);
35
+ const key = factKeyOf(r.from);
36
+ const fact = key && (batch.facts.get(key) ?? this.facts.get(key));
37
+ if (fact && fact.origin === 'model') batch.fact(reanchor(fact));
38
+ for (const m of this.from.get(r.from) ?? []) if (m.kind === 'mentions') relation(m);
39
+ }
40
+ for (const r of this.from.get(section) ?? []) {
41
+ if (r.kind !== 'mentions') continue;
42
+ relation(r);
43
+ const ent = entities.get(r.to);
44
+ if (ent && ent.origin === 'model') {
45
+ const next = reanchor(ent);
46
+ entities.set(r.to, next);
47
+ batch.fact(next);
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Model facts anchored to `path` AND to another source, rewritten without that anchor — a
55
+ * deleted file never leaves a fact stale that other sources still back. A fact anchored only
56
+ * to `path` is untouched: it stays and shows stale (§5.2).
57
+ */
58
+ export function factsWithoutAnchor(facts: Iterable<StoredFact>, path: string): StoredFact[] {
59
+ return [...facts]
60
+ .filter((f) => f.origin === 'model' && f.fileAnchors.length > 1 && f.fileAnchors.some((a) => a.path === path))
61
+ .map((f) => ({ ...f, fileAnchors: f.fileAnchors.filter((a) => a.path !== path) }));
62
+ }
@@ -4,25 +4,44 @@
4
4
  * `planReview` and `reviewDirectory`, so the plan's numbers and the run agree.
5
5
  */
6
6
 
7
- import { ParserRegistry } from '../ingest/parsers.js';
7
+ import { htmlParser, markdownParser, ParserRegistry, plainTextParser } from '../ingest/parsers.js';
8
+ import { isBinaryDocumentType, mediaTypeOf } from '../ingest/parserSupport.js';
8
9
  import { CONTENT_HASH_FIELD, type ChunkFingerprint, type IngestManifest, type SourceDocument } from '../ingest/types.js';
9
10
  import type { KnowledgePack, KnowledgeParser } from './model.js';
10
11
  import { matchGlob } from './partitions.js';
11
- import { compareStr } from './refs.js';
12
+ import { compareStr, walkRelative } from './refs.js';
12
13
 
13
14
  /** Default per-file size cap (bytes). */
14
15
  export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
15
- /** Ignore files read through the source, when present. */
16
- export const IGNORE_FILES = ['.gitignore', '.builderforce/ignore'] as const;
16
+ /**
17
+ * Version of the extractors' output. Bump it whenever an extractor emits different nodes,
18
+ * edges or keys for the same text: cached `Extracted` of another version is ignored, and a
19
+ * review that finds a different version in {@link extractorManifestKey} re-extracts every file
20
+ * exactly once (judged sections with unchanged text are re-anchored, not judged again).
21
+ */
22
+ export const EXTRACTOR_VERSION = 1;
17
23
  /** Always ignored: VCS internals, installed dependencies, builderforce config. */
18
- const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '/.gitignore'];
24
+ const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore'];
19
25
 
20
26
  const MEDIA_TYPES: Record<string, string> = {
21
27
  md: 'text/markdown', markdown: 'text/markdown', mdx: 'text/markdown',
22
28
  html: 'text/html', htm: 'text/html', xhtml: 'application/xhtml+xml', xml: 'application/xml',
23
29
  json: 'application/json', csv: 'text/csv', tsv: 'text/tab-separated-values',
30
+ pdf: 'application/pdf',
31
+ doc: 'application/msword',
32
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
33
+ xls: 'application/vnd.ms-excel',
34
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
35
+ ppt: 'application/vnd.ms-powerpoint',
36
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
37
+ odt: 'application/vnd.oasis.opendocument.text',
38
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
39
+ odp: 'application/vnd.oasis.opendocument.presentation',
24
40
  };
25
41
 
42
+ /** Binary documents whose text a HOST extractor may supply (§4.5); otherwise skipped as binary. */
43
+ const DOCUMENT_EXT = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
44
+
26
45
  const BINARY_EXT = new Set([
27
46
  'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'icns', 'tif', 'tiff', 'psd', 'avif', 'heic',
28
47
  'mp3', 'mp4', 'mov', 'avi', 'mkv', 'webm', 'wav', 'flac', 'ogg', 'm4a',
@@ -46,6 +65,20 @@ export function isBinaryPath(path: string): boolean {
46
65
  return BINARY_EXT.has(extOf(path));
47
66
  }
48
67
 
68
+ export function isDocumentPath(path: string): boolean {
69
+ return DOCUMENT_EXT.has(extOf(path));
70
+ }
71
+
72
+ /**
73
+ * The pack whose parser claims a pdf/office file's media type — a host-registered
74
+ * extractor, wherever its pack sits: {@link composePacks} makes the builtin text parsers
75
+ * refuse binary document types ({@link isBinaryDocumentType}), so without a host parser
76
+ * nothing claims it and it stays binary.
77
+ */
78
+ export function resolveDocument(composed: ComposedPacks, path: string): ReturnType<ComposedPacks['resolve']> {
79
+ return composed.resolve(stubSource(path));
80
+ }
81
+
49
82
  /** A NUL in the first 8 KB means binary, whatever the extension said. */
50
83
  export function isBinaryText(text: string): boolean {
51
84
  return text.slice(0, 8192).includes('\u0000');
@@ -70,9 +103,28 @@ export interface ComposedPacks {
70
103
  resolve(source: SourceDocument): { parser: KnowledgeParser; pack: KnowledgePack } | undefined;
71
104
  }
72
105
 
106
+ /** The builtin text parsers, which would otherwise claim an office file's XML/plain-text media type. */
107
+ const BUILTIN_TEXT_PARSERS: ReadonlySet<KnowledgeParser> = new Set<KnowledgeParser>([markdownParser, htmlParser, plainTextParser]);
108
+
109
+ /**
110
+ * Within knowledge composition the builtin docs parsers do not accept binary document media
111
+ * types; a host-registered parser (any pack, any order) is untouched. The ingest pipeline
112
+ * keeps the builtins as they are.
113
+ */
114
+ const guardBuiltin = (p: KnowledgeParser): KnowledgeParser =>
115
+ BUILTIN_TEXT_PARSERS.has(p) ? { ...p, accepts: (s) => !isBinaryDocumentType(mediaTypeOf(s)) && p.accepts(s) } : p;
116
+
73
117
  export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
74
118
  const owner = new Map<KnowledgeParser, KnowledgePack>();
75
- for (const pack of packs) for (const p of pack.parsers) if (!owner.has(p)) owner.set(p, pack);
119
+ const guarded = new Map<KnowledgeParser, KnowledgeParser>();
120
+ for (const pack of packs) {
121
+ for (const p of pack.parsers) {
122
+ if (guarded.has(p)) continue;
123
+ const g = guardBuiltin(p);
124
+ guarded.set(p, g);
125
+ owner.set(g, pack);
126
+ }
127
+ }
76
128
  const registry = new ParserRegistry([...owner.keys()]);
77
129
  return {
78
130
  registry,
@@ -88,9 +140,16 @@ export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
88
140
  * A `.gitignore`-style matcher: `#` comments, `!` negation (last match wins), a trailing
89
141
  * `/` for directories only, a `/` elsewhere anchors to the root, otherwise any depth.
90
142
  */
91
- export function ignoreMatcher(texts: readonly string[]): (path: string) => boolean {
143
+ export function ignoreMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
92
144
  const rules: Array<{ glob: string; negate: boolean; dirOnly: boolean }> = [];
93
- for (const line of [...DEFAULT_IGNORES, ...texts.flatMap((t) => t.split(/\r?\n/))]) {
145
+ const lines = [
146
+ ...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
147
+ ...texts.flatMap((t) => {
148
+ const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
149
+ return text.split(/\r?\n/).map((line) => ({ line, base }));
150
+ }),
151
+ ];
152
+ for (const { line, base } of lines) {
94
153
  let p = line.replace(/\s+$/, '');
95
154
  if (!p || p.startsWith('#')) continue;
96
155
  const negate = p.startsWith('!');
@@ -99,7 +158,9 @@ export function ignoreMatcher(texts: readonly string[]): (path: string) => boole
99
158
  if (dirOnly) p = p.slice(0, -1);
100
159
  const anchored = p.includes('/');
101
160
  p = p.replace(/^\//, '');
102
- if (p) rules.push({ glob: anchored ? p : `**/${p}`, negate, dirOnly });
161
+ // A nested `.gitignore` scopes its patterns to its own folder.
162
+ const prefix = base ? `${base}/` : '';
163
+ if (p) rules.push({ glob: anchored ? `${prefix}${p}` : `${prefix}**/${p}`, negate, dirOnly });
103
164
  }
104
165
  return (path) => {
105
166
  const segments = path.split('/');
@@ -113,16 +174,49 @@ export function ignoreMatcher(texts: readonly string[]): (path: string) => boole
113
174
  };
114
175
  }
115
176
 
177
+ /**
178
+ * The ignore files present in a listing, each with the folder its patterns are relative to,
179
+ * in precedence order (the last match wins): every `.gitignore` — the root's first, then
180
+ * nested ones by path — and `.builderforce/ignore` LAST, so it can override them.
181
+ */
182
+ export function ignoreSourcesOf(paths: readonly string[]): Array<{ path: string; base: string }> {
183
+ const git: Array<{ path: string; base: string }> = [];
184
+ let builderforce = false;
185
+ for (const path of [...paths].sort(compareStr)) {
186
+ if (path === '.builderforce/ignore') builderforce = true;
187
+ else if (path === '.gitignore' || path.endsWith('/.gitignore')) {
188
+ if (path.split('/').some((seg) => seg === 'node_modules' || seg === '.git')) continue;
189
+ git.push({ path, base: path.slice(0, -'.gitignore'.length).replace(/\/$/, '') });
190
+ }
191
+ }
192
+ git.sort((a, b) => Number(a.base !== '') - Number(b.base !== '') || compareStr(a.path, b.path));
193
+ return builderforce ? [...git, { path: '.builderforce/ignore', base: '' }] : git;
194
+ }
195
+
116
196
  /** Manifest entry holding `{ id: path, hash }` for every reviewed file of a root. */
117
197
  export const filesManifestKey = (rootId: string): string => `knowledge:${rootId}`;
198
+ /** Manifest entry holding `{ id: 'version', hash: String(EXTRACTOR_VERSION) }`: the extractor version the files were last reviewed with. */
199
+ export const extractorManifestKey = (rootId: string): string => `knowledge:${rootId}:extractor`;
118
200
  /** Manifest entry holding `{ id: sectionRef, hash: textHash }` for every judged section. */
119
201
  export const judgedManifestKey = (rootId: string): string => `knowledge:${rootId}:judged`;
202
+ /** Manifest entry holding `{ id: claimRef, hash: fileHash }` for every claim still awaiting comparison. */
203
+ export const compareManifestKey = (rootId: string): string => `knowledge:${rootId}:compare`;
120
204
 
121
205
  export async function manifestMap(manifest: IngestManifest, key: string): Promise<Map<string, string>> {
122
206
  const prior: ChunkFingerprint[] = (await manifest.get(key)) ?? [];
123
207
  return new Map(prior.map((f) => [f.id, f.hash] as const));
124
208
  }
125
209
 
210
+ /** The extractor version a root was last fully reviewed with; undefined when never recorded (a pre-versioning manifest). */
211
+ export async function storedExtractorVersion(manifest: IngestManifest, rootId: string): Promise<number | undefined> {
212
+ const v = Number((await manifestMap(manifest, extractorManifestKey(rootId))).get('version'));
213
+ return Number.isFinite(v) ? v : undefined;
214
+ }
215
+
216
+ export async function saveExtractorVersion(manifest: IngestManifest, rootId: string): Promise<void> {
217
+ await manifest.set(extractorManifestKey(rootId), [{ id: 'version', hash: String(EXTRACTOR_VERSION) }]);
218
+ }
219
+
126
220
  export async function saveManifestMap(manifest: IngestManifest, key: string, map: ReadonlyMap<string, string>): Promise<void> {
127
221
  const entries = [...map].sort((a, b) => compareStr(a[0], b[0])).map(([id, hash]) => ({ id, hash }));
128
222
  await manifest.set(key, entries);
@@ -130,17 +224,9 @@ export async function saveManifestMap(manifest: IngestManifest, key: string, map
130
224
 
131
225
  /**
132
226
  * Resolves a link/import target against the linking file's folder (a leading `/` is the
133
- * root). Pure path arithmetic: undefined only when the target escapes the root.
227
+ * root). Pure path arithmetic: undefined when the target escapes the root or is the root itself.
134
228
  */
135
229
  export function resolveRelativePath(fromPath: string, target: string): string | undefined {
136
- const t = target.replace(/\\/g, '/');
137
- const out = t.startsWith('/') ? [] : fromPath.split('/').slice(0, -1);
138
- for (const seg of t.split('/')) {
139
- if (seg === '' || seg === '.') continue;
140
- if (seg === '..') {
141
- if (out.length === 0) return undefined;
142
- out.pop();
143
- } else out.push(seg);
144
- }
145
- return out.length ? out.join('/') : undefined;
230
+ const { ups, segments } = walkRelative(fromPath, target);
231
+ return ups > 0 || segments.length === 0 ? undefined : segments.join('/');
146
232
  }
@@ -4,9 +4,11 @@
4
4
  */
5
5
 
6
6
  import { hashText } from '../ingest/hash.js';
7
+ import { buildGraph } from './build.js';
7
8
  import type {
8
- DirectorySource, Extracted, JudgementPort, JudgementRequest, JudgementResult, KEdge, KNode, NodeRef,
9
+ DirectorySource, Extracted, JudgementPort, JudgementRequest, JudgementResult, KEdge, KNode, KnowledgeStore, NodeRef,
9
10
  } from './model.js';
11
+ import { DOCS_PACK } from './packs/docs.js';
10
12
  import { LocalSnapshotStore, type SnapshotPersistence } from './stores/localSnapshotStore.js';
11
13
  import { srcRef } from './refs.js';
12
14
 
@@ -90,3 +92,16 @@ export function extractedOf(node: KNode, edges: KEdge[] = []): Extracted {
90
92
  }
91
93
 
92
94
  export const ref = (path: string): NodeRef => srcRef(ROOT, path);
95
+
96
+ /** The graph of a reviewed source: its files' cached extracts joined with what the store holds. */
97
+ export async function graphOf(source: SpySource, store: KnowledgeStore) {
98
+ const extracted: Extracted[] = [];
99
+ for await (const f of source.list()) {
100
+ const hit = (await store.getExtracted!(f.hash))?.find((e) => e.sourceRef === srcRef(ROOT, f.path));
101
+ if (hit) extracted.push(hit);
102
+ }
103
+ return buildGraph({
104
+ rootId: ROOT, extracted, packs: [DOCS_PACK],
105
+ facts: await store.facts({ rootId: ROOT }), relations: await store.relations({ rootId: ROOT }),
106
+ });
107
+ }