@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.1
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/README.md +27 -0
- package/bin/tmct.mjs +61 -0
- package/package.json +14 -2
- package/src/adapters/memory/backends-exports.mjs +8 -0
- package/src/adapters/memory/core.mjs +812 -175
- package/src/adapters/memory/corpus-bands.mjs +155 -0
- package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
- package/src/adapters/memory/row-backend-dynamo.mjs +315 -0
- package/src/adapters/memory/row-backend-memory.mjs +85 -0
- package/src/adapters/memory/row-backend.mjs +162 -0
- package/src/adapters/memory/rows.mjs +328 -0
- package/src/adapters/memory/shacl.mjs +24 -0
- package/src/adapters/memory/systemic-failure.mjs +28 -0
- package/src/adapters/research-queue-store.mjs +215 -32
- package/src/domain/ask.mjs +341 -75
- package/src/domain/cli-verbs.mjs +17 -0
- package/src/domain/fact-phrase.mjs +40 -0
- package/src/domain/news-feed.mjs +42 -4
- package/src/domain/phrase-exports.mjs +4 -0
- package/src/domain/retrieval-marker.mjs +120 -0
- package/src/domain/retrieval-modes.mjs +13 -0
- package/src/domain/retrieval-plan.mjs +224 -0
- package/src/services/chat-session.mjs +36 -9
- package/src/services/chat.mjs +73 -16
- package/src/services/corpus-loader.mjs +222 -0
- package/src/services/extract-facts.mjs +244 -33
- package/src/services/init.mjs +15 -5
- package/src/services/news.mjs +4 -2
- package/src/services/subgraph-retrieval.mjs +332 -0
- package/src/surfaces/web/http-row-backend.mjs +150 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +134 -131
- package/src/surfaces/web/news-browser-entry.mjs +6 -2
- package/src/tools/handlers/tmct-ingest.mjs +3 -1
- package/src/tools/memory-backend-conformance.mjs +238 -0
|
@@ -52,6 +52,23 @@ 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 {
|
|
56
|
+
BackendRejected, BackendUnavailable, isRowBackend, rowBackendProblems, assertValidRow,
|
|
57
|
+
BOOKKEEPING_ROW_CLASS, ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION,
|
|
58
|
+
} from "./row-backend.mjs";
|
|
59
|
+
// The row-backend contract lives in its own module (a consumer imports it
|
|
60
|
+
// without loading the engine); re-exported here so store consumers keep one
|
|
61
|
+
// import site, the same way the trust and retraction vocabularies are.
|
|
62
|
+
export {
|
|
63
|
+
BackendRejected, BackendUnavailable, isRowBackend, rowBackendProblems,
|
|
64
|
+
isValidRow, rowProblems, assertValidRow,
|
|
65
|
+
ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION, ROW_CLASSES, MAX_ROW_BYTES,
|
|
66
|
+
} from "./row-backend.mjs";
|
|
67
|
+
// rows.mjs imports this module back for the class constants. The cycle is
|
|
68
|
+
// fine as long as neither side READS an imported binding while the other's
|
|
69
|
+
// body is still running — rows.mjs builds its class map on first use, and
|
|
70
|
+
// every use here is inside a function.
|
|
71
|
+
import { payloadToRows, rowsToPayload, diffRows } from "./rows.mjs";
|
|
55
72
|
|
|
56
73
|
// The rollup vocabulary and its tuning constants live with the compaction
|
|
57
74
|
// layer; re-exported here so store consumers keep one import site.
|
|
@@ -122,6 +139,7 @@ const MEMORY_VOCABULARY = [
|
|
|
122
139
|
{ 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
140
|
{ 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
141
|
{ 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" },
|
|
142
|
+
{ 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
143
|
{ 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
144
|
{ 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
145
|
{ 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 +193,8 @@ export function emptyMemory() {
|
|
|
175
193
|
* (default) is the live graph; a numeric version resolves a snapshot copy
|
|
176
194
|
* (see snapshotMemory below). The single source of truth for this path. */
|
|
177
195
|
export function resolveMemoryGraphFile(dir, version = null) {
|
|
178
|
-
if (
|
|
179
|
-
throw new Error("resolveMemoryGraphFile: dir is a
|
|
196
|
+
if (isMemoryOrSqliteHandle(dir)) {
|
|
197
|
+
throw new Error("resolveMemoryGraphFile: dir is a store handle, not a file path (Backend A only)");
|
|
180
198
|
}
|
|
181
199
|
if (version === null) return join(dir, MEMORY_GRAPH_REL);
|
|
182
200
|
return join(dir, MEMORY_DIR_REL, `graph.v${version}.json`);
|
|
@@ -186,12 +204,14 @@ const memoryGraphFile = (dir) => resolveMemoryGraphFile(dir);
|
|
|
186
204
|
|
|
187
205
|
// ---- Storage-backend seam --------------------------------------------------
|
|
188
206
|
// `dir` is either a plain repo-path string (Backend A, file-backed) or a
|
|
189
|
-
// handle from createInMemoryStore() (Backend B)
|
|
190
|
-
// (Backend C)
|
|
207
|
+
// handle from createInMemoryStore() (Backend B), createSqliteMemoryStore()
|
|
208
|
+
// (Backend C), or wrapRowBackend() over a consumer's own row store
|
|
209
|
+
// (Backend D). Only loadMemory/mutateMemory dispatch on backend; every other
|
|
191
210
|
// function operates on the plain payload object they hand back.
|
|
192
211
|
|
|
193
212
|
const BACKEND_MEMORY = "memory";
|
|
194
213
|
const BACKEND_SQLITE = "sqlite";
|
|
214
|
+
const BACKEND_ROW = "row";
|
|
195
215
|
|
|
196
216
|
function isMemoryHandle(dir) {
|
|
197
217
|
return !!dir && typeof dir === "object" && dir.backend === BACKEND_MEMORY;
|
|
@@ -199,14 +219,20 @@ function isMemoryHandle(dir) {
|
|
|
199
219
|
function isSqliteHandle(dir) {
|
|
200
220
|
return !!dir && typeof dir === "object" && dir.backend === BACKEND_SQLITE;
|
|
201
221
|
}
|
|
202
|
-
/** True for a Backend
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
222
|
+
/** True for a Backend D handle — the wrapper wrapRowBackend puts around a
|
|
223
|
+
* consumer's injected row store. A row store has no path and no connection of
|
|
224
|
+
* tmct's own, so callers that reach for either have to branch on this. */
|
|
225
|
+
export function isRowHandle(dir) {
|
|
226
|
+
return !!dir && typeof dir === "object" && dir.backend === BACKEND_ROW;
|
|
227
|
+
}
|
|
228
|
+
/** True for any store handle — Backend B, C or D — that is NOT a plain
|
|
229
|
+
* repo-path string. Exported so every OTHER module that takes a `dir` and
|
|
230
|
+
* might reach a raw `node:path`/`node:fs` call (blocks.mjs's session-block
|
|
231
|
+
* index chief among them) can guard the same way this module already does,
|
|
232
|
+
* instead of a bare `join(dir, …)` throwing Node's generic "path argument
|
|
233
|
+
* must be of type string" at a caller with no idea why. */
|
|
208
234
|
export function isMemoryOrSqliteHandle(dir) {
|
|
209
|
-
return isMemoryHandle(dir) || isSqliteHandle(dir);
|
|
235
|
+
return isMemoryHandle(dir) || isSqliteHandle(dir) || isRowHandle(dir);
|
|
210
236
|
}
|
|
211
237
|
|
|
212
238
|
/** Backend B — pure in-memory store: `{ backend: "memory", payload }` held by
|
|
@@ -302,6 +328,13 @@ const SOURCE_ID_PROP = "mgx:sourceId"; // the assertion key this record
|
|
|
302
328
|
const SUPERSEDES_PROP = "mgx:supersedes"; // the id(s) this record replaced; absent until the first supersession
|
|
303
329
|
const SUPERSEDED_BY_PROP = "mgx:supersededBy"; // the id(s) that replaced this record; absent on a live head
|
|
304
330
|
|
|
331
|
+
/** How the extractor read the sentence one assertion came from — a space-joined
|
|
332
|
+
* list from the closed EXTRACTION_FINDINGS vocabulary, absent when the write
|
|
333
|
+
* recorded none. It sits on the assertion record rather than the triple, so a
|
|
334
|
+
* second source stating the same thing cleanly inherits no caveat. */
|
|
335
|
+
export const EXTRACTION_FINDING_PROP = "mgx:extractionFinding";
|
|
336
|
+
export { EXTRACTION_FINDINGS } from "./shacl.mjs";
|
|
337
|
+
|
|
305
338
|
/** The Source key a Fact's provenance union projects onto: the first tag that
|
|
306
339
|
* derives one, since the tags of one fact are asserted in arrival order and
|
|
307
340
|
* the earliest is its primary source. `src:none` when no tag parses. */
|
|
@@ -654,9 +687,10 @@ function installSqliteWarningFilter() {
|
|
|
654
687
|
}
|
|
655
688
|
|
|
656
689
|
/** Open (creating if absent) a resident node:sqlite connection: a Backend C
|
|
657
|
-
* handle `{ backend: "sqlite", db, dbPath }
|
|
658
|
-
*
|
|
659
|
-
* once per session; close via
|
|
690
|
+
* handle `{ backend: "sqlite", db, dbPath }`, carrying the row-backend methods
|
|
691
|
+
* over its own tables. `node:sqlite` is imported lazily — only opting into
|
|
692
|
+
* this backend ever loads it. Meant to be opened once per session; close via
|
|
693
|
+
* closeSqliteMemoryStore at session end. */
|
|
660
694
|
export async function createSqliteMemoryStore(dbPath) {
|
|
661
695
|
installSqliteWarningFilter();
|
|
662
696
|
const { DatabaseSync } = await import("node:sqlite");
|
|
@@ -665,26 +699,198 @@ export async function createSqliteMemoryStore(dbPath) {
|
|
|
665
699
|
db.exec("PRAGMA synchronous = NORMAL");
|
|
666
700
|
db.exec(SQLITE_DDL);
|
|
667
701
|
backfillFactsProjection(db);
|
|
668
|
-
const handle = { backend: BACKEND_SQLITE, db, dbPath };
|
|
702
|
+
const handle = attachSqliteRowMethods({ backend: BACKEND_SQLITE, db, dbPath });
|
|
669
703
|
backfillFactHeads(handle);
|
|
670
704
|
return handle;
|
|
671
705
|
}
|
|
672
706
|
|
|
673
707
|
/** Close a Backend C handle's connection. A no-op for anything else (so a
|
|
674
708
|
* caller that doesn't know which backend it has can call this unconditionally
|
|
675
|
-
* at session end).
|
|
709
|
+
* at session end). A Backend D handle is closed through its own `impl.close()`
|
|
710
|
+
* instead — openMemoryBackend's returned `close` is the call site. */
|
|
676
711
|
export function closeSqliteMemoryStore(handle) {
|
|
677
712
|
if (isSqliteHandle(handle)) handle.db.close();
|
|
678
713
|
}
|
|
679
714
|
|
|
715
|
+
// ---- Backend D — a consumer's own row store ------------------------------
|
|
716
|
+
// The consumer constructs the store (row-backend.mjs is the contract) and
|
|
717
|
+
// tmct binds it into the same `memoryDir` token every memory call threads.
|
|
718
|
+
// The payload this handle hands back is `basePayload` overlaid with the rows
|
|
719
|
+
// the store holds; the payload it writes back is the DELTA against what it
|
|
720
|
+
// last assembled, so a turn pays for what it changed and nothing else.
|
|
721
|
+
//
|
|
722
|
+
// `basePayload` is a read-only overlay for a bundled seed graph. Its rows are
|
|
723
|
+
// assembled into every read and are excluded from every write, so a session
|
|
724
|
+
// over a 60k-fact seed still stores only the handful of facts that session
|
|
725
|
+
// taught.
|
|
726
|
+
//
|
|
727
|
+
// No cross-writer cache guard exists here, unlike Backend C's PRAGMA
|
|
728
|
+
// data_version check: a second writer's rows appear at this handle's next cold
|
|
729
|
+
// open, and the derived state recomputes then. A consumer that needs to see
|
|
730
|
+
// another writer's rows immediately constructs a fresh handle per request,
|
|
731
|
+
// which is what the serverless pattern does anyway.
|
|
732
|
+
|
|
733
|
+
const ROW_META_MEMORY_KEY = "memory";
|
|
734
|
+
const ROW_META_PREFIXES_KEY = "prefixes";
|
|
735
|
+
const ROW_SYLLOGISE_STATE_KEY = "syllogiseState";
|
|
736
|
+
const ROW_NODE_ID_KEY = "nodeId";
|
|
737
|
+
|
|
738
|
+
/** Bind a row backend as a `memoryDir` token: `{ backend: "row", impl,
|
|
739
|
+
* cachedPayload, basePayload }`. `basePayload` is the read-only seed overlay;
|
|
740
|
+
* `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 } = {}) {
|
|
743
|
+
const problems = rowBackendProblems(impl);
|
|
744
|
+
if (problems.length) {
|
|
745
|
+
throw new BackendRejected(`not a memory row backend: ${problems.join("; ")}`);
|
|
746
|
+
}
|
|
747
|
+
return {
|
|
748
|
+
backend: BACKEND_ROW,
|
|
749
|
+
impl,
|
|
750
|
+
cachedPayload: null,
|
|
751
|
+
basePayload: cloneMemoryPayload(basePayload),
|
|
752
|
+
baseRows: null,
|
|
753
|
+
storedRows: null,
|
|
754
|
+
onOversizedRow,
|
|
755
|
+
log,
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** Drain whatever `readRows()` returned: the contract allows an array or an
|
|
760
|
+
* async iterable, so a paginating backend can stream its pages. */
|
|
761
|
+
async function collectRows(source) {
|
|
762
|
+
const value = await source;
|
|
763
|
+
if (Array.isArray(value)) return value;
|
|
764
|
+
const rows = [];
|
|
765
|
+
for await (const row of value) rows.push(row);
|
|
766
|
+
return rows;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** The seed rows under the session's own, keyed so a session row with a base
|
|
770
|
+
* row's key wins. */
|
|
771
|
+
function overlayRows(baseRows, sessionRows) {
|
|
772
|
+
const byKey = new Map();
|
|
773
|
+
for (const row of baseRows) byKey.set(row.rowKey, row);
|
|
774
|
+
for (const row of sessionRows) byKey.set(row.rowKey, row);
|
|
775
|
+
return [...byKey.values()];
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/** The seed keys this handle must never write or delete: every base row the
|
|
779
|
+
* session store does not already hold a row for. */
|
|
780
|
+
function seedOnlyKeys(handle) {
|
|
781
|
+
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)));
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
async function readRowMeta(handle, key, fallback) {
|
|
786
|
+
const raw = await handle.impl.readMeta(key);
|
|
787
|
+
if (raw === null || raw === undefined) return fallback;
|
|
788
|
+
try { return JSON.parse(raw); } catch { return fallback; }
|
|
789
|
+
}
|
|
790
|
+
|
|
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) {
|
|
796
|
+
if (!handle.cachedPayload) {
|
|
797
|
+
const empty = emptyMemory();
|
|
798
|
+
const stored = await collectRows(handle.impl.readRows());
|
|
799
|
+
handle.baseRows = payloadToRows(handle.basePayload || empty);
|
|
800
|
+
handle.storedRows = stored.filter((row) => row?.rowClass !== BOOKKEEPING_ROW_CLASS);
|
|
801
|
+
handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
|
|
802
|
+
meta: {
|
|
803
|
+
memory: await readRowMeta(handle, ROW_META_MEMORY_KEY, handle.basePayload?.memory ?? empty.memory),
|
|
804
|
+
prefixes: await readRowMeta(handle, ROW_META_PREFIXES_KEY, handle.basePayload?.prefixes ?? empty.prefixes),
|
|
805
|
+
},
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
return cloneJson(handle.cachedPayload);
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** A record with its audit stamp removed. `mgx:updatedAt` moves on every
|
|
812
|
+
* individual a trust recompute touches, which is every fact in the store on
|
|
813
|
+
* every mutate, so comparing raw bytes calls every row changed. */
|
|
814
|
+
function recordWithoutAuditStamp(json) {
|
|
815
|
+
let record;
|
|
816
|
+
try { record = JSON.parse(json); } catch { return json; }
|
|
817
|
+
const ind = record?.individual;
|
|
818
|
+
if (!Array.isArray(ind?.attributes)) return json;
|
|
819
|
+
return JSON.stringify({
|
|
820
|
+
...record,
|
|
821
|
+
individual: { ...ind, attributes: ind.attributes.filter((a) => a?.prop !== UPDATED_AT_PROP) },
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/** A row worth a write: something about it changed beyond the audit stamp. A
|
|
826
|
+
* row whose only difference is that stamp says nothing new, and writing it
|
|
827
|
+
* would let a handle with a stale read overwrite a concurrent writer's real
|
|
828
|
+
* change with its own no-op. */
|
|
829
|
+
function movedBeyondAuditStamp(beforeRow, row) {
|
|
830
|
+
if (!beforeRow) return true;
|
|
831
|
+
return recordWithoutAuditStamp(beforeRow.json) !== recordWithoutAuditStamp(row.json);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** persistMemory's write for Backend D: project the mutated payload, diff it
|
|
835
|
+
* against what this handle last assembled, and write only the delta. A failed
|
|
836
|
+
* write drops the cache so the next read rebuilds from the store rather than
|
|
837
|
+
* from a payload that never landed. */
|
|
838
|
+
async function persistRowPayload(handle, payload) {
|
|
839
|
+
await readRowPayload(handle);
|
|
840
|
+
const before = overlayRows(handle.baseRows, handle.storedRows);
|
|
841
|
+
const beforeByKey = new Map(before.map((row) => [row.rowKey, row]));
|
|
842
|
+
const after = payloadToRows(payload, {
|
|
843
|
+
priorRows: before,
|
|
844
|
+
onOversizedRow: handle.onOversizedRow,
|
|
845
|
+
...(handle.log ? { log: handle.log } : {}),
|
|
846
|
+
});
|
|
847
|
+
const { puts, deletes } = diffRows(before, after);
|
|
848
|
+
const seedKeys = seedOnlyKeys(handle);
|
|
849
|
+
const writes = puts
|
|
850
|
+
.filter((row) => !seedKeys.has(row.rowKey))
|
|
851
|
+
.filter((row) => movedBeyondAuditStamp(beforeByKey.get(row.rowKey), row));
|
|
852
|
+
const removals = deletes.filter((key) => !seedKeys.has(key));
|
|
853
|
+
try {
|
|
854
|
+
if (writes.length) await handle.impl.putRows(writes);
|
|
855
|
+
if (removals.length) await handle.impl.deleteRows(removals);
|
|
856
|
+
await handle.impl.putMeta(ROW_META_MEMORY_KEY, JSON.stringify(payload.memory ?? emptyMemory().memory));
|
|
857
|
+
await handle.impl.putMeta(ROW_META_PREFIXES_KEY, JSON.stringify(payload.prefixes ?? emptyMemory().prefixes));
|
|
858
|
+
} catch (e) {
|
|
859
|
+
handle.cachedPayload = null;
|
|
860
|
+
handle.storedRows = null;
|
|
861
|
+
handle.baseRows = null;
|
|
862
|
+
throw e;
|
|
863
|
+
}
|
|
864
|
+
const removed = new Set(removals);
|
|
865
|
+
const next = new Map(handle.storedRows.filter((row) => !removed.has(row.rowKey)).map((row) => [row.rowKey, row]));
|
|
866
|
+
for (const row of writes) next.set(row.rowKey, row);
|
|
867
|
+
handle.storedRows = [...next.values()];
|
|
868
|
+
handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
|
|
869
|
+
meta: { memory: payload.memory, prefixes: payload.prefixes },
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
|
|
680
873
|
/** Resolve a backend token ("memory" | "sqlite" | anything else) into
|
|
681
874
|
* `{ dir, close }` — the ONE shared resolver, so every entry point (init's
|
|
682
875
|
* corpus seed, bin/tmct.mjs, chat) picks the same backend for a repo rather
|
|
683
876
|
* than silently splitting its memory across two stores. The empty/"default"
|
|
684
877
|
* token routes to the sqlite store: the flat-file Backend A is retired from
|
|
685
878
|
* routing (loadMemory/persistMemory still honour a plain dir string for
|
|
686
|
-
* callers that hold one directly).
|
|
879
|
+
* callers that hold one directly).
|
|
880
|
+
*
|
|
881
|
+
* `backendChoice` may also be an OBJECT: a row backend, which gets wrapped as
|
|
882
|
+
* a Backend D handle, or a handle wrapRowBackend already produced (the way a
|
|
883
|
+
* caller passes a seed overlay in). Either passes through untouched by config
|
|
884
|
+
* resolution — no repo path is read, nothing is created on disk — and the
|
|
885
|
+
* returned `close` closes the injected store. */
|
|
687
886
|
export async function openMemoryBackend(repoRoot, backendChoice) {
|
|
887
|
+
if (isRowHandle(backendChoice)) {
|
|
888
|
+
return { dir: backendChoice, close: async () => { await backendChoice.impl.close(); } };
|
|
889
|
+
}
|
|
890
|
+
if (isRowBackend(backendChoice)) {
|
|
891
|
+
const handle = wrapRowBackend(backendChoice);
|
|
892
|
+
return { dir: handle, close: async () => { await handle.impl.close(); } };
|
|
893
|
+
}
|
|
688
894
|
if (backendChoice === BACKEND_MEMORY) {
|
|
689
895
|
return { dir: createInMemoryStore(), close: async () => {} };
|
|
690
896
|
}
|
|
@@ -701,7 +907,9 @@ export async function openMemoryBackend(repoRoot, backendChoice) {
|
|
|
701
907
|
/** openMemoryBackend for a caller that only wants to READ what a repo already
|
|
702
908
|
* holds: null when the repo has no store yet, because opening one creates it.
|
|
703
909
|
* 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.
|
|
910
|
+
* pointed at, and must leave a repo with no memory exactly as they found it.
|
|
911
|
+
* String tokens only — an injected row backend has no repo store to probe for,
|
|
912
|
+
* so a caller holding one calls openMemoryBackend directly. */
|
|
705
913
|
export async function openExistingMemoryBackend(repoRoot, backendChoice = "") {
|
|
706
914
|
if (!repoRoot || typeof repoRoot !== "string") return null;
|
|
707
915
|
const dbPath = join(repoRoot, ".tmct", "memory", "graph.sqlite");
|
|
@@ -724,7 +932,9 @@ export async function readOnlyMemorySnapshot(memoryDir) {
|
|
|
724
932
|
/** openMemoryBackend for an entry point that holds only a repo path and has no
|
|
725
933
|
* CLI-flag tier (the fold's idle pass, `tmct import --file`): resolve the
|
|
726
934
|
* backend token the way the chat path does minus the flag —
|
|
727
|
-
* TMCT_MEMORY_BACKEND env > tmct.toml's [memory] backend > the default.
|
|
935
|
+
* TMCT_MEMORY_BACKEND env > tmct.toml's [memory] backend > the default. Config
|
|
936
|
+
* can only name a string backend, so an injected row backend never arrives
|
|
937
|
+
* here; a caller holding one calls openMemoryBackend directly. */
|
|
728
938
|
export async function openConfiguredMemoryBackend(repoRoot, env = process.env) {
|
|
729
939
|
let backend = String(env?.TMCT_MEMORY_BACKEND || "").trim().toLowerCase();
|
|
730
940
|
if (!backend) {
|
|
@@ -779,28 +989,13 @@ function buildSqlitePayloadFromRows(handle) {
|
|
|
779
989
|
const individuals = db.prepare("SELECT json FROM individuals ORDER BY ord").all()
|
|
780
990
|
.map((r) => JSON.parse(r.json));
|
|
781
991
|
|
|
782
|
-
const edgesForProp = db.prepare(
|
|
783
|
-
"SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ? ORDER BY rowid",
|
|
784
|
-
);
|
|
785
|
-
const objectProperties = db.prepare("SELECT prop, predicate, count FROM relations ORDER BY ord").all()
|
|
786
|
-
.map((r) => ({
|
|
787
|
-
predicate: r.predicate,
|
|
788
|
-
prop: r.prop,
|
|
789
|
-
count: r.count,
|
|
790
|
-
examples: edgesForProp.all(r.prop).map((e) => {
|
|
791
|
-
const edge = { subject: e.subject, object: e.object, subjectLabel: e.subject_label, objectLabel: e.object_label };
|
|
792
|
-
if (e.extra) Object.assign(edge, JSON.parse(e.extra));
|
|
793
|
-
return edge;
|
|
794
|
-
}),
|
|
795
|
-
}));
|
|
796
|
-
|
|
797
992
|
return {
|
|
798
993
|
generated_at: getMeta("generated_at", empty.generated_at),
|
|
799
994
|
memory: getMeta("memory", empty.memory),
|
|
800
995
|
prefixes: getMeta("prefixes", empty.prefixes),
|
|
801
996
|
vocabulary: getMeta("vocabulary", empty.vocabulary),
|
|
802
997
|
classes: getMeta("classes", empty.classes),
|
|
803
|
-
objectProperties,
|
|
998
|
+
objectProperties: sqliteEdgeGroups(db).map((entry) => entry.group),
|
|
804
999
|
individuals,
|
|
805
1000
|
proseIndex: getMeta("proseIndex", empty.proseIndex),
|
|
806
1001
|
};
|
|
@@ -820,10 +1015,10 @@ function cacheUpsertIndividual(cache, ind) {
|
|
|
820
1015
|
else cache.individuals.push(clone);
|
|
821
1016
|
}
|
|
822
1017
|
|
|
823
|
-
/** Mirrors
|
|
824
|
-
*
|
|
825
|
-
function
|
|
826
|
-
cache.individuals = cache.individuals.filter((i) =>
|
|
1018
|
+
/** Mirrors `DELETE FROM individuals`: drop every cached individual the write
|
|
1019
|
+
* just removed. */
|
|
1020
|
+
function cacheDropIndividuals(cache, droppedIds) {
|
|
1021
|
+
cache.individuals = cache.individuals.filter((i) => !droppedIds.has(i?.id));
|
|
827
1022
|
}
|
|
828
1023
|
|
|
829
1024
|
/** Find-or-create the cached edge group for `prop` — mirrors a relation row
|
|
@@ -858,16 +1053,370 @@ function cacheDropEdgesExcept(group, newKeys) {
|
|
|
858
1053
|
group.examples = group.examples.filter((e) => newKeys.has(`${e.subject}\u0000${e.object}`));
|
|
859
1054
|
}
|
|
860
1055
|
|
|
861
|
-
/** Mirrors
|
|
862
|
-
*
|
|
863
|
-
function
|
|
864
|
-
cache.objectProperties = cache.objectProperties.filter((g) =>
|
|
1056
|
+
/** Mirrors `DELETE FROM relations`: drop every cached edge group the write just
|
|
1057
|
+
* removed. */
|
|
1058
|
+
function cacheDropGroups(cache, droppedProps) {
|
|
1059
|
+
cache.objectProperties = cache.objectProperties.filter((g) => !droppedProps.has(g?.prop));
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// ---- Backend C as a row store ---------------------------------------------
|
|
1063
|
+
// The store's own tables ALREADY hold rows: an individual is a row keyed by its
|
|
1064
|
+
// id, an edge group a row keyed by its prop, and the payload's scalars are meta
|
|
1065
|
+
// values. The projection below says so in both directions, so one set of
|
|
1066
|
+
// writers serves both callers — persistSqlitePayload, which diffs a mutated
|
|
1067
|
+
// payload into rows, and the published row-backend contract (row-backend.mjs)
|
|
1068
|
+
// the same handle answers.
|
|
1069
|
+
//
|
|
1070
|
+
// A row the tables cannot hand back byte for byte goes to `unmapped_rows`
|
|
1071
|
+
// verbatim instead: a record whose class no row class covers, an index term the
|
|
1072
|
+
// record itself does not imply, a bookkeeping entry, anything carrying its own
|
|
1073
|
+
// TTL. That table is created the first time such a row arrives, so a store
|
|
1074
|
+
// holding only tmct's own payload never grows one.
|
|
1075
|
+
|
|
1076
|
+
const EDGE_GROUP_ROW_CLASS = "edge-group";
|
|
1077
|
+
const EDGE_GROUP_KEY_PREFIX = "edge-group:";
|
|
1078
|
+
|
|
1079
|
+
const ROW_CLASS_BY_INDIVIDUAL_CLASS = new Map([
|
|
1080
|
+
[FACT_CLASS, "fact"],
|
|
1081
|
+
[SOURCE_CLASS, "source"],
|
|
1082
|
+
[UTTERANCE_CLASS, "utterance"],
|
|
1083
|
+
[MEMORY_SESSION_CLASS, "session"],
|
|
1084
|
+
[RULE_CLASS, "rule"],
|
|
1085
|
+
[RETRACTION_CLASS, "retraction"],
|
|
1086
|
+
]);
|
|
1087
|
+
|
|
1088
|
+
const UNMAPPED_ROWS_TABLE = "unmapped_rows";
|
|
1089
|
+
const UNMAPPED_ROWS_DDL = `CREATE TABLE IF NOT EXISTS ${UNMAPPED_ROWS_TABLE} (
|
|
1090
|
+
row_key TEXT PRIMARY KEY, row_class TEXT NOT NULL, term TEXT NOT NULL, json TEXT NOT NULL, expires_at INTEGER
|
|
1091
|
+
)`;
|
|
1092
|
+
const UNMAPPED_ROWS_PRESENT_SQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?";
|
|
1093
|
+
|
|
1094
|
+
const individualRowJson = (ord, json) => `{"ord":${ord},"individual":${json}}`;
|
|
1095
|
+
const ROW_ORD_RE = /^\{"ord":(-?\d+),/;
|
|
1096
|
+
|
|
1097
|
+
/** The ord a row carries, read off the front of its own json. */
|
|
1098
|
+
function ordOfRow(row) {
|
|
1099
|
+
const match = ROW_ORD_RE.exec(row?.json || "");
|
|
1100
|
+
if (match) return Number(match[1]);
|
|
1101
|
+
try {
|
|
1102
|
+
const ord = Number(JSON.parse(row.json).ord);
|
|
1103
|
+
return Number.isFinite(ord) ? ord : 0;
|
|
1104
|
+
} catch { return 0; }
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/** One stored individual as a row. `json` is the blob the `individuals` table
|
|
1108
|
+
* holds, passed in so the row and the table can never disagree about it. */
|
|
1109
|
+
function individualRow(ind, ord, json) {
|
|
1110
|
+
const rowClass = ROW_CLASS_BY_INDIVIDUAL_CLASS.get(ind?.class) || "";
|
|
1111
|
+
return {
|
|
1112
|
+
rowKey: String(ind.id),
|
|
1113
|
+
rowClass,
|
|
1114
|
+
term: rowClass === "fact" ? normFactTerm(individualKey(ind, "subject")) : "",
|
|
1115
|
+
json: individualRowJson(ord, json),
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/** One edge with its four columns first and any other key after, so a group
|
|
1120
|
+
* projected from a payload and the same group read back off the tables
|
|
1121
|
+
* serialize to the same bytes. */
|
|
1122
|
+
function canonicalEdge(edge) {
|
|
1123
|
+
const canonical = {
|
|
1124
|
+
subject: edge.subject,
|
|
1125
|
+
object: edge.object,
|
|
1126
|
+
subjectLabel: edge.subjectLabel ?? null,
|
|
1127
|
+
objectLabel: edge.objectLabel ?? null,
|
|
1128
|
+
};
|
|
1129
|
+
for (const key of Object.keys(edge)) if (!STD_EDGE_KEYS.has(key)) canonical[key] = edge[key];
|
|
1130
|
+
return canonical;
|
|
865
1131
|
}
|
|
866
1132
|
|
|
867
|
-
/**
|
|
868
|
-
*
|
|
869
|
-
|
|
870
|
-
|
|
1133
|
+
/** One edge group as a row, examples in stored order — that order is recency,
|
|
1134
|
+
* since a changed edge moves to the end of its group. */
|
|
1135
|
+
function edgeGroupRow(group, ord) {
|
|
1136
|
+
const examples = (group.examples || []).map(canonicalEdge);
|
|
1137
|
+
return {
|
|
1138
|
+
rowKey: `${EDGE_GROUP_KEY_PREFIX}${group.prop}`,
|
|
1139
|
+
rowClass: EDGE_GROUP_ROW_CLASS,
|
|
1140
|
+
term: "",
|
|
1141
|
+
json: JSON.stringify({
|
|
1142
|
+
ord,
|
|
1143
|
+
group: {
|
|
1144
|
+
predicate: group.predicate ?? null,
|
|
1145
|
+
prop: group.prop,
|
|
1146
|
+
count: Number.isFinite(group.count) ? group.count : examples.length,
|
|
1147
|
+
examples,
|
|
1148
|
+
},
|
|
1149
|
+
}),
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/** Every edge group in the store, each with the `relations` ord it sorts by.
|
|
1154
|
+
* Edges come back in rowid order, which is the order they were last written. */
|
|
1155
|
+
function sqliteEdgeGroups(db) {
|
|
1156
|
+
const byProp = new Map();
|
|
1157
|
+
for (const r of db.prepare("SELECT prop, ord, predicate, count FROM relations ORDER BY ord, prop").all()) {
|
|
1158
|
+
byProp.set(r.prop, {
|
|
1159
|
+
ord: r.ord,
|
|
1160
|
+
group: { predicate: r.predicate, prop: r.prop, count: r.count, examples: [] },
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
if (!byProp.size) return [];
|
|
1164
|
+
for (const e of db.prepare("SELECT prop, subject, object, subject_label, object_label, extra FROM edges ORDER BY rowid").all()) {
|
|
1165
|
+
const entry = byProp.get(e.prop);
|
|
1166
|
+
if (!entry) continue;
|
|
1167
|
+
const edge = { subject: e.subject, object: e.object, subjectLabel: e.subject_label, objectLabel: e.object_label };
|
|
1168
|
+
if (e.extra) Object.assign(edge, JSON.parse(e.extra));
|
|
1169
|
+
entry.group.examples.push(edge);
|
|
1170
|
+
}
|
|
1171
|
+
return [...byProp.values()];
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/** The rows the store's tables hold for the payload — its individuals and edge
|
|
1175
|
+
* groups, and nothing else. This is what a payload write diffs against, so a
|
|
1176
|
+
* verbatim row a consumer stored beside them is never in the diff and never
|
|
1177
|
+
* deleted as absent-from-payload. Classes and terms come off the columns, so
|
|
1178
|
+
* reading them parses no blob. */
|
|
1179
|
+
function sqlitePayloadStoreRows(handle) {
|
|
1180
|
+
const rows = [];
|
|
1181
|
+
const stored = handle.db.prepare(
|
|
1182
|
+
"SELECT i.id AS id, i.ord AS ord, i.class AS class, i.json AS json, f.subject AS subject"
|
|
1183
|
+
+ " FROM individuals i LEFT JOIN facts f ON f.id = i.id ORDER BY i.ord, i.id",
|
|
1184
|
+
).all();
|
|
1185
|
+
for (const r of stored) {
|
|
1186
|
+
const rowClass = ROW_CLASS_BY_INDIVIDUAL_CLASS.get(r.class) || "";
|
|
1187
|
+
rows.push({
|
|
1188
|
+
rowKey: r.id,
|
|
1189
|
+
rowClass,
|
|
1190
|
+
term: rowClass === "fact" ? normFactTerm(r.subject || "") : "",
|
|
1191
|
+
json: individualRowJson(r.ord, r.json),
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
for (const entry of sqliteEdgeGroups(handle.db)) rows.push(edgeGroupRow(entry.group, entry.ord));
|
|
1195
|
+
return rows;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/** A mutated payload as rows, plus what a write needs to apply each of them. An
|
|
1199
|
+
* existing key keeps the ord it already had; a new one takes the next free
|
|
1200
|
+
* number in its own sequence, since individuals and relations number
|
|
1201
|
+
* separately, exactly as their tables do. */
|
|
1202
|
+
function sqlitePayloadRows(payload, priorRows) {
|
|
1203
|
+
const priorOrd = new Map();
|
|
1204
|
+
let nextIndividualOrd = 0;
|
|
1205
|
+
let nextGroupOrd = 0;
|
|
1206
|
+
for (const row of priorRows) {
|
|
1207
|
+
const ord = ordOfRow(row);
|
|
1208
|
+
priorOrd.set(row.rowKey, ord);
|
|
1209
|
+
if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
|
|
1210
|
+
if (ord >= nextGroupOrd) nextGroupOrd = ord + 1;
|
|
1211
|
+
} else if (ord >= nextIndividualOrd) nextIndividualOrd = ord + 1;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
const rows = [];
|
|
1215
|
+
const partsByKey = new Map();
|
|
1216
|
+
for (const ind of payload.individuals || []) {
|
|
1217
|
+
if (!ind?.id) continue;
|
|
1218
|
+
const json = JSON.stringify(ind);
|
|
1219
|
+
const rowKey = String(ind.id);
|
|
1220
|
+
const ord = priorOrd.get(rowKey) ?? nextIndividualOrd++;
|
|
1221
|
+
rows.push(individualRow(ind, ord, json));
|
|
1222
|
+
partsByKey.set(rowKey, { kind: "individual", ord, individual: ind, json });
|
|
1223
|
+
}
|
|
1224
|
+
for (const group of payload.objectProperties || []) {
|
|
1225
|
+
if (!group?.prop) continue;
|
|
1226
|
+
const rowKey = `${EDGE_GROUP_KEY_PREFIX}${group.prop}`;
|
|
1227
|
+
const ord = priorOrd.get(rowKey) ?? nextGroupOrd++;
|
|
1228
|
+
const row = edgeGroupRow(group, ord);
|
|
1229
|
+
rows.push(row);
|
|
1230
|
+
partsByKey.set(rowKey, { kind: EDGE_GROUP_ROW_CLASS, ord, group: JSON.parse(row.json).group });
|
|
1231
|
+
}
|
|
1232
|
+
return { rows, partsByKey };
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/** What a row is as far as the store's own tables are concerned: an individual
|
|
1236
|
+
* or an edge group when they can hand it back byte for byte, null when only
|
|
1237
|
+
* the verbatim table can hold it. */
|
|
1238
|
+
function nativeRowParts(row) {
|
|
1239
|
+
if (row.expiresAt !== undefined) return null; // no column carries a TTL stamp
|
|
1240
|
+
let record;
|
|
1241
|
+
try { record = JSON.parse(row.json); } catch { return null; }
|
|
1242
|
+
if (!record || typeof record !== "object" || !Number.isFinite(record.ord)) return null;
|
|
1243
|
+
|
|
1244
|
+
if (row.rowClass === EDGE_GROUP_ROW_CLASS) {
|
|
1245
|
+
const group = record.group;
|
|
1246
|
+
if (!group?.prop) return null;
|
|
1247
|
+
const rebuilt = edgeGroupRow(group, record.ord);
|
|
1248
|
+
if (rebuilt.rowKey !== row.rowKey || rebuilt.term !== row.term || rebuilt.json !== row.json) return null;
|
|
1249
|
+
return { kind: EDGE_GROUP_ROW_CLASS, ord: record.ord, group };
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
const ind = record.individual;
|
|
1253
|
+
if (!ind?.id) return null;
|
|
1254
|
+
const json = JSON.stringify(ind);
|
|
1255
|
+
const rebuilt = individualRow(ind, record.ord, json);
|
|
1256
|
+
if (rebuilt.rowKey !== row.rowKey || rebuilt.rowClass !== row.rowClass) return null;
|
|
1257
|
+
if (rebuilt.term !== row.term || rebuilt.json !== row.json) return null;
|
|
1258
|
+
return { kind: "individual", ord: record.ord, individual: ind, json };
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/** The state one write transaction carries: the statements it reuses, the cache
|
|
1262
|
+
* it patches in lockstep, and the groups and (subject, predicate) pairs it
|
|
1263
|
+
* touched, so the two derived tables re-materialise for exactly what moved and
|
|
1264
|
+
* nothing else. A group whose records are all untouched cannot have moved —
|
|
1265
|
+
* its base carries no recency, so only its own records can change it. */
|
|
1266
|
+
function sqliteWriteContext(handle, { cache = null } = {}) {
|
|
1267
|
+
const db = handle.db;
|
|
1268
|
+
return {
|
|
1269
|
+
db,
|
|
1270
|
+
cache,
|
|
1271
|
+
touchedGroups: new Set(),
|
|
1272
|
+
touchedPairs: new Set(),
|
|
1273
|
+
hasUnmappedRows: !!db.prepare(UNMAPPED_ROWS_PRESENT_SQL).get(UNMAPPED_ROWS_TABLE),
|
|
1274
|
+
unmapped: null,
|
|
1275
|
+
upsertInd: db.prepare("INSERT OR REPLACE INTO individuals(id, ord, class, label, json) VALUES (?, ?, ?, ?, ?)"),
|
|
1276
|
+
upsertFact: db.prepare(FACT_PROJECTION_UPSERT_SQL),
|
|
1277
|
+
deleteInd: db.prepare("DELETE FROM individuals WHERE id = ?"),
|
|
1278
|
+
deleteFact: db.prepare("DELETE FROM facts WHERE id = ?"),
|
|
1279
|
+
getFact: db.prepare("SELECT triple_hash, subject, predicate FROM facts WHERE id = ?"),
|
|
1280
|
+
upsertRel: db.prepare("INSERT OR REPLACE INTO relations(prop, ord, predicate, count) VALUES (?, ?, ?, ?)"),
|
|
1281
|
+
edgesForProp: db.prepare("SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ?"),
|
|
1282
|
+
upsertEdge: db.prepare("INSERT OR REPLACE INTO edges(prop, subject, object, subject_label, object_label, extra) VALUES (?, ?, ?, ?, ?, ?)"),
|
|
1283
|
+
deleteEdge: db.prepare("DELETE FROM edges WHERE prop = ? AND subject = ? AND object = ?"),
|
|
1284
|
+
deleteGroupEdges: db.prepare("DELETE FROM edges WHERE prop = ?"),
|
|
1285
|
+
deleteRel: db.prepare("DELETE FROM relations WHERE prop = ?"),
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/** The verbatim table's statements, creating the table the first time a write
|
|
1290
|
+
* actually needs it. */
|
|
1291
|
+
function unmappedStatements(ctx) {
|
|
1292
|
+
if (!ctx.unmapped) {
|
|
1293
|
+
ctx.db.exec(UNMAPPED_ROWS_DDL);
|
|
1294
|
+
ctx.hasUnmappedRows = true;
|
|
1295
|
+
ctx.unmapped = {
|
|
1296
|
+
upsert: ctx.db.prepare(`INSERT OR REPLACE INTO ${UNMAPPED_ROWS_TABLE}(row_key, row_class, term, json, expires_at) VALUES (?, ?, ?, ?, ?)`),
|
|
1297
|
+
remove: ctx.db.prepare(`DELETE FROM ${UNMAPPED_ROWS_TABLE} WHERE row_key = ?`),
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
return ctx.unmapped;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/** Drop a key from the verbatim table, so no key ever lives in both lanes.
|
|
1304
|
+
* Skipped whole for a store that has never held a verbatim row. */
|
|
1305
|
+
function dropUnmappedRow(ctx, rowKey) {
|
|
1306
|
+
if (ctx.hasUnmappedRows) unmappedStatements(ctx).remove.run(rowKey);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
function writeIndividualRow(ctx, { ord, individual, json }) {
|
|
1310
|
+
ctx.upsertInd.run(individual.id, ord, individual.class ?? null, individual.label ?? null, json);
|
|
1311
|
+
// The queryable projection of the blob just written, same transaction — every
|
|
1312
|
+
// write path that reaches a Fact (teach, corpus seed, entailment, migration, a
|
|
1313
|
+
// trust recompute) lands here, so none can leave the two out of step.
|
|
1314
|
+
if (individual.class === FACT_CLASS) {
|
|
1315
|
+
ctx.upsertFact.run(...factProjectionValues(individual, json));
|
|
1316
|
+
ctx.touchedGroups.add(factGroupId(individual.id));
|
|
1317
|
+
ctx.touchedPairs.add(subjectPredicateKey(individualKey(individual, "subject"), individualKey(individual, "predicate")));
|
|
1318
|
+
}
|
|
1319
|
+
dropUnmappedRow(ctx, String(individual.id));
|
|
1320
|
+
if (ctx.cache) cacheUpsertIndividual(ctx.cache, individual);
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
/** A group's edges, diffed WITHIN the group and scoped to its own rows
|
|
1324
|
+
* (edges_by_prop) rather than the whole edges table — a group that gains one
|
|
1325
|
+
* new edge (statedBy, touched by nearly every appendFact call) writes exactly
|
|
1326
|
+
* that one row, not the group's entire history. */
|
|
1327
|
+
function writeEdgeGroupRow(ctx, { ord, group }) {
|
|
1328
|
+
const existingByKey = new Map(
|
|
1329
|
+
ctx.edgesForProp.all(group.prop).map((r) => [`${r.subject}${r.object}`, r]),
|
|
1330
|
+
);
|
|
1331
|
+
const newKeys = new Set();
|
|
1332
|
+
const cacheGroup = ctx.cache ? cacheGroupFor(ctx.cache, group.prop) : null;
|
|
1333
|
+
for (const e of group.examples || []) {
|
|
1334
|
+
const key = `${e.subject}${e.object}`;
|
|
1335
|
+
newKeys.add(key);
|
|
1336
|
+
const extraKeys = Object.keys(e).filter((k) => !STD_EDGE_KEYS.has(k));
|
|
1337
|
+
const extra = extraKeys.length ? JSON.stringify(Object.fromEntries(extraKeys.map((k) => [k, e[k]]))) : null;
|
|
1338
|
+
const existing = existingByKey.get(key);
|
|
1339
|
+
const unchanged = existing
|
|
1340
|
+
&& (existing.subject_label ?? null) === (e.subjectLabel ?? null)
|
|
1341
|
+
&& (existing.object_label ?? null) === (e.objectLabel ?? null)
|
|
1342
|
+
&& (existing.extra ?? null) === (extra ?? null);
|
|
1343
|
+
if (unchanged) continue;
|
|
1344
|
+
ctx.upsertEdge.run(group.prop, e.subject, e.object, e.subjectLabel ?? null, e.objectLabel ?? null, extra);
|
|
1345
|
+
if (cacheGroup) cacheUpsertEdge(cacheGroup, e, extraKeys);
|
|
1346
|
+
}
|
|
1347
|
+
for (const key of existingByKey.keys()) {
|
|
1348
|
+
if (newKeys.has(key)) continue;
|
|
1349
|
+
const [s, o] = key.split("");
|
|
1350
|
+
ctx.deleteEdge.run(group.prop, s, o);
|
|
1351
|
+
}
|
|
1352
|
+
if (cacheGroup) cacheDropEdgesExcept(cacheGroup, newKeys);
|
|
1353
|
+
const count = Number.isFinite(group.count) ? group.count : (group.examples || []).length;
|
|
1354
|
+
ctx.upsertRel.run(group.prop, ord, group.predicate ?? null, count);
|
|
1355
|
+
dropUnmappedRow(ctx, `${EDGE_GROUP_KEY_PREFIX}${group.prop}`);
|
|
1356
|
+
if (cacheGroup) { cacheGroup.predicate = group.predicate ?? null; cacheGroup.count = count; }
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
function writeUnmappedRow(ctx, row) {
|
|
1360
|
+
unmappedStatements(ctx).upsert.run(row.rowKey, row.rowClass, row.term, row.json, row.expiresAt ?? null);
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
/** Apply rows to the store's tables. `knownParts` is what the payload
|
|
1364
|
+
* projection already worked out for the rows it minted, so the write path does
|
|
1365
|
+
* not re-derive what it just built. */
|
|
1366
|
+
function writeSqliteRows(ctx, rows, knownParts = null) {
|
|
1367
|
+
for (const row of rows) {
|
|
1368
|
+
const parts = knownParts?.get(row.rowKey) || nativeRowParts(row);
|
|
1369
|
+
if (!parts) { writeUnmappedRow(ctx, row); continue; }
|
|
1370
|
+
if (parts.kind === EDGE_GROUP_ROW_CLASS) writeEdgeGroupRow(ctx, parts);
|
|
1371
|
+
else writeIndividualRow(ctx, parts);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/** Remove rows by key from whichever lane holds them. A retracted record's own
|
|
1376
|
+
* group and (subject, predicate) are read off the projection BEFORE the row
|
|
1377
|
+
* goes, since once it is gone there is nothing left to read them off. */
|
|
1378
|
+
function deleteSqliteRows(ctx, rowKeys) {
|
|
1379
|
+
const droppedIndividuals = new Set();
|
|
1380
|
+
const droppedProps = new Set();
|
|
1381
|
+
for (const rowKey of rowKeys) {
|
|
1382
|
+
if (rowKey.startsWith(EDGE_GROUP_KEY_PREFIX)) {
|
|
1383
|
+
const prop = rowKey.slice(EDGE_GROUP_KEY_PREFIX.length);
|
|
1384
|
+
ctx.deleteGroupEdges.run(prop);
|
|
1385
|
+
ctx.deleteRel.run(prop);
|
|
1386
|
+
droppedProps.add(prop);
|
|
1387
|
+
} else {
|
|
1388
|
+
const gone = ctx.getFact.get(rowKey);
|
|
1389
|
+
if (gone) {
|
|
1390
|
+
ctx.touchedGroups.add(gone.triple_hash);
|
|
1391
|
+
ctx.touchedPairs.add(subjectPredicateKey(gone.subject, gone.predicate));
|
|
1392
|
+
}
|
|
1393
|
+
ctx.deleteInd.run(rowKey);
|
|
1394
|
+
ctx.deleteFact.run(rowKey); // a no-op for a non-Fact id; keeps the projection from outliving its blob
|
|
1395
|
+
droppedIndividuals.add(rowKey);
|
|
1396
|
+
}
|
|
1397
|
+
dropUnmappedRow(ctx, rowKey);
|
|
1398
|
+
}
|
|
1399
|
+
if (ctx.cache && droppedIndividuals.size) cacheDropIndividuals(ctx.cache, droppedIndividuals);
|
|
1400
|
+
if (ctx.cache && droppedProps.size) cacheDropGroups(ctx.cache, droppedProps);
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/** Re-materialise the derived tables for what a write touched, inside that
|
|
1404
|
+
* write's own transaction, so no reader can ever see one without the other. */
|
|
1405
|
+
function recomputeDerivedTables(ctx, foldSource, headIndex) {
|
|
1406
|
+
if (!ctx.touchedGroups.size) return;
|
|
1407
|
+
const foldCtx = factFoldContext(foldSource);
|
|
1408
|
+
recomputeFactHeads(ctx.db, foldCtx, ctx.touchedGroups, headIndex);
|
|
1409
|
+
recordObjectSupersessions(ctx.db, foldCtx, ctx.touchedPairs);
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/** Persist a mutated payload into a Backend C handle: the payload projected to
|
|
1413
|
+
* rows, diffed against the rows already stored, and only the difference
|
|
1414
|
+
* written, in one transaction. Patches `handle.cachedPayload` in lockstep; a
|
|
1415
|
+
* rolled-back write invalidates the cache instead of leaving a partial patch.
|
|
1416
|
+
*
|
|
1417
|
+
* The 4 KB wire cap the row contract enforces is not applied here: it protects
|
|
1418
|
+
* a network hop, and a local file store holds a seed's whole statedBy group in
|
|
1419
|
+
* one row. */
|
|
871
1420
|
function persistSqlitePayload(handle, payload) {
|
|
872
1421
|
const db = handle.db;
|
|
873
1422
|
const empty = emptyMemory();
|
|
@@ -890,124 +1439,19 @@ function persistSqlitePayload(handle, payload) {
|
|
|
890
1439
|
cache.proseIndex = cloneJson(payload.proseIndex ?? empty.proseIndex);
|
|
891
1440
|
}
|
|
892
1441
|
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
const
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
const upsertFact = db.prepare(FACT_PROJECTION_UPSERT_SQL);
|
|
901
|
-
const seenIds = new Set();
|
|
902
|
-
// Every group and every (subject, predicate) this write reaches, so the two
|
|
903
|
-
// derived tables are re-materialised for exactly what moved and nothing
|
|
904
|
-
// else. A group whose records are all untouched cannot have moved: its base
|
|
905
|
-
// carries no recency, so only its own records can change it.
|
|
906
|
-
const touchedGroups = new Set();
|
|
907
|
-
const touchedPairs = new Set();
|
|
908
|
-
for (const ind of payload.individuals || []) {
|
|
909
|
-
seenIds.add(ind.id);
|
|
910
|
-
const json = JSON.stringify(ind);
|
|
911
|
-
const existing = getInd.get(ind.id);
|
|
912
|
-
if (existing && existing.json === json) continue; // unchanged — skip the write entirely (cache already matches)
|
|
913
|
-
const ord = existing ? existing.ord : nextOrd++;
|
|
914
|
-
upsertInd.run(ind.id, ord, ind.class ?? null, ind.label ?? null, json);
|
|
915
|
-
// The queryable projection of the blob just written, same transaction —
|
|
916
|
-
// every write path that reaches a Fact (teach, corpus seed, entailment,
|
|
917
|
-
// migration, a trust recompute) lands here, so none can leave the two
|
|
918
|
-
// out of step.
|
|
919
|
-
if (ind.class === FACT_CLASS) {
|
|
920
|
-
upsertFact.run(...factProjectionValues(ind, json));
|
|
921
|
-
touchedGroups.add(factGroupId(ind.id));
|
|
922
|
-
touchedPairs.add(subjectPredicateKey(individualKey(ind, "subject"), individualKey(ind, "predicate")));
|
|
923
|
-
}
|
|
924
|
-
if (cache) cacheUpsertIndividual(cache, ind);
|
|
925
|
-
}
|
|
926
|
-
// Removal (what removeFacts' retraction lands as — every append path only
|
|
927
|
-
// ever adds): a cheap index-only scan of the primary-key column, never the
|
|
928
|
-
// JSON payload.
|
|
929
|
-
const deleteInd = db.prepare("DELETE FROM individuals WHERE id = ?");
|
|
930
|
-
const deleteFact = db.prepare("DELETE FROM facts WHERE id = ?");
|
|
931
|
-
const getFact = db.prepare("SELECT triple_hash, subject, predicate FROM facts WHERE id = ?");
|
|
932
|
-
for (const row of db.prepare("SELECT id FROM individuals").all()) {
|
|
933
|
-
if (seenIds.has(row.id)) continue;
|
|
934
|
-
// Read the projection before dropping it: a retracted record's own group
|
|
935
|
-
// and (subject, predicate) still have to be re-materialised, and once the
|
|
936
|
-
// row is gone there is nothing left to read them off.
|
|
937
|
-
const gone = getFact.get(row.id);
|
|
938
|
-
if (gone) {
|
|
939
|
-
touchedGroups.add(gone.triple_hash);
|
|
940
|
-
touchedPairs.add(subjectPredicateKey(gone.subject, gone.predicate));
|
|
941
|
-
}
|
|
942
|
-
deleteInd.run(row.id);
|
|
943
|
-
deleteFact.run(row.id); // a no-op for a non-Fact id; keeps the projection from outliving its blob
|
|
944
|
-
}
|
|
945
|
-
if (cache) cacheDropIndividualsExcept(cache, seenIds);
|
|
946
|
-
|
|
947
|
-
// objectProperties/edges: per-edge diff WITHIN each group, scoped to that
|
|
948
|
-
// group's own rows (edges_by_prop) rather than the whole edges table — a
|
|
949
|
-
// group that gains one new edge (e.g. statedBy, touched by nearly every
|
|
950
|
-
// appendFact call) writes exactly that one new row, not the group's
|
|
951
|
-
// entire history.
|
|
952
|
-
const getRelOrd = db.prepare("SELECT ord FROM relations WHERE prop = ?");
|
|
953
|
-
const maxRelOrd = db.prepare("SELECT COALESCE(MAX(ord), -1) AS m FROM relations").get().m;
|
|
954
|
-
let nextRelOrd = maxRelOrd + 1;
|
|
955
|
-
const upsertRel = db.prepare("INSERT OR REPLACE INTO relations(prop, ord, predicate, count) VALUES (?, ?, ?, ?)");
|
|
956
|
-
const edgesForProp = db.prepare("SELECT subject, object, subject_label, object_label, extra FROM edges WHERE prop = ?");
|
|
957
|
-
const upsertEdge = db.prepare("INSERT OR REPLACE INTO edges(prop, subject, object, subject_label, object_label, extra) VALUES (?, ?, ?, ?, ?, ?)");
|
|
958
|
-
const deleteEdge = db.prepare("DELETE FROM edges WHERE prop = ? AND subject = ? AND object = ?");
|
|
959
|
-
const seenProps = new Set();
|
|
960
|
-
for (const group of payload.objectProperties || []) {
|
|
961
|
-
seenProps.add(group.prop);
|
|
962
|
-
const existingRows = edgesForProp.all(group.prop);
|
|
963
|
-
const existingByKey = new Map(existingRows.map((r) => [`${r.subject}\u0000${r.object}`, r]));
|
|
964
|
-
const newKeys = new Set();
|
|
965
|
-
const cacheGroup = cache ? cacheGroupFor(cache, group.prop) : null;
|
|
966
|
-
for (const e of group.examples || []) {
|
|
967
|
-
const key = `${e.subject}\u0000${e.object}`;
|
|
968
|
-
newKeys.add(key);
|
|
969
|
-
const extraKeys = Object.keys(e).filter((k) => !STD_EDGE_KEYS.has(k));
|
|
970
|
-
const extra = extraKeys.length ? JSON.stringify(Object.fromEntries(extraKeys.map((k) => [k, e[k]]))) : null;
|
|
971
|
-
const existing = existingByKey.get(key);
|
|
972
|
-
const unchanged = existing
|
|
973
|
-
&& (existing.subject_label ?? null) === (e.subjectLabel ?? null)
|
|
974
|
-
&& (existing.object_label ?? null) === (e.objectLabel ?? null)
|
|
975
|
-
&& (existing.extra ?? null) === (extra ?? null);
|
|
976
|
-
if (unchanged) continue;
|
|
977
|
-
upsertEdge.run(group.prop, e.subject, e.object, e.subjectLabel ?? null, e.objectLabel ?? null, extra);
|
|
978
|
-
if (cacheGroup) cacheUpsertEdge(cacheGroup, e, extraKeys);
|
|
979
|
-
}
|
|
980
|
-
for (const key of existingByKey.keys()) {
|
|
981
|
-
if (newKeys.has(key)) continue;
|
|
982
|
-
const [s, o] = key.split("\u0000");
|
|
983
|
-
deleteEdge.run(group.prop, s, o);
|
|
984
|
-
}
|
|
985
|
-
if (cacheGroup) cacheDropEdgesExcept(cacheGroup, newKeys);
|
|
986
|
-
const relCount = Number.isFinite(group.count) ? group.count : (group.examples || []).length;
|
|
987
|
-
const relOrd = getRelOrd.get(group.prop)?.ord ?? nextRelOrd++;
|
|
988
|
-
upsertRel.run(group.prop, relOrd, group.predicate ?? null, relCount);
|
|
989
|
-
if (cacheGroup) { cacheGroup.predicate = group.predicate ?? null; cacheGroup.count = relCount; }
|
|
990
|
-
}
|
|
991
|
-
for (const row of db.prepare("SELECT prop FROM relations").all()) {
|
|
992
|
-
if (seenProps.has(row.prop)) continue;
|
|
993
|
-
db.prepare("DELETE FROM edges WHERE prop = ?").run(row.prop);
|
|
994
|
-
db.prepare("DELETE FROM relations WHERE prop = ?").run(row.prop);
|
|
995
|
-
}
|
|
996
|
-
if (cache) cacheDropGroupsExcept(cache, seenProps);
|
|
997
|
-
|
|
998
|
-
// The derived tables, re-materialised in the SAME transaction as the
|
|
999
|
-
// records they summarise, so no reader can ever see one without the other.
|
|
1000
|
-
if (touchedGroups.size) {
|
|
1001
|
-
const ctx = factFoldContext(payload);
|
|
1002
|
-
recomputeFactHeads(db, ctx, touchedGroups, handle.cachedFactHeads);
|
|
1003
|
-
recordObjectSupersessions(db, ctx, touchedPairs);
|
|
1004
|
-
}
|
|
1442
|
+
const ctx = sqliteWriteContext(handle, { cache });
|
|
1443
|
+
const before = sqlitePayloadStoreRows(handle);
|
|
1444
|
+
const { rows: after, partsByKey } = sqlitePayloadRows(payload, before);
|
|
1445
|
+
const { puts, deletes } = diffRows(before, after);
|
|
1446
|
+
writeSqliteRows(ctx, puts, partsByKey);
|
|
1447
|
+
deleteSqliteRows(ctx, deletes);
|
|
1448
|
+
recomputeDerivedTables(ctx, payload, handle.cachedFactHeads);
|
|
1005
1449
|
|
|
1006
1450
|
db.exec("COMMIT");
|
|
1007
1451
|
} catch (e) {
|
|
1008
1452
|
db.exec("ROLLBACK");
|
|
1009
1453
|
// The cache may hold a partially-applied patch at this point (some of the
|
|
1010
|
-
//
|
|
1454
|
+
// writes above already mutated it before the failure) that was never
|
|
1011
1455
|
// actually committed to SQLite — never trust it silently. Drop it so the
|
|
1012
1456
|
// next loadMemory() call does an honest full rebuild instead.
|
|
1013
1457
|
handle.cachedPayload = undefined;
|
|
@@ -1016,6 +1460,144 @@ function persistSqlitePayload(handle, payload) {
|
|
|
1016
1460
|
}
|
|
1017
1461
|
}
|
|
1018
1462
|
|
|
1463
|
+
// ---- The row-backend contract, over the same tables ------------------------
|
|
1464
|
+
|
|
1465
|
+
/** Every verbatim row still live, expired ones filtered out the way the
|
|
1466
|
+
* reference backend filters its own. */
|
|
1467
|
+
function readUnmappedRows(db) {
|
|
1468
|
+
if (!db.prepare(UNMAPPED_ROWS_PRESENT_SQL).get(UNMAPPED_ROWS_TABLE)) return [];
|
|
1469
|
+
const now = Math.floor(Date.now() / 1000);
|
|
1470
|
+
const rows = [];
|
|
1471
|
+
for (const r of db.prepare(`SELECT row_key, row_class, term, json, expires_at FROM ${UNMAPPED_ROWS_TABLE}`).all()) {
|
|
1472
|
+
if (r.expires_at !== null && r.expires_at <= now) continue;
|
|
1473
|
+
const row = { rowKey: r.row_key, rowClass: r.row_class, term: r.term, json: r.json };
|
|
1474
|
+
if (r.expires_at !== null) row.expiresAt = r.expires_at;
|
|
1475
|
+
rows.push(row);
|
|
1476
|
+
}
|
|
1477
|
+
return rows;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
/** Run `write` in one transaction, then drop the caches: a row write reaches
|
|
1481
|
+
* the tables without going through the payload those caches mirror, so the
|
|
1482
|
+
* next read rebuilds from the tables rather than from a payload that no longer
|
|
1483
|
+
* describes them. */
|
|
1484
|
+
function inSqliteRowTransaction(handle, write) {
|
|
1485
|
+
const db = handle.db;
|
|
1486
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1487
|
+
try {
|
|
1488
|
+
write(sqliteWriteContext(handle));
|
|
1489
|
+
db.exec("COMMIT");
|
|
1490
|
+
} catch (e) {
|
|
1491
|
+
db.exec("ROLLBACK");
|
|
1492
|
+
throw e;
|
|
1493
|
+
} finally {
|
|
1494
|
+
handle.cachedPayload = null;
|
|
1495
|
+
handle.cachedFactHeads = null;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
const SQLITE_TABLES = Object.freeze([
|
|
1500
|
+
"meta", "individuals", "relations", "edges", "facts", "fact_heads", "fact_object_supersessions",
|
|
1501
|
+
]);
|
|
1502
|
+
|
|
1503
|
+
/** Give a Backend C handle the published row-backend methods (row-backend.mjs).
|
|
1504
|
+
* They read and write the same seven tables the payload path does, so a
|
|
1505
|
+
* consumer holding the store as a row backend and tmct holding it as a memory
|
|
1506
|
+
* store see one store rather than two. */
|
|
1507
|
+
function attachSqliteRowMethods(handle) {
|
|
1508
|
+
return Object.assign(handle, {
|
|
1509
|
+
async readRows() {
|
|
1510
|
+
return [...sqlitePayloadStoreRows(handle), ...readUnmappedRows(handle.db)];
|
|
1511
|
+
},
|
|
1512
|
+
|
|
1513
|
+
async readRowsByTerm(term) {
|
|
1514
|
+
return (await handle.readRows()).filter((row) => row.term === term);
|
|
1515
|
+
},
|
|
1516
|
+
|
|
1517
|
+
async putRows(candidateRows) {
|
|
1518
|
+
// Validate every row before writing any of them, so a batch carrying one
|
|
1519
|
+
// malformed row is refused whole rather than half-applied.
|
|
1520
|
+
const validated = (candidateRows || []).map((row) => assertValidRow(row));
|
|
1521
|
+
if (!validated.length) return;
|
|
1522
|
+
inSqliteRowTransaction(handle, (ctx) => {
|
|
1523
|
+
writeSqliteRows(ctx, validated);
|
|
1524
|
+
recomputeDerivedTables(ctx, buildSqlitePayloadFromRows(handle), null);
|
|
1525
|
+
});
|
|
1526
|
+
},
|
|
1527
|
+
|
|
1528
|
+
async deleteRows(rowKeys) {
|
|
1529
|
+
const keys = [...(rowKeys || [])];
|
|
1530
|
+
if (!keys.length) return;
|
|
1531
|
+
inSqliteRowTransaction(handle, (ctx) => {
|
|
1532
|
+
deleteSqliteRows(ctx, keys);
|
|
1533
|
+
recomputeDerivedTables(ctx, buildSqlitePayloadFromRows(handle), null);
|
|
1534
|
+
});
|
|
1535
|
+
},
|
|
1536
|
+
|
|
1537
|
+
async readMeta(key) {
|
|
1538
|
+
const row = handle.db.prepare("SELECT v FROM meta WHERE k = ?").get(key);
|
|
1539
|
+
return row ? row.v : null;
|
|
1540
|
+
},
|
|
1541
|
+
|
|
1542
|
+
async putMeta(key, value) {
|
|
1543
|
+
handle.db.prepare("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)").run(key, String(value));
|
|
1544
|
+
handle.cachedPayload = null;
|
|
1545
|
+
handle.cachedFactHeads = null;
|
|
1546
|
+
},
|
|
1547
|
+
|
|
1548
|
+
async deleteAll() {
|
|
1549
|
+
const db = handle.db;
|
|
1550
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1551
|
+
try {
|
|
1552
|
+
for (const table of SQLITE_TABLES) db.exec(`DELETE FROM ${table}`);
|
|
1553
|
+
if (db.prepare(UNMAPPED_ROWS_PRESENT_SQL).get(UNMAPPED_ROWS_TABLE)) db.exec(`DELETE FROM ${UNMAPPED_ROWS_TABLE}`);
|
|
1554
|
+
db.exec("COMMIT");
|
|
1555
|
+
} catch (e) {
|
|
1556
|
+
db.exec("ROLLBACK");
|
|
1557
|
+
throw e;
|
|
1558
|
+
} finally {
|
|
1559
|
+
handle.cachedPayload = null;
|
|
1560
|
+
handle.cachedFactHeads = null;
|
|
1561
|
+
}
|
|
1562
|
+
},
|
|
1563
|
+
|
|
1564
|
+
async close() {
|
|
1565
|
+
closeSqliteMemoryStore(handle);
|
|
1566
|
+
},
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/** A sqlite file as an injectable row backend: the same store
|
|
1571
|
+
* `createSqliteMemoryStore` opens, presented under the published contract. The
|
|
1572
|
+
* connection opens on the first call, so constructing one touches no disk and
|
|
1573
|
+
* needs no await. */
|
|
1574
|
+
export function createSqliteRowBackend(dbPath) {
|
|
1575
|
+
let opening = null;
|
|
1576
|
+
let closed = false;
|
|
1577
|
+
const handle = () => {
|
|
1578
|
+
if (closed) throw new BackendUnavailable("this row backend was closed and can no longer be used");
|
|
1579
|
+
opening = opening || createSqliteMemoryStore(dbPath);
|
|
1580
|
+
return opening;
|
|
1581
|
+
};
|
|
1582
|
+
const through = (method) => async (...args) => (await handle())[method](...args);
|
|
1583
|
+
return {
|
|
1584
|
+
kind: ROW_BACKEND_KIND,
|
|
1585
|
+
contractVersion: ROW_BACKEND_CONTRACT_VERSION,
|
|
1586
|
+
readRows: through("readRows"),
|
|
1587
|
+
readRowsByTerm: through("readRowsByTerm"),
|
|
1588
|
+
putRows: through("putRows"),
|
|
1589
|
+
deleteRows: through("deleteRows"),
|
|
1590
|
+
readMeta: through("readMeta"),
|
|
1591
|
+
putMeta: through("putMeta"),
|
|
1592
|
+
deleteAll: through("deleteAll"),
|
|
1593
|
+
async close() {
|
|
1594
|
+
const open = opening ? await opening : null;
|
|
1595
|
+
closed = true;
|
|
1596
|
+
if (open) closeSqliteMemoryStore(open);
|
|
1597
|
+
},
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1019
1601
|
/** Atomic write of raw text (temp in the same dir + rename) — the discipline
|
|
1020
1602
|
* every writer in this module (and fold.mjs/sessions.mjs's own copies) uses:
|
|
1021
1603
|
* a crash never destroys the previous file, a concurrent reader never sees a
|
|
@@ -1049,7 +1631,7 @@ const resolveManifestFile = (dir) => join(dir, MEMORY_MANIFEST_REL);
|
|
|
1049
1631
|
* `opts.retentionVersions`. Returns `{ skipped, version, prunedVersion }`. */
|
|
1050
1632
|
export async function snapshotMemory(dir, { retentionVersions } = {}) {
|
|
1051
1633
|
if (isMemoryOrSqliteHandle(dir)) {
|
|
1052
|
-
throw new Error("snapshotMemory only supports the flat-JSON backend (Backend A) — a
|
|
1634
|
+
throw new Error("snapshotMemory only supports the flat-JSON backend (Backend A) — a store handle has no on-disk graph.json to snapshot");
|
|
1053
1635
|
}
|
|
1054
1636
|
const graphFile = resolveMemoryGraphFile(dir);
|
|
1055
1637
|
let graphText;
|
|
@@ -1093,7 +1675,7 @@ export async function snapshotMemory(dir, { retentionVersions } = {}) {
|
|
|
1093
1675
|
return { skipped: false, version: v, prunedVersion };
|
|
1094
1676
|
}
|
|
1095
1677
|
|
|
1096
|
-
/** Load the memory graph for a repo dir OR a Backend B/C handle (see the
|
|
1678
|
+
/** Load the memory graph for a repo dir OR a Backend B/C/D handle (see the
|
|
1097
1679
|
* storage-backend seam above `createInMemoryStore`). A missing Backend-A
|
|
1098
1680
|
* store is the bootstrap: return the empty payload (uncached — the first
|
|
1099
1681
|
* append creates the file). The result is a raw entities payload;
|
|
@@ -1101,6 +1683,7 @@ export async function snapshotMemory(dir, { retentionVersions } = {}) {
|
|
|
1101
1683
|
export async function loadMemory(dir) {
|
|
1102
1684
|
if (isMemoryHandle(dir)) return migrateStoredMemory(dir.payload);
|
|
1103
1685
|
if (isSqliteHandle(dir)) return migrateStoredMemory(readSqlitePayload(dir));
|
|
1686
|
+
if (isRowHandle(dir)) return migrateStoredMemory(await readRowPayload(dir));
|
|
1104
1687
|
let text;
|
|
1105
1688
|
try {
|
|
1106
1689
|
text = await readFile(memoryGraphFile(dir), "utf8");
|
|
@@ -1299,11 +1882,13 @@ function migrateFactAssertionKeys(payload) {
|
|
|
1299
1882
|
}
|
|
1300
1883
|
|
|
1301
1884
|
/** Persist a mutated payload back to `dir`: an atomic file write (Backend A),
|
|
1302
|
-
* a no-op assignment (Backend B, already the live object),
|
|
1303
|
-
*
|
|
1885
|
+
* a no-op assignment (Backend B, already the live object), a diffed per-row
|
|
1886
|
+
* SQL write (Backend C, persistSqlitePayload), or a diffed row write into an
|
|
1887
|
+
* injected store (Backend D, persistRowPayload). */
|
|
1304
1888
|
async function persistMemory(dir, payload) {
|
|
1305
1889
|
if (isMemoryHandle(dir)) { dir.payload = payload; return; }
|
|
1306
1890
|
if (isSqliteHandle(dir)) { persistSqlitePayload(dir, payload); return; }
|
|
1891
|
+
if (isRowHandle(dir)) { await persistRowPayload(dir, payload); return; }
|
|
1307
1892
|
await mkdir(dirname(memoryGraphFile(dir)), { recursive: true });
|
|
1308
1893
|
await atomicWriteJson(memoryGraphFile(dir), payload);
|
|
1309
1894
|
}
|
|
@@ -1316,7 +1901,7 @@ async function persistMemory(dir, payload) {
|
|
|
1316
1901
|
export const SYLLOGISE_STATE_REL = join(MEMORY_DIR_REL, "syllogise-state.json");
|
|
1317
1902
|
const SQLITE_SYLLOGISE_STATE_KEY = "syllogiseState";
|
|
1318
1903
|
|
|
1319
|
-
/** Load the syllogise watermark for a repo dir OR a Backend B/C handle.
|
|
1904
|
+
/** Load the syllogise watermark for a repo dir OR a Backend B/C/D handle.
|
|
1320
1905
|
* Null when no complete pass has recorded one. */
|
|
1321
1906
|
export async function loadSyllogiseState(dir) {
|
|
1322
1907
|
if (isMemoryHandle(dir)) return dir.syllogiseState ? structuredClone(dir.syllogiseState) : null;
|
|
@@ -1324,6 +1909,7 @@ export async function loadSyllogiseState(dir) {
|
|
|
1324
1909
|
const row = dir.db.prepare("SELECT v FROM meta WHERE k = ?").get(SQLITE_SYLLOGISE_STATE_KEY);
|
|
1325
1910
|
return row?.v ? JSON.parse(row.v) : null;
|
|
1326
1911
|
}
|
|
1912
|
+
if (isRowHandle(dir)) return readRowMeta(dir, ROW_SYLLOGISE_STATE_KEY, null);
|
|
1327
1913
|
try {
|
|
1328
1914
|
return JSON.parse(await readFile(join(dir, SYLLOGISE_STATE_REL), "utf8"));
|
|
1329
1915
|
} catch (e) {
|
|
@@ -1333,13 +1919,17 @@ export async function loadSyllogiseState(dir) {
|
|
|
1333
1919
|
}
|
|
1334
1920
|
|
|
1335
1921
|
/** Persist the syllogise watermark — atomic file write (Backend A), a cloned
|
|
1336
|
-
* handle field (Backend B),
|
|
1922
|
+
* handle field (Backend B), a meta-table row (Backend C), or a meta value in
|
|
1923
|
+
* the injected store (Backend D). A watermark is one scalar whose worst race
|
|
1924
|
+
* costs a redundant re-syllogise, which is why it travels as meta rather than
|
|
1925
|
+
* as rows. */
|
|
1337
1926
|
export async function saveSyllogiseState(dir, state) {
|
|
1338
1927
|
if (isMemoryHandle(dir)) { dir.syllogiseState = structuredClone(state); return; }
|
|
1339
1928
|
if (isSqliteHandle(dir)) {
|
|
1340
1929
|
dir.db.prepare("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)").run(SQLITE_SYLLOGISE_STATE_KEY, JSON.stringify(state));
|
|
1341
1930
|
return;
|
|
1342
1931
|
}
|
|
1932
|
+
if (isRowHandle(dir)) { await dir.impl.putMeta(ROW_SYLLOGISE_STATE_KEY, JSON.stringify(state)); return; }
|
|
1343
1933
|
const file = join(dir, SYLLOGISE_STATE_REL);
|
|
1344
1934
|
await mkdir(dirname(file), { recursive: true });
|
|
1345
1935
|
await atomicWriteJson(file, state);
|
|
@@ -1361,6 +1951,7 @@ export async function loadNodeId(dir) {
|
|
|
1361
1951
|
const row = dir.db.prepare("SELECT v FROM meta WHERE k = ?").get(SQLITE_NODE_ID_KEY);
|
|
1362
1952
|
return row?.v ? JSON.parse(row.v).nodeId || null : null;
|
|
1363
1953
|
}
|
|
1954
|
+
if (isRowHandle(dir)) return (await readRowMeta(dir, ROW_NODE_ID_KEY, null))?.nodeId || null;
|
|
1364
1955
|
try {
|
|
1365
1956
|
return JSON.parse(await readFile(join(dir, NODE_ID_REL), "utf8")).nodeId || null;
|
|
1366
1957
|
} catch (e) {
|
|
@@ -1370,14 +1961,16 @@ export async function loadNodeId(dir) {
|
|
|
1370
1961
|
}
|
|
1371
1962
|
|
|
1372
1963
|
/** Record this store's node id — atomic file write (Backend A), a handle field
|
|
1373
|
-
* (Backend B),
|
|
1374
|
-
*
|
|
1964
|
+
* (Backend B), a meta-table row (Backend C), or a meta value in the injected
|
|
1965
|
+
* store (Backend D). Callers mint through resolveStoreNodeId, which never
|
|
1966
|
+
* overwrites an id a store already holds, so this value is written once. */
|
|
1375
1967
|
export async function saveNodeId(dir, nodeId) {
|
|
1376
1968
|
if (isMemoryHandle(dir)) { dir.nodeId = nodeId; return; }
|
|
1377
1969
|
if (isSqliteHandle(dir)) {
|
|
1378
1970
|
dir.db.prepare("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)").run(SQLITE_NODE_ID_KEY, JSON.stringify({ nodeId }));
|
|
1379
1971
|
return;
|
|
1380
1972
|
}
|
|
1973
|
+
if (isRowHandle(dir)) { await dir.impl.putMeta(ROW_NODE_ID_KEY, JSON.stringify({ nodeId })); return; }
|
|
1381
1974
|
const file = join(dir, NODE_ID_REL);
|
|
1382
1975
|
await mkdir(dirname(file), { recursive: true });
|
|
1383
1976
|
await atomicWriteJson(file, { nodeId });
|
|
@@ -2063,6 +2656,20 @@ function nextChainVersion(head) {
|
|
|
2063
2656
|
return deepest + 1;
|
|
2064
2657
|
}
|
|
2065
2658
|
|
|
2659
|
+
/** A write's extraction findings, deduped and codepoint-sorted. The sort is
|
|
2660
|
+
* what keeps the stored string a pure function of the finding SET: two stores
|
|
2661
|
+
* handed the same findings in different orders hold byte-identical records,
|
|
2662
|
+
* and the read-time union below reads the same either way. */
|
|
2663
|
+
function normalizeExtractionFindings(extraction) {
|
|
2664
|
+
if (!Array.isArray(extraction)) return [];
|
|
2665
|
+
const names = new Set();
|
|
2666
|
+
for (const raw of extraction) {
|
|
2667
|
+
const name = normText(raw);
|
|
2668
|
+
if (name) names.add(name);
|
|
2669
|
+
}
|
|
2670
|
+
return [...names].sort();
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2066
2673
|
/**
|
|
2067
2674
|
* Plan ONE source's assertion of one triple: the record it wants to write, plus
|
|
2068
2675
|
* the demotion that implies when the source is replacing its own earlier belief.
|
|
@@ -2078,7 +2685,7 @@ function nextChainVersion(head) {
|
|
|
2078
2685
|
* which is what keeps a re-seed and a duplicate mesh path idempotent.
|
|
2079
2686
|
*/
|
|
2080
2687
|
function planFactAssertion(payload, spec) {
|
|
2081
|
-
const { groupId, s, p, o, label, tokens, group, createdAt, observedAt, quantifier, environments } = spec;
|
|
2688
|
+
const { groupId, s, p, o, label, tokens, group, createdAt, observedAt, quantifier, environments, extraction = [] } = spec;
|
|
2082
2689
|
const recordId = `${groupId}@${group.sourceId}`;
|
|
2083
2690
|
const idx = memoryIndexOf(payload);
|
|
2084
2691
|
const head = idx ? idx.individualsById.get(recordId) : payload.individuals.find((x) => x?.id === recordId);
|
|
@@ -2092,17 +2699,24 @@ function planFactAssertion(payload, spec) {
|
|
|
2092
2699
|
let observedAtVal = observedAt;
|
|
2093
2700
|
let supersedes = [];
|
|
2094
2701
|
let quantifierVal = quantifier;
|
|
2702
|
+
let extractionVal = extraction;
|
|
2095
2703
|
|
|
2096
2704
|
if (head) {
|
|
2097
2705
|
const current = { assertedAt: embeddedTagTimestamp(headTags), observedAt: headAttr(OBSERVED_AT_PROP) };
|
|
2098
2706
|
if (supersedesPriorAssertion(incoming, current)) {
|
|
2099
2707
|
demote = { head, id: `${recordId}#v${nextChainVersion(head)}` };
|
|
2100
2708
|
supersedes = [demote.id];
|
|
2709
|
+
// A fresh belief is read fresh: the new head carries only the findings
|
|
2710
|
+
// this write recorded, and the demoted leaf keeps its own.
|
|
2101
2711
|
} else {
|
|
2102
2712
|
tags = [...new Set([...headTags, ...group.tags])];
|
|
2103
2713
|
createdAtVal = headAttr(CREATED_AT_PROP) || createdAtVal;
|
|
2104
2714
|
observedAtVal = observedAt || headAttr(OBSERVED_AT_PROP);
|
|
2105
2715
|
supersedes = headAttr(SUPERSEDES_PROP).split(" ").filter(Boolean);
|
|
2716
|
+
// The same source saying the same thing again unions its findings on,
|
|
2717
|
+
// exactly as its tags union: a re-delivery never erases how the first
|
|
2718
|
+
// reading of this assertion went.
|
|
2719
|
+
extractionVal = normalizeExtractionFindings([...headAttr(EXTRACTION_FINDING_PROP).split(" "), ...extraction]);
|
|
2106
2720
|
}
|
|
2107
2721
|
// A re-assert carrying no quantifier never SILENTLY erases one already
|
|
2108
2722
|
// recorded — the same first-write-wins discipline createdAt keeps.
|
|
@@ -2121,6 +2735,7 @@ function planFactAssertion(payload, spec) {
|
|
|
2121
2735
|
{ prop: SOURCE_ID_PROP, key: "sourceId", value: group.sourceId },
|
|
2122
2736
|
...(tags.length ? [{ prop: "mgx:factProvenance", key: "provenance", value: tags.join(" | ") }] : []),
|
|
2123
2737
|
...(observedAtVal ? [{ prop: OBSERVED_AT_PROP, key: "observedAt", value: observedAtVal }] : []),
|
|
2738
|
+
...(extractionVal.length ? [{ prop: EXTRACTION_FINDING_PROP, key: "extraction", value: extractionVal.join(" ") }] : []),
|
|
2124
2739
|
...(tokens.length ? [{ prop: "mgx:hasProseTokens", key: "prose_tokens", value: tokens.join(" ") }] : []),
|
|
2125
2740
|
...(quantifierVal ? [{ prop: "mgx:factQuantifier", key: "quantifier", value: quantifierVal }] : []),
|
|
2126
2741
|
...(environments ? [{ prop: "mgx:factJustification", key: "justification", value: environments.map((e) => e.join(" ")).join(" | ") }] : []),
|
|
@@ -2309,9 +2924,12 @@ function compactFactGroup(payload, groupId) {
|
|
|
2309
2924
|
* source's own lineage, never a duplicate. `premiseTrusts`/`ruleConfidence`
|
|
2310
2925
|
* optionally engage trust.mjs's entailed hook; `observedAt` records when the
|
|
2311
2926
|
* asserting party WITNESSED the claim, which is not when this store heard it.
|
|
2312
|
-
*
|
|
2313
|
-
*
|
|
2314
|
-
|
|
2927
|
+
* `extraction` is the closed-vocabulary finding list saying how the extractor
|
|
2928
|
+
* read the sentence this assertion came from, recorded on the record rather
|
|
2929
|
+
* than the triple. Validated against ontology/memory-shapes.ttl
|
|
2930
|
+
* (memory/shacl.mjs) before the write. Returns { id } — the group id, the
|
|
2931
|
+
* public fact id every reader uses. */
|
|
2932
|
+
export async function appendFact(dir, { subject, predicate, object, provenance = "", createdAt = "", observedAt = "", quantifier = "", extraction, premiseTrusts, ruleConfidence } = {}) {
|
|
2315
2933
|
const s = normFactTerm(subject);
|
|
2316
2934
|
const p = normFactPredicate(predicate);
|
|
2317
2935
|
const o = normFactTerm(object);
|
|
@@ -2320,6 +2938,7 @@ export async function appendFact(dir, { subject, predicate, object, provenance =
|
|
|
2320
2938
|
const text = `${s} ${p} ${o}`;
|
|
2321
2939
|
const tokens = proseTokensFor({ doc: text });
|
|
2322
2940
|
const q = normText(quantifier);
|
|
2941
|
+
const findings = normalizeExtractionFindings(extraction);
|
|
2323
2942
|
await mutateMemory(dir, async (payload) => {
|
|
2324
2943
|
const groups = assertionGroupsFor(payload, groupId, normText(provenance), createdAt);
|
|
2325
2944
|
for (const id of groups.length ? [] : restateFactGroup(payload, groupId, { quantifier: q })) {
|
|
@@ -2328,6 +2947,7 @@ export async function appendFact(dir, { subject, predicate, object, provenance =
|
|
|
2328
2947
|
for (const group of groups) {
|
|
2329
2948
|
const plan = planFactAssertion(payload, {
|
|
2330
2949
|
groupId, s, p, o, label: labelOf(text), tokens, group, createdAt, observedAt, quantifier: q,
|
|
2950
|
+
extraction: findings,
|
|
2331
2951
|
});
|
|
2332
2952
|
await assertIndividualValid(plan.candidate); // the SHACL gate -- throws, never writes, on a violation
|
|
2333
2953
|
for (const id of applyFactAssertion(payload, plan)) {
|
|
@@ -2375,8 +2995,9 @@ function normalizeJustificationEnvironments(justification) {
|
|
|
2375
2995
|
* not thrown. Optional per-fact `premiseTrusts`/`ruleConfidence` (batched
|
|
2376
2996
|
* entailed-hook passthrough) and `justification` (premise fact ids — a flat
|
|
2377
2997
|
* list, or a list of lists for multiple independent derivations — stored as
|
|
2378
|
-
* mgx:factJustification's ' | '-separated environments, last-write-wins)
|
|
2379
|
-
*
|
|
2998
|
+
* mgx:factJustification's ' | '-separated environments, last-write-wins), and
|
|
2999
|
+
* optional per-fact `extraction` (appendFact's finding list, same per-assertion
|
|
3000
|
+
* scoping). Returns { ids, appended, skipped }. */
|
|
2380
3001
|
export async function appendFacts(dir, facts) {
|
|
2381
3002
|
const prepared = [];
|
|
2382
3003
|
let skipped = 0;
|
|
@@ -2394,6 +3015,7 @@ export async function appendFacts(dir, facts) {
|
|
|
2394
3015
|
createdAt: f?.createdAt || "",
|
|
2395
3016
|
observedAt: f?.observedAt || "",
|
|
2396
3017
|
quantifier: normText(f?.quantifier),
|
|
3018
|
+
extraction: normalizeExtractionFindings(f?.extraction),
|
|
2397
3019
|
premiseTrusts: Array.isArray(f?.premiseTrusts) ? f.premiseTrusts : undefined,
|
|
2398
3020
|
ruleConfidence: typeof f?.ruleConfidence === "number" ? f.ruleConfidence : undefined,
|
|
2399
3021
|
environments: normalizeJustificationEnvironments(f?.justification),
|
|
@@ -2419,7 +3041,7 @@ export async function appendFacts(dir, facts) {
|
|
|
2419
3041
|
const plan = planFactAssertion(payload, {
|
|
2420
3042
|
groupId: f.id, s: f.s, p: f.p, o: f.o, label: labelOf(f.text), tokens: f.tokens,
|
|
2421
3043
|
group, createdAt: f.createdAt, observedAt: f.observedAt, quantifier: f.quantifier,
|
|
2422
|
-
environments: f.environments,
|
|
3044
|
+
environments: f.environments, extraction: f.extraction,
|
|
2423
3045
|
});
|
|
2424
3046
|
for (const id of applyFactAssertion(payload, plan)) {
|
|
2425
3047
|
if (seen.has(id)) continue;
|
|
@@ -2848,6 +3470,11 @@ export async function resolveRelationChaseReverse(memory, name, objectTerm, help
|
|
|
2848
3470
|
* the per-record hop list, for a reader that wants to see WHICH source said it
|
|
2849
3471
|
* and when rather than one blended number.
|
|
2850
3472
|
*
|
|
3473
|
+
* `extraction` joins both levels when any assertion recorded a finding: the
|
|
3474
|
+
* row's union for a consumer deciding whether to lean on the triple at all,
|
|
3475
|
+
* each hop's own list for one that needs to know which reading produced it.
|
|
3476
|
+
* Absent — never empty — when nothing was recorded.
|
|
3477
|
+
*
|
|
2851
3478
|
* The fold reads live HEADS only. A record its own source has since superseded
|
|
2852
3479
|
* is that source's PAST belief, not a second vote for the present one; folding
|
|
2853
3480
|
* it back in would let one source's edit history inflate its own corroboration.
|
|
@@ -2961,6 +3588,7 @@ function foldFactGroup(id, heads, ctx) {
|
|
|
2961
3588
|
const sourceIds = [];
|
|
2962
3589
|
const sourceTypes = [];
|
|
2963
3590
|
const tags = new Set();
|
|
3591
|
+
const findings = new Set();
|
|
2964
3592
|
const environments = [];
|
|
2965
3593
|
const seenEnvironment = new Set();
|
|
2966
3594
|
let quantifier = "";
|
|
@@ -3008,11 +3636,14 @@ function foldFactGroup(id, heads, ctx) {
|
|
|
3008
3636
|
}
|
|
3009
3637
|
const createdAt = attrOf(head, CREATED_AT_PROP);
|
|
3010
3638
|
const observedAt = attrOf(head, OBSERVED_AT_PROP);
|
|
3639
|
+
const extraction = attrOf(head, EXTRACTION_FINDING_PROP).split(" ").filter(Boolean);
|
|
3640
|
+
for (const finding of extraction) findings.add(finding);
|
|
3011
3641
|
assertions.push({
|
|
3012
3642
|
id: head.id, sourceId, sourceType,
|
|
3013
3643
|
provenance: headTags.join(" | "),
|
|
3014
3644
|
createdAt,
|
|
3015
3645
|
...(observedAt ? { observedAt } : {}),
|
|
3646
|
+
...(extraction.length ? { extraction } : {}),
|
|
3016
3647
|
ownTrust: Number(attrOf(head, TRUST_SCORE_PROP)) || 0,
|
|
3017
3648
|
assertedAt: assertionTimestampFor(headTags, createdAt),
|
|
3018
3649
|
});
|
|
@@ -3045,6 +3676,12 @@ function foldFactGroup(id, heads, ctx) {
|
|
|
3045
3676
|
provenance: [...tags].sort().join(" | "),
|
|
3046
3677
|
quantifier, // "" unless a plural class-membership teach set one
|
|
3047
3678
|
sourceIds, sourceTypes,
|
|
3679
|
+
// Every finding any live assertion of this triple carries, unioned the same
|
|
3680
|
+
// way the provenance tags above are, and ABSENT when there are none. A
|
|
3681
|
+
// consumer that needs to know which source read it that way reads the
|
|
3682
|
+
// per-assertion `extraction` in the hop list instead. Absence means no
|
|
3683
|
+
// findings were recorded — never that the sentence read cleanly.
|
|
3684
|
+
...(findings.size ? { extraction: [...findings].sort() } : {}),
|
|
3048
3685
|
// `environments`: every persisted premise set (empty unless entailed);
|
|
3049
3686
|
// `justification`: their deduped union in first-occurrence order, for
|
|
3050
3687
|
// readers that only need "which premises does this fact cite at all".
|