@polycode-projects/the-mechanical-code-talker 6.0.10 → 6.0.12

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.10",
3
+ "version": "6.0.12",
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.",
@@ -205,6 +205,10 @@
205
205
  "build:wink-vendor": "node scripts/build-wink-vendor.mjs",
206
206
  "build:three-vendor": "node scripts/build-three-vendor.mjs",
207
207
  "build:chat-seed": "node scripts/build-chat-seed.mjs",
208
+ "build:seed-sqlite:mid": "node scripts/build-seed-sqlite.mjs mid",
209
+ "build:seed-sqlite:xl": "node scripts/build-seed-sqlite.mjs xl",
210
+ "build:seed-sqlite": "node scripts/build-seed-sqlite.mjs",
211
+ "verify:image": "bash scripts/verify-image-local.sh",
208
212
  "build:demo-graph": "node scripts/build-demo-graph.mjs",
209
213
  "build:demo-pack": "node scripts/build-demo-pack.mjs",
210
214
  "build:demo-sprites-pack": "node scripts/build-demo-sprites-pack.mjs",
@@ -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.
@@ -712,6 +712,27 @@ export function closeSqliteMemoryStore(handle) {
712
712
  if (isSqliteHandle(handle)) handle.db.close();
713
713
  }
714
714
 
715
+ /** Open a pre-built seed file READ-ONLY: the same tables
716
+ * `createSqliteMemoryStore` writes, opened without the DDL, the backfills or
717
+ * the WAL pragma, so the file itself never changes and it can sit on a
718
+ * read-only image layer. This is the base layer a
719
+ * `wrapRowBackendOverSqliteSeed` handle assembles under a session's own rows.
720
+ * No row-backend methods are attached: nothing may ever write here. Close it
721
+ * with `closeSqliteMemoryStore`. */
722
+ export async function openSqliteSeedStore(dbPath) {
723
+ installSqliteWarningFilter();
724
+ const { DatabaseSync } = await import("node:sqlite");
725
+ try {
726
+ return { backend: BACKEND_SQLITE, db: new DatabaseSync(dbPath, { readOnly: true }), dbPath, readOnly: true };
727
+ } catch (cause) {
728
+ // A seed file whose writer never closed keeps a live -wal beside it, and
729
+ // recovering that needs write access the caller does not have. Say which
730
+ // file and say read-only, or the raw sqlite message sends the reader
731
+ // looking for a missing file that is right there.
732
+ throw new BackendUnavailable(`could not open the seed store ${dbPath} read-only: ${cause.message}`, { cause });
733
+ }
734
+ }
735
+
715
736
  // ---- Backend D — a consumer's own row store ------------------------------
716
737
  // The consumer constructs the store (row-backend.mjs is the contract) and
717
738
  // tmct binds it into the same `memoryDir` token every memory call threads.
@@ -738,17 +759,39 @@ const ROW_NODE_ID_KEY = "nodeId";
738
759
  /** Bind a row backend as a `memoryDir` token: `{ backend: "row", impl,
739
760
  * cachedPayload, basePayload }`. `basePayload` is the read-only seed overlay;
740
761
  * `onOversizedRow` is the projection's posture for a record over the per-row
741
- * cap ("throw", the default, or "drop"), and `log` takes the drop notices. */
742
- export function wrapRowBackend(impl, { basePayload = null, onOversizedRow = "throw", log = undefined } = {}) {
762
+ * cap ("throw", the default, or "drop"), and `log` takes the drop notices.
763
+ *
764
+ * `sqliteSeedStore` is the same seed overlay held as an OPEN sqlite store
765
+ * (`openSqliteSeedStore`) instead of a parsed payload — see
766
+ * `wrapRowBackendOverSqliteSeed`, the entry point that takes one.
767
+ * `sqliteSeedOverlayRows` are rows that layer over that seed and under the
768
+ * session's own (a turn's retrieved corpus subgraph), read-only exactly as
769
+ * the seed is. */
770
+ export function wrapRowBackend(impl, {
771
+ basePayload = null,
772
+ sqliteSeedStore = null,
773
+ sqliteSeedOverlayRows = null,
774
+ onOversizedRow = "throw",
775
+ log = undefined,
776
+ } = {}) {
743
777
  const problems = rowBackendProblems(impl);
744
778
  if (problems.length) {
745
779
  throw new BackendRejected(`not a memory row backend: ${problems.join("; ")}`);
746
780
  }
781
+ if (sqliteSeedStore && !isSqliteHandle(sqliteSeedStore)) {
782
+ throw new BackendRejected("sqliteSeedStore must be an open sqlite store handle (openSqliteSeedStore)");
783
+ }
784
+ if (sqliteSeedStore && basePayload) {
785
+ throw new BackendRejected("a handle takes its seed either as a basePayload or as a sqliteSeedStore, never both");
786
+ }
747
787
  return {
748
788
  backend: BACKEND_ROW,
749
789
  impl,
750
790
  cachedPayload: null,
751
791
  basePayload: cloneMemoryPayload(basePayload),
792
+ sqliteSeedStore,
793
+ sqliteSeedOverlayRows: sqliteSeedOverlayRows ? [...sqliteSeedOverlayRows] : null,
794
+ sqliteSeedKeyOrds: null,
752
795
  baseRows: null,
753
796
  storedRows: null,
754
797
  onOversizedRow,
@@ -756,6 +799,16 @@ export function wrapRowBackend(impl, { basePayload = null, onOversizedRow = "thr
756
799
  };
757
800
  }
758
801
 
802
+ /** `wrapRowBackend` over a seed held as an open read-only sqlite store. The
803
+ * seed's rows stream into assembly one at a time and the keys the session may
804
+ * never write come off the store's own key columns, so a 60k-fact seed is
805
+ * never materialized as a row array: the assembled payload is the only copy
806
+ * of it this process holds. `overlayRows` layer over the seed and under the
807
+ * 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 });
810
+ }
811
+
759
812
  /** Drain whatever `readRows()` returned: the contract allows an array or an
760
813
  * async iterable, so a paginating backend can stream its pages. */
761
814
  async function collectRows(source) {
@@ -779,7 +832,12 @@ function overlayRows(baseRows, sessionRows) {
779
832
  * session store does not already hold a row for. */
780
833
  function seedOnlyKeys(handle) {
781
834
  const sessionKeys = new Set(handle.storedRows.map((r) => r.rowKey));
782
- return new Set(handle.baseRows.map((r) => r.rowKey).filter((key) => !sessionKeys.has(key)));
835
+ const baseKeys = handle.sqliteSeedStore
836
+ ? sqliteSeedKeyOrds(handle).keys()
837
+ : handle.baseRows.map((r) => r.rowKey);
838
+ const seedOnly = new Set();
839
+ for (const key of baseKeys) if (!sessionKeys.has(key)) seedOnly.add(key);
840
+ return seedOnly;
783
841
  }
784
842
 
785
843
  async function readRowMeta(handle, key, fallback) {
@@ -788,30 +846,42 @@ async function readRowMeta(handle, key, fallback) {
788
846
  try { return JSON.parse(raw); } catch { return fallback; }
789
847
  }
790
848
 
791
- /** loadMemory's read for Backend D: one `readRows()` per cold open, assembled
792
- * once with the seed overlay, then served from `cachedPayload` with no
793
- * further backend traffic. Bookkeeping rows are held aside — they round-trip
794
- * through the store but never compose into a payload. */
795
- async function readRowPayload(handle) {
849
+ /** The assembled payload ITSELF, assembled on the first call and served from
850
+ * `cachedPayload` after that with no further backend traffic. Bookkeeping rows
851
+ * are held aside — they round-trip through the store but never compose into a
852
+ * payload. The caller must not hand this object out: `readRowPayload` is the
853
+ * seam that clones, and cloning a seed-sized payload is the single most
854
+ * expensive thing this backend does, so a caller that only needs the cache
855
+ * warm calls this one instead. */
856
+ async function ensureRowPayload(handle) {
796
857
  if (!handle.cachedPayload) {
797
858
  const empty = emptyMemory();
798
859
  const stored = await collectRows(handle.impl.readRows());
799
- // "keep": the base overlay's own rows never reach the wire (persistRowPayload
800
- // excludes every seed key from every write via seedOnlyKeys below), so the
801
- // per-row byte cap that protects a real backend's real item-size limit has
802
- // nothing to protect here — capping it would silently drop a real corpus
803
- // band's own high-fan-out property (one edge per fact is normal, not a
804
- // pathology) and break every read that depends on it.
805
- handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
806
860
  handle.storedRows = stored.filter((row) => row?.rowClass !== BOOKKEEPING_ROW_CLASS);
807
- handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
808
- meta: {
809
- memory: await readRowMeta(handle, ROW_META_MEMORY_KEY, handle.basePayload?.memory ?? empty.memory),
810
- prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, handle.basePayload?.prefixes ?? empty.prefixes),
811
- },
812
- });
861
+ const meta = {
862
+ memory: await readRowMeta(handle, ROW_META_MEMORY_KEY, seedScalar(handle, "memory", empty.memory)),
863
+ prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, seedScalar(handle, "prefixes", empty.prefixes)),
864
+ };
865
+ if (handle.sqliteSeedStore) {
866
+ handle.cachedPayload = assembleSqliteSeededPayload(handle, meta);
867
+ } else {
868
+ // "keep": the base overlay's own rows never reach the wire (persistRowPayload
869
+ // excludes every seed key from every write via seedOnlyKeys below), so the
870
+ // per-row byte cap that protects a real backend's real item-size limit has
871
+ // nothing to protect here — capping it would silently drop a real corpus
872
+ // band's own high-fan-out property (one edge per fact is normal, not a
873
+ // pathology) and break every read that depends on it.
874
+ handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
875
+ handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
876
+ }
813
877
  }
814
- return cloneJson(handle.cachedPayload);
878
+ return handle.cachedPayload;
879
+ }
880
+
881
+ /** loadMemory's read for Backend D: one `readRows()` per cold open, then a
882
+ * clone of the assembled payload per call. */
883
+ async function readRowPayload(handle) {
884
+ return cloneJson(await ensureRowPayload(handle));
815
885
  }
816
886
 
817
887
  /** A record with its audit stamp removed. `mgx:updatedAt` moves on every
@@ -842,16 +912,19 @@ function movedBeyondAuditStamp(beforeRow, row) {
842
912
  * write drops the cache so the next read rebuilds from the store rather than
843
913
  * from a payload that never landed. */
844
914
  async function persistRowPayload(handle, payload) {
845
- await readRowPayload(handle);
846
- const before = overlayRows(handle.baseRows, handle.storedRows);
915
+ await ensureRowPayload(handle);
916
+ const seedKeys = seedOnlyKeys(handle);
917
+ // On the sqlite path the seed is out of BOTH sides of the diff: the rows it
918
+ // holds are exactly the keys no write may touch, so projecting them would
919
+ // materialize the whole seed only to filter every row of it back out.
920
+ const before = handle.sqliteSeedStore ? handle.storedRows : overlayRows(handle.baseRows, handle.storedRows);
847
921
  const beforeByKey = new Map(before.map((row) => [row.rowKey, row]));
848
- const after = payloadToRows(payload, {
849
- priorRows: before,
922
+ const after = payloadToRows(handle.sqliteSeedStore ? payloadWithoutRowKeys(payload, seedKeys) : payload, {
923
+ priorRows: handle.sqliteSeedStore ? sqliteSeedPriorRows(handle) : before,
850
924
  onOversizedRow: handle.onOversizedRow,
851
925
  ...(handle.log ? { log: handle.log } : {}),
852
926
  });
853
927
  const { puts, deletes } = diffRows(before, after);
854
- const seedKeys = seedOnlyKeys(handle);
855
928
  const writes = puts
856
929
  .filter((row) => !seedKeys.has(row.rowKey))
857
930
  .filter((row) => movedBeyondAuditStamp(beforeByKey.get(row.rowKey), row));
@@ -871,9 +944,198 @@ async function persistRowPayload(handle, payload) {
871
944
  const next = new Map(handle.storedRows.filter((row) => !removed.has(row.rowKey)).map((row) => [row.rowKey, row]));
872
945
  for (const row of writes) next.set(row.rowKey, row);
873
946
  handle.storedRows = [...next.values()];
874
- handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
875
- meta: { memory: payload.memory, prefixes: payload.prefixes },
876
- });
947
+ const meta = { memory: payload.memory, prefixes: payload.prefixes };
948
+ if (handle.sqliteSeedStore && !removals.length) {
949
+ patchAssembledPayload(handle.cachedPayload, meta, writes);
950
+ } else if (handle.sqliteSeedStore) {
951
+ handle.cachedPayload = null;
952
+ handle.cachedPayload = assembleSqliteSeededPayload(handle, meta);
953
+ } else {
954
+ // Dropped before the rebuild, not after it: the payload this replaces is the
955
+ // largest object the handle holds, and keeping it reachable while the next
956
+ // one assembles doubles the peak for no reason.
957
+ handle.cachedPayload = null;
958
+ handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), { meta });
959
+ }
960
+ }
961
+
962
+ /** The payload minus a set of row keys, for a projection that must not spend
963
+ * bytes on rows the write path is about to filter out anyway. */
964
+ function payloadWithoutRowKeys(payload, excluded) {
965
+ if (!excluded.size) return payload;
966
+ return {
967
+ ...payload,
968
+ individuals: (payload?.individuals || []).filter((ind) => !excluded.has(String(ind?.id ?? ""))),
969
+ objectProperties: (payload?.objectProperties || []).filter((group) => !excluded.has(`${EDGE_GROUP_KEY_PREFIX}${group?.prop}`)),
970
+ };
971
+ }
972
+
973
+ // ---- A sqlite store as the seed layer --------------------------------------
974
+ // The seed a Backend D handle reads under its session's own rows can be an
975
+ // open read-only sqlite store instead of a parsed payload. Nothing about the
976
+ // contract changes: the same rows assemble in the same order and the same keys
977
+ // are barred from every write. What changes is how many copies of the seed
978
+ // exist at once — the rows stream out of the store one at a time and the
979
+ // write path never projects them, so the assembled payload is the only one.
980
+
981
+ /** node:sqlite's row-at-a-time read where the runtime has it, the whole result
982
+ * set where it does not. Streaming is the point: a seed row is garbage the
983
+ * moment assembly has parsed it. */
984
+ function statementRowStream(statement) {
985
+ return typeof statement.iterate === "function" ? statement.iterate() : statement.all();
986
+ }
987
+
988
+ /** Every row the seed store holds, one at a time. `coveredByAnotherLayer(key)`
989
+ * drops the keys the subgraph overlay or the session's own rows already own,
990
+ * so assembly sees each key exactly once. */
991
+ function* sqliteSeedRowStream(store, coveredByAnotherLayer) {
992
+ const individuals = store.db.prepare(
993
+ "SELECT i.id AS id, i.ord AS ord, i.class AS class, i.json AS json, f.subject AS subject"
994
+ + " FROM individuals i LEFT JOIN facts f ON f.id = i.id ORDER BY i.ord, i.id",
995
+ );
996
+ for (const r of statementRowStream(individuals)) {
997
+ if (coveredByAnotherLayer(r.id)) continue;
998
+ const rowClass = ROW_CLASS_BY_INDIVIDUAL_CLASS.get(r.class) || "";
999
+ yield {
1000
+ rowKey: r.id,
1001
+ rowClass,
1002
+ term: rowClass === "fact" ? normFactTerm(r.subject || "") : "",
1003
+ json: individualRowJson(r.ord, r.json),
1004
+ };
1005
+ }
1006
+ // One query per group rather than one over every edge in the store: a group
1007
+ // is freed as soon as assembly has taken it, so the edges of the largest
1008
+ // property are all this ever holds at once.
1009
+ const edgesOfProp = store.db.prepare(
1010
+ "SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ? ORDER BY rowid",
1011
+ );
1012
+ for (const relation of store.db.prepare("SELECT prop, ord, predicate, count FROM relations ORDER BY ord, prop").all()) {
1013
+ if (coveredByAnotherLayer(`${EDGE_GROUP_KEY_PREFIX}${relation.prop}`)) continue;
1014
+ const examples = [];
1015
+ for (const e of edgesOfProp.all(relation.prop)) {
1016
+ const edge = { subject: e.subject, object: e.object, subjectLabel: e.subject_label, objectLabel: e.object_label };
1017
+ if (e.extra) Object.assign(edge, JSON.parse(e.extra));
1018
+ examples.push(edge);
1019
+ }
1020
+ yield edgeGroupRow({ predicate: relation.predicate, prop: relation.prop, count: relation.count, examples }, relation.ord);
1021
+ }
1022
+ for (const row of readUnmappedRows(store.db)) {
1023
+ if (!coveredByAnotherLayer(row.rowKey)) yield row;
1024
+ }
1025
+ }
1026
+
1027
+ /** Every key the read-only layers hold, with the ord each one carries — the
1028
+ * keys-only view of the seed the write path needs. A key and an integer per
1029
+ * row is small where the rows themselves are not, so this is held for the
1030
+ * handle's life once a write has asked for it. */
1031
+ function sqliteSeedKeyOrds(handle) {
1032
+ if (handle.sqliteSeedKeyOrds) return handle.sqliteSeedKeyOrds;
1033
+ const db = handle.sqliteSeedStore.db;
1034
+ const ords = new Map();
1035
+ for (const r of statementRowStream(db.prepare("SELECT id, ord FROM individuals"))) ords.set(r.id, r.ord);
1036
+ for (const r of statementRowStream(db.prepare("SELECT prop, ord FROM relations"))) ords.set(`${EDGE_GROUP_KEY_PREFIX}${r.prop}`, r.ord);
1037
+ for (const row of readUnmappedRows(db)) ords.set(row.rowKey, ordOfRow(row));
1038
+ for (const row of handle.sqliteSeedOverlayRows || []) ords.set(row.rowKey, ordOfRow(row));
1039
+ handle.sqliteSeedKeyOrds = ords;
1040
+ return ords;
1041
+ }
1042
+
1043
+ /** What `payloadToRows` reads off prior rows: the ord each key already carries,
1044
+ * in the smallest row shape that carries one. The session's own rows come
1045
+ * last, so a key both layers hold keeps the session's ord — the precedence
1046
+ * assembly gives it. */
1047
+ function* sqliteSeedPriorRows(handle) {
1048
+ for (const [rowKey, ord] of sqliteSeedKeyOrds(handle)) yield { rowKey, json: `{"ord":${ord}}` };
1049
+ yield* handle.storedRows;
1050
+ }
1051
+
1052
+ function* chainedRows(...sources) {
1053
+ for (const source of sources) yield* source;
1054
+ }
1055
+
1056
+ /** seed ⊕ overlay ⊕ session, assembled once: the seed streams out of sqlite,
1057
+ * the overlay rows layer over it, and the session's own rows win both. */
1058
+ function assembleSqliteSeededPayload(handle, meta) {
1059
+ const covered = new Set(handle.storedRows.map((row) => row.rowKey));
1060
+ const overlay = (handle.sqliteSeedOverlayRows || []).filter((row) => row?.rowKey && !covered.has(row.rowKey));
1061
+ for (const row of overlay) covered.add(row.rowKey);
1062
+ return rowsToPayload(
1063
+ chainedRows(sqliteSeedRowStream(handle.sqliteSeedStore, (key) => covered.has(key)), overlay, handle.storedRows),
1064
+ { meta },
1065
+ );
1066
+ }
1067
+
1068
+ /** The assembled payload after a write that only added or rewrote rows, brought
1069
+ * up to date without reading the seed again.
1070
+ *
1071
+ * Why the positions work out: a write only ever carries session rows, and
1072
+ * `payloadToRows` gives a newly-keyed row an ord past every ord already
1073
+ * assembled, so a new individual belongs at the tail and a rewritten one
1074
+ * belongs exactly where it already sits. Both are where a rebuild from the
1075
+ * same rows would put them, and the fact set is unchanged or grown, so the
1076
+ * fact ordering `renormalizeAssembledPayload` reapplies lands the same way.
1077
+ * Everything the payload derives goes through that one function, the same one
1078
+ * `rowsToPayload` itself ends on, so a patched payload and a rebuilt one
1079
+ * cannot drift apart.
1080
+ *
1081
+ * A REMOVAL is not patchable this way and does not come here: dropping an
1082
+ * individual from the assembled array drops it from wherever the fact ordering
1083
+ * moved it to, which is a different position from the one it occupied in row
1084
+ * order, and every fact after it shifts. `persistRowPayload` rebuilds for those.
1085
+ * Mutates and returns `payload`. */
1086
+ function patchAssembledPayload(payload, meta, writes) {
1087
+ payload.memory = meta.memory;
1088
+ payload.prefixes = meta.prefixes;
1089
+ if (!writes.length) return renormalizeAssembledPayload(payload);
1090
+
1091
+ const individualPositions = new Map();
1092
+ for (let i = 0; i < payload.individuals.length; i += 1) individualPositions.set(payload.individuals[i]?.id, i);
1093
+ const groupPositions = new Map();
1094
+ for (let i = 0; i < payload.objectProperties.length; i += 1) groupPositions.set(payload.objectProperties[i]?.prop, i);
1095
+
1096
+ for (const row of writes) {
1097
+ if (row.rowClass === BOOKKEEPING_ROW_CLASS) continue;
1098
+ const record = JSON.parse(row.json);
1099
+ if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
1100
+ const group = record?.group;
1101
+ if (!group?.prop) continue;
1102
+ const at = groupPositions.get(group.prop);
1103
+ if (at === undefined) {
1104
+ groupPositions.set(group.prop, payload.objectProperties.length);
1105
+ payload.objectProperties.push(group);
1106
+ } else payload.objectProperties[at] = group;
1107
+ continue;
1108
+ }
1109
+ const individual = record?.individual;
1110
+ if (!individual?.id) continue;
1111
+ const at = individualPositions.get(individual.id);
1112
+ if (at === undefined) {
1113
+ individualPositions.set(individual.id, payload.individuals.length);
1114
+ payload.individuals.push(individual);
1115
+ } else payload.individuals[at] = individual;
1116
+ }
1117
+ return renormalizeAssembledPayload(payload);
1118
+ }
1119
+
1120
+ /** Every distinct subject and object a seed store's facts carry, off the
1121
+ * `facts` projection's own columns — the raw values, folded by whoever needs
1122
+ * them. A caller that would otherwise walk the seed's individuals to collect
1123
+ * its vocabulary asks the database instead and parses no record at all. */
1124
+ export function* sqliteSeedFactTermValues(store) {
1125
+ for (const column of ["subject", "object"]) {
1126
+ for (const r of statementRowStream(store.db.prepare(`SELECT DISTINCT ${column} AS value FROM facts`))) {
1127
+ if (r.value) yield r.value;
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ /** The seed's own value for one of the two stored scalars, whichever way this
1133
+ * handle holds its seed. */
1134
+ function seedScalar(handle, key, fallback) {
1135
+ if (!handle.sqliteSeedStore) return handle.basePayload?.[key] ?? fallback;
1136
+ const row = handle.sqliteSeedStore.db.prepare("SELECT v FROM meta WHERE k = ?").get(key);
1137
+ if (!row) return fallback;
1138
+ try { return JSON.parse(row.v); } catch { return fallback; }
877
1139
  }
878
1140
 
879
1141
  /** Resolve a backend token ("memory" | "sqlite" | anything else) into
@@ -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;
@@ -1,6 +1,5 @@
1
1
  // news-viz.mjs — news.html: a thin client over the row service's news
2
- // routes (PLAN_MEMORY_BACKEND.md's news.html-goes-thin revision), on the
3
- // ledger.html dashboard precedent (src/services/ledger-viz.mjs: `.dash`/
2
+ // routes, on the ledger.html dashboard precedent (src/services/ledger-viz.mjs: `.dash`/
4
3
  // `.kpirow`/`.tile`/`.tile-bars`, the same THEME_TOKENS_CSS palette).
5
4
  //
6
5
  // This page carries no engine and no seed. Every card, tile, bar, source