@polycode-projects/the-mechanical-code-talker 5.0.45 → 6.0.0

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.
@@ -52,6 +52,20 @@ import {
52
52
  } from "../../domain/memory/retraction.mjs";
53
53
  import { admittedNodes, stableRecordIds } from "../../domain/memory/causal-stability.mjs";
54
54
  import { assertIndividualValid } from "./shacl.mjs";
55
+ import { BackendRejected, isRowBackend, rowBackendProblems, BOOKKEEPING_ROW_CLASS } from "./row-backend.mjs";
56
+ // The row-backend contract lives in its own module (a consumer imports it
57
+ // without loading the engine); re-exported here so store consumers keep one
58
+ // import site, the same way the trust and retraction vocabularies are.
59
+ export {
60
+ BackendRejected, BackendUnavailable, isRowBackend, rowBackendProblems,
61
+ isValidRow, rowProblems, assertValidRow,
62
+ ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION, ROW_CLASSES, MAX_ROW_BYTES,
63
+ } from "./row-backend.mjs";
64
+ // rows.mjs imports this module back for the class constants. The cycle is
65
+ // fine as long as neither side READS an imported binding while the other's
66
+ // body is still running — rows.mjs builds its class map on first use, and
67
+ // every use here is inside a function.
68
+ import { payloadToRows, rowsToPayload, diffRows } from "./rows.mjs";
55
69
 
56
70
  // The rollup vocabulary and its tuning constants live with the compaction
57
71
  // layer; re-exported here so store consumers keep one import site.
@@ -122,6 +136,7 @@ const MEMORY_VOCABULARY = [
122
136
  { prop: "mgx:factProvenance", note: "LEGACY COMPAT SHIM: the ' | '-joined provenance tag string a fact came from; the source-of-truth is now the mgx:statedBy edges derived from it" },
123
137
  { prop: "mgx:sourceId", note: "the assertion key a Fact record is filed under — the Source id of the ONE party asserting it, which is also the @-suffix of the record's own id. `src:none` when no tag names a Source, so every record has a key rather than a hole" },
124
138
  { prop: "mgx:observedAt", note: "OPTIONAL valid time: when the asserting party WITNESSED the claim, as against mgx:createdAt's transaction time (when this store recorded it). A stale article read today loses to an eyewitness report from yesterday. Stored only when a caller supplies one — never fabricated, never backfilled" },
139
+ { prop: "mgx:extractionFinding", note: "OPTIONAL: the space-joined structural findings the extractor recorded about how THIS assertion's sentence was read, from the closed vocabulary identifier-token | clause-fallback | pronoun-carry | definitional-frame. Per assertion, never per triple: a later clean re-assertion of the same triple carries none. Absence means no findings were recorded, never that the sentence was checked and read cleanly" },
125
140
  { prop: "mgx:supersedes", note: "the record id(s) this one replaced when its own source re-asserted the triple with a newer embedded timestamp. A space-joined LIST; absent, never empty, until the first supersession" },
126
141
  { prop: "mgx:supersededBy", note: "the record id(s) that replaced this one. Its presence is what makes a record a demoted leaf rather than a live head, and the group fold skips it: a source's past belief is not a second vote for the present one. A LIST, because one source with two live replicas can fork before they sync" },
127
142
  { prop: "mgx:factQuantifier", note: "OPTIONAL: the quantifier word a plural class-membership teach used ('every'/'some'/'a few'), for literal recall by 'how many Xs are Ys' — never real cardinality counting" },
@@ -175,8 +190,8 @@ export function emptyMemory() {
175
190
  * (default) is the live graph; a numeric version resolves a snapshot copy
176
191
  * (see snapshotMemory below). The single source of truth for this path. */
177
192
  export function resolveMemoryGraphFile(dir, version = null) {
178
- if (isMemoryHandle(dir) || isSqliteHandle(dir)) {
179
- throw new Error("resolveMemoryGraphFile: dir is a memory/sqlite handle, not a file path (Backend A only)");
193
+ if (isMemoryOrSqliteHandle(dir)) {
194
+ throw new Error("resolveMemoryGraphFile: dir is a store handle, not a file path (Backend A only)");
180
195
  }
181
196
  if (version === null) return join(dir, MEMORY_GRAPH_REL);
182
197
  return join(dir, MEMORY_DIR_REL, `graph.v${version}.json`);
@@ -186,12 +201,14 @@ const memoryGraphFile = (dir) => resolveMemoryGraphFile(dir);
186
201
 
187
202
  // ---- Storage-backend seam --------------------------------------------------
188
203
  // `dir` is either a plain repo-path string (Backend A, file-backed) or a
189
- // handle from createInMemoryStore() (Backend B) or createSqliteMemoryStore()
190
- // (Backend C). Only loadMemory/mutateMemory dispatch on backend; every other
204
+ // handle from createInMemoryStore() (Backend B), createSqliteMemoryStore()
205
+ // (Backend C), or wrapRowBackend() over a consumer's own row store
206
+ // (Backend D). Only loadMemory/mutateMemory dispatch on backend; every other
191
207
  // function operates on the plain payload object they hand back.
192
208
 
193
209
  const BACKEND_MEMORY = "memory";
194
210
  const BACKEND_SQLITE = "sqlite";
211
+ const BACKEND_ROW = "row";
195
212
 
196
213
  function isMemoryHandle(dir) {
197
214
  return !!dir && typeof dir === "object" && dir.backend === BACKEND_MEMORY;
@@ -199,14 +216,20 @@ function isMemoryHandle(dir) {
199
216
  function isSqliteHandle(dir) {
200
217
  return !!dir && typeof dir === "object" && dir.backend === BACKEND_SQLITE;
201
218
  }
202
- /** True for a Backend B (in-memory) or Backend C (sqlite) handle — anything
203
- * that is NOT a plain repo-path string. Exported so every OTHER module that
204
- * takes a `dir` and might reach a raw `node:path`/`node:fs` call (blocks.mjs's
205
- * session-block index chief among them) can guard the same way this module
206
- * already does, instead of a bare `join(dir, …)` throwing Node's generic
207
- * "path argument must be of type string" at a caller with no idea why. */
219
+ /** True for a Backend D handle — the wrapper wrapRowBackend puts around a
220
+ * consumer's injected row store. A row store has no path and no connection of
221
+ * tmct's own, so callers that reach for either have to branch on this. */
222
+ export function isRowHandle(dir) {
223
+ return !!dir && typeof dir === "object" && dir.backend === BACKEND_ROW;
224
+ }
225
+ /** True for any store handle — Backend B, C or D — that is NOT a plain
226
+ * repo-path string. Exported so every OTHER module that takes a `dir` and
227
+ * might reach a raw `node:path`/`node:fs` call (blocks.mjs's session-block
228
+ * index chief among them) can guard the same way this module already does,
229
+ * instead of a bare `join(dir, …)` throwing Node's generic "path argument
230
+ * must be of type string" at a caller with no idea why. */
208
231
  export function isMemoryOrSqliteHandle(dir) {
209
- return isMemoryHandle(dir) || isSqliteHandle(dir);
232
+ return isMemoryHandle(dir) || isSqliteHandle(dir) || isRowHandle(dir);
210
233
  }
211
234
 
212
235
  /** Backend B — pure in-memory store: `{ backend: "memory", payload }` held by
@@ -302,6 +325,13 @@ const SOURCE_ID_PROP = "mgx:sourceId"; // the assertion key this record
302
325
  const SUPERSEDES_PROP = "mgx:supersedes"; // the id(s) this record replaced; absent until the first supersession
303
326
  const SUPERSEDED_BY_PROP = "mgx:supersededBy"; // the id(s) that replaced this record; absent on a live head
304
327
 
328
+ /** How the extractor read the sentence one assertion came from — a space-joined
329
+ * list from the closed EXTRACTION_FINDINGS vocabulary, absent when the write
330
+ * recorded none. It sits on the assertion record rather than the triple, so a
331
+ * second source stating the same thing cleanly inherits no caveat. */
332
+ export const EXTRACTION_FINDING_PROP = "mgx:extractionFinding";
333
+ export { EXTRACTION_FINDINGS } from "./shacl.mjs";
334
+
305
335
  /** The Source key a Fact's provenance union projects onto: the first tag that
306
336
  * derives one, since the tags of one fact are asserted in arrival order and
307
337
  * the earliest is its primary source. `src:none` when no tag parses. */
@@ -672,19 +702,191 @@ export async function createSqliteMemoryStore(dbPath) {
672
702
 
673
703
  /** Close a Backend C handle's connection. A no-op for anything else (so a
674
704
  * caller that doesn't know which backend it has can call this unconditionally
675
- * at session end). */
705
+ * at session end). A Backend D handle is closed through its own `impl.close()`
706
+ * instead — openMemoryBackend's returned `close` is the call site. */
676
707
  export function closeSqliteMemoryStore(handle) {
677
708
  if (isSqliteHandle(handle)) handle.db.close();
678
709
  }
679
710
 
711
+ // ---- Backend D — a consumer's own row store ------------------------------
712
+ // The consumer constructs the store (row-backend.mjs is the contract) and
713
+ // tmct binds it into the same `memoryDir` token every memory call threads.
714
+ // The payload this handle hands back is `basePayload` overlaid with the rows
715
+ // the store holds; the payload it writes back is the DELTA against what it
716
+ // last assembled, so a turn pays for what it changed and nothing else.
717
+ //
718
+ // `basePayload` is a read-only overlay for a bundled seed graph. Its rows are
719
+ // assembled into every read and are excluded from every write, so a session
720
+ // over a 60k-fact seed still stores only the handful of facts that session
721
+ // taught.
722
+ //
723
+ // No cross-writer cache guard exists here, unlike Backend C's PRAGMA
724
+ // data_version check: a second writer's rows appear at this handle's next cold
725
+ // open, and the derived state recomputes then. A consumer that needs to see
726
+ // another writer's rows immediately constructs a fresh handle per request,
727
+ // which is what the serverless pattern does anyway.
728
+
729
+ const ROW_META_MEMORY_KEY = "memory";
730
+ const ROW_META_PREFIXES_KEY = "prefixes";
731
+ const ROW_SYLLOGISE_STATE_KEY = "syllogiseState";
732
+ const ROW_NODE_ID_KEY = "nodeId";
733
+
734
+ /** Bind a row backend as a `memoryDir` token: `{ backend: "row", impl,
735
+ * cachedPayload, basePayload }`. `basePayload` is the read-only seed overlay;
736
+ * `onOversizedRow` is the projection's posture for a record over the per-row
737
+ * cap ("throw", the default, or "drop"), and `log` takes the drop notices. */
738
+ export function wrapRowBackend(impl, { basePayload = null, onOversizedRow = "throw", log = undefined } = {}) {
739
+ const problems = rowBackendProblems(impl);
740
+ if (problems.length) {
741
+ throw new BackendRejected(`not a memory row backend: ${problems.join("; ")}`);
742
+ }
743
+ return {
744
+ backend: BACKEND_ROW,
745
+ impl,
746
+ cachedPayload: null,
747
+ basePayload: cloneMemoryPayload(basePayload),
748
+ baseRows: null,
749
+ storedRows: null,
750
+ onOversizedRow,
751
+ log,
752
+ };
753
+ }
754
+
755
+ /** Drain whatever `readRows()` returned: the contract allows an array or an
756
+ * async iterable, so a paginating backend can stream its pages. */
757
+ async function collectRows(source) {
758
+ const value = await source;
759
+ if (Array.isArray(value)) return value;
760
+ const rows = [];
761
+ for await (const row of value) rows.push(row);
762
+ return rows;
763
+ }
764
+
765
+ /** The seed rows under the session's own, keyed so a session row with a base
766
+ * row's key wins. */
767
+ function overlayRows(baseRows, sessionRows) {
768
+ const byKey = new Map();
769
+ for (const row of baseRows) byKey.set(row.rowKey, row);
770
+ for (const row of sessionRows) byKey.set(row.rowKey, row);
771
+ return [...byKey.values()];
772
+ }
773
+
774
+ /** The seed keys this handle must never write or delete: every base row the
775
+ * session store does not already hold a row for. */
776
+ function seedOnlyKeys(handle) {
777
+ const sessionKeys = new Set(handle.storedRows.map((r) => r.rowKey));
778
+ return new Set(handle.baseRows.map((r) => r.rowKey).filter((key) => !sessionKeys.has(key)));
779
+ }
780
+
781
+ async function readRowMeta(handle, key, fallback) {
782
+ const raw = await handle.impl.readMeta(key);
783
+ if (raw === null || raw === undefined) return fallback;
784
+ try { return JSON.parse(raw); } catch { return fallback; }
785
+ }
786
+
787
+ /** loadMemory's read for Backend D: one `readRows()` per cold open, assembled
788
+ * once with the seed overlay, then served from `cachedPayload` with no
789
+ * further backend traffic. Bookkeeping rows are held aside — they round-trip
790
+ * through the store but never compose into a payload. */
791
+ async function readRowPayload(handle) {
792
+ if (!handle.cachedPayload) {
793
+ const empty = emptyMemory();
794
+ const stored = await collectRows(handle.impl.readRows());
795
+ handle.baseRows = payloadToRows(handle.basePayload || empty);
796
+ handle.storedRows = stored.filter((row) => row?.rowClass !== BOOKKEEPING_ROW_CLASS);
797
+ handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
798
+ meta: {
799
+ memory: await readRowMeta(handle, ROW_META_MEMORY_KEY, handle.basePayload?.memory ?? empty.memory),
800
+ prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, handle.basePayload?.prefixes ?? empty.prefixes),
801
+ },
802
+ });
803
+ }
804
+ return cloneJson(handle.cachedPayload);
805
+ }
806
+
807
+ /** A record with its audit stamp removed. `mgx:updatedAt` moves on every
808
+ * individual a trust recompute touches, which is every fact in the store on
809
+ * every mutate, so comparing raw bytes calls every row changed. */
810
+ function recordWithoutAuditStamp(json) {
811
+ let record;
812
+ try { record = JSON.parse(json); } catch { return json; }
813
+ const ind = record?.individual;
814
+ if (!Array.isArray(ind?.attributes)) return json;
815
+ return JSON.stringify({
816
+ ...record,
817
+ individual: { ...ind, attributes: ind.attributes.filter((a) => a?.prop !== UPDATED_AT_PROP) },
818
+ });
819
+ }
820
+
821
+ /** A row worth a write: something about it changed beyond the audit stamp. A
822
+ * row whose only difference is that stamp says nothing new, and writing it
823
+ * would let a handle with a stale read overwrite a concurrent writer's real
824
+ * change with its own no-op. */
825
+ function movedBeyondAuditStamp(beforeRow, row) {
826
+ if (!beforeRow) return true;
827
+ return recordWithoutAuditStamp(beforeRow.json) !== recordWithoutAuditStamp(row.json);
828
+ }
829
+
830
+ /** persistMemory's write for Backend D: project the mutated payload, diff it
831
+ * against what this handle last assembled, and write only the delta. A failed
832
+ * write drops the cache so the next read rebuilds from the store rather than
833
+ * from a payload that never landed. */
834
+ async function persistRowPayload(handle, payload) {
835
+ await readRowPayload(handle);
836
+ const before = overlayRows(handle.baseRows, handle.storedRows);
837
+ const beforeByKey = new Map(before.map((row) => [row.rowKey, row]));
838
+ const after = payloadToRows(payload, {
839
+ priorRows: before,
840
+ onOversizedRow: handle.onOversizedRow,
841
+ ...(handle.log ? { log: handle.log } : {}),
842
+ });
843
+ const { puts, deletes } = diffRows(before, after);
844
+ const seedKeys = seedOnlyKeys(handle);
845
+ const writes = puts
846
+ .filter((row) => !seedKeys.has(row.rowKey))
847
+ .filter((row) => movedBeyondAuditStamp(beforeByKey.get(row.rowKey), row));
848
+ const removals = deletes.filter((key) => !seedKeys.has(key));
849
+ try {
850
+ if (writes.length) await handle.impl.putRows(writes);
851
+ if (removals.length) await handle.impl.deleteRows(removals);
852
+ await handle.impl.putMeta(ROW_META_MEMORY_KEY, JSON.stringify(payload.memory ?? emptyMemory().memory));
853
+ await handle.impl.putMeta(ROW_META_PREFIXES_KEY, JSON.stringify(payload.prefixes ?? emptyMemory().prefixes));
854
+ } catch (e) {
855
+ handle.cachedPayload = null;
856
+ handle.storedRows = null;
857
+ handle.baseRows = null;
858
+ throw e;
859
+ }
860
+ const removed = new Set(removals);
861
+ const next = new Map(handle.storedRows.filter((row) => !removed.has(row.rowKey)).map((row) => [row.rowKey, row]));
862
+ for (const row of writes) next.set(row.rowKey, row);
863
+ handle.storedRows = [...next.values()];
864
+ handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
865
+ meta: { memory: payload.memory, prefixes: payload.prefixes },
866
+ });
867
+ }
868
+
680
869
  /** Resolve a backend token ("memory" | "sqlite" | anything else) into
681
870
  * `{ dir, close }` — the ONE shared resolver, so every entry point (init's
682
871
  * corpus seed, bin/tmct.mjs, chat) picks the same backend for a repo rather
683
872
  * than silently splitting its memory across two stores. The empty/"default"
684
873
  * token routes to the sqlite store: the flat-file Backend A is retired from
685
874
  * routing (loadMemory/persistMemory still honour a plain dir string for
686
- * callers that hold one directly). */
875
+ * callers that hold one directly).
876
+ *
877
+ * `backendChoice` may also be an OBJECT: a row backend, which gets wrapped as
878
+ * a Backend D handle, or a handle wrapRowBackend already produced (the way a
879
+ * caller passes a seed overlay in). Either passes through untouched by config
880
+ * resolution — no repo path is read, nothing is created on disk — and the
881
+ * returned `close` closes the injected store. */
687
882
  export async function openMemoryBackend(repoRoot, backendChoice) {
883
+ if (isRowHandle(backendChoice)) {
884
+ return { dir: backendChoice, close: async () => { await backendChoice.impl.close(); } };
885
+ }
886
+ if (isRowBackend(backendChoice)) {
887
+ const handle = wrapRowBackend(backendChoice);
888
+ return { dir: handle, close: async () => { await handle.impl.close(); } };
889
+ }
688
890
  if (backendChoice === BACKEND_MEMORY) {
689
891
  return { dir: createInMemoryStore(), close: async () => {} };
690
892
  }
@@ -701,7 +903,9 @@ export async function openMemoryBackend(repoRoot, backendChoice) {
701
903
  /** openMemoryBackend for a caller that only wants to READ what a repo already
702
904
  * holds: null when the repo has no store yet, because opening one creates it.
703
905
  * The cold surfaces (the `cli` tool route) answer over a repo they were merely
704
- * pointed at, and must leave a repo with no memory exactly as they found it. */
906
+ * pointed at, and must leave a repo with no memory exactly as they found it.
907
+ * String tokens only — an injected row backend has no repo store to probe for,
908
+ * so a caller holding one calls openMemoryBackend directly. */
705
909
  export async function openExistingMemoryBackend(repoRoot, backendChoice = "") {
706
910
  if (!repoRoot || typeof repoRoot !== "string") return null;
707
911
  const dbPath = join(repoRoot, ".tmct", "memory", "graph.sqlite");
@@ -724,7 +928,9 @@ export async function readOnlyMemorySnapshot(memoryDir) {
724
928
  /** openMemoryBackend for an entry point that holds only a repo path and has no
725
929
  * CLI-flag tier (the fold's idle pass, `tmct import --file`): resolve the
726
930
  * backend token the way the chat path does minus the flag —
727
- * TMCT_MEMORY_BACKEND env > tmct.toml's [memory] backend > the default. */
931
+ * TMCT_MEMORY_BACKEND env > tmct.toml's [memory] backend > the default. Config
932
+ * can only name a string backend, so an injected row backend never arrives
933
+ * here; a caller holding one calls openMemoryBackend directly. */
728
934
  export async function openConfiguredMemoryBackend(repoRoot, env = process.env) {
729
935
  let backend = String(env?.TMCT_MEMORY_BACKEND || "").trim().toLowerCase();
730
936
  if (!backend) {
@@ -1049,7 +1255,7 @@ const resolveManifestFile = (dir) => join(dir, MEMORY_MANIFEST_REL);
1049
1255
  * `opts.retentionVersions`. Returns `{ skipped, version, prunedVersion }`. */
1050
1256
  export async function snapshotMemory(dir, { retentionVersions } = {}) {
1051
1257
  if (isMemoryOrSqliteHandle(dir)) {
1052
- throw new Error("snapshotMemory only supports the flat-JSON backend (Backend A) — a memory/sqlite handle has no on-disk graph.json to snapshot");
1258
+ throw new Error("snapshotMemory only supports the flat-JSON backend (Backend A) — a store handle has no on-disk graph.json to snapshot");
1053
1259
  }
1054
1260
  const graphFile = resolveMemoryGraphFile(dir);
1055
1261
  let graphText;
@@ -1093,7 +1299,7 @@ export async function snapshotMemory(dir, { retentionVersions } = {}) {
1093
1299
  return { skipped: false, version: v, prunedVersion };
1094
1300
  }
1095
1301
 
1096
- /** Load the memory graph for a repo dir OR a Backend B/C handle (see the
1302
+ /** Load the memory graph for a repo dir OR a Backend B/C/D handle (see the
1097
1303
  * storage-backend seam above `createInMemoryStore`). A missing Backend-A
1098
1304
  * store is the bootstrap: return the empty payload (uncached — the first
1099
1305
  * append creates the file). The result is a raw entities payload;
@@ -1101,6 +1307,7 @@ export async function snapshotMemory(dir, { retentionVersions } = {}) {
1101
1307
  export async function loadMemory(dir) {
1102
1308
  if (isMemoryHandle(dir)) return migrateStoredMemory(dir.payload);
1103
1309
  if (isSqliteHandle(dir)) return migrateStoredMemory(readSqlitePayload(dir));
1310
+ if (isRowHandle(dir)) return migrateStoredMemory(await readRowPayload(dir));
1104
1311
  let text;
1105
1312
  try {
1106
1313
  text = await readFile(memoryGraphFile(dir), "utf8");
@@ -1299,11 +1506,13 @@ function migrateFactAssertionKeys(payload) {
1299
1506
  }
1300
1507
 
1301
1508
  /** Persist a mutated payload back to `dir`: an atomic file write (Backend A),
1302
- * a no-op assignment (Backend B, already the live object), or a diffed
1303
- * per-row SQL write (Backend C, persistSqlitePayload). */
1509
+ * a no-op assignment (Backend B, already the live object), a diffed per-row
1510
+ * SQL write (Backend C, persistSqlitePayload), or a diffed row write into an
1511
+ * injected store (Backend D, persistRowPayload). */
1304
1512
  async function persistMemory(dir, payload) {
1305
1513
  if (isMemoryHandle(dir)) { dir.payload = payload; return; }
1306
1514
  if (isSqliteHandle(dir)) { persistSqlitePayload(dir, payload); return; }
1515
+ if (isRowHandle(dir)) { await persistRowPayload(dir, payload); return; }
1307
1516
  await mkdir(dirname(memoryGraphFile(dir)), { recursive: true });
1308
1517
  await atomicWriteJson(memoryGraphFile(dir), payload);
1309
1518
  }
@@ -1316,7 +1525,7 @@ async function persistMemory(dir, payload) {
1316
1525
  export const SYLLOGISE_STATE_REL = join(MEMORY_DIR_REL, "syllogise-state.json");
1317
1526
  const SQLITE_SYLLOGISE_STATE_KEY = "syllogiseState";
1318
1527
 
1319
- /** Load the syllogise watermark for a repo dir OR a Backend B/C handle.
1528
+ /** Load the syllogise watermark for a repo dir OR a Backend B/C/D handle.
1320
1529
  * Null when no complete pass has recorded one. */
1321
1530
  export async function loadSyllogiseState(dir) {
1322
1531
  if (isMemoryHandle(dir)) return dir.syllogiseState ? structuredClone(dir.syllogiseState) : null;
@@ -1324,6 +1533,7 @@ export async function loadSyllogiseState(dir) {
1324
1533
  const row = dir.db.prepare("SELECT v FROM meta WHERE k = ?").get(SQLITE_SYLLOGISE_STATE_KEY);
1325
1534
  return row?.v ? JSON.parse(row.v) : null;
1326
1535
  }
1536
+ if (isRowHandle(dir)) return readRowMeta(dir, ROW_SYLLOGISE_STATE_KEY, null);
1327
1537
  try {
1328
1538
  return JSON.parse(await readFile(join(dir, SYLLOGISE_STATE_REL), "utf8"));
1329
1539
  } catch (e) {
@@ -1333,13 +1543,17 @@ export async function loadSyllogiseState(dir) {
1333
1543
  }
1334
1544
 
1335
1545
  /** Persist the syllogise watermark — atomic file write (Backend A), a cloned
1336
- * handle field (Backend B), or a meta-table row (Backend C). */
1546
+ * handle field (Backend B), a meta-table row (Backend C), or a meta value in
1547
+ * the injected store (Backend D). A watermark is one scalar whose worst race
1548
+ * costs a redundant re-syllogise, which is why it travels as meta rather than
1549
+ * as rows. */
1337
1550
  export async function saveSyllogiseState(dir, state) {
1338
1551
  if (isMemoryHandle(dir)) { dir.syllogiseState = structuredClone(state); return; }
1339
1552
  if (isSqliteHandle(dir)) {
1340
1553
  dir.db.prepare("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)").run(SQLITE_SYLLOGISE_STATE_KEY, JSON.stringify(state));
1341
1554
  return;
1342
1555
  }
1556
+ if (isRowHandle(dir)) { await dir.impl.putMeta(ROW_SYLLOGISE_STATE_KEY, JSON.stringify(state)); return; }
1343
1557
  const file = join(dir, SYLLOGISE_STATE_REL);
1344
1558
  await mkdir(dirname(file), { recursive: true });
1345
1559
  await atomicWriteJson(file, state);
@@ -1361,6 +1575,7 @@ export async function loadNodeId(dir) {
1361
1575
  const row = dir.db.prepare("SELECT v FROM meta WHERE k = ?").get(SQLITE_NODE_ID_KEY);
1362
1576
  return row?.v ? JSON.parse(row.v).nodeId || null : null;
1363
1577
  }
1578
+ if (isRowHandle(dir)) return (await readRowMeta(dir, ROW_NODE_ID_KEY, null))?.nodeId || null;
1364
1579
  try {
1365
1580
  return JSON.parse(await readFile(join(dir, NODE_ID_REL), "utf8")).nodeId || null;
1366
1581
  } catch (e) {
@@ -1370,14 +1585,16 @@ export async function loadNodeId(dir) {
1370
1585
  }
1371
1586
 
1372
1587
  /** Record this store's node id — atomic file write (Backend A), a handle field
1373
- * (Backend B), or a meta-table row (Backend C). Callers mint through
1374
- * resolveStoreNodeId, which never overwrites an id a store already holds. */
1588
+ * (Backend B), a meta-table row (Backend C), or a meta value in the injected
1589
+ * store (Backend D). Callers mint through resolveStoreNodeId, which never
1590
+ * overwrites an id a store already holds, so this value is written once. */
1375
1591
  export async function saveNodeId(dir, nodeId) {
1376
1592
  if (isMemoryHandle(dir)) { dir.nodeId = nodeId; return; }
1377
1593
  if (isSqliteHandle(dir)) {
1378
1594
  dir.db.prepare("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)").run(SQLITE_NODE_ID_KEY, JSON.stringify({ nodeId }));
1379
1595
  return;
1380
1596
  }
1597
+ if (isRowHandle(dir)) { await dir.impl.putMeta(ROW_NODE_ID_KEY, JSON.stringify({ nodeId })); return; }
1381
1598
  const file = join(dir, NODE_ID_REL);
1382
1599
  await mkdir(dirname(file), { recursive: true });
1383
1600
  await atomicWriteJson(file, { nodeId });
@@ -2063,6 +2280,20 @@ function nextChainVersion(head) {
2063
2280
  return deepest + 1;
2064
2281
  }
2065
2282
 
2283
+ /** A write's extraction findings, deduped and codepoint-sorted. The sort is
2284
+ * what keeps the stored string a pure function of the finding SET: two stores
2285
+ * handed the same findings in different orders hold byte-identical records,
2286
+ * and the read-time union below reads the same either way. */
2287
+ function normalizeExtractionFindings(extraction) {
2288
+ if (!Array.isArray(extraction)) return [];
2289
+ const names = new Set();
2290
+ for (const raw of extraction) {
2291
+ const name = normText(raw);
2292
+ if (name) names.add(name);
2293
+ }
2294
+ return [...names].sort();
2295
+ }
2296
+
2066
2297
  /**
2067
2298
  * Plan ONE source's assertion of one triple: the record it wants to write, plus
2068
2299
  * the demotion that implies when the source is replacing its own earlier belief.
@@ -2078,7 +2309,7 @@ function nextChainVersion(head) {
2078
2309
  * which is what keeps a re-seed and a duplicate mesh path idempotent.
2079
2310
  */
2080
2311
  function planFactAssertion(payload, spec) {
2081
- const { groupId, s, p, o, label, tokens, group, createdAt, observedAt, quantifier, environments } = spec;
2312
+ const { groupId, s, p, o, label, tokens, group, createdAt, observedAt, quantifier, environments, extraction = [] } = spec;
2082
2313
  const recordId = `${groupId}@${group.sourceId}`;
2083
2314
  const idx = memoryIndexOf(payload);
2084
2315
  const head = idx ? idx.individualsById.get(recordId) : payload.individuals.find((x) => x?.id === recordId);
@@ -2092,17 +2323,24 @@ function planFactAssertion(payload, spec) {
2092
2323
  let observedAtVal = observedAt;
2093
2324
  let supersedes = [];
2094
2325
  let quantifierVal = quantifier;
2326
+ let extractionVal = extraction;
2095
2327
 
2096
2328
  if (head) {
2097
2329
  const current = { assertedAt: embeddedTagTimestamp(headTags), observedAt: headAttr(OBSERVED_AT_PROP) };
2098
2330
  if (supersedesPriorAssertion(incoming, current)) {
2099
2331
  demote = { head, id: `${recordId}#v${nextChainVersion(head)}` };
2100
2332
  supersedes = [demote.id];
2333
+ // A fresh belief is read fresh: the new head carries only the findings
2334
+ // this write recorded, and the demoted leaf keeps its own.
2101
2335
  } else {
2102
2336
  tags = [...new Set([...headTags, ...group.tags])];
2103
2337
  createdAtVal = headAttr(CREATED_AT_PROP) || createdAtVal;
2104
2338
  observedAtVal = observedAt || headAttr(OBSERVED_AT_PROP);
2105
2339
  supersedes = headAttr(SUPERSEDES_PROP).split(" ").filter(Boolean);
2340
+ // The same source saying the same thing again unions its findings on,
2341
+ // exactly as its tags union: a re-delivery never erases how the first
2342
+ // reading of this assertion went.
2343
+ extractionVal = normalizeExtractionFindings([...headAttr(EXTRACTION_FINDING_PROP).split(" "), ...extraction]);
2106
2344
  }
2107
2345
  // A re-assert carrying no quantifier never SILENTLY erases one already
2108
2346
  // recorded — the same first-write-wins discipline createdAt keeps.
@@ -2121,6 +2359,7 @@ function planFactAssertion(payload, spec) {
2121
2359
  { prop: SOURCE_ID_PROP, key: "sourceId", value: group.sourceId },
2122
2360
  ...(tags.length ? [{ prop: "mgx:factProvenance", key: "provenance", value: tags.join(" | ") }] : []),
2123
2361
  ...(observedAtVal ? [{ prop: OBSERVED_AT_PROP, key: "observedAt", value: observedAtVal }] : []),
2362
+ ...(extractionVal.length ? [{ prop: EXTRACTION_FINDING_PROP, key: "extraction", value: extractionVal.join(" ") }] : []),
2124
2363
  ...(tokens.length ? [{ prop: "mgx:hasProseTokens", key: "prose_tokens", value: tokens.join(" ") }] : []),
2125
2364
  ...(quantifierVal ? [{ prop: "mgx:factQuantifier", key: "quantifier", value: quantifierVal }] : []),
2126
2365
  ...(environments ? [{ prop: "mgx:factJustification", key: "justification", value: environments.map((e) => e.join(" ")).join(" | ") }] : []),
@@ -2309,9 +2548,12 @@ function compactFactGroup(payload, groupId) {
2309
2548
  * source's own lineage, never a duplicate. `premiseTrusts`/`ruleConfidence`
2310
2549
  * optionally engage trust.mjs's entailed hook; `observedAt` records when the
2311
2550
  * asserting party WITNESSED the claim, which is not when this store heard it.
2312
- * Validated against ontology/memory-shapes.ttl (memory/shacl.mjs) before the
2313
- * write. Returns { id } — the group id, the public fact id every reader uses. */
2314
- export async function appendFact(dir, { subject, predicate, object, provenance = "", createdAt = "", observedAt = "", quantifier = "", premiseTrusts, ruleConfidence } = {}) {
2551
+ * `extraction` is the closed-vocabulary finding list saying how the extractor
2552
+ * read the sentence this assertion came from, recorded on the record rather
2553
+ * than the triple. Validated against ontology/memory-shapes.ttl
2554
+ * (memory/shacl.mjs) before the write. Returns { id } — the group id, the
2555
+ * public fact id every reader uses. */
2556
+ export async function appendFact(dir, { subject, predicate, object, provenance = "", createdAt = "", observedAt = "", quantifier = "", extraction, premiseTrusts, ruleConfidence } = {}) {
2315
2557
  const s = normFactTerm(subject);
2316
2558
  const p = normFactPredicate(predicate);
2317
2559
  const o = normFactTerm(object);
@@ -2320,6 +2562,7 @@ export async function appendFact(dir, { subject, predicate, object, provenance =
2320
2562
  const text = `${s} ${p} ${o}`;
2321
2563
  const tokens = proseTokensFor({ doc: text });
2322
2564
  const q = normText(quantifier);
2565
+ const findings = normalizeExtractionFindings(extraction);
2323
2566
  await mutateMemory(dir, async (payload) => {
2324
2567
  const groups = assertionGroupsFor(payload, groupId, normText(provenance), createdAt);
2325
2568
  for (const id of groups.length ? [] : restateFactGroup(payload, groupId, { quantifier: q })) {
@@ -2328,6 +2571,7 @@ export async function appendFact(dir, { subject, predicate, object, provenance =
2328
2571
  for (const group of groups) {
2329
2572
  const plan = planFactAssertion(payload, {
2330
2573
  groupId, s, p, o, label: labelOf(text), tokens, group, createdAt, observedAt, quantifier: q,
2574
+ extraction: findings,
2331
2575
  });
2332
2576
  await assertIndividualValid(plan.candidate); // the SHACL gate -- throws, never writes, on a violation
2333
2577
  for (const id of applyFactAssertion(payload, plan)) {
@@ -2375,8 +2619,9 @@ function normalizeJustificationEnvironments(justification) {
2375
2619
  * not thrown. Optional per-fact `premiseTrusts`/`ruleConfidence` (batched
2376
2620
  * entailed-hook passthrough) and `justification` (premise fact ids — a flat
2377
2621
  * list, or a list of lists for multiple independent derivations — stored as
2378
- * mgx:factJustification's ' | '-separated environments, last-write-wins).
2379
- * Returns { ids, appended, skipped }. */
2622
+ * mgx:factJustification's ' | '-separated environments, last-write-wins), and
2623
+ * optional per-fact `extraction` (appendFact's finding list, same per-assertion
2624
+ * scoping). Returns { ids, appended, skipped }. */
2380
2625
  export async function appendFacts(dir, facts) {
2381
2626
  const prepared = [];
2382
2627
  let skipped = 0;
@@ -2394,6 +2639,7 @@ export async function appendFacts(dir, facts) {
2394
2639
  createdAt: f?.createdAt || "",
2395
2640
  observedAt: f?.observedAt || "",
2396
2641
  quantifier: normText(f?.quantifier),
2642
+ extraction: normalizeExtractionFindings(f?.extraction),
2397
2643
  premiseTrusts: Array.isArray(f?.premiseTrusts) ? f.premiseTrusts : undefined,
2398
2644
  ruleConfidence: typeof f?.ruleConfidence === "number" ? f.ruleConfidence : undefined,
2399
2645
  environments: normalizeJustificationEnvironments(f?.justification),
@@ -2419,7 +2665,7 @@ export async function appendFacts(dir, facts) {
2419
2665
  const plan = planFactAssertion(payload, {
2420
2666
  groupId: f.id, s: f.s, p: f.p, o: f.o, label: labelOf(f.text), tokens: f.tokens,
2421
2667
  group, createdAt: f.createdAt, observedAt: f.observedAt, quantifier: f.quantifier,
2422
- environments: f.environments,
2668
+ environments: f.environments, extraction: f.extraction,
2423
2669
  });
2424
2670
  for (const id of applyFactAssertion(payload, plan)) {
2425
2671
  if (seen.has(id)) continue;
@@ -2848,6 +3094,11 @@ export async function resolveRelationChaseReverse(memory, name, objectTerm, help
2848
3094
  * the per-record hop list, for a reader that wants to see WHICH source said it
2849
3095
  * and when rather than one blended number.
2850
3096
  *
3097
+ * `extraction` joins both levels when any assertion recorded a finding: the
3098
+ * row's union for a consumer deciding whether to lean on the triple at all,
3099
+ * each hop's own list for one that needs to know which reading produced it.
3100
+ * Absent — never empty — when nothing was recorded.
3101
+ *
2851
3102
  * The fold reads live HEADS only. A record its own source has since superseded
2852
3103
  * is that source's PAST belief, not a second vote for the present one; folding
2853
3104
  * it back in would let one source's edit history inflate its own corroboration.
@@ -2961,6 +3212,7 @@ function foldFactGroup(id, heads, ctx) {
2961
3212
  const sourceIds = [];
2962
3213
  const sourceTypes = [];
2963
3214
  const tags = new Set();
3215
+ const findings = new Set();
2964
3216
  const environments = [];
2965
3217
  const seenEnvironment = new Set();
2966
3218
  let quantifier = "";
@@ -3008,11 +3260,14 @@ function foldFactGroup(id, heads, ctx) {
3008
3260
  }
3009
3261
  const createdAt = attrOf(head, CREATED_AT_PROP);
3010
3262
  const observedAt = attrOf(head, OBSERVED_AT_PROP);
3263
+ const extraction = attrOf(head, EXTRACTION_FINDING_PROP).split(" ").filter(Boolean);
3264
+ for (const finding of extraction) findings.add(finding);
3011
3265
  assertions.push({
3012
3266
  id: head.id, sourceId, sourceType,
3013
3267
  provenance: headTags.join(" | "),
3014
3268
  createdAt,
3015
3269
  ...(observedAt ? { observedAt } : {}),
3270
+ ...(extraction.length ? { extraction } : {}),
3016
3271
  ownTrust: Number(attrOf(head, TRUST_SCORE_PROP)) || 0,
3017
3272
  assertedAt: assertionTimestampFor(headTags, createdAt),
3018
3273
  });
@@ -3045,6 +3300,12 @@ function foldFactGroup(id, heads, ctx) {
3045
3300
  provenance: [...tags].sort().join(" | "),
3046
3301
  quantifier, // "" unless a plural class-membership teach set one
3047
3302
  sourceIds, sourceTypes,
3303
+ // Every finding any live assertion of this triple carries, unioned the same
3304
+ // way the provenance tags above are, and ABSENT when there are none. A
3305
+ // consumer that needs to know which source read it that way reads the
3306
+ // per-assertion `extraction` in the hop list instead. Absence means no
3307
+ // findings were recorded — never that the sentence read cleanly.
3308
+ ...(findings.size ? { extraction: [...findings].sort() } : {}),
3048
3309
  // `environments`: every persisted premise set (empty unless entailed);
3049
3310
  // `justification`: their deduped union in first-occurrence order, for
3050
3311
  // readers that only need "which premises does this fact cite at all".