@seanhogg/builderforce-memory 2026.10.62 → 2026.10.66

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 (177) hide show
  1. package/dist/knowledge/pack/frame.d.ts +12 -3
  2. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  3. package/dist/knowledge/pack/frame.js +18 -4
  4. package/dist/knowledge/pack/frame.js.map +1 -1
  5. package/dist/knowledge/pack/manifest.d.ts +11 -3
  6. package/dist/knowledge/pack/manifest.d.ts.map +1 -1
  7. package/dist/knowledge/pack/manifest.js +26 -12
  8. package/dist/knowledge/pack/manifest.js.map +1 -1
  9. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
  10. package/dist/knowledge/pack/sections/extr.js +16 -4
  11. package/dist/knowledge/pack/sections/extr.js.map +1 -1
  12. package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
  13. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
  14. package/dist/knowledge/pack/sections/extrLists.js +5 -6
  15. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  16. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  17. package/dist/knowledge/pack/sections/facts.js +3 -2
  18. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  19. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  20. package/dist/knowledge/pack/sections/rows.js +11 -2
  21. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  22. package/dist/knowledge/pack/strings.d.ts.map +1 -1
  23. package/dist/knowledge/pack/strings.js +6 -1
  24. package/dist/knowledge/pack/strings.js.map +1 -1
  25. package/dist/knowledge/pack/varint.d.ts +14 -0
  26. package/dist/knowledge/pack/varint.d.ts.map +1 -1
  27. package/dist/knowledge/pack/varint.js +32 -1
  28. package/dist/knowledge/pack/varint.js.map +1 -1
  29. package/dist/knowledge/review.d.ts +6 -6
  30. package/dist/knowledge/review.d.ts.map +1 -1
  31. package/dist/knowledge/review.js +56 -329
  32. package/dist/knowledge/review.js.map +1 -1
  33. package/dist/knowledge/reviewAnalyse.d.ts +17 -0
  34. package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
  35. package/dist/knowledge/reviewAnalyse.js +61 -0
  36. package/dist/knowledge/reviewAnalyse.js.map +1 -0
  37. package/dist/knowledge/reviewApply.d.ts +33 -0
  38. package/dist/knowledge/reviewApply.d.ts.map +1 -0
  39. package/dist/knowledge/reviewApply.js +121 -0
  40. package/dist/knowledge/reviewApply.js.map +1 -0
  41. package/dist/knowledge/reviewContext.d.ts +77 -0
  42. package/dist/knowledge/reviewContext.d.ts.map +1 -0
  43. package/dist/knowledge/reviewContext.js +111 -0
  44. package/dist/knowledge/reviewContext.js.map +1 -0
  45. package/dist/knowledge/reviewFinish.d.ts +9 -0
  46. package/dist/knowledge/reviewFinish.d.ts.map +1 -0
  47. package/dist/knowledge/reviewFinish.js +62 -0
  48. package/dist/knowledge/reviewFinish.js.map +1 -0
  49. package/dist/knowledge/reviewRunModel.d.ts +3 -0
  50. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  51. package/dist/knowledge/reviewRunModel.js.map +1 -1
  52. package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
  53. package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
  54. package/dist/knowledge/stores/extractLogWriter.js +38 -13
  55. package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
  56. package/dist/knowledge/stores/extractRefs.d.ts +68 -0
  57. package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
  58. package/dist/knowledge/stores/extractRefs.js +168 -0
  59. package/dist/knowledge/stores/extractRefs.js.map +1 -0
  60. package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
  61. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  62. package/dist/knowledge/stores/localSnapshotStore.js +25 -5
  63. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  64. package/dist/knowledge/stores/rowDelta.d.ts +6 -0
  65. package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
  66. package/dist/knowledge/stores/rowDelta.js.map +1 -1
  67. package/dist/knowledge/stores/rowMemory.d.ts +30 -0
  68. package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
  69. package/dist/knowledge/stores/rowMemory.js +46 -1
  70. package/dist/knowledge/stores/rowMemory.js.map +1 -1
  71. package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
  72. package/dist/knowledge/stores/rowSync.js +2 -1
  73. package/dist/knowledge/stores/rowSync.js.map +1 -1
  74. package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
  75. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
  76. package/dist/knowledge/stores/snapshotFormat.js +22 -9
  77. package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
  78. package/dist/stats/distributions.d.ts +34 -0
  79. package/dist/stats/distributions.d.ts.map +1 -0
  80. package/dist/stats/distributions.js +180 -0
  81. package/dist/stats/distributions.js.map +1 -0
  82. package/dist/stats/estimators.d.ts +53 -0
  83. package/dist/stats/estimators.d.ts.map +1 -0
  84. package/dist/stats/estimators.js +79 -0
  85. package/dist/stats/estimators.js.map +1 -0
  86. package/dist/stats/fitting.d.ts +48 -0
  87. package/dist/stats/fitting.d.ts.map +1 -0
  88. package/dist/stats/fitting.js +209 -0
  89. package/dist/stats/fitting.js.map +1 -0
  90. package/dist/stats/index.d.ts +26 -0
  91. package/dist/stats/index.d.ts.map +1 -0
  92. package/dist/stats/index.js +18 -0
  93. package/dist/stats/index.js.map +1 -0
  94. package/dist/stats/information.d.ts +9 -0
  95. package/dist/stats/information.d.ts.map +1 -0
  96. package/dist/stats/information.js +21 -0
  97. package/dist/stats/information.js.map +1 -0
  98. package/dist/stats/multivariate.d.ts +25 -0
  99. package/dist/stats/multivariate.d.ts.map +1 -0
  100. package/dist/stats/multivariate.js +89 -0
  101. package/dist/stats/multivariate.js.map +1 -0
  102. package/dist/stats/policies.d.ts +19 -0
  103. package/dist/stats/policies.d.ts.map +1 -0
  104. package/dist/stats/policies.js +75 -0
  105. package/dist/stats/policies.js.map +1 -0
  106. package/dist/stats/prng.d.ts +11 -0
  107. package/dist/stats/prng.d.ts.map +1 -0
  108. package/dist/stats/prng.js +41 -0
  109. package/dist/stats/prng.js.map +1 -0
  110. package/dist/stats/scores.d.ts +33 -0
  111. package/dist/stats/scores.d.ts.map +1 -0
  112. package/dist/stats/scores.js +134 -0
  113. package/dist/stats/scores.js.map +1 -0
  114. package/dist/stats/tests.d.ts +48 -0
  115. package/dist/stats/tests.d.ts.map +1 -0
  116. package/dist/stats/tests.js +143 -0
  117. package/dist/stats/tests.js.map +1 -0
  118. package/dist/stats/timeSeries.d.ts +34 -0
  119. package/dist/stats/timeSeries.d.ts.map +1 -0
  120. package/dist/stats/timeSeries.js +71 -0
  121. package/dist/stats/timeSeries.js.map +1 -0
  122. package/dist/working/fold.d.ts +65 -0
  123. package/dist/working/fold.d.ts.map +1 -0
  124. package/dist/working/fold.js +228 -0
  125. package/dist/working/fold.js.map +1 -0
  126. package/dist/working/index.d.ts +3 -0
  127. package/dist/working/index.d.ts.map +1 -1
  128. package/dist/working/index.js +2 -0
  129. package/dist/working/index.js.map +1 -1
  130. package/dist/working/textSummary.d.ts +46 -0
  131. package/dist/working/textSummary.d.ts.map +1 -0
  132. package/dist/working/textSummary.js +142 -0
  133. package/dist/working/textSummary.js.map +1 -0
  134. package/package.json +5 -1
  135. package/src/contract/exports.snapshot.json +48 -1
  136. package/src/contract/regression.extractEviction.test.ts +162 -0
  137. package/src/contract/regression.fixCommits.test.ts +112 -0
  138. package/src/contract/regression.packWire.test.ts +174 -0
  139. package/src/contract/types.contract.test.ts +2 -1
  140. package/src/knowledge/pack/frame.ts +21 -5
  141. package/src/knowledge/pack/manifest.ts +26 -11
  142. package/src/knowledge/pack/sections/extr.ts +14 -4
  143. package/src/knowledge/pack/sections/extrLists.ts +4 -6
  144. package/src/knowledge/pack/sections/facts.ts +3 -2
  145. package/src/knowledge/pack/sections/rows.ts +11 -2
  146. package/src/knowledge/pack/strings.ts +5 -1
  147. package/src/knowledge/pack/varint.ts +33 -1
  148. package/src/knowledge/review.ts +58 -311
  149. package/src/knowledge/reviewAnalyse.ts +59 -0
  150. package/src/knowledge/reviewApply.ts +128 -0
  151. package/src/knowledge/reviewContext.ts +158 -0
  152. package/src/knowledge/reviewFinish.ts +63 -0
  153. package/src/knowledge/reviewRunModel.ts +3 -0
  154. package/src/knowledge/stores/extractLogWriter.ts +36 -12
  155. package/src/knowledge/stores/extractRefs.ts +161 -0
  156. package/src/knowledge/stores/localSnapshotStore.ts +22 -5
  157. package/src/knowledge/stores/rowDelta.ts +6 -0
  158. package/src/knowledge/stores/rowMemory.ts +50 -1
  159. package/src/knowledge/stores/rowSync.ts +2 -1
  160. package/src/knowledge/stores/snapshotFormat.ts +27 -10
  161. package/src/stats/distributions.ts +180 -0
  162. package/src/stats/estimators.ts +101 -0
  163. package/src/stats/fitting.ts +252 -0
  164. package/src/stats/index.ts +59 -0
  165. package/src/stats/information.ts +20 -0
  166. package/src/stats/multivariate.ts +93 -0
  167. package/src/stats/policies.ts +84 -0
  168. package/src/stats/prng.ts +45 -0
  169. package/src/stats/scores.ts +135 -0
  170. package/src/stats/stats.test.ts +294 -0
  171. package/src/stats/tests.ts +164 -0
  172. package/src/stats/timeSeries.ts +92 -0
  173. package/src/working/fold.test.ts +196 -0
  174. package/src/working/fold.ts +252 -0
  175. package/src/working/index.ts +13 -0
  176. package/src/working/textSummary.test.ts +113 -0
  177. package/src/working/textSummary.ts +156 -0
@@ -0,0 +1,158 @@
1
+ /**
2
+ * knowledge/reviewContext.ts — the state ONE review run shares between its stages (review.ts): the plan and what the store
3
+ * holds (opened by {@link openReview}), the run's books (files finished, owed, failed), and the two store writes every stage
4
+ * uses: {@link writeBatch} (the judged batch, with the scope) and {@link retire} (sources that are gone).
5
+ *
6
+ * Moved out of review.ts's one long closure so each stage is a function of this context. No behaviour of its own beyond that.
7
+ */
8
+
9
+ import type { ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation } from './model.js';
10
+ import { planDetail, refreshPlan, type PlanDetail, type PlannedFile } from './plan.js';
11
+ import { composePacks, judgedManifestKey, manifestMap } from './sources.js';
12
+ import { knownKeysOfEntities } from './extractFile.js';
13
+ import { backfillCandidates, backfillNoExtract } from './backfillNoExtract.js';
14
+ import { DEFAULT_REVIEW_MODEL_CALLS, JudgedBatch, type JudgeBudget } from './judge.js';
15
+ import { JudgeBreaker } from './judgeCalls.js';
16
+ import { pendingClaims, type PendingClaims } from './reviewCompare.js';
17
+ import { factsWithoutAnchor, StoredIndex } from './reviewStored.js';
18
+ import { compareStr, srcRef } from './refs.js';
19
+ import type { ComposedPacks } from './sources.js';
20
+ import type { NodeRef } from './model.js';
21
+
22
+ export type ReviewProgressEvent = Parameters<NonNullable<ReviewArgs['onProgress']>>[0];
23
+
24
+ export interface ReviewContext {
25
+ args: ReviewArgs;
26
+ rootId: string;
27
+ scope: { rootId: string };
28
+ scopeRecord: ScopeRecord;
29
+ packIds: string[];
30
+ report: ReviewReport;
31
+ detail: PlanDetail;
32
+ composed: ComposedPacks;
33
+ stored: StoredIndex;
34
+ entities: Map<string, StoredFact>;
35
+ knownKeys: ReadonlyMap<string, NodeRef>;
36
+ budget: JudgeBudget;
37
+ batch: JudgedBatch;
38
+ breaker: JudgeBreaker;
39
+ judgedPrior: Map<string, string>;
40
+ judgedNow: Map<string, string>;
41
+ /** The files manifest as this run leaves it. */
42
+ filesNow: Map<string, string>;
43
+ newClaims: PendingClaims;
44
+ /** Changed files of the plan, and the ones this run works on (`only` narrows them, in its order). */
45
+ changed: PlannedFile[];
46
+ work: PlannedFile[];
47
+ /** Files whose judging is still owed. */
48
+ owedJudge: string[];
49
+ /** Changed files this run finished (or had nothing to do for). */
50
+ finished: Set<string>;
51
+ /** Files that failed for a reason that says nothing final about them, at the manifest's own bytes. */
52
+ unreadable: Set<string>;
53
+ /** Consecutive transient failures by path at one hash. */
54
+ failures: Map<string, { hash: string; count: number }>;
55
+ /** Model calls each unfinished file is still owed. */
56
+ measured: Map<string, number>;
57
+ /** Facts a retire rewrote: a later retire never restores an anchor an earlier one dropped. */
58
+ rewritten: Map<string, StoredFact>;
59
+ started: number;
60
+ now(): number;
61
+ progress(p: ReviewProgressEvent): void;
62
+ /** Answers a replica's re-check request for `hash`, once its work is done. */
63
+ settledRecheck(hash: string): Promise<void>;
64
+ }
65
+
66
+ const emptyReport = (rootId: string): ReviewReport => ({
67
+ rootId, digest: '', extracted: 0, judged: 0, unjudged: 0, invalidJudgements: 0,
68
+ factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], awaitingJudge: [], aborted: false, durationMs: 0,
69
+ });
70
+
71
+ /** Plans the run, reads what the store holds of the root, preloads the extract cache and runs the no-extract backfill. */
72
+ export async function openReview(args: ReviewArgs): Promise<ReviewContext> {
73
+ const now = () => Date.now();
74
+ const started = now();
75
+ const { source, store, packs, manifest, signal } = args;
76
+ const rootId = source.rootId;
77
+ const scope = { rootId };
78
+ const progress = (p: ReviewProgressEvent) => args.onProgress?.(p);
79
+
80
+ const detail = args.plan
81
+ ? await refreshPlan(args.plan, manifest)
82
+ : await planDetail(source, manifest, packs, { ...(args.force ? { force: true } : {}), compare: !!args.similar && !!args.judgement });
83
+ progress({ phase: 'plan', done: detail.files.length, total: detail.files.length });
84
+ const packIds = packs.map((p) => p.id).sort(compareStr);
85
+ const [storedFacts, storedRelations] = await Promise.all([store.facts(scope), store.relations(scope)]);
86
+ const stored = new StoredIndex(storedFacts, storedRelations);
87
+ const entities = new Map(storedFacts.filter((f) => f.key.startsWith('ent:')).map((f) => [f.key, f] as const));
88
+ const judgedPrior = await manifestMap(manifest, judgedManifestKey(rootId));
89
+ // Files with no stored body: assets the manifest names (queued so their node is written, no read) and the ones a replica asked to re-check (queued; this review stores their body or asset node).
90
+ const asked = (await store.recheckHashes?.()) ?? [];
91
+ // ONE bulk fetch of the extract cache for the whole run instead of a round trip per file: the files this run extracts and the ones the backfill looks up.
92
+ const preChanged = detail.files.filter((f) => f.changed && (!args.only || args.only.includes(f.path)));
93
+ const preload = [...new Set([...preChanged.map((f) => f.hash), ...backfillCandidates(detail, asked)])];
94
+ if (preload.length > 0) await store.preloadExtracted?.(preload);
95
+ await backfillNoExtract({ store, detail, asked, only: args.only, signal });
96
+ // A re-check request is answered only when the work it asked for is done: the body stored, the binary recorded, or the failure recorded.
97
+ const askedSet = new Set(asked);
98
+ // Claims awaiting comparison: those a previous run could not compare, then this run's.
99
+ const newClaims = await pendingClaims(manifest, rootId, stored.facts);
100
+
101
+ const changed = detail.files.filter((f) => f.changed);
102
+ // `only` (pass 2) narrows what this run works on; the other changed files are untouched and stay owed (owedAfterRun sees them all).
103
+ // Pass 2 works in the order it was given (priority), so a model-call ceiling is spent on the most important files first.
104
+ const byPath = new Map(changed.map((f) => [f.path, f] as const));
105
+ return {
106
+ args, rootId, scope, scopeRecord: { rootId, title: source.title, packs: packIds }, packIds, report: emptyReport(rootId),
107
+ detail, composed: composePacks(packs), stored, entities, knownKeys: knownKeysOfEntities(entities.keys()),
108
+ budget: {
109
+ modelCalls: args.budget?.modelCalls ?? DEFAULT_REVIEW_MODEL_CALLS,
110
+ deadline: started + (Number.isFinite(args.budget?.ms) ? args.budget.ms : Number.POSITIVE_INFINITY),
111
+ used: 0, now,
112
+ },
113
+ batch: new JudgedBatch(), breaker: new JudgeBreaker(),
114
+ judgedPrior, judgedNow: new Map(judgedPrior), filesNow: new Map(detail.prior), newClaims,
115
+ changed, work: args.only ? args.only.flatMap((p) => byPath.get(p) ?? []) : changed,
116
+ owedJudge: [], finished: new Set(), unreadable: new Set(), failures: new Map(detail.extractor.failures ?? []), measured: new Map(),
117
+ rewritten: new Map(), started, now, progress,
118
+ settledRecheck: async (hash) => { if (askedSet.has(hash)) await store.clearRecheck?.([hash]); },
119
+ };
120
+ }
121
+
122
+ /** Throws if a batch carries `extracted` items — perception is never memory. */
123
+ export function assertStoredBatch(batch: { facts: readonly StoredFact[]; relations: readonly StoredRelation[] }): void {
124
+ const bad = [...batch.facts, ...batch.relations].find((x) => (x.origin as string) === 'extracted');
125
+ if (bad) throw new Error('knowledge: extracted output is never written to a KnowledgeStore');
126
+ }
127
+
128
+ /** Stores what the judged batch holds (with `withScope`); a no-op when there is nothing and the scope is the run's own. */
129
+ export async function writeBatch(c: ReviewContext, withScope: ScopeRecord = c.scopeRecord): Promise<void> {
130
+ const out = c.batch.take();
131
+ assertStoredBatch(out);
132
+ if (out.facts.length === 0 && out.relations.length === 0 && withScope === c.scopeRecord) return;
133
+ await c.args.store.write({ scope: withScope, ...out });
134
+ c.report.factsWritten += out.facts.length;
135
+ c.report.relationsWritten += out.relations.length;
136
+ }
137
+
138
+ /**
139
+ * Sources that are gone: their knowledge goes stale at no hash, their judged sections are forgotten, and facts other
140
+ * sources still back drop their anchor (recorded in `rewritten`, so a later retire never restores it).
141
+ */
142
+ export async function retire(c: ReviewContext, paths: readonly string[]): Promise<void> {
143
+ const live = new Map([...c.stored.facts, ...c.entities, ...c.rewritten]);
144
+ for (const path of paths) {
145
+ await c.args.store.markStale(c.scope, srcRef(c.rootId, path), '');
146
+ c.report.staleMarked += 1;
147
+ c.filesNow.delete(path);
148
+ const sectionPrefix = `${srcRef(c.rootId, path)}#`;
149
+ for (const section of [...c.judgedNow.keys()]) if (section.startsWith(sectionPrefix)) c.judgedNow.delete(section);
150
+ for (const fact of factsWithoutAnchor(live.values(), path)) {
151
+ c.batch.fact(fact);
152
+ live.set(fact.key, fact);
153
+ c.rewritten.set(fact.key, fact);
154
+ if (c.entities.has(fact.key)) c.entities.set(fact.key, fact);
155
+ }
156
+ }
157
+ await writeBatch(c);
158
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * knowledge/reviewFinish.ts — the end of a review: the near-duplicate compare, then everything the run produced is stored and
3
+ * durable BEFORE the manifests say its files are done, then the report's totals, the manifests and the scope's digest stamp.
4
+ * Moved out of review.ts.
5
+ */
6
+
7
+ import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
8
+ import type { ReviewReport } from './model.js';
9
+ import type { CompareOutcome } from './judge.js';
10
+ import { owedAfterRun, saveExtractorState } from './owedFiles.js';
11
+ import { filesManifestKey, judgedManifestKey, saveManifestMap } from './sources.js';
12
+ import { compareNew, saveAwaiting } from './reviewCompare.js';
13
+ import { writeBatch, type ReviewContext } from './reviewContext.js';
14
+ import { canonicalJson, compareStr } from './refs.js';
15
+
16
+ export async function finishReview(c: ReviewContext, flush: () => Promise<void>): Promise<ReviewReport> {
17
+ const { args, report } = c;
18
+ const { manifest } = args;
19
+ // The compare phase needs a pack asking for it AND both ports.
20
+ const wantsCompare = args.packs.some((p) => p.judgement?.contradictions);
21
+ const canCompare = wantsCompare && !!args.judgement && !!args.similar;
22
+ let outcome: CompareOutcome | undefined;
23
+ if (!report.aborted && canCompare && !args.mechanical) {
24
+ outcome = await compareNew({
25
+ args, pending: c.newClaims, known: c.stored.facts, budget: c.budget, batch: c.batch,
26
+ onPairs: (total) => c.progress({ phase: 'compare', done: 0, total }),
27
+ });
28
+ // Aborted only if the abort landed before the last pair was compared.
29
+ if (outcome?.aborted) report.aborted = true;
30
+ }
31
+ // DURABILITY ORDER: everything the run produced is stored and durable BEFORE a manifest says its files are
32
+ // done. A manifest ahead of the store loses knowledge for good (the next review sees those files unchanged
33
+ // and skips them); a store ahead of the manifest only re-reviews files. `write()` first stores what the compare
34
+ // phase left in the batch, then one flush covers the awaiting set (it names stored claims) and the files
35
+ // manifest: nothing mutates the store between them. The trailing write only stamps lastDigest; the end of
36
+ // the batch persists it.
37
+ await writeBatch(c);
38
+ await flush();
39
+ // No pack asks for contradictions: nothing waits, and an earlier run's awaiting set is left as it was.
40
+ if (wantsCompare && !args.mechanical) await saveAwaiting(manifest, c.rootId, c.newClaims, outcome);
41
+
42
+ // Pass 2: what is still owed is every file of its slice it did not finish (an abort leaves the unreached ones owed too).
43
+ report.awaitingJudge = args.only ? c.work.filter((f) => !c.finished.has(f.path)).map((f) => f.path) : c.owedJudge;
44
+ report.awaitingJudgeCount = report.awaitingJudge.length;
45
+ report.judgedFiles = args.only ? c.work.length - report.awaitingJudge.length : 0;
46
+ if (c.breaker.stopped) report.judgeStopped = c.breaker.stopped;
47
+ report.judged = c.batch.judged;
48
+ report.unjudged = c.batch.unjudged;
49
+ report.invalidJudgements = c.batch.invalid;
50
+ report.digest = sha256Hex(canonicalJson({ rootId: c.rootId, packs: c.packIds, files: [...c.filesNow].sort((a, b) => compareStr(a[0], b[0])) }));
51
+ await saveManifestMap(manifest, filesManifestKey(c.rootId), c.filesNow);
52
+ await saveManifestMap(manifest, judgedManifestKey(c.rootId), c.judgedNow);
53
+ // After every run: today's version and every file still owed a re-extraction — the unfinished ones,
54
+ // content-changed or not, and the owed paths the plan did not list that the manifest still holds.
55
+ await saveExtractorState(manifest, c.rootId, owedAfterRun({
56
+ state: c.detail.extractor, changed: c.changed, prior: c.detail.prior, finished: c.finished, carried: c.detail.carried,
57
+ live: c.filesNow, measured: c.measured, unreadable: c.unreadable,
58
+ }), c.failures, c.detail.extractor.documentsNow);
59
+ await writeBatch(c, report.aborted ? c.scopeRecord : { ...c.scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(c.now()).toISOString() });
60
+ report.durationMs = c.now() - c.started;
61
+ c.progress({ phase: 'done', done: c.work.length, total: c.work.length });
62
+ return report;
63
+ }
@@ -25,9 +25,12 @@ export interface ReviewStep {
25
25
 
26
26
  /** A file a review could not finish: its prior knowledge and manifest hash are kept, so the next review retries it. */
27
27
  export interface ReviewFailure {
28
+ /** The file's path; for an `analyzer` failure, `analyzer:<pack id>` (never a path: read `kind` first). */
28
29
  path: string;
29
30
  phase: ReviewPhase;
30
31
  reason: string;
32
+ /** What failed: absent or `file` for a file of the root, `analyzer` for a pack's analyzer (`path` then names the pack, not a file). */
33
+ kind?: 'file' | 'analyzer';
31
34
  }
32
35
 
33
36
  /** Lane ids 0..width-1 for in-flight work: `take` the lowest free one, `free` it when the work settles. */
@@ -6,7 +6,8 @@
6
6
 
7
7
  import type { Extracted } from '../model.js';
8
8
  import type { ExtractedLogPersistence } from './localSnapshotStore.js';
9
- import { parseLog } from './snapshotFormat.js';
9
+ import type { RowMemory } from './rowMemory.js';
10
+ import { compactedLogLine, parseLog } from './snapshotFormat.js';
10
11
 
11
12
  export class ExtractLogWriter {
12
13
  /** Entries not yet appended. */
@@ -14,27 +15,49 @@ export class ExtractLogWriter {
14
15
  /** The log's last line is torn (no newline), so the next append starts on a fresh line. */
15
16
  private torn = false;
16
17
 
17
- constructor(private readonly port: ExtractedLogPersistence) {}
18
+ /** `isLive(hash)`: the body is still in the cache (not evicted), so a failed append may put it back in line. */
19
+ constructor(private readonly port: ExtractedLogPersistence, private readonly isLive: (hash: string) => boolean = () => true) {}
18
20
 
19
21
  read(): Promise<string | undefined> { return this.port.read(); }
20
22
 
21
23
  /** Queues an entry for the next {@link flush}. */
22
24
  queue(hash: string, entries: Extracted[]): void { this.pending.set(hash, entries); }
23
25
 
24
- /** Fills `into` from the log's text (last line per hash wins) and compacts the log when dead bytes exceed live bytes. */
25
- async load(text: string | undefined, into: Map<string, Extracted[]>): Promise<void> {
26
- const parsed = parseLog(text);
27
- for (const [h, e] of parsed.entries) into.set(h, e);
26
+ /** An evicted body that was never appended is not appended at all. */
27
+ unqueue(hash: string): void { this.pending.delete(hash); }
28
+
29
+ /**
30
+ * Fills `mem` by REPLAYING the log's lines in order, exactly as the puts happened (last line per hash wins; a put claims only the
31
+ * entries it added or changed, and evicts what is then neither current nor previous for any source, extractRefs.ts), then compacts
32
+ * the log when dead bytes (superseded lines, evicted bodies, torn lines) exceed live bytes. A compacted line carries the body's
33
+ * reference state (`c`/`p`, snapshotFormat.ts), so the replay of a compacted log RESTORES the state instead of re-deriving it
34
+ * from a put order compaction no longer has.
35
+ */
36
+ async load(text: string | undefined, mem: RowMemory): Promise<void> {
37
+ const parsed = parseLog(text, (h, e, state) => { if (state) mem.restoreBody(h, e, state); else mem.putBody(h, e); });
38
+ const kept = [...parsed.liveLines].filter(([h]) => mem.extracted.has(h));
39
+ const liveBytes = kept.reduce((n, [, l]) => n + l.length, 0);
40
+ // A body that names no source (no reference state) keeps its line byte for byte; any other carries its state.
41
+ const live = kept.map(([h, line]) => {
42
+ const state = mem.bodyState(h);
43
+ return state.current.length + state.previous.length === 0 ? line : compactedLogLine(h, mem.extracted.get(h)!, state);
44
+ });
45
+ const deadBytes = Math.max(0, (text?.length ?? 0) - liveBytes);
28
46
  this.torn = !!text && !text.endsWith('\n');
29
- // Needs the port's `replace`; a failure is ignored (the log stays correct, only larger). Another window appending between
30
- // this read and the replace loses those lines from the cache — a cache miss, re-extracted next review.
31
- if (!this.port.replace || parsed.deadBytes <= parsed.liveBytes) return;
47
+ // Needs the port's `replace`; a failure keeps the uncompacted log (still correct, only larger) and is reported to `onError`.
48
+ // Another window appending between this read and the replace loses those lines from the cache — a cache miss, re-extracted next review.
49
+ if (!this.port.replace || deadBytes <= liveBytes) return;
32
50
  try {
33
- await this.port.replace([...parsed.liveLines.values()].join(''));
51
+ await this.port.replace(live.join(''));
34
52
  this.torn = false;
35
- } catch { /* keep the uncompacted log */ }
53
+ } catch (err) {
54
+ this.onError?.(err);
55
+ }
36
56
  }
37
57
 
58
+ /** Told about a compaction that failed (the load itself succeeds). */
59
+ onError: ((err: unknown) => void) | undefined;
60
+
38
61
  /**
39
62
  * Appends the not-yet-logged entries as ONE `append` of complete lines. A failed append keeps them pending and marks the
40
63
  * log torn (it may hold a partial line), so the next append starts on a fresh line.
@@ -50,7 +73,8 @@ export class ExtractLogWriter {
50
73
  this.torn = false;
51
74
  } catch (err) {
52
75
  this.torn = true;
53
- for (const [h, e] of batch) if (!this.pending.has(h)) this.pending.set(h, e);
76
+ // An entry evicted while the append was in flight is not put back: appended later, it would supersede its successor.
77
+ for (const [h, e] of batch) if (!this.pending.has(h) && this.isLive(h)) this.pending.set(h, e);
54
78
  throw err;
55
79
  }
56
80
  }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * knowledge/stores/extractRefs.ts — which extract bodies a {@link LocalSnapshotStore} still needs. The extract cache is keyed by
3
+ * content hash, so every edit of a file adds a body; without this, the superseded bodies were kept in memory, the snapshot, the
4
+ * extract log and the host's rows forever.
5
+ *
6
+ * A source's identity is its `sourceRef` (plus the `~tag` of a root-level output's hash, as `fileLeafKey` cuts it, so two
7
+ * analyzers writing the same ref do not supersede each other). Each source has ONE current body and keeps ONE previous body
8
+ * (a grace: switching a branch back hits the cache). A body is kept while it is the current or the previous body of some
9
+ * source; when it is neither, it is evicted.
10
+ *
11
+ * A put CLAIMS only the entries it adds or changes against the body already stored under that hash. `putExtract` merges a new
12
+ * entry into the cached body of a shared hash, so the body also carries entries of files that have since moved to another hash;
13
+ * re-putting it must never make those files current at it again (that evicted their real current body).
14
+ *
15
+ * A body with no entries (`[]`: a binary file, nothing to extract) or entries without a `sourceRef` names no source and is never
16
+ * evicted by this: it is a few bytes. Pure bookkeeping, no I/O: the store owns the maps, the log and the dirty marks.
17
+ */
18
+
19
+ import type { Extracted } from '../model.js';
20
+ import { canonicalJson } from '../refs.js';
21
+
22
+ /** The identity of a source within a body: `sourceRef`, or `~tag|sourceRef` for a root-level output's hash. */
23
+ export function sourceIdentity(hash: string, sourceRef: string): string {
24
+ if (!hash.startsWith('~')) return sourceRef;
25
+ const colon = hash.indexOf(':');
26
+ return `${colon > 0 ? hash.slice(0, colon) : hash}|${sourceRef}`;
27
+ }
28
+
29
+ /** The source refs of a body's entries (an entry without one names no source). */
30
+ export function sourceRefsOf(entries: readonly Extracted[]): string[] {
31
+ const out: string[] = [];
32
+ for (const e of entries) if (typeof e?.sourceRef === 'string' && e.sourceRef) out.push(e.sourceRef);
33
+ return out;
34
+ }
35
+
36
+ /** Adds `v` to the set at `k` of `m`. */
37
+ function addTo(m: Map<string, Set<string>>, k: string, v: string): void {
38
+ const s = m.get(k);
39
+ if (s) s.add(v); else m.set(k, new Set([v]));
40
+ }
41
+
42
+ /** Removes `v` from the set at `k` of `m`, dropping an emptied set. */
43
+ function removeFrom(m: Map<string, Set<string>>, k: string, v: string): void {
44
+ const s = m.get(k);
45
+ if (!s) return;
46
+ s.delete(v);
47
+ if (s.size === 0) m.delete(k);
48
+ }
49
+
50
+ export class ExtractRefs {
51
+ /** Body hash → the sources it is current for. */
52
+ private readonly live = new Map<string, Set<string>>();
53
+ /** Source → its current bodies (one after a put; several only after `seed`s whose order is unknown). */
54
+ private readonly owners = new Map<string, Set<string>>();
55
+ /** Source → its previous body (the grace). */
56
+ private readonly previous = new Map<string, string>();
57
+ /** Body hash → the sources it is the previous body of. */
58
+ private readonly previousOf = new Map<string, Set<string>>();
59
+
60
+ /**
61
+ * `entries` are now stored under `hash`, replacing `prior` (what was stored under it before, if anything). The sources of the
62
+ * entries that are new or changed against `prior` become current at `hash`. Returns the bodies that are now neither current
63
+ * nor previous for any source: the caller evicts them.
64
+ */
65
+ put(hash: string, entries: readonly Extracted[], prior?: readonly Extracted[]): string[] {
66
+ const before = new Map((prior ?? []).filter((e) => typeof e?.sourceRef === 'string').map((e) => [e.sourceRef, canonicalJson(e)] as const));
67
+ const present = new Set(sourceRefsOf(entries).map((r) => sourceIdentity(hash, r)));
68
+ const claims = new Set<string>();
69
+ for (const e of entries) {
70
+ if (typeof e?.sourceRef !== 'string' || !e.sourceRef) continue;
71
+ if (before.get(e.sourceRef) !== canonicalJson(e)) claims.add(sourceIdentity(hash, e.sourceRef));
72
+ }
73
+ const touched = new Set<string>();
74
+ // A source whose entry left this body is no longer current at it.
75
+ for (const id of [...(this.live.get(hash) ?? [])]) {
76
+ if (present.has(id)) continue;
77
+ removeFrom(this.live, hash, id);
78
+ removeFrom(this.owners, id, hash);
79
+ }
80
+ touched.add(hash);
81
+ for (const id of claims) {
82
+ for (const other of [...(this.owners.get(id) ?? [])]) {
83
+ if (other === hash) continue;
84
+ removeFrom(this.live, other, id);
85
+ this.setPrevious(id, other, touched);
86
+ touched.add(other);
87
+ }
88
+ this.owners.set(id, new Set([hash]));
89
+ addTo(this.live, hash, id);
90
+ }
91
+ return [...touched].filter((h) => h !== hash && !this.kept(h));
92
+ }
93
+
94
+ /**
95
+ * Records a body whose place in time is unknown (a snapshot, a reload, a lazily read body, a row the host lists) WITHOUT
96
+ * superseding anything: it shares its sources with the bodies already there until the next `put` of one of them.
97
+ */
98
+ seed(hash: string, sourceRefs: readonly string[]): void {
99
+ for (const r of sourceRefs) {
100
+ const id = sourceIdentity(hash, r);
101
+ addTo(this.live, hash, id);
102
+ addTo(this.owners, id, hash);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * What `hash` is to its sources, as source refs: the ones it is current for and the ones it is the previous body of. What a
108
+ * compacted extract log writes beside the body, so its replay restores exactly this instead of re-deriving it.
109
+ */
110
+ stateOf(hash: string): { current: string[]; previous: string[] } {
111
+ const refOf = (id: string): string => (hash.startsWith('~') ? id.slice(id.indexOf('|') + 1) : id);
112
+ return { current: [...(this.live.get(hash) ?? [])].map(refOf), previous: [...(this.previousOf.get(hash) ?? [])].map(refOf) };
113
+ }
114
+
115
+ /** Puts back what {@link stateOf} recorded, superseding nothing (a compacted log is a consistent state, not a sequence of puts). */
116
+ restore(hash: string, state: { current: readonly string[]; previous: readonly string[] }): void {
117
+ this.seed(hash, state.current);
118
+ for (const r of state.previous) {
119
+ const id = sourceIdentity(hash, r);
120
+ const old = this.previous.get(id);
121
+ if (old !== undefined) removeFrom(this.previousOf, old, id);
122
+ this.previous.set(id, hash);
123
+ addTo(this.previousOf, hash, id);
124
+ }
125
+ }
126
+
127
+ /** True when the hash is tracked (current or previous for some source). */
128
+ has(hash: string): boolean { return this.kept(hash); }
129
+
130
+ /** Bodies tracked (for tests and diagnostics). */
131
+ get size(): number { return new Set([...this.live.keys(), ...this.previousOf.keys()]).size; }
132
+
133
+ /** A copy: the same order knowledge, independent from here on. */
134
+ clone(): ExtractRefs {
135
+ const c = new ExtractRefs();
136
+ for (const [k, s] of this.live) c.live.set(k, new Set(s));
137
+ for (const [k, s] of this.owners) c.owners.set(k, new Set(s));
138
+ for (const [k, v] of this.previous) c.previous.set(k, v);
139
+ for (const [k, s] of this.previousOf) c.previousOf.set(k, new Set(s));
140
+ return c;
141
+ }
142
+
143
+ /** Forgets a body that left the store by another path (a reload that no longer lists it). */
144
+ forget(hash: string): void {
145
+ for (const id of [...(this.live.get(hash) ?? [])]) removeFrom(this.owners, id, hash);
146
+ this.live.delete(hash);
147
+ for (const id of [...(this.previousOf.get(hash) ?? [])]) this.previous.delete(id);
148
+ this.previousOf.delete(hash);
149
+ }
150
+
151
+ private kept(hash: string): boolean { return this.live.has(hash) || this.previousOf.has(hash); }
152
+
153
+ /** `hash` becomes the previous body of `id`; the body it replaces there is touched (it may now be unreferenced). */
154
+ private setPrevious(id: string, hash: string, touched: Set<string>): void {
155
+ const old = this.previous.get(id);
156
+ if (old === hash) return;
157
+ if (old !== undefined) { removeFrom(this.previousOf, old, id); touched.add(old); }
158
+ this.previous.set(id, hash);
159
+ addTo(this.previousOf, hash, id);
160
+ }
161
+ }
@@ -107,7 +107,7 @@ export class LocalSnapshotStore implements KnowledgeStore {
107
107
  this.now = opts.now ?? (() => new Date().toISOString());
108
108
  this.nowMs = opts.nowMs ?? Date.now;
109
109
  this.checkpointMs = opts.checkpointMs ?? 30_000;
110
- this.log = !this.rows && opts.extractedLog ? new ExtractLogWriter(opts.extractedLog) : undefined;
110
+ this.log = !this.rows && opts.extractedLog ? new ExtractLogWriter(opts.extractedLog, (h) => this.mem.extracted.has(h)) : undefined;
111
111
  }
112
112
 
113
113
  /** Loads once; every later call is a no-op, so reads never wait on the mutation queue after the first. */
@@ -140,14 +140,18 @@ export class LocalSnapshotStore implements KnowledgeStore {
140
140
  logText = this.log ? await this.log.read() : undefined;
141
141
  }
142
142
  this.mem.fill(snap, !this.log);
143
+ // Row mode: bodies the host holds but never sent are tracked by key, so a later edit's eviction reaches them too.
144
+ if (this.rows?.extractedSources) {
145
+ for (const [h, refs] of Object.entries(await this.rows.extractedSources())) if (!this.mem.extracted.has(h)) this.mem.seedKey(h, refs);
146
+ }
143
147
  if (this.log) {
144
- await this.log.load(logText, this.mem.extracted);
148
+ await this.log.load(logText, this.mem);
145
149
  // An old snapshot still carrying the cache: move it into the log once; the next snapshot write omits it.
146
150
  const legacy = Object.entries(snap.extracted ?? {});
147
151
  if (legacy.length) {
148
152
  for (const [h, e] of legacy) {
149
153
  if (this.mem.extracted.has(h)) continue;
150
- this.mem.extracted.set(h, e);
154
+ this.mem.seedBody(h, e);
151
155
  this.log.queue(h, e);
152
156
  }
153
157
  this.dirty = true;
@@ -332,10 +336,13 @@ export class LocalSnapshotStore implements KnowledgeStore {
332
336
 
333
337
  putExtracted(hash: string, extracted: Extracted[]): Promise<void> {
334
338
  return this.mutate(() => {
335
- // The same entry again (a second pass re-puts what the first stored) is skipped: no append, no dirty snapshot.
339
+ // The same entry again (a second pass re-puts what the first stored) is skipped: no append, no dirty snapshot, and no
340
+ // claim — a re-put never makes the files of a shared body current at it again (extractRefs.ts).
336
341
  const prior = this.mem.extracted.get(hash);
337
342
  if (prior && canonicalJson(prior) === canonicalJson(extracted)) return;
338
- this.mem.extracted.set(hash, extracted);
343
+ // Only the entries new or changed against `prior` become current; bodies no longer current or previous for any source
344
+ // leave memory here, and the cache's persistence below.
345
+ for (const h of this.mem.putBody(hash, extracted)) this.evicted(h);
339
346
  this.sync?.forget(hash);
340
347
  this.delta?.mark('extracted', [hash]);
341
348
  if (this.log) this.log.queue(hash, extracted);
@@ -343,6 +350,16 @@ export class LocalSnapshotStore implements KnowledgeStore {
343
350
  }, false);
344
351
  }
345
352
 
353
+ /**
354
+ * A body {@link RowMemory.putBody} evicted: a row delete (row mode), never appended if still queued and dropped from the log at its
355
+ * next compaction (log mode), or gone from the next snapshot write (snapshot mode).
356
+ */
357
+ private evicted(hash: string): void {
358
+ this.delta?.mark('extracted', [hash], true);
359
+ this.log?.unqueue(hash);
360
+ if (!this.log) this.dirty = true;
361
+ }
362
+
346
363
  /** See {@link canonicalDump}. Static so it can reach private state without widening the instance's public surface. */
347
364
  static async dumpOf(store: LocalSnapshotStore): Promise<string> {
348
365
  await store.fresh();
@@ -46,6 +46,12 @@ export interface RowPersistence {
46
46
  loadAllExtracted?(): Promise<Record<string, Extracted[]>>;
47
47
  /** The extract bodies of one content hash that are not in memory (reload returns rows, bodies load lazily). Optional. */
48
48
  loadExtracted?(hash: string): Promise<Extracted[] | undefined>;
49
+ /**
50
+ * The source refs of EVERY stored extract body by hash, without the bodies (e.g. a `hash, source_ref` index), read once at load
51
+ * so the store can evict bodies superseded by later edits even when it never loaded them. Optional: without it only bodies that
52
+ * passed through memory are tracked.
53
+ */
54
+ extractedSources?(): Promise<Record<string, string[]>>;
49
55
  /** True when another writer changed the store since this store last saw it (e.g. `PRAGMA data_version`). Optional. */
50
56
  changedElsewhere?(): Promise<boolean>;
51
57
  }
@@ -6,6 +6,7 @@
6
6
 
7
7
  import type { Extracted, ScopeRecord, StoredFact, StoredRelation } from '../model.js';
8
8
  import { pathOfRef } from '../refs.js';
9
+ import { ExtractRefs, sourceRefsOf } from './extractRefs.js';
9
10
  import type { RowState } from './rowDelta.js';
10
11
  import { relKey, serializeSnapshot, type KnowledgeSnapshot } from './snapshotFormat.js';
11
12
 
@@ -13,7 +14,10 @@ export class RowMemory implements RowState {
13
14
  scopes: ScopeRecord[] = [];
14
15
  readonly facts = new Map<string, Map<string, StoredFact>>();
15
16
  readonly relations = new Map<string, Map<string, StoredRelation>>();
17
+ /** The extract cache by content hash. Written through {@link putBody} / {@link seedBody}, so {@link refs} stays in step. */
16
18
  readonly extracted = new Map<string, Extracted[]>();
19
+ /** Which bodies still hold a current source (extractRefs.ts). */
20
+ private refs = new ExtractRefs();
17
21
  readonly recheck = new Set<string>();
18
22
  /** Per root: source path → keys of the relations touching it (`from` or `to`). */
19
23
  private byPath = new Map<string, Map<string, Set<string>>>();
@@ -47,6 +51,51 @@ export class RowMemory implements RowState {
47
51
  for (const [rootId, m] of this.relations) for (const r of m.values()) this.index(rootId, r);
48
52
  }
49
53
 
54
+ /**
55
+ * After a reload into this fresh memory: keeps `old`'s body references (their put order, and the bodies it knows only by key)
56
+ * and adds the bodies this memory holds that `old` did not track, as seeds.
57
+ */
58
+ adoptRefs(old: RowMemory): void {
59
+ this.refs = old.refs.clone();
60
+ for (const [h, e] of this.extracted) if (!this.refs.has(h)) this.refs.seed(h, sourceRefsOf(e));
61
+ }
62
+
63
+ /**
64
+ * Stores `entries` under `hash`; the sources of the entries new or changed against what `hash` held become current at it, and
65
+ * the bodies no longer current or previous for any source are evicted (extractRefs.ts). Returns the evicted hashes, for the
66
+ * caller's persistence (a row delete, a log entry not to append).
67
+ */
68
+ putBody(hash: string, entries: Extracted[]): string[] {
69
+ const prior = this.extracted.get(hash);
70
+ this.extracted.set(hash, entries);
71
+ const evicted = this.refs.put(hash, entries, prior);
72
+ for (const h of evicted) this.extracted.delete(h);
73
+ return evicted;
74
+ }
75
+
76
+ /** Keeps a body whose place in time is unknown (a snapshot, a reload, a lazy read) without superseding any other. */
77
+ seedBody(hash: string, entries: Extracted[]): void {
78
+ this.extracted.set(hash, entries);
79
+ this.refs.seed(hash, sourceRefsOf(entries));
80
+ }
81
+
82
+ /** Stores a body with the reference state a compacted log recorded for it (extractRefs.ts `stateOf`). */
83
+ restoreBody(hash: string, entries: Extracted[], state: { current: readonly string[]; previous: readonly string[] }): void {
84
+ this.extracted.set(hash, entries);
85
+ this.refs.restore(hash, state);
86
+ }
87
+
88
+ /** What a body is to its sources (current / previous), for a compacted log line. */
89
+ bodyState(hash: string): { current: string[]; previous: string[] } { return this.refs.stateOf(hash); }
90
+
91
+ /** Tracks a body the host holds but memory does not (known by its key and source refs only), so eviction covers it. */
92
+ seedKey(hash: string, sourceRefs: readonly string[]): void {
93
+ this.refs.seed(hash, sourceRefs);
94
+ }
95
+
96
+ /** Bodies the reference index tracks (diagnostics and tests). */
97
+ get trackedBodies(): number { return this.refs.size; }
98
+
50
99
  /** Puts a snapshot's rows into these (empty) maps; the extract cache only when `withExtracted` (a log owns it otherwise). */
51
100
  fill(snap: KnowledgeSnapshot, withExtracted: boolean): void {
52
101
  this.scopes = [...snap.scopes];
@@ -59,7 +108,7 @@ export class RowMemory implements RowState {
59
108
  this.relsOf(rootId);
60
109
  if (Array.isArray(rows)) for (const r of rows) this.putRelation(rootId, r);
61
110
  }
62
- if (withExtracted) for (const [h, e] of Object.entries(snap.extracted ?? {})) this.extracted.set(h, e);
111
+ if (withExtracted) for (const [h, e] of Object.entries(snap.extracted ?? {})) this.seedBody(h, e);
63
112
  }
64
113
 
65
114
  /** Canonical text of the rows with the given extract cache; `undefined` omits it (a log owns it). */
@@ -67,6 +67,7 @@ export class RowSync {
67
67
  for (const [h, e] of old.extracted) if (!next.extracted.has(h)) next.extracted.set(h, e);
68
68
  this.delta.overlay(old, next);
69
69
  next.reindex();
70
+ next.adoptRefs(old);
70
71
  this.host.setMem(next);
71
72
  this.misses.clear();
72
73
  this.generation += 1;
@@ -95,7 +96,7 @@ export class RowSync {
95
96
  const found = await this.rows.loadExtracted(hash);
96
97
  if (!found) { if (startedIn === this.generation) this.misses.add(hash); return undefined; }
97
98
  const now = this.host.mem();
98
- if (!now.extracted.has(hash)) now.extracted.set(hash, found);
99
+ if (!now.extracted.has(hash)) now.seedBody(hash, found);
99
100
  return now.extracted.get(hash);
100
101
  }
101
102