@polycode-projects/the-mechanical-code-talker 6.0.11 → 6.0.13

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "6.0.11",
3
+ "version": "6.0.13",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -68,7 +68,7 @@ export {
68
68
  // fine as long as neither side READS an imported binding while the other's
69
69
  // body is still running — rows.mjs builds its class map on first use, and
70
70
  // every use here is inside a function.
71
- import { payloadToRows, rowsToPayload, diffRows } from "./rows.mjs";
71
+ import { payloadToRows, rowsToPayload, diffRows, renormalizeAssembledPayload } from "./rows.mjs";
72
72
 
73
73
  // The rollup vocabulary and its tuning constants live with the compaction
74
74
  // layer; re-exported here so store consumers keep one import site.
@@ -766,12 +766,22 @@ const ROW_NODE_ID_KEY = "nodeId";
766
766
  * `wrapRowBackendOverSqliteSeed`, the entry point that takes one.
767
767
  * `sqliteSeedOverlayRows` are rows that layer over that seed and under the
768
768
  * session's own (a turn's retrieved corpus subgraph), read-only exactly as
769
- * the seed is. */
769
+ * the seed is.
770
+ *
771
+ * `copyOnRead: false` hands every reader the assembled payload itself instead
772
+ * of a copy of it. Copying a seed-sized payload is the most expensive thing
773
+ * this backend does — over a second per read at 60k facts — and a caller that
774
+ * drives the whole session through this one handle (a worker cycle, a request
775
+ * handler) has nobody to protect the payload from. Anyone sharing a handle
776
+ * across independent readers leaves the default alone: without the copy, a
777
+ * reader that mutates what it read has changed the store's own view of
778
+ * itself. */
770
779
  export function wrapRowBackend(impl, {
771
780
  basePayload = null,
772
781
  sqliteSeedStore = null,
773
782
  sqliteSeedOverlayRows = null,
774
783
  onOversizedRow = "throw",
784
+ copyOnRead = true,
775
785
  log = undefined,
776
786
  } = {}) {
777
787
  const problems = rowBackendProblems(impl);
@@ -795,6 +805,7 @@ export function wrapRowBackend(impl, {
795
805
  baseRows: null,
796
806
  storedRows: null,
797
807
  onOversizedRow,
808
+ copyOnRead,
798
809
  log,
799
810
  };
800
811
  }
@@ -805,8 +816,8 @@ export function wrapRowBackend(impl, {
805
816
  * never materialized as a row array: the assembled payload is the only copy
806
817
  * of it this process holds. `overlayRows` layer over the seed and under the
807
818
  * session's own rows. */
808
- export function wrapRowBackendOverSqliteSeed(impl, sqliteSeedStore, { overlayRows = null, onOversizedRow = "throw", log = undefined } = {}) {
809
- return wrapRowBackend(impl, { sqliteSeedStore, sqliteSeedOverlayRows: overlayRows, onOversizedRow, log });
819
+ export function wrapRowBackendOverSqliteSeed(impl, sqliteSeedStore, { overlayRows = null, onOversizedRow = "throw", copyOnRead = true, log = undefined } = {}) {
820
+ return wrapRowBackend(impl, { sqliteSeedStore, sqliteSeedOverlayRows: overlayRows, onOversizedRow, copyOnRead, log });
810
821
  }
811
822
 
812
823
  /** Drain whatever `readRows()` returned: the contract allows an array or an
@@ -846,11 +857,14 @@ async function readRowMeta(handle, key, fallback) {
846
857
  try { return JSON.parse(raw); } catch { return fallback; }
847
858
  }
848
859
 
849
- /** loadMemory's read for Backend D: one `readRows()` per cold open, assembled
850
- * once with the seed overlay, then served from `cachedPayload` with no
851
- * further backend traffic. Bookkeeping rows are held aside — they round-trip
852
- * through the store but never compose into a payload. */
853
- async function readRowPayload(handle) {
860
+ /** The assembled payload ITSELF, assembled on the first call and served from
861
+ * `cachedPayload` after that with no further backend traffic. Bookkeeping rows
862
+ * are held aside — they round-trip through the store but never compose into a
863
+ * payload. The caller must not hand this object out: `readRowPayload` is the
864
+ * seam that clones, and cloning a seed-sized payload is the single most
865
+ * expensive thing this backend does, so a caller that only needs the cache
866
+ * warm calls this one instead. */
867
+ async function ensureRowPayload(handle) {
854
868
  if (!handle.cachedPayload) {
855
869
  const empty = emptyMemory();
856
870
  const stored = await collectRows(handle.impl.readRows());
@@ -860,7 +874,7 @@ async function readRowPayload(handle) {
860
874
  prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, seedScalar(handle, "prefixes", empty.prefixes)),
861
875
  };
862
876
  if (handle.sqliteSeedStore) {
863
- handle.cachedPayload = assembleSqliteSeededPayload(handle, meta);
877
+ handle.cachedPayload = migrateStoredMemory(assembleSqliteSeededPayload(handle, meta));
864
878
  } else {
865
879
  // "keep": the base overlay's own rows never reach the wire (persistRowPayload
866
880
  // excludes every seed key from every write via seedOnlyKeys below), so the
@@ -869,10 +883,49 @@ async function readRowPayload(handle) {
869
883
  // band's own high-fan-out property (one edge per fact is normal, not a
870
884
  // pathology) and break every read that depends on it.
871
885
  handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
872
- handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
886
+ handle.cachedPayload = migrateStoredMemory(rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta }));
873
887
  }
874
888
  }
875
- return cloneJson(handle.cachedPayload);
889
+ return handle.cachedPayload;
890
+ }
891
+
892
+ /** loadMemory's read for Backend D: one `readRows()` per cold open, then a
893
+ * clone of the assembled payload per call — unless the handle was opened
894
+ * `copyOnRead: false`, where the reader gets the assembled payload itself. */
895
+ async function readRowPayload(handle) {
896
+ const payload = await ensureRowPayload(handle);
897
+ return handle.copyOnRead === false ? payload : cloneJson(payload);
898
+ }
899
+
900
+ /** A payload a mutation can work on without any of it reaching the one it was
901
+ * copied from. Every container a write reaches into is its own: the individuals
902
+ * array and each individual, the edge groups and each group's example list.
903
+ * What stays shared is what a write never changes in place — an individual's
904
+ * `attributes` array is REPLACED by `setAttr`, never pushed onto, and an edge
905
+ * is replaced rather than edited, so both sides keep reading their own.
906
+ *
907
+ * This is `structuredClone`'s job done at the granularity writes actually use.
908
+ * At seed scale the deep copy runs well over a second and a cycle pays it on
909
+ * every fact it grounds; this is a few milliseconds of pointer copying. */
910
+ function mutablePayloadCopy(payload) {
911
+ return {
912
+ ...payload,
913
+ individuals: (payload.individuals || []).map((ind) => ({ ...ind })),
914
+ objectProperties: (payload.objectProperties || []).map((group) => ({
915
+ ...group, examples: [...(group.examples || [])],
916
+ })),
917
+ };
918
+ }
919
+
920
+ /** Forget a row handle's assembled payload, so the next read rebuilds it from
921
+ * the store. The one thing that must happen after a mutation dies part-way
922
+ * through: the payload it was changing is neither what the store holds nor a
923
+ * coherent graph. */
924
+ function dropAssembledRowPayload(handle) {
925
+ if (!isRowHandle(handle)) return;
926
+ handle.cachedPayload = null;
927
+ handle.storedRows = null;
928
+ handle.baseRows = null;
876
929
  }
877
930
 
878
931
  /** A record with its audit stamp removed. `mgx:updatedAt` moves on every
@@ -903,7 +956,7 @@ function movedBeyondAuditStamp(beforeRow, row) {
903
956
  * write drops the cache so the next read rebuilds from the store rather than
904
957
  * from a payload that never landed. */
905
958
  async function persistRowPayload(handle, payload) {
906
- await readRowPayload(handle);
959
+ await ensureRowPayload(handle);
907
960
  const seedKeys = seedOnlyKeys(handle);
908
961
  // On the sqlite path the seed is out of BOTH sides of the diff: the rows it
909
962
  // holds are exactly the keys no write may touch, so projecting them would
@@ -926,9 +979,7 @@ async function persistRowPayload(handle, payload) {
926
979
  await handle.impl.putMeta(ROW_META_MEMORY_KEY, JSON.stringify(payload.memory ?? emptyMemory().memory));
927
980
  await handle.impl.putMeta(ROW_META_PREFIXES_KEY, JSON.stringify(payload.prefixes ?? emptyMemory().prefixes));
928
981
  } catch (e) {
929
- handle.cachedPayload = null;
930
- handle.storedRows = null;
931
- handle.baseRows = null;
982
+ dropAssembledRowPayload(handle);
932
983
  throw e;
933
984
  }
934
985
  const removed = new Set(removals);
@@ -936,13 +987,18 @@ async function persistRowPayload(handle, payload) {
936
987
  for (const row of writes) next.set(row.rowKey, row);
937
988
  handle.storedRows = [...next.values()];
938
989
  const meta = { memory: payload.memory, prefixes: payload.prefixes };
939
- // Dropped before the rebuild, not after it: the payload this replaces is the
940
- // largest object the handle holds, and keeping it reachable while the next
941
- // one assembles doubles the peak for no reason.
942
- handle.cachedPayload = null;
943
- handle.cachedPayload = handle.sqliteSeedStore
944
- ? assembleSqliteSeededPayload(handle, meta)
945
- : rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
990
+ if (handle.sqliteSeedStore && !removals.length) {
991
+ patchAssembledPayload(handle.cachedPayload, meta, writes);
992
+ } else if (handle.sqliteSeedStore) {
993
+ handle.cachedPayload = null;
994
+ handle.cachedPayload = migrateStoredMemory(assembleSqliteSeededPayload(handle, meta));
995
+ } else {
996
+ // Dropped before the rebuild, not after it: the payload this replaces is the
997
+ // largest object the handle holds, and keeping it reachable while the next
998
+ // one assembles doubles the peak for no reason.
999
+ handle.cachedPayload = null;
1000
+ handle.cachedPayload = migrateStoredMemory(rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta }));
1001
+ }
946
1002
  }
947
1003
 
948
1004
  /** The payload minus a set of row keys, for a projection that must not spend
@@ -1051,6 +1107,58 @@ function assembleSqliteSeededPayload(handle, meta) {
1051
1107
  );
1052
1108
  }
1053
1109
 
1110
+ /** The assembled payload after a write that only added or rewrote rows, brought
1111
+ * up to date without reading the seed again.
1112
+ *
1113
+ * Why the positions work out: a write only ever carries session rows, and
1114
+ * `payloadToRows` gives a newly-keyed row an ord past every ord already
1115
+ * assembled, so a new individual belongs at the tail and a rewritten one
1116
+ * belongs exactly where it already sits. Both are where a rebuild from the
1117
+ * same rows would put them, and the fact set is unchanged or grown, so the
1118
+ * fact ordering `renormalizeAssembledPayload` reapplies lands the same way.
1119
+ * Everything the payload derives goes through that one function, the same one
1120
+ * `rowsToPayload` itself ends on, so a patched payload and a rebuilt one
1121
+ * cannot drift apart.
1122
+ *
1123
+ * A REMOVAL is not patchable this way and does not come here: dropping an
1124
+ * individual from the assembled array drops it from wherever the fact ordering
1125
+ * moved it to, which is a different position from the one it occupied in row
1126
+ * order, and every fact after it shifts. `persistRowPayload` rebuilds for those.
1127
+ * Mutates and returns `payload`. */
1128
+ function patchAssembledPayload(payload, meta, writes) {
1129
+ payload.memory = meta.memory;
1130
+ payload.prefixes = meta.prefixes;
1131
+ if (!writes.length) return renormalizeAssembledPayload(payload);
1132
+
1133
+ const individualPositions = new Map();
1134
+ for (let i = 0; i < payload.individuals.length; i += 1) individualPositions.set(payload.individuals[i]?.id, i);
1135
+ const groupPositions = new Map();
1136
+ for (let i = 0; i < payload.objectProperties.length; i += 1) groupPositions.set(payload.objectProperties[i]?.prop, i);
1137
+
1138
+ for (const row of writes) {
1139
+ if (row.rowClass === BOOKKEEPING_ROW_CLASS) continue;
1140
+ const record = JSON.parse(row.json);
1141
+ if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
1142
+ const group = record?.group;
1143
+ if (!group?.prop) continue;
1144
+ const at = groupPositions.get(group.prop);
1145
+ if (at === undefined) {
1146
+ groupPositions.set(group.prop, payload.objectProperties.length);
1147
+ payload.objectProperties.push(group);
1148
+ } else payload.objectProperties[at] = group;
1149
+ continue;
1150
+ }
1151
+ const individual = record?.individual;
1152
+ if (!individual?.id) continue;
1153
+ const at = individualPositions.get(individual.id);
1154
+ if (at === undefined) {
1155
+ individualPositions.set(individual.id, payload.individuals.length);
1156
+ payload.individuals.push(individual);
1157
+ } else payload.individuals[at] = individual;
1158
+ }
1159
+ return renormalizeAssembledPayload(payload);
1160
+ }
1161
+
1054
1162
  /** Every distinct subject and object a seed store's facts carry, off the
1055
1163
  * `facts` projection's own columns — the raw values, folded by whoever needs
1056
1164
  * them. A caller that would otherwise walk the seed's individuals to collect
@@ -1885,7 +1993,9 @@ export async function snapshotMemory(dir, { retentionVersions } = {}) {
1885
1993
  export async function loadMemory(dir) {
1886
1994
  if (isMemoryHandle(dir)) return migrateStoredMemory(dir.payload);
1887
1995
  if (isSqliteHandle(dir)) return migrateStoredMemory(readSqlitePayload(dir));
1888
- if (isRowHandle(dir)) return migrateStoredMemory(await readRowPayload(dir));
1996
+ // Not migrated here: a row handle migrates the payload once, as it assembles
1997
+ // it, so every read after the first is spared two walks of the whole graph.
1998
+ if (isRowHandle(dir)) return readRowPayload(dir);
1889
1999
  let text;
1890
2000
  try {
1891
2001
  text = await readFile(memoryGraphFile(dir), "utf8");
@@ -2249,15 +2359,31 @@ function retractionsFor(payload, groupId) {
2249
2359
  * linear scan in that case. */
2250
2360
  const memoryIndexOf = (payload) => payload?.[MEMORY_INDEX] || null;
2251
2361
 
2362
+ /** Load, change, persist. A row handle always works on a copy here, even one
2363
+ * opened `copyOnRead: false`: a write drops every change that lands on a
2364
+ * seed-owned row, so a mutation applied straight to the assembled payload
2365
+ * would leave the handle holding changes the store refused. The copy is what
2366
+ * keeps "what this handle reads" and "what a fresh handle would assemble" the
2367
+ * same thing.
2368
+ *
2369
+ * A row handle does skip the prose index built here: `persistRowPayload`
2370
+ * re-derives every derived structure from the rows it just wrote, so building
2371
+ * one now builds it twice over the whole graph. */
2252
2372
  async function mutateMemory(dir, fn) {
2253
- const payload = await loadMemory(dir);
2254
- buildMemoryIndex(payload);
2255
- const out = (await fn(payload)) ?? payload;
2256
- migrateLegacyProvenance(out);
2257
- recomputeSourceReliability(out);
2258
- out.proseIndex = buildProseIndex(out.individuals);
2259
- await persistMemory(dir, out);
2260
- return out;
2373
+ const overRowHandle = isRowHandle(dir);
2374
+ const payload = overRowHandle ? mutablePayloadCopy(await ensureRowPayload(dir)) : await loadMemory(dir);
2375
+ try {
2376
+ buildMemoryIndex(payload);
2377
+ const out = (await fn(payload)) ?? payload;
2378
+ migrateLegacyProvenance(out);
2379
+ recomputeSourceReliability(out);
2380
+ if (!overRowHandle) out.proseIndex = buildProseIndex(out.individuals);
2381
+ await persistMemory(dir, out);
2382
+ return overRowHandle ? dir.cachedPayload : out;
2383
+ } catch (e) {
2384
+ dropAssembledRowPayload(dir);
2385
+ throw e;
2386
+ }
2261
2387
  }
2262
2388
 
2263
2389
  const labelOf = (text) => (text.length > LABEL_CAP ? text.slice(0, LABEL_CAP - 1) + "…" : text);
@@ -2486,7 +2612,10 @@ function recomputeSourceReliability(payload) {
2486
2612
  if (!Array.isArray(payload?.individuals) || !Array.isArray(payload?.objectProperties)) return;
2487
2613
  const rows = readFactRows(payload); // Fact-only — contradiction accounting is inherently Fact-shaped
2488
2614
  const contradictedFactIds = new Set();
2489
- for (const group of findContradictions(payload)) for (const r of group) contradictedFactIds.add(r.id);
2615
+ // The fold above is the same one findContradictions would take for itself,
2616
+ // and over a seed-sized graph it is half a second. Nothing changes the
2617
+ // payload between the two, so it goes across.
2618
+ for (const group of findContradictions(payload, { factRows: rows })) for (const r of group) contradictedFactIds.add(r.id);
2490
2619
 
2491
2620
  const bySource = new Map(); // sessionSourceId -> { factsAsserted, factsContradicted }
2492
2621
  for (const row of rows) {
@@ -4129,8 +4258,8 @@ export const MULTI_VALUED_PREDICATES = MERGE_PREDICATES;
4129
4258
  * only what its own clock could not order (the resolver's trust and codepoint
4130
4259
  * tie-breaks — see resolveSiblingGroups), so ordinary succession stops reading
4131
4260
  * as disagreement; every other predicate keeps the full keep-both contract. */
4132
- export function findContradictions(memory, { floor = CONTRADICTION_TRUST_FLOOR } = {}) {
4133
- const rows = readFactRows(memory).filter((r) => r.trust >= floor);
4261
+ export function findContradictions(memory, { floor = CONTRADICTION_TRUST_FLOOR, factRows = null } = {}) {
4262
+ const rows = (factRows || readFactRows(memory)).filter((r) => r.trust >= floor);
4134
4263
  const byKey = new Map();
4135
4264
  for (const r of rows) {
4136
4265
  if (resolutionStrategyFor(r.predicate) === RESOLUTION_MERGE) continue;
@@ -209,7 +209,12 @@ function sortFactIndividualsById(individuals) {
209
209
  /** Re-derive each record's backward supersession pointer from the union of the
210
210
  * forward ones. Two turns that superseded the same record concurrently both
211
211
  * land, because each wrote its own row and neither touched the record they
212
- * replaced. */
212
+ * replaced.
213
+ *
214
+ * Idempotent: a record that no longer has any successor loses the pointer it
215
+ * used to carry. Rows never carry one (`storedIndividualForm` strips it), so
216
+ * that arm is dead when this runs over a fresh projection and live when it
217
+ * runs again over individuals it already derived. */
213
218
  function applyDerivedSupersessions(individuals) {
214
219
  const successorsById = new Map();
215
220
  for (const ind of individuals) {
@@ -222,11 +227,12 @@ function applyDerivedSupersessions(individuals) {
222
227
  }
223
228
  for (const ind of individuals) {
224
229
  const successors = successorsById.get(ind?.id);
225
- if (!successors) continue;
226
- ind.attributes = [
227
- ...(ind.attributes || []).filter((a) => a?.prop !== SUPERSEDED_BY_PROP),
228
- { prop: SUPERSEDED_BY_PROP, key: "supersededBy", value: [...successors].sort().join(" ") },
229
- ];
230
+ const carried = (ind?.attributes || []).some((a) => a?.prop === SUPERSEDED_BY_PROP);
231
+ if (!successors && !carried) continue;
232
+ const rest = (ind.attributes || []).filter((a) => a?.prop !== SUPERSEDED_BY_PROP);
233
+ ind.attributes = successors
234
+ ? [...rest, { prop: SUPERSEDED_BY_PROP, key: "supersededBy", value: [...successors].sort().join(" ") }]
235
+ : rest;
230
236
  }
231
237
  }
232
238
 
@@ -275,13 +281,27 @@ export function rowsToPayload(rows, { meta = null } = {}) {
275
281
  individualEntries.sort(byOrdThenRowKey);
276
282
  groupEntries.sort(byOrdThenRowKey);
277
283
 
278
- const individuals = individualEntries.map((e) => e.individual).filter(Boolean);
284
+ payload.individuals = individualEntries.map((e) => e.individual).filter(Boolean);
285
+ payload.objectProperties = groupEntries.map((e) => e.group).filter(Boolean);
286
+ return renormalizeAssembledPayload(payload);
287
+ }
288
+
289
+ /** Everything an assembled payload derives from its own individuals: the fact
290
+ * ordering, the backward supersession pointers, the class counts, the prose
291
+ * index and `generated_at`. `rowsToPayload` ends here, and so does a caller
292
+ * that assembled a payload once and then changed a few of its individuals in
293
+ * place — running this leaves the same payload either route, which is what
294
+ * lets a cached assembly be patched instead of rebuilt from its rows.
295
+ * Mutates and returns `payload`. */
296
+ export function renormalizeAssembledPayload(payload) {
297
+ const individuals = payload.individuals || [];
279
298
  sortFactIndividualsById(individuals);
280
299
  applyDerivedSupersessions(individuals);
281
-
282
- payload.individuals = individuals;
283
- payload.objectProperties = groupEntries.map((e) => e.group).filter(Boolean);
284
300
  payload.classes = recountedClasses(individuals);
301
+ // Released before the replacement is built, not after: over a seed-sized
302
+ // store the prose index is the largest derived structure here, and holding
303
+ // the outgoing one while the incoming one grows doubles it for no reason.
304
+ payload.proseIndex = null;
285
305
  payload.proseIndex = buildProseIndex(individuals);
286
306
  payload.generated_at = latestUtteranceTimestamp(individuals);
287
307
  return payload;
@@ -63,7 +63,7 @@ import { basename, join, resolve } from "node:path";
63
63
  import { runTurn, uuidv7, stripLeadingDiscourseAdverb } from "./chat.mjs";
64
64
  import { beginsWithVowelSound, grammarRules } from "./finish.mjs";
65
65
  import { splitSentencesPreservingPaths, stripCitationResidue } from "./sentences.mjs";
66
- import { loadMemory, readFactRows, appendFact, removeFacts } from "../adapters/memory/core.mjs";
66
+ import { loadMemory, readFactRows, appendFacts, removeFacts } from "../adapters/memory/core.mjs";
67
67
  import { loadConfig } from "../adapters/config.mjs";
68
68
  import { touchedFactRows } from "../domain/memory/touched-facts.mjs";
69
69
  import { normFactTerm } from "../domain/hash.mjs";
@@ -971,9 +971,14 @@ export async function ingestText(text, {
971
971
  const subjects = new Set(rows.map((r) => r.subject));
972
972
  if (subjects.size === 1) carrySubject = [...subjects][0];
973
973
  const tag = `extracted:${sourceTag}`;
974
+ // One write for the whole sentence, not one per row: a write reads
975
+ // and re-derives the whole graph, so N of them cost N times what one
976
+ // carrying the same N rows does. The batch stays inside the sentence
977
+ // — a later sentence still reads everything the earlier ones wrote.
978
+ const writes = [];
974
979
  for (const row of rows) {
975
980
  const extraction = findingsForRow(row, readingFindings, identifierTerms);
976
- await appendFact(dir, {
981
+ writes.push({
977
982
  subject: row.subject, predicate: row.predicate, object: row.object,
978
983
  provenance: tag, quantifier: row.quantifier || "", observedAt,
979
984
  ...(extraction.length ? { extraction } : {}),
@@ -985,6 +990,7 @@ export async function ingestText(text, {
985
990
  });
986
991
  taggedIds.add(row.id);
987
992
  }
993
+ await appendFacts(dir, writes);
988
994
  continue;
989
995
  }
990
996
  const ungrounded = ungroundedTermsIn(lastDecline);
@@ -1009,15 +1015,17 @@ export async function ingestText(text, {
1009
1015
  if (!keptCandidates.length) continue;
1010
1016
  optimisticSentences += 1;
1011
1017
  const tag = `optimistic-extract:${sourceTag}`;
1018
+ const candidateWrites = [];
1012
1019
  for (const t of keptCandidates) {
1013
1020
  const extraction = findingsForRow(t, mintFindings.has(t) ? [mintFindings.get(t)] : [], identifierTerms);
1014
- const written = await appendFact(dir, {
1021
+ candidateWrites.push({
1015
1022
  subject: t.subject, predicate: t.predicate, object: t.object, provenance: tag, observedAt,
1016
1023
  ...(extraction.length ? { extraction } : {}),
1017
1024
  });
1018
1025
  optimisticFacts.push({ ...t, provenance: tag, sentence, ...(extraction.length ? { extraction } : {}) });
1019
- taggedIds.add(written.id);
1020
1026
  }
1027
+ const { ids } = await appendFacts(dir, candidateWrites);
1028
+ for (const id of ids) taggedIds.add(id);
1021
1029
  }
1022
1030
  }
1023
1031
 
@@ -494,6 +494,27 @@ function mergeSnapshotsById(existing, incoming, cap) {
494
494
  return { items, added };
495
495
  }
496
496
 
497
+ const fetchedAtMs = (snapshot) => {
498
+ const ms = toMs(snapshot?.fetchedAt);
499
+ return Number.isFinite(ms) ? ms : 0;
500
+ };
501
+
502
+ /** True once a snapshot has been through a grounding round. `mergeSnapshotsById`
503
+ * files a snapshot the moment it arrives, so "known" and "grounded" are two
504
+ * different states and only this one means the facts landed. */
505
+ const isGroundedSnapshot = (snapshot) => (snapshot?.processedRounds || 0) > 0;
506
+
507
+ /** One source's fetched-but-not-yet-grounded snapshots, oldest first. A cycle
508
+ * that ran out of time leaves its backlog here, so the next cycle works
509
+ * through that before anything newer and the same article is never ingested
510
+ * twice. Ordered off the snapshots' own fields, so two cycles reading the same
511
+ * state take the same work in the same order. */
512
+ function pendingSnapshotsFor(items, sourceId) {
513
+ return (items || [])
514
+ .filter((snap) => snap?.sourceId === sourceId && !isGroundedSnapshot(snap))
515
+ .sort((a, b) => (fetchedAtMs(a) - fetchedAtMs(b)) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
516
+ }
517
+
497
518
  function emptyCycleAccumulator(at) {
498
519
  return { at, sentences: 0, recognized: 0, optimisticCount: 0, factsAdded: 0, termsResolved: 0, derived: 0 };
499
520
  }
@@ -548,21 +569,28 @@ export async function pollNewsSources(ctx) {
548
569
  perSource.push({ sourceId, status: "failed" });
549
570
  continue;
550
571
  }
572
+ let added = [];
551
573
  if (result.notModified) {
552
574
  recordSuccess(health, nowVal, "not-modified");
553
- perSource.push({ sourceId, status: "not-modified" });
554
- continue;
575
+ } else {
576
+ recordSuccess(health, nowVal, "ok");
577
+ const merged = mergeSnapshotsById(state.items, result.items, config.itemCap);
578
+ state.items = merged.items;
579
+ added = merged.added;
580
+ newItemsTotal += added.length;
555
581
  }
556
- recordSuccess(health, nowVal, "ok");
557
- const { items: mergedItems, added } = mergeSnapshotsById(state.items, result.items, config.itemCap);
558
- state.items = mergedItems;
559
- newItemsTotal += added.length;
560
582
 
583
+ // Everything this source has fetched and not yet grounded, not just what
584
+ // arrived on this fetch: a source that answers 304 still has a backlog to
585
+ // finish, and an aborted cycle's leftovers would otherwise sit in the state
586
+ // marked known and never be read again.
561
587
  const before = emptyCycleAccumulator(nowVal);
562
588
  const after = emptyCycleAccumulator(nowVal);
563
- for (const snapshot of added) {
589
+ let grounded = 0;
590
+ for (const snapshot of pendingSnapshotsFor(state.items, sourceId)) {
564
591
  if (shouldAbort()) { aborted = true; break; }
565
592
  const r = await ingestNewsSnapshot(ctx, snapshot);
593
+ grounded += 1;
566
594
  after.sentences += r.sentences;
567
595
  after.recognized += r.recognized;
568
596
  after.optimisticCount += r.optimisticCount;
@@ -571,10 +599,17 @@ export async function pollNewsSources(ctx) {
571
599
  factsTotal += r.facts;
572
600
  derivedTotal += r.derived;
573
601
  }
574
- if (added.length) {
602
+ if (grounded) {
575
603
  state.metrics = [...(state.metrics || []), cycleMetrics(before, after, { source: sourceId })];
576
604
  }
577
- perSource.push({ sourceId, status: "ok", newItems: added.length });
605
+ const pendingLeft = pendingSnapshotsFor(state.items, sourceId).length;
606
+ perSource.push({
607
+ sourceId,
608
+ status: result.notModified ? "not-modified" : "ok",
609
+ newItems: added.length,
610
+ grounded,
611
+ pending: pendingLeft,
612
+ });
578
613
  if (aborted) break;
579
614
  }
580
615