@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,80 @@
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 } 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
+ /**
21
+ * The compare manifest persists age with each entry — `hash` is `<age>:<fileHash>`, age 0 the
22
+ * oldest — because a host manifest may hand entries back in id order. An entry without an age
23
+ * (written before ages were kept) reads as the oldest.
24
+ */
25
+ const ageOf = (hash: string): number => {
26
+ const sep = hash.indexOf(':');
27
+ const age = sep < 0 ? NaN : Number(hash.slice(0, sep));
28
+ return Number.isFinite(age) ? age : -1;
29
+ };
30
+
31
+ /** Claims a previous run left awaiting comparison, oldest first, read back from their stored facts (a gone fact drops out). */
32
+ export async function pendingClaims(manifest: IngestManifest, rootId: string, facts: ReadonlyMap<string, StoredFact>): Promise<PendingClaims> {
33
+ const out: PendingClaims = new Map();
34
+ const stored = (await manifest.get(compareManifestKey(rootId))) ?? [];
35
+ const oldestFirst = [...stored].sort((a, b) => ageOf(a.hash) - ageOf(b.hash) || compareStr(a.id, b.id));
36
+ for (const { id: ref } of oldestFirst) {
37
+ const fact = facts.get(factKeyOf(ref as NodeRef) ?? '');
38
+ if (fact?.key.startsWith('claim:')) out.set(ref, { text: claimTextOf(fact.content), hash: fact.fileAnchors[0]?.contentHash ?? '' });
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /**
44
+ * Compares `pending` against its near-duplicates, within the budget. Undefined when the
45
+ * phase cannot run (no judgement port, no index, nothing pending).
46
+ */
47
+ export async function compareNew(a: {
48
+ args: ReviewArgs; pending: PendingClaims; known: ReadonlyMap<string, StoredFact>; budget: JudgeBudget; batch: JudgedBatch;
49
+ onPairs(total: number): void;
50
+ }): Promise<CompareOutcome | undefined> {
51
+ const { args, pending } = a;
52
+ if (!args.judgement || !args.similar || pending.size === 0) return undefined;
53
+ const pairs = await args.similar([...pending.keys()].sort(compareStr), new Map([...pending].map(([ref, c]) => [ref, c.text] as const)));
54
+ const claims: PendingClaims = new Map(pending);
55
+ for (const p of pairs) {
56
+ for (const id of [p.a, p.b]) {
57
+ const fact = !claims.has(id) ? a.known.get(factKeyOf(id as NodeRef) ?? '') : undefined;
58
+ if (fact?.key.startsWith('claim:')) claims.set(id, { text: claimTextOf(fact.content), hash: fact.fileAnchors[0]?.contentHash ?? '' });
59
+ }
60
+ }
61
+ a.onPairs(pairs.length);
62
+ // Run even with the budget spent: compareClaims counts every pair it skips as unjudged.
63
+ return compareClaims({ port: args.judgement, pairs, claims, budget: a.budget, batch: a.batch, ...(args.signal ? { signal: args.signal } : {}) });
64
+ }
65
+
66
+ /**
67
+ * Persists the claims still awaiting comparison, capped at {@link MAX_AWAITING_CLAIMS} (the
68
+ * most recent: a previous run's first, this run's last — and the order survives the reload,
69
+ * see {@link pendingClaims}). Call it only when a pack asks for contradictions; an `outcome`
70
+ * undefined means the compare did not run (no ports, an abort before it), so every pending
71
+ * claim is kept, whereas after a compare only the pairs it skipped still wait.
72
+ */
73
+ export async function saveAwaiting(
74
+ manifest: IngestManifest, rootId: string, pending: PendingClaims, outcome: CompareOutcome | undefined,
75
+ ): Promise<void> {
76
+ const awaiting: Array<[string, string]> = [];
77
+ for (const [ref, c] of pending) if (!outcome || outcome.skipped.has(ref)) awaiting.push([ref, c.hash]);
78
+ const kept = awaiting.slice(-MAX_AWAITING_CLAIMS);
79
+ await manifest.set(compareManifestKey(rootId), kept.map(([id, hash], age) => ({ id, hash: `${age}:${hash}` })));
80
+ }
@@ -0,0 +1,81 @@
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
+ /**
67
+ * Near-duplicate claim pairs to compare / possible-same entities; from the knowledge index.
68
+ * Called with the pending claim refs (sorted) and, as an optional second argument, each
69
+ * ref's claim text (`subject predicate object`, the form the compare uses) — so a host
70
+ * need not re-read every fact to recover what the review already holds. A port that takes
71
+ * only `ids` keeps working.
72
+ */
73
+ similar?: (ids: string[], texts?: ReadonlyMap<string, string>) => Promise<SimilarPair[]>;
74
+ budget: { modelCalls: number; ms: number };
75
+ /** *Continue*: the plan the person confirmed. Reused without a re-walk; `changed` is re-read from the manifest. */
76
+ plan?: PlanDetail;
77
+ /** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
78
+ force?: boolean;
79
+ signal?: AbortSignal;
80
+ onProgress?(p: ReviewProgress): void;
81
+ }
@@ -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,45 @@
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} owes every file one
20
+ * re-extraction (judged sections with unchanged text are re-anchored, not judged again; see
21
+ * owedFiles.ts for how an unfinished one is carried to the next review).
22
+ */
23
+ export const EXTRACTOR_VERSION = 1;
17
24
  /** Always ignored: VCS internals, installed dependencies, builderforce config. */
18
- const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '/.gitignore'];
25
+ const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore'];
19
26
 
20
27
  const MEDIA_TYPES: Record<string, string> = {
21
28
  md: 'text/markdown', markdown: 'text/markdown', mdx: 'text/markdown',
22
29
  html: 'text/html', htm: 'text/html', xhtml: 'application/xhtml+xml', xml: 'application/xml',
23
30
  json: 'application/json', csv: 'text/csv', tsv: 'text/tab-separated-values',
31
+ pdf: 'application/pdf',
32
+ doc: 'application/msword',
33
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
34
+ xls: 'application/vnd.ms-excel',
35
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
36
+ ppt: 'application/vnd.ms-powerpoint',
37
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
38
+ odt: 'application/vnd.oasis.opendocument.text',
39
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
40
+ odp: 'application/vnd.oasis.opendocument.presentation',
24
41
  };
25
42
 
43
+ /** Binary documents whose text a HOST extractor may supply (§4.5); otherwise skipped as binary. */
44
+ const DOCUMENT_EXT = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
45
+
26
46
  const BINARY_EXT = new Set([
27
47
  'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'icns', 'tif', 'tiff', 'psd', 'avif', 'heic',
28
48
  'mp3', 'mp4', 'mov', 'avi', 'mkv', 'webm', 'wav', 'flac', 'ogg', 'm4a',
@@ -46,6 +66,20 @@ export function isBinaryPath(path: string): boolean {
46
66
  return BINARY_EXT.has(extOf(path));
47
67
  }
48
68
 
69
+ export function isDocumentPath(path: string): boolean {
70
+ return DOCUMENT_EXT.has(extOf(path));
71
+ }
72
+
73
+ /**
74
+ * The pack whose parser claims a pdf/office file's media type — a host-registered
75
+ * extractor, wherever its pack sits: {@link composePacks} makes the builtin text parsers
76
+ * refuse binary document types ({@link isBinaryDocumentType}), so without a host parser
77
+ * nothing claims it and it stays binary.
78
+ */
79
+ export function resolveDocument(composed: ComposedPacks, path: string): ReturnType<ComposedPacks['resolve']> {
80
+ return composed.resolve(stubSource(path));
81
+ }
82
+
49
83
  /** A NUL in the first 8 KB means binary, whatever the extension said. */
50
84
  export function isBinaryText(text: string): boolean {
51
85
  return text.slice(0, 8192).includes('\u0000');
@@ -70,9 +104,28 @@ export interface ComposedPacks {
70
104
  resolve(source: SourceDocument): { parser: KnowledgeParser; pack: KnowledgePack } | undefined;
71
105
  }
72
106
 
107
+ /** The builtin text parsers, which would otherwise claim an office file's XML/plain-text media type. */
108
+ const BUILTIN_TEXT_PARSERS: ReadonlySet<KnowledgeParser> = new Set<KnowledgeParser>([markdownParser, htmlParser, plainTextParser]);
109
+
110
+ /**
111
+ * Within knowledge composition the builtin docs parsers do not accept binary document media
112
+ * types; a host-registered parser (any pack, any order) is untouched. The ingest pipeline
113
+ * keeps the builtins as they are.
114
+ */
115
+ const guardBuiltin = (p: KnowledgeParser): KnowledgeParser =>
116
+ BUILTIN_TEXT_PARSERS.has(p) ? { ...p, accepts: (s) => !isBinaryDocumentType(mediaTypeOf(s)) && p.accepts(s) } : p;
117
+
73
118
  export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
74
119
  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);
120
+ const guarded = new Map<KnowledgeParser, KnowledgeParser>();
121
+ for (const pack of packs) {
122
+ for (const p of pack.parsers) {
123
+ if (guarded.has(p)) continue;
124
+ const g = guardBuiltin(p);
125
+ guarded.set(p, g);
126
+ owner.set(g, pack);
127
+ }
128
+ }
76
129
  const registry = new ParserRegistry([...owner.keys()]);
77
130
  return {
78
131
  registry,
@@ -88,9 +141,16 @@ export function composePacks(packs: readonly KnowledgePack[]): ComposedPacks {
88
141
  * A `.gitignore`-style matcher: `#` comments, `!` negation (last match wins), a trailing
89
142
  * `/` for directories only, a `/` elsewhere anchors to the root, otherwise any depth.
90
143
  */
91
- export function ignoreMatcher(texts: readonly string[]): (path: string) => boolean {
144
+ export function ignoreMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
92
145
  const rules: Array<{ glob: string; negate: boolean; dirOnly: boolean }> = [];
93
- for (const line of [...DEFAULT_IGNORES, ...texts.flatMap((t) => t.split(/\r?\n/))]) {
146
+ const lines = [
147
+ ...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
148
+ ...texts.flatMap((t) => {
149
+ const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
150
+ return text.split(/\r?\n/).map((line) => ({ line, base }));
151
+ }),
152
+ ];
153
+ for (const { line, base } of lines) {
94
154
  let p = line.replace(/\s+$/, '');
95
155
  if (!p || p.startsWith('#')) continue;
96
156
  const negate = p.startsWith('!');
@@ -99,7 +159,9 @@ export function ignoreMatcher(texts: readonly string[]): (path: string) => boole
99
159
  if (dirOnly) p = p.slice(0, -1);
100
160
  const anchored = p.includes('/');
101
161
  p = p.replace(/^\//, '');
102
- if (p) rules.push({ glob: anchored ? p : `**/${p}`, negate, dirOnly });
162
+ // A nested `.gitignore` scopes its patterns to its own folder.
163
+ const prefix = base ? `${base}/` : '';
164
+ if (p) rules.push({ glob: anchored ? `${prefix}${p}` : `${prefix}**/${p}`, negate, dirOnly });
103
165
  }
104
166
  return (path) => {
105
167
  const segments = path.split('/');
@@ -113,10 +175,33 @@ export function ignoreMatcher(texts: readonly string[]): (path: string) => boole
113
175
  };
114
176
  }
115
177
 
178
+ /**
179
+ * The ignore files present in a listing, each with the folder its patterns are relative to,
180
+ * in precedence order (the last match wins): every `.gitignore` — the root's first, then
181
+ * nested ones by path — and `.builderforce/ignore` LAST, so it can override them.
182
+ */
183
+ export function ignoreSourcesOf(paths: readonly string[]): Array<{ path: string; base: string }> {
184
+ const git: Array<{ path: string; base: string }> = [];
185
+ let builderforce = false;
186
+ for (const path of [...paths].sort(compareStr)) {
187
+ if (path === '.builderforce/ignore') builderforce = true;
188
+ else if (path === '.gitignore' || path.endsWith('/.gitignore')) {
189
+ if (path.split('/').some((seg) => seg === 'node_modules' || seg === '.git')) continue;
190
+ git.push({ path, base: path.slice(0, -'.gitignore'.length).replace(/\/$/, '') });
191
+ }
192
+ }
193
+ git.sort((a, b) => Number(a.base !== '') - Number(b.base !== '') || compareStr(a.path, b.path));
194
+ return builderforce ? [...git, { path: '.builderforce/ignore', base: '' }] : git;
195
+ }
196
+
116
197
  /** Manifest entry holding `{ id: path, hash }` for every reviewed file of a root. */
117
198
  export const filesManifestKey = (rootId: string): string => `knowledge:${rootId}`;
199
+ /** Manifest entry holding the extractor version the files were last reviewed with, and the files still owed a re-extraction (owedFiles.ts). */
200
+ export const extractorManifestKey = (rootId: string): string => `knowledge:${rootId}:extractor`;
118
201
  /** Manifest entry holding `{ id: sectionRef, hash: textHash }` for every judged section. */
119
202
  export const judgedManifestKey = (rootId: string): string => `knowledge:${rootId}:judged`;
203
+ /** Manifest entry holding `{ id: claimRef, hash: '<age>:<fileHash>' }` for every claim still awaiting comparison (age 0 = oldest). */
204
+ export const compareManifestKey = (rootId: string): string => `knowledge:${rootId}:compare`;
120
205
 
121
206
  export async function manifestMap(manifest: IngestManifest, key: string): Promise<Map<string, string>> {
122
207
  const prior: ChunkFingerprint[] = (await manifest.get(key)) ?? [];
@@ -130,17 +215,9 @@ export async function saveManifestMap(manifest: IngestManifest, key: string, map
130
215
 
131
216
  /**
132
217
  * 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.
218
+ * root). Pure path arithmetic: undefined when the target escapes the root or is the root itself.
134
219
  */
135
220
  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;
221
+ const { ups, segments } = walkRelative(fromPath, target);
222
+ return ups > 0 || segments.length === 0 ? undefined : segments.join('/');
146
223
  }
@@ -4,9 +4,13 @@
4
4
  */
5
5
 
6
6
  import { hashText } from '../ingest/hash.js';
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { buildGraph } from './build.js';
7
9
  import type {
8
- DirectorySource, Extracted, JudgementPort, JudgementRequest, JudgementResult, KEdge, KNode, NodeRef,
10
+ DirectorySource, Extracted, JudgementPort, JudgementRequest, JudgementResult, KEdge, KNode, KnowledgePack, KnowledgeStore, NodeRef, ReviewArgs,
9
11
  } from './model.js';
12
+ import { loadExtractorState } from './owedFiles.js';
13
+ import { DOCS_PACK } from './packs/docs.js';
10
14
  import { LocalSnapshotStore, type SnapshotPersistence } from './stores/localSnapshotStore.js';
11
15
  import { srcRef } from './refs.js';
12
16
 
@@ -46,6 +50,27 @@ export function memStore(): LocalSnapshotStore {
46
50
  return new LocalSnapshotStore(memPersistence(), { now: () => '2026-10-28T00:00:00.000Z' });
47
51
  }
48
52
 
53
+ /** Three one-section docs, the common fixture of the review tests. */
54
+ export const FILES = { 'a.md': '# A\nalpha\n', 'b.md': '# B\nbeta\n', 'c.md': '# C\ngamma\n' };
55
+ export const ALL = ['a.md', 'b.md', 'c.md'];
56
+
57
+ /** `ReviewArgs` over the docs pack with a generous budget; `extra` overrides anything. */
58
+ export const args = (
59
+ source: SpySource, store: KnowledgeStore = memStore(), manifest = new InMemoryIngestManifest(), extra: Partial<ReviewArgs> = {},
60
+ ): ReviewArgs => ({ source, store, manifest, packs: [DOCS_PACK], budget: { modelCalls: 200, ms: 60_000 }, ...extra });
61
+
62
+ /** A root's extractor entry as `{ version, owed: sorted paths }`. */
63
+ export async function stateOf(manifest: InMemoryIngestManifest) {
64
+ const { version, owed } = await loadExtractorState(manifest, ROOT);
65
+ return { version, owed: [...owed.keys()].sort() };
66
+ }
67
+
68
+ /** A `similar` port that pairs the first two ids it is given (nothing to pair with fewer). */
69
+ export const similar = async (ids: string[]) => (ids.length >= 2 ? [{ a: ids[0]!, b: ids[1]!, similarity: 0.95 }] : []);
70
+
71
+ /** The docs pack with contradictions off: no compare phase, so no awaiting set. */
72
+ export const quietPack: KnowledgePack = { ...DOCS_PACK, judgement: { ...DOCS_PACK.judgement!, contradictions: false } };
73
+
49
74
  /** Answers every extract with one claim + one entity, every compare with `contradicts`. */
50
75
  export function fakeJudge(
51
76
  shape: (req: JudgementRequest) => JudgementResult = defaultJudgement,
@@ -90,3 +115,16 @@ export function extractedOf(node: KNode, edges: KEdge[] = []): Extracted {
90
115
  }
91
116
 
92
117
  export const ref = (path: string): NodeRef => srcRef(ROOT, path);
118
+
119
+ /** The graph of a reviewed source: its files' cached extracts joined with what the store holds. */
120
+ export async function graphOf(source: SpySource, store: KnowledgeStore) {
121
+ const extracted: Extracted[] = [];
122
+ for await (const f of source.list()) {
123
+ const hit = (await store.getExtracted!(f.hash))?.find((e) => e.sourceRef === srcRef(ROOT, f.path));
124
+ if (hit) extracted.push(hit);
125
+ }
126
+ return buildGraph({
127
+ rootId: ROOT, extracted, packs: [DOCS_PACK],
128
+ facts: await store.facts({ rootId: ROOT }), relations: await store.relations({ rootId: ROOT }),
129
+ });
130
+ }
@@ -1,15 +1,15 @@
1
1
  /**
2
2
  * knowledge/truncate.ts — the graph opens bounded (PRD 38 §5.3).
3
3
  *
4
- * Always kept: focus nodes, every node named by a finding, changed nodes, and the 1-hop
5
- * neighbours of all of those (up to the hard cap). The rest of the budget goes by
6
- * importance (then ref). Everything else folds into `area` nodes; edges are re-pointed to
7
- * the areas, merged, and self-loops dropped.
4
+ * The top `maxNodes` by importance (then ref), PLUS focus nodes, every node named by a
5
+ * finding, changed nodes and the 1-hop neighbours of all of those — up to the hard cap.
6
+ * Everything else folds into `area` nodes; edges are re-pointed to the areas, merged, and
7
+ * self-loops dropped.
8
8
  */
9
9
 
10
10
  import type { EdgeVerdict, KEdge, KNode, KnowledgeGraph, NodeRef } from './model.js';
11
11
  import { areaImportance, byImportance } from './importance.js';
12
- import { compareStr, pathOfRef, srcRef } from './refs.js';
12
+ import { aboutTargets, compareStr, pathOfRef, srcRef } from './refs.js';
13
13
 
14
14
  /** Hard cap on nodes, however many the keep rules ask for. */
15
15
  export const TRUNCATION_HARD_CAP = 2000;
@@ -50,14 +50,10 @@ export function truncateGraph(g: KnowledgeGraph, opts: TruncateOptions): { nodes
50
50
  const around = [...(neighbours.get(s) ?? [])].map((r) => byRef.get(r)!).filter(Boolean).sort(byImportance);
51
51
  for (const n of around) keep(n.ref);
52
52
  }
53
- for (const n of [...g.nodes].sort(byImportance)) {
54
- if (kept.length >= opts.maxNodes) break;
55
- keep(n.ref);
56
- }
53
+ for (const n of [...g.nodes].sort(byImportance).slice(0, opts.maxNodes)) keep(n.ref);
57
54
 
58
55
  // Fold the rest into areas.
59
- const aboutTarget = new Map<NodeRef, NodeRef>();
60
- for (const e of g.edges) if (e.kind === 'about' && !aboutTarget.has(e.from)) aboutTarget.set(e.from, e.to);
56
+ const aboutTarget = aboutTargets(g.edges);
61
57
  const rootId = g.scope.rootId;
62
58
  const areaOf = (n: KNode): NodeRef => {
63
59
  if (n.area) return n.area;
@@ -96,6 +92,7 @@ export function truncateGraph(g: KnowledgeGraph, opts: TruncateOptions): { nodes
96
92
  if (!prior) { edges.set(id, { ...e, from, to }); continue; }
97
93
  prior.weight += e.weight;
98
94
  if (e.cycle) prior.cycle = true;
95
+ if (e.stale) prior.stale = true;
99
96
  if (e.confidence !== undefined) prior.confidence = Math.max(prior.confidence ?? 0, e.confidence);
100
97
  if (e.verdict && (!prior.verdict || VERDICT_RANK[e.verdict] > VERDICT_RANK[prior.verdict])) prior.verdict = e.verdict;
101
98
  }
@@ -76,6 +76,11 @@ export interface ChatClient {
76
76
  apiKey: string;
77
77
  /** Abort a request after this long. Default: no limit beyond the caller's signal. */
78
78
  timeoutMs?: number;
79
+ /**
80
+ * Extra request headers a gateway needs (tenant / run attribution, …). They cannot
81
+ * override `Content-Type`, `Authorization` or `Accept`.
82
+ */
83
+ headers?: Record<string, string>;
79
84
  }
80
85
 
81
86
  /** A non-2xx answer, with the status and (bounded) body kept apart for the caller's message. */
@@ -88,6 +93,13 @@ export class ChatCompletionError extends Error {
88
93
 
89
94
  const ERROR_BODY_CHARS = 300;
90
95
 
96
+ /** Header names the client owns; `ChatClient.headers` may not set them, in any letter case. */
97
+ const RESERVED_HEADERS = new Set(['content-type', 'authorization', 'accept']);
98
+
99
+ function extraHeaders(headers: Record<string, string> | undefined): Record<string, string> {
100
+ return Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => !RESERVED_HEADERS.has(name.toLowerCase())));
101
+ }
102
+
91
103
  function chatBody(req: ChatRequest, stream: boolean): string {
92
104
  return JSON.stringify({
93
105
  ...(req.model ? { model: req.model } : {}),
@@ -108,6 +120,7 @@ async function post(client: ChatClient, req: ChatRequest, stream: boolean, signa
108
120
  const res = await fetch(`${client.baseUrl.replace(/\/$/, '')}/chat/completions`, {
109
121
  method: 'POST',
110
122
  headers: {
123
+ ...extraHeaders(client.headers),
111
124
  'Content-Type': 'application/json',
112
125
  Authorization: `Bearer ${client.apiKey}`,
113
126
  ...(stream ? { Accept: 'text/event-stream' } : {}),