@polycode-projects/the-mechanical-code-talker 5.0.46 → 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.
- package/package.json +14 -2
- package/src/adapters/memory/backends-exports.mjs +8 -0
- package/src/adapters/memory/core.mjs +291 -30
- 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/research-queue-store.mjs +215 -32
- package/src/domain/fact-phrase.mjs +40 -0
- package/src/domain/phrase-exports.mjs +4 -0
- package/src/domain/retrieval-plan.mjs +224 -0
- package/src/services/chat-session.mjs +23 -7
- 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 +361 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +127 -127
- 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
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// rows.mjs — the row projection: a memory payload out to wire rows and back.
|
|
2
|
+
// One module owns the whole mapping, so every backend that stores rows
|
|
3
|
+
// (in-memory, sqlite, a consumer's own key-value store) writes the same shape
|
|
4
|
+
// and reads back the same payload.
|
|
5
|
+
//
|
|
6
|
+
// What stores and what does not:
|
|
7
|
+
//
|
|
8
|
+
// - `individuals` project one row each, carrying their `ord` so a store can
|
|
9
|
+
// rebuild the array in the order it was written;
|
|
10
|
+
// - `objectProperties` project one `edge-group` row per prop, examples in
|
|
11
|
+
// stored order (that order is recency — an updated edge moves to the end);
|
|
12
|
+
// - `memory` and `prefixes` are the two true scalars, and travel as meta;
|
|
13
|
+
// - `classes`, `vocabulary`, `proseIndex` and `generated_at` are derived, so
|
|
14
|
+
// assembly recomputes them and no row ever carries them. A large store's
|
|
15
|
+
// prose index serialized whole would dwarf the per-row cap on its own.
|
|
16
|
+
//
|
|
17
|
+
// Assembly is a pure function of the row set. Order rides row content — the
|
|
18
|
+
// `ord` in each row's json, then the row key as the tie-break — so a backend
|
|
19
|
+
// handing the same rows back in a different order builds the same payload.
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
emptyMemory,
|
|
23
|
+
FACT_CLASS, SOURCE_CLASS, UTTERANCE_CLASS, MEMORY_SESSION_CLASS, RULE_CLASS, RETRACTION_CLASS,
|
|
24
|
+
} from "./core.mjs";
|
|
25
|
+
import { normFactTerm } from "../../domain/hash.mjs";
|
|
26
|
+
import { buildProseIndex } from "../../domain/prose.mjs";
|
|
27
|
+
import {
|
|
28
|
+
BackendRejected, BOOKKEEPING_ROW_CLASS, MAX_ROW_BYTES, assertValidRow, rowJsonBytes,
|
|
29
|
+
} from "./row-backend.mjs";
|
|
30
|
+
|
|
31
|
+
const EDGE_GROUP_ROW_CLASS = "edge-group";
|
|
32
|
+
const EDGE_GROUP_KEY_PREFIX = "edge-group:";
|
|
33
|
+
const BOOKKEEPING_KEY_PREFIX = "bookkeeping:";
|
|
34
|
+
|
|
35
|
+
const SUPERSEDES_PROP = "mgx:supersedes";
|
|
36
|
+
const SUPERSEDED_BY_PROP = "mgx:supersededBy";
|
|
37
|
+
const PROVENANCE_PROP = "mgx:factProvenance";
|
|
38
|
+
const UTTERANCE_TS_PROP = "mgx:utteranceTs";
|
|
39
|
+
|
|
40
|
+
/** The two internal row kinds that stay out of meta: each entry is its own row,
|
|
41
|
+
* so concurrent turns append to the queue instead of racing a read-modify-write
|
|
42
|
+
* over one shared value. */
|
|
43
|
+
export const BOOKKEEPING_RESEARCH_QUEUE = "research-queue";
|
|
44
|
+
export const BOOKKEEPING_RESEARCHED_TERM = "researched-term";
|
|
45
|
+
|
|
46
|
+
const attrValue = (ind, prop) => (ind?.attributes || []).find((a) => a?.prop === prop)?.value || "";
|
|
47
|
+
const attrByKey = (ind, key) => (ind?.attributes || []).find((a) => a?.key === key)?.value || "";
|
|
48
|
+
|
|
49
|
+
// Built on first use rather than at module load: core.mjs imports this module,
|
|
50
|
+
// so its exported constants are still in their temporal dead zone while this
|
|
51
|
+
// file's own body runs.
|
|
52
|
+
let rowClassByIndividualClass = null;
|
|
53
|
+
function individualRowClasses() {
|
|
54
|
+
if (!rowClassByIndividualClass) {
|
|
55
|
+
rowClassByIndividualClass = new Map([
|
|
56
|
+
[FACT_CLASS, "fact"],
|
|
57
|
+
[SOURCE_CLASS, "source"],
|
|
58
|
+
[UTTERANCE_CLASS, "utterance"],
|
|
59
|
+
[MEMORY_SESSION_CLASS, "session"],
|
|
60
|
+
[RULE_CLASS, "rule"],
|
|
61
|
+
[RETRACTION_CLASS, "retraction"],
|
|
62
|
+
]);
|
|
63
|
+
}
|
|
64
|
+
return rowClassByIndividualClass;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The row class one individual projects onto. An individual whose class is
|
|
68
|
+
* outside the closed set has no honest row to land in, so it is refused here
|
|
69
|
+
* rather than stored under a class that read paths would misread. */
|
|
70
|
+
function rowClassForIndividual(ind) {
|
|
71
|
+
const rowClass = individualRowClasses().get(ind?.class);
|
|
72
|
+
if (rowClass) return rowClass;
|
|
73
|
+
throw new BackendRejected(
|
|
74
|
+
`individual ${JSON.stringify(ind?.id ?? null)} has class ${JSON.stringify(ind?.class ?? null)}, which no row class covers`,
|
|
75
|
+
{ rowKey: String(ind?.id || "") },
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A fact record's stored form: everything it holds except the backward
|
|
80
|
+
* supersession pointer. Only the forward `supersedes` list is stored, so a
|
|
81
|
+
* second supersession writes its own new row and never rewrites this one —
|
|
82
|
+
* two writers can only lose a write when they share a row key. Assembly
|
|
83
|
+
* derives the backward pointer again from the forward ones. */
|
|
84
|
+
function storedIndividualForm(ind) {
|
|
85
|
+
if (!(ind?.attributes || []).some((a) => a?.prop === SUPERSEDED_BY_PROP)) return ind;
|
|
86
|
+
return { ...ind, attributes: ind.attributes.filter((a) => a?.prop !== SUPERSEDED_BY_PROP) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The ord each row key carries. An existing key keeps the ord it already had
|
|
90
|
+
* and a new one takes the next free number, matching how a store keeps a row's
|
|
91
|
+
* sort position across an update. Without prior rows the ords are the payload's
|
|
92
|
+
* own array order. */
|
|
93
|
+
function ordAssigner(priorRows) {
|
|
94
|
+
const priorOrds = new Map();
|
|
95
|
+
let next = 0;
|
|
96
|
+
for (const row of priorRows || []) {
|
|
97
|
+
let ord;
|
|
98
|
+
try { ord = Number(JSON.parse(row?.json ?? "{}").ord); } catch { ord = NaN; }
|
|
99
|
+
if (!Number.isFinite(ord)) continue;
|
|
100
|
+
priorOrds.set(row.rowKey, ord);
|
|
101
|
+
if (ord >= next) next = ord + 1;
|
|
102
|
+
}
|
|
103
|
+
return (rowKey) => {
|
|
104
|
+
const prior = priorOrds.get(rowKey);
|
|
105
|
+
if (prior !== undefined) return prior;
|
|
106
|
+
const ord = next;
|
|
107
|
+
next += 1;
|
|
108
|
+
return ord;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Refuse or drop an oversized row. The default posture throws: one fact that
|
|
113
|
+
* big is an extraction pathology and the turn should fail loudly, naming the
|
|
114
|
+
* provenance that produced it. A consumer whose turn is itself the last resort
|
|
115
|
+
* passes `onOversizedRow: "drop"` instead, and the turn completes with
|
|
116
|
+
* everything else persisted. */
|
|
117
|
+
function admitRow(row, provenance, { onOversizedRow, log }) {
|
|
118
|
+
const bytes = rowJsonBytes(row);
|
|
119
|
+
if (bytes <= MAX_ROW_BYTES) return true;
|
|
120
|
+
const where = provenance ? ` (provenance: ${provenance})` : "";
|
|
121
|
+
const detail = `${row.rowClass} row ${row.rowKey} serializes to ${bytes} bytes, over the ${MAX_ROW_BYTES}-byte cap${where}`;
|
|
122
|
+
if (onOversizedRow === "drop") {
|
|
123
|
+
log(`dropped an oversized memory row: ${detail}`);
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
throw new BackendRejected(detail, { rowKey: row.rowKey, rowClass: row.rowClass, provenance });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const warnToConsole = (message) => console.warn(message);
|
|
130
|
+
|
|
131
|
+
/** Project a memory payload into wire rows.
|
|
132
|
+
*
|
|
133
|
+
* `priorRows` are the rows this payload was last projected as; pass them and
|
|
134
|
+
* every unchanged row comes back byte-identical, so `diffRows` writes only
|
|
135
|
+
* what actually moved. `onOversizedRow` is "throw" (default) or "drop", and
|
|
136
|
+
* `log` takes the drop notices. */
|
|
137
|
+
export function payloadToRows(payload, { priorRows = null, onOversizedRow = "throw", log = warnToConsole } = {}) {
|
|
138
|
+
if (onOversizedRow !== "throw" && onOversizedRow !== "drop") {
|
|
139
|
+
throw new TypeError(`onOversizedRow must be "throw" or "drop", got ${JSON.stringify(onOversizedRow)}`);
|
|
140
|
+
}
|
|
141
|
+
const ordFor = ordAssigner(priorRows);
|
|
142
|
+
const posture = { onOversizedRow, log };
|
|
143
|
+
const rows = [];
|
|
144
|
+
|
|
145
|
+
for (const ind of payload?.individuals || []) {
|
|
146
|
+
if (!ind?.id) continue;
|
|
147
|
+
const rowClass = rowClassForIndividual(ind);
|
|
148
|
+
const row = {
|
|
149
|
+
rowKey: String(ind.id),
|
|
150
|
+
rowClass,
|
|
151
|
+
term: rowClass === "fact" ? normFactTerm(attrByKey(ind, "subject")) : "",
|
|
152
|
+
json: JSON.stringify({ ord: ordFor(String(ind.id)), individual: storedIndividualForm(ind) }),
|
|
153
|
+
};
|
|
154
|
+
if (admitRow(row, attrValue(ind, PROVENANCE_PROP), posture)) rows.push(row);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
for (const group of payload?.objectProperties || []) {
|
|
158
|
+
if (!group?.prop) continue;
|
|
159
|
+
const rowKey = `${EDGE_GROUP_KEY_PREFIX}${group.prop}`;
|
|
160
|
+
const row = {
|
|
161
|
+
rowKey,
|
|
162
|
+
rowClass: EDGE_GROUP_ROW_CLASS,
|
|
163
|
+
term: "",
|
|
164
|
+
json: JSON.stringify({ ord: ordFor(rowKey), group }),
|
|
165
|
+
};
|
|
166
|
+
if (admitRow(row, "", posture)) rows.push(row);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return rows;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The two scalars that travel as meta rather than as rows. */
|
|
173
|
+
export function payloadMeta(payload) {
|
|
174
|
+
const empty = emptyMemory();
|
|
175
|
+
return {
|
|
176
|
+
memory: payload?.memory ?? empty.memory,
|
|
177
|
+
prefixes: payload?.prefixes ?? empty.prefixes,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const byOrdThenRowKey = (a, b) => (
|
|
182
|
+
a.ord - b.ord || (a.rowKey < b.rowKey ? -1 : a.rowKey > b.rowKey ? 1 : 0)
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
/** Sort the Fact individuals by their content-addressed ids, in place and in
|
|
186
|
+
* their own slots, so two writers holding one fact set fold it in the same
|
|
187
|
+
* order however their rows arrived. Codepoint order, never localeCompare —
|
|
188
|
+
* the whole point is that two locales land on the same order. */
|
|
189
|
+
function sortFactIndividualsById(individuals) {
|
|
190
|
+
const slots = [];
|
|
191
|
+
const facts = [];
|
|
192
|
+
for (let i = 0; i < individuals.length; i += 1) {
|
|
193
|
+
if (individuals[i]?.class !== FACT_CLASS) continue;
|
|
194
|
+
slots.push(i);
|
|
195
|
+
facts.push(individuals[i]);
|
|
196
|
+
}
|
|
197
|
+
facts.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
198
|
+
for (let i = 0; i < slots.length; i += 1) individuals[slots[i]] = facts[i];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Re-derive each record's backward supersession pointer from the union of the
|
|
202
|
+
* forward ones. Two turns that superseded the same record concurrently both
|
|
203
|
+
* land, because each wrote its own row and neither touched the record they
|
|
204
|
+
* replaced. */
|
|
205
|
+
function applyDerivedSupersessions(individuals) {
|
|
206
|
+
const successorsById = new Map();
|
|
207
|
+
for (const ind of individuals) {
|
|
208
|
+
if (ind?.class !== FACT_CLASS) continue;
|
|
209
|
+
for (const replaced of attrValue(ind, SUPERSEDES_PROP).split(" ").filter(Boolean)) {
|
|
210
|
+
const successors = successorsById.get(replaced) || new Set();
|
|
211
|
+
successors.add(ind.id);
|
|
212
|
+
successorsById.set(replaced, successors);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
for (const ind of individuals) {
|
|
216
|
+
const successors = successorsById.get(ind?.id);
|
|
217
|
+
if (!successors) continue;
|
|
218
|
+
ind.attributes = [
|
|
219
|
+
...(ind.attributes || []).filter((a) => a?.prop !== SUPERSEDED_BY_PROP),
|
|
220
|
+
{ prop: SUPERSEDED_BY_PROP, key: "supersededBy", value: [...successors].sort().join(" ") },
|
|
221
|
+
];
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Recount `classes[]` from the assembled individuals, the same count-and-
|
|
226
|
+
* sample shape the store keeps. */
|
|
227
|
+
function recountedClasses(individuals) {
|
|
228
|
+
const classes = [];
|
|
229
|
+
for (const name of [MEMORY_SESSION_CLASS, UTTERANCE_CLASS, FACT_CLASS, SOURCE_CLASS, RULE_CLASS]) {
|
|
230
|
+
const of = individuals.filter((i) => i?.class === name);
|
|
231
|
+
if (of.length) classes.push({ name, count: of.length, sample: of.slice(0, 3).map((i) => i.label) });
|
|
232
|
+
}
|
|
233
|
+
return classes;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** The store's `generated_at`: the latest utterance timestamp it holds, which
|
|
237
|
+
* is the same value the write path raises it to. */
|
|
238
|
+
function latestUtteranceTimestamp(individuals) {
|
|
239
|
+
let latest = "";
|
|
240
|
+
for (const ind of individuals) {
|
|
241
|
+
if (ind?.class !== UTTERANCE_CLASS) continue;
|
|
242
|
+
const ts = attrValue(ind, UTTERANCE_TS_PROP);
|
|
243
|
+
if (ts > latest) latest = ts;
|
|
244
|
+
}
|
|
245
|
+
return latest;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Assemble a memory payload from a row set. `meta` carries the two stored
|
|
249
|
+
* scalars; without it the payload takes the empty store's own values.
|
|
250
|
+
* Bookkeeping rows are excluded by field: they round-trip through the store
|
|
251
|
+
* but never reach an answer. */
|
|
252
|
+
export function rowsToPayload(rows, { meta = null } = {}) {
|
|
253
|
+
const payload = emptyMemory();
|
|
254
|
+
if (meta?.memory !== undefined) payload.memory = meta.memory;
|
|
255
|
+
if (meta?.prefixes !== undefined) payload.prefixes = meta.prefixes;
|
|
256
|
+
|
|
257
|
+
const individualEntries = [];
|
|
258
|
+
const groupEntries = [];
|
|
259
|
+
for (const row of rows || []) {
|
|
260
|
+
if (!row || row.rowClass === BOOKKEEPING_ROW_CLASS) continue;
|
|
261
|
+
const record = JSON.parse(row.json);
|
|
262
|
+
const ord = Number.isFinite(Number(record?.ord)) ? Number(record.ord) : 0;
|
|
263
|
+
const entry = { ord, rowKey: String(row.rowKey || "") };
|
|
264
|
+
if (row.rowClass === EDGE_GROUP_ROW_CLASS) groupEntries.push({ ...entry, group: record?.group });
|
|
265
|
+
else individualEntries.push({ ...entry, individual: record?.individual });
|
|
266
|
+
}
|
|
267
|
+
individualEntries.sort(byOrdThenRowKey);
|
|
268
|
+
groupEntries.sort(byOrdThenRowKey);
|
|
269
|
+
|
|
270
|
+
const individuals = individualEntries.map((e) => e.individual).filter(Boolean);
|
|
271
|
+
sortFactIndividualsById(individuals);
|
|
272
|
+
applyDerivedSupersessions(individuals);
|
|
273
|
+
|
|
274
|
+
payload.individuals = individuals;
|
|
275
|
+
payload.objectProperties = groupEntries.map((e) => e.group).filter(Boolean);
|
|
276
|
+
payload.classes = recountedClasses(individuals);
|
|
277
|
+
payload.proseIndex = buildProseIndex(individuals);
|
|
278
|
+
payload.generated_at = latestUtteranceTimestamp(individuals);
|
|
279
|
+
return payload;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The rows to write and the row keys to delete to turn `before` into `after`.
|
|
283
|
+
* A row whose stored bytes did not change is not in either list, so a store
|
|
284
|
+
* pays only for what actually moved. */
|
|
285
|
+
export function diffRows(before, after) {
|
|
286
|
+
const beforeByKey = new Map((before || []).filter((r) => r?.rowKey).map((r) => [r.rowKey, r]));
|
|
287
|
+
const puts = [];
|
|
288
|
+
const kept = new Set();
|
|
289
|
+
for (const row of after || []) {
|
|
290
|
+
if (!row?.rowKey) continue;
|
|
291
|
+
kept.add(row.rowKey);
|
|
292
|
+
const prior = beforeByKey.get(row.rowKey);
|
|
293
|
+
const unchanged = prior
|
|
294
|
+
&& prior.json === row.json
|
|
295
|
+
&& prior.term === row.term
|
|
296
|
+
&& prior.rowClass === row.rowClass;
|
|
297
|
+
if (!unchanged) puts.push(row);
|
|
298
|
+
}
|
|
299
|
+
const deletes = [...beforeByKey.keys()].filter((key) => !kept.has(key));
|
|
300
|
+
return { puts, deletes };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** One internal entry as its own row: a research-queue item, a researched-term
|
|
304
|
+
* marker, anything that must never compose into a visitor-facing answer. */
|
|
305
|
+
export function bookkeepingRow(kind, key, value) {
|
|
306
|
+
const rowKey = `${BOOKKEEPING_KEY_PREFIX}${kind}:${key}`;
|
|
307
|
+
return assertValidRow({
|
|
308
|
+
rowKey,
|
|
309
|
+
rowClass: BOOKKEEPING_ROW_CLASS,
|
|
310
|
+
term: "",
|
|
311
|
+
json: JSON.stringify({ kind, key, value }),
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** The bookkeeping entries a row set holds, in row-key order. `kind` narrows to
|
|
316
|
+
* one family; omit it for all of them. */
|
|
317
|
+
export function bookkeepingEntries(rows, kind = "") {
|
|
318
|
+
const entries = [];
|
|
319
|
+
for (const row of rows || []) {
|
|
320
|
+
if (row?.rowClass !== BOOKKEEPING_ROW_CLASS) continue;
|
|
321
|
+
let record;
|
|
322
|
+
try { record = JSON.parse(row.json); } catch { continue; }
|
|
323
|
+
if (kind && record?.kind !== kind) continue;
|
|
324
|
+
entries.push({ rowKey: row.rowKey, kind: record?.kind || "", key: record?.key || "", value: record?.value });
|
|
325
|
+
}
|
|
326
|
+
entries.sort((a, b) => (a.rowKey < b.rowKey ? -1 : a.rowKey > b.rowKey ? 1 : 0));
|
|
327
|
+
return entries;
|
|
328
|
+
}
|
|
@@ -6,6 +6,20 @@
|
|
|
6
6
|
// only fires on genuine malformation, never a sparse-but-valid write.
|
|
7
7
|
|
|
8
8
|
const MEMORY_CLASSES = new Set(["Utterance", "Fact", "Session", "Source", "Rule"]);
|
|
9
|
+
|
|
10
|
+
// The closed vocabulary of structural findings an assertion record may carry —
|
|
11
|
+
// what the extractor observed about how it read the sentence, never a score.
|
|
12
|
+
// Only the findings that are KEPT live here: a decline reason names a candidate
|
|
13
|
+
// that was never stored, so it has no record to ride. A consumer declines by
|
|
14
|
+
// name, which is only testable on both sides of the seam if the names are a
|
|
15
|
+
// closed set, so an unlisted one is a violation rather than a pass-through.
|
|
16
|
+
export const EXTRACTION_FINDINGS = Object.freeze([
|
|
17
|
+
"identifier-token", // an endpoint's raw surface was an identifier, not a word
|
|
18
|
+
"clause-fallback", // the row grounded from a clause fragment after the whole sentence declined
|
|
19
|
+
"pronoun-carry", // the subject was substituted from the paragraph's pronoun carry
|
|
20
|
+
"definitional-frame", // the row came from a definitional copula frame ("X is the name for Y")
|
|
21
|
+
]);
|
|
22
|
+
const EXTRACTION_FINDING_SET = new Set(EXTRACTION_FINDINGS);
|
|
9
23
|
const RULE_KINDS = new Set([
|
|
10
24
|
"compose2", "filter", "recursive",
|
|
11
25
|
"action-signature", "action-precond", "action-effect", "action-constraint",
|
|
@@ -99,6 +113,16 @@ function checkFact(ind, violations) {
|
|
|
99
113
|
if (observedAt !== undefined && !Number.isFinite(Date.parse(observedAt))) {
|
|
100
114
|
violations.push(`mgx:observedAt, when present, must be a parseable instant (got ${JSON.stringify(observedAt)})`);
|
|
101
115
|
}
|
|
116
|
+
const extraction = attrValue(ind, "mgx:extractionFinding");
|
|
117
|
+
if (extraction !== undefined) {
|
|
118
|
+
const found = extraction.split(" ").filter(Boolean);
|
|
119
|
+
if (!found.length) violations.push("mgx:extractionFinding, when present, must name at least one finding");
|
|
120
|
+
for (const finding of found) {
|
|
121
|
+
if (!EXTRACTION_FINDING_SET.has(finding)) {
|
|
122
|
+
violations.push(`mgx:extractionFinding must name findings from the closed vocabulary ${EXTRACTION_FINDINGS.join(" | ")} (got ${JSON.stringify(finding)})`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
102
126
|
for (const prop of SUPERSESSION_LINK_PROPS) {
|
|
103
127
|
const links = attrValue(ind, prop);
|
|
104
128
|
if (links === undefined) continue; // absent, never empty, until a chain's first supersession
|
|
@@ -1,33 +1,55 @@
|
|
|
1
|
-
// research-queue-store.mjs — persists the "research <topic>" queue
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// across process restarts. The file is per-repo and machine-local (.tmct/ is
|
|
6
|
-
// gitignored), exactly like the graph/sqlite store it sits next to.
|
|
1
|
+
// research-queue-store.mjs — persists the "research <topic>" queue, and the
|
|
2
|
+
// researched-terms set a consumer dedups against, so a run started in one
|
|
3
|
+
// session resumes in the next: "research next" steps the queue, "research
|
|
4
|
+
// status" reports it, "research stop" clears it, all across process restarts.
|
|
7
5
|
//
|
|
8
6
|
// The seam is the memoryDir backend token runTurn already carries:
|
|
9
7
|
// - a repo-path string (Backend A): the queue file is <repo>/.tmct/…;
|
|
10
8
|
// - a sqlite handle carrying dbPath (Backend C, the CLI default): the queue
|
|
11
9
|
// file is the dbPath's .tmct/ sibling;
|
|
12
|
-
// -
|
|
13
|
-
//
|
|
10
|
+
// - a row backend (Backend D): one bookkeeping row per queue entry;
|
|
11
|
+
// - an in-memory handle (Backend B) or null (the browser session): no path
|
|
12
|
+
// and no store, so persistence is a silent no-op and the in-page queue
|
|
13
|
+
// behaves as before.
|
|
14
|
+
//
|
|
15
|
+
// The row path stores ENTRIES, never one blob: each queued, done or skipped
|
|
16
|
+
// title is its own row carrying its own status. Two turns that step the queue
|
|
17
|
+
// at the same time write different rows and both land, where a single shared
|
|
18
|
+
// value would have made the second write erase the first. A row class of
|
|
19
|
+
// `bookkeeping` is what keeps every one of these out of an answer: read paths
|
|
20
|
+
// exclude the class by field, so nothing here can compose into a reply.
|
|
14
21
|
//
|
|
15
22
|
// Fail closed: an absent, unreadable, or invalid file reads as "no run" — never
|
|
16
23
|
// a crash, never a fabricated queue.
|
|
17
24
|
|
|
18
25
|
import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
|
|
19
26
|
import { dirname, join } from "node:path";
|
|
27
|
+
import {
|
|
28
|
+
bookkeepingRow, bookkeepingEntries,
|
|
29
|
+
BOOKKEEPING_RESEARCH_QUEUE, BOOKKEEPING_RESEARCHED_TERM,
|
|
30
|
+
} from "./memory/rows.mjs";
|
|
31
|
+
import { normFactTerm } from "../domain/hash.mjs";
|
|
32
|
+
import { isRowHandle } from "./memory/core.mjs";
|
|
20
33
|
|
|
21
34
|
const QUEUE_FILE = "research-queue.json";
|
|
35
|
+
const RESEARCHED_TERMS_FILE = "researched-terms.json";
|
|
36
|
+
|
|
37
|
+
const RUN_ENTRY = "run";
|
|
38
|
+
const STATUS_PENDING = "pending";
|
|
39
|
+
const STATUS_DONE = "done";
|
|
40
|
+
const STATUS_SKIPPED = "skipped";
|
|
41
|
+
|
|
42
|
+
/** A row backend bound as a memoryDir token carries its store on `impl`. */
|
|
43
|
+
const rowStoreOf = (memoryDir) => (isRowHandle(memoryDir) ? memoryDir.impl : null);
|
|
22
44
|
|
|
23
|
-
/** The on-disk path for `memoryDir`'s
|
|
24
|
-
* nowhere to persist (in-memory backend,
|
|
25
|
-
* A repo-path string keys off <repo>/.tmct;
|
|
26
|
-
*
|
|
27
|
-
function
|
|
45
|
+
/** The on-disk path for one of `memoryDir`'s sidecar files, or null when this
|
|
46
|
+
* session has nowhere to persist (in-memory backend, a row backend, or a
|
|
47
|
+
* browser session with no store). A repo-path string keys off <repo>/.tmct;
|
|
48
|
+
* a store handle keys off its own dbPath's .tmct/ sibling. */
|
|
49
|
+
function sidecarPath(memoryDir, file) {
|
|
28
50
|
if (!memoryDir) return null;
|
|
29
|
-
if (typeof memoryDir === "string") return join(memoryDir, ".tmct",
|
|
30
|
-
if (typeof memoryDir.dbPath === "string") return join(dirname(dirname(memoryDir.dbPath)),
|
|
51
|
+
if (typeof memoryDir === "string") return join(memoryDir, ".tmct", file);
|
|
52
|
+
if (typeof memoryDir.dbPath === "string") return join(dirname(dirname(memoryDir.dbPath)), file);
|
|
31
53
|
return null;
|
|
32
54
|
}
|
|
33
55
|
|
|
@@ -42,35 +64,196 @@ function isQueueState(state) {
|
|
|
42
64
|
&& Array.isArray(state.skipped);
|
|
43
65
|
}
|
|
44
66
|
|
|
67
|
+
async function readJsonFile(path) {
|
|
68
|
+
let raw;
|
|
69
|
+
try { raw = await readFile(path, "utf8"); } catch { return null; }
|
|
70
|
+
try { return JSON.parse(raw); } catch { return null; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function writeJsonFile(path, value) {
|
|
74
|
+
try {
|
|
75
|
+
await mkdir(dirname(path), { recursive: true });
|
|
76
|
+
await writeFile(path, JSON.stringify(value), "utf8");
|
|
77
|
+
} catch { /* a sidecar we can't persist stays in memory for this session */ }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---- the row path -----------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
/** Every bookkeeping entry of one kind the store holds. A row backend's read is
|
|
83
|
+
* the whole session partition, so the caller filters from there. */
|
|
84
|
+
async function readBookkeeping(impl, kind) {
|
|
85
|
+
const rows = [];
|
|
86
|
+
const value = await impl.readRows();
|
|
87
|
+
if (Array.isArray(value)) rows.push(...value);
|
|
88
|
+
else for await (const row of value) rows.push(row);
|
|
89
|
+
return bookkeepingEntries(rows, kind);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The rows one queue state projects onto: the run's own scalars, then one row
|
|
93
|
+
* per title carrying that title's status and its position in its list. */
|
|
94
|
+
function queueRows(state) {
|
|
95
|
+
const rows = [bookkeepingRow(BOOKKEEPING_RESEARCH_QUEUE, `${state.key}#${RUN_ENTRY}`, {
|
|
96
|
+
runKey: state.key,
|
|
97
|
+
topic: state.topic,
|
|
98
|
+
title: state.title,
|
|
99
|
+
limit: state.limit,
|
|
100
|
+
maxDepth: state.maxDepth,
|
|
101
|
+
maxTopics: state.maxTopics,
|
|
102
|
+
nodeCapReached: Boolean(state.nodeCapReached),
|
|
103
|
+
})];
|
|
104
|
+
const entry = (title, value) => rows.push(
|
|
105
|
+
bookkeepingRow(BOOKKEEPING_RESEARCH_QUEUE, `${state.key}#entry#${title}`, { runKey: state.key, ...value }),
|
|
106
|
+
);
|
|
107
|
+
state.pending.forEach((title, ord) => entry(title, {
|
|
108
|
+
status: STATUS_PENDING, title, ord, depth: state.depths?.[normFactTerm(title)],
|
|
109
|
+
}));
|
|
110
|
+
state.done.forEach((d, ord) => entry(d.title, {
|
|
111
|
+
status: STATUS_DONE, title: d.title, ord, facts: d.facts, depth: d.depth,
|
|
112
|
+
}));
|
|
113
|
+
state.skipped.forEach((title, ord) => entry(title, { status: STATUS_SKIPPED, title, ord }));
|
|
114
|
+
return rows;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Rebuild a queue state from its entry rows. `pending`, `done` and `skipped`
|
|
118
|
+
* come back in each list's own recorded order, and a title's status decides
|
|
119
|
+
* which list it lands in — so a turn that marked one title done and a turn
|
|
120
|
+
* that queued another both survive, whichever order their rows arrived in. */
|
|
121
|
+
function queueStateFrom(entries) {
|
|
122
|
+
const run = entries.find((e) => e.key.endsWith(`#${RUN_ENTRY}`))?.value;
|
|
123
|
+
if (!run?.runKey) return null;
|
|
124
|
+
const mine = entries
|
|
125
|
+
.map((e) => e.value)
|
|
126
|
+
.filter((v) => v?.runKey === run.runKey && v.status && typeof v.title === "string");
|
|
127
|
+
const inOrder = (status) => mine
|
|
128
|
+
.filter((v) => v.status === status)
|
|
129
|
+
.sort((a, b) => (a.ord ?? 0) - (b.ord ?? 0) || (a.title < b.title ? -1 : a.title > b.title ? 1 : 0));
|
|
130
|
+
|
|
131
|
+
const pending = inOrder(STATUS_PENDING);
|
|
132
|
+
const depths = {};
|
|
133
|
+
for (const v of pending) {
|
|
134
|
+
if (Number.isFinite(v.depth)) depths[normFactTerm(v.title)] = v.depth;
|
|
135
|
+
}
|
|
136
|
+
const state = {
|
|
137
|
+
topic: run.topic, key: run.runKey, title: run.title,
|
|
138
|
+
limit: run.limit, maxDepth: run.maxDepth, maxTopics: run.maxTopics,
|
|
139
|
+
pending: pending.map((v) => v.title),
|
|
140
|
+
depths,
|
|
141
|
+
done: inOrder(STATUS_DONE).map((v) => ({ title: v.title, facts: v.facts, depth: v.depth })),
|
|
142
|
+
skipped: inOrder(STATUS_SKIPPED).map((v) => v.title),
|
|
143
|
+
nodeCapReached: Boolean(run.nodeCapReached),
|
|
144
|
+
};
|
|
145
|
+
return isQueueState(state) ? state : null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function loadRowQueue(impl) {
|
|
149
|
+
return queueStateFrom(await readBookkeeping(impl, BOOKKEEPING_RESEARCH_QUEUE));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A title only ever moves forward: queued, then finished or passed over. A
|
|
153
|
+
* writer holding an older snapshot must not push a finished title back into
|
|
154
|
+
* the queue, which is what lets two turns step the same run at once and keep
|
|
155
|
+
* both results. */
|
|
156
|
+
const isSettled = (status) => status === STATUS_DONE || status === STATUS_SKIPPED;
|
|
157
|
+
|
|
158
|
+
/** Write the run's rows and drop only what this state actually retired: the
|
|
159
|
+
* rows of an earlier run, and any title of THIS run the state no longer
|
|
160
|
+
* mentions. A title another writer has already finished keeps that result, and
|
|
161
|
+
* a row another writer added for a title this state never saw is left alone. */
|
|
162
|
+
async function saveRowQueue(impl, state) {
|
|
163
|
+
const stored = await readBookkeeping(impl, BOOKKEEPING_RESEARCH_QUEUE);
|
|
164
|
+
const settled = new Set(stored
|
|
165
|
+
.filter((e) => e.value?.runKey === state.key && isSettled(e.value?.status))
|
|
166
|
+
.map((e) => e.rowKey));
|
|
167
|
+
const rows = queueRows(state).filter((row) => {
|
|
168
|
+
const entry = JSON.parse(row.json).value;
|
|
169
|
+
return !entry.status || isSettled(entry.status) || !settled.has(row.rowKey);
|
|
170
|
+
});
|
|
171
|
+
const keep = new Set(rows.map((r) => r.rowKey));
|
|
172
|
+
const stale = stored
|
|
173
|
+
.filter((e) => !keep.has(e.rowKey) && !settled.has(e.rowKey))
|
|
174
|
+
.filter((e) => e.value?.runKey !== state.key || e.key.startsWith(`${state.key}#entry#`))
|
|
175
|
+
.map((e) => e.rowKey);
|
|
176
|
+
await impl.putRows(rows);
|
|
177
|
+
if (stale.length) await impl.deleteRows(stale);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function clearRowQueue(impl) {
|
|
181
|
+
const keys = (await readBookkeeping(impl, BOOKKEEPING_RESEARCH_QUEUE)).map((e) => e.rowKey);
|
|
182
|
+
if (keys.length) await impl.deleteRows(keys);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ---- the public surface -----------------------------------------------------
|
|
186
|
+
|
|
45
187
|
/** The persisted queue for `memoryDir`, or null when none is stored, the store
|
|
46
|
-
* cannot persist, or
|
|
188
|
+
* cannot persist, or what is stored is missing/corrupt/ill-shaped. */
|
|
47
189
|
export async function loadResearchQueue(memoryDir) {
|
|
48
|
-
const
|
|
190
|
+
const impl = rowStoreOf(memoryDir);
|
|
191
|
+
if (impl) return loadRowQueue(impl);
|
|
192
|
+
const path = sidecarPath(memoryDir, QUEUE_FILE);
|
|
49
193
|
if (!path) return null;
|
|
50
|
-
|
|
51
|
-
try { raw = await readFile(path, "utf8"); } catch { return null; }
|
|
52
|
-
let state;
|
|
53
|
-
try { state = JSON.parse(raw); } catch { return null; }
|
|
194
|
+
const state = await readJsonFile(path);
|
|
54
195
|
return isQueueState(state) ? state : null;
|
|
55
196
|
}
|
|
56
197
|
|
|
57
|
-
/** Write-through the current queue. A null/absent state clears the
|
|
58
|
-
* stopped or completed-and-cleared run leaves nothing behind. A store with
|
|
59
|
-
*
|
|
198
|
+
/** Write-through the current queue. A null/absent state clears the store, so a
|
|
199
|
+
* stopped or completed-and-cleared run leaves nothing behind. A store with
|
|
200
|
+
* nowhere to persist is a no-op. A write that fails leaves the in-memory queue
|
|
201
|
+
* standing. */
|
|
60
202
|
export async function saveResearchQueue(memoryDir, state) {
|
|
61
|
-
const
|
|
203
|
+
const impl = rowStoreOf(memoryDir);
|
|
204
|
+
if (impl) {
|
|
205
|
+
if (!state) { await clearResearchQueue(memoryDir); return; }
|
|
206
|
+
try { await saveRowQueue(impl, state); } catch { /* a queue we can't persist stays in memory */ }
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const path = sidecarPath(memoryDir, QUEUE_FILE);
|
|
62
210
|
if (!path) return;
|
|
63
211
|
if (!state) { await clearResearchQueue(memoryDir); return; }
|
|
64
|
-
|
|
65
|
-
await mkdir(dirname(path), { recursive: true });
|
|
66
|
-
await writeFile(path, JSON.stringify(state), "utf8");
|
|
67
|
-
} catch { /* a queue we can't persist stays in memory for this session */ }
|
|
212
|
+
await writeJsonFile(path, state);
|
|
68
213
|
}
|
|
69
214
|
|
|
70
|
-
/**
|
|
71
|
-
*
|
|
215
|
+
/** Drop the persisted queue (idempotent — an already-absent one is the cleared
|
|
216
|
+
* state we want). A store with nowhere to persist is a no-op. */
|
|
72
217
|
export async function clearResearchQueue(memoryDir) {
|
|
73
|
-
const
|
|
218
|
+
const impl = rowStoreOf(memoryDir);
|
|
219
|
+
if (impl) {
|
|
220
|
+
try { await clearRowQueue(impl); } catch { /* already gone, or unreachable */ }
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const path = sidecarPath(memoryDir, QUEUE_FILE);
|
|
74
224
|
if (!path) return;
|
|
75
225
|
try { await unlink(path); } catch { /* already gone */ }
|
|
76
226
|
}
|
|
227
|
+
|
|
228
|
+
/** The terms a consumer has already researched for this store, as a Set. One
|
|
229
|
+
* row per term on a row backend, so two turns marking different terms both
|
|
230
|
+
* land. Empty when nothing is stored or the store cannot persist. */
|
|
231
|
+
export async function loadResearchedTerms(memoryDir) {
|
|
232
|
+
const impl = rowStoreOf(memoryDir);
|
|
233
|
+
if (impl) {
|
|
234
|
+
const entries = await readBookkeeping(impl, BOOKKEEPING_RESEARCHED_TERM);
|
|
235
|
+
return new Set(entries.map((e) => e.key).filter(Boolean));
|
|
236
|
+
}
|
|
237
|
+
const path = sidecarPath(memoryDir, RESEARCHED_TERMS_FILE);
|
|
238
|
+
if (!path) return new Set();
|
|
239
|
+
const stored = await readJsonFile(path);
|
|
240
|
+
return new Set(Array.isArray(stored) ? stored.filter((t) => typeof t === "string") : []);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Mark `term` researched. Additive on a row backend — its own row, so a
|
|
244
|
+
* concurrent turn marking a different term cannot erase it. */
|
|
245
|
+
export async function markTermResearched(memoryDir, term) {
|
|
246
|
+
if (!term) return;
|
|
247
|
+
const impl = rowStoreOf(memoryDir);
|
|
248
|
+
if (impl) {
|
|
249
|
+
try { await impl.putRows([bookkeepingRow(BOOKKEEPING_RESEARCHED_TERM, term, { term })]); }
|
|
250
|
+
catch { /* a marker we can't persist costs one repeated lookup */ }
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const path = sidecarPath(memoryDir, RESEARCHED_TERMS_FILE);
|
|
254
|
+
if (!path) return;
|
|
255
|
+
const terms = await loadResearchedTerms(memoryDir);
|
|
256
|
+
if (terms.has(term)) return;
|
|
257
|
+
terms.add(term);
|
|
258
|
+
await writeJsonFile(path, [...terms].sort());
|
|
259
|
+
}
|