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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -417,7 +417,9 @@ export function createNewsSession({
417
417
  forgotten = false;
418
418
  const nowVal = typeof now === "function" ? now() : now;
419
419
  const sourceTag = `teach:upload:${fileLabel}@${nowVal}`;
420
- const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal });
420
+ const result = await ingestText(text, {
421
+ memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal, findings: true,
422
+ });
421
423
  cache.rows = null;
422
424
  foldedRows = null;
423
425
  return { facts: result.extracted.length + result.optimistic.length, sentences: result.sentences };
@@ -469,7 +471,9 @@ export function createNewsSession({
469
471
  for (const snapshot of items) {
470
472
  const text = [snapshot.title, snapshot.summary].filter(Boolean).join(". ");
471
473
  const sourceTag = `news-fixture:${sourceId}@${snapshot.id}`;
472
- const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal });
474
+ const result = await ingestText(text, {
475
+ memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal, findings: true,
476
+ });
473
477
  const allFacts = [...result.extracted, ...result.optimistic];
474
478
  snapshot.factIds = allFacts.map((f) => factIdFor(normFactTerm(f.subject), normFactPredicate(f.predicate), normFactTerm(f.object)));
475
479
  factsTotal += allFacts.length;
@@ -27,7 +27,9 @@ export async function tmct_ingest(args, { config, ingest }) {
27
27
  const optimistic = args?.optimistic === true;
28
28
  const { dir, close } = await openConfiguredMemoryBackend(dirname(dirname(config.graphFile)));
29
29
  try {
30
- const result = await ingest(text, { memoryDir: dir, config, sourceTag: "tool", optimistic, canonical: true });
30
+ const result = await ingest(text, {
31
+ memoryDir: dir, config, sourceTag: "tool", optimistic, canonical: true, findings: true,
32
+ });
31
33
  const grounded = result.extracted.length + result.optimistic.length;
32
34
  const header = `${result.sentences} sentence(s), ${result.recognized} recognized`
33
35
  + (optimistic ? `, ${result.optimistic.length} optimistic candidate(s)` : "")
@@ -0,0 +1,238 @@
1
+ // memory-backend-conformance.mjs — the published contract test suite for a
2
+ // memory row backend (src/adapters/memory/row-backend.mjs's §3.1 interface),
3
+ // shaped like conformance.mjs: an implementation is conformant iff it passes
4
+ // `runMemoryBackendConformance(name, makeBackend)` against a bare backend
5
+ // object, no other tmct internals required. `makeBackend()` returns a fresh,
6
+ // independent backend each call — its own session, holding nothing from any
7
+ // earlier call.
8
+ //
9
+ // What the suite checks: the duck-typed shape; every row class round-trips
10
+ // through `putRows`/`readRows`; a bookkeeping row round-trips but never
11
+ // reaches an assembled answer; meta scalars round-trip and an unset key
12
+ // reads null; `deleteRows` and `deleteAll` leave their targets absent from
13
+ // every later read, satisfied whether the backend removes the row or
14
+ // tombstones it behind a filtered read; a batch carrying one bad row still
15
+ // leaves the good rows durable; one row set fed in two arrival orders
16
+ // assembles to the same payload; the two failure classes carry their stable
17
+ // codes; and the optional term read, when implemented, answers exactly the
18
+ // rows on that term.
19
+ //
20
+ // Public surface: runMemoryBackendConformance(name, makeBackend),
21
+ // assertWireRow, buildFixtureRows, collectRows.
22
+ import { test } from "node:test";
23
+ import assert from "node:assert/strict";
24
+
25
+ import {
26
+ ROW_CLASSES, BOOKKEEPING_ROW_CLASS,
27
+ BackendRejected, BackendUnavailable,
28
+ isRowBackend, rowBackendProblems,
29
+ } from "../adapters/memory/row-backend.mjs";
30
+ import { rowsToPayload, bookkeepingRow, BOOKKEEPING_RESEARCH_QUEUE } from "../adapters/memory/rows.mjs";
31
+
32
+ /** `readRows()`/`readRowsByTerm()` may hand back a `Promise<row[]>` or an
33
+ * `AsyncIterable<row>` — this normalizes either into a plain array.
34
+ * Awaiting a non-thenable async-iterable is a documented no-op, so this
35
+ * works without knowing which shape a given backend chose. */
36
+ export async function collectRows(rowsOrIterable) {
37
+ const value = await rowsOrIterable;
38
+ if (Array.isArray(value)) return value;
39
+ const collected = [];
40
+ for await (const row of value) collected.push(row);
41
+ return collected;
42
+ }
43
+
44
+ export function assertWireRow(row, where) {
45
+ assert.ok(row && typeof row === "object", `${where}: a wire row`);
46
+ assert.equal(typeof row.rowKey, "string", `${where}: rowKey is a string`);
47
+ assert.ok(row.rowKey.length > 0, `${where}: rowKey is non-empty`);
48
+ assert.ok(ROW_CLASSES.includes(row.rowClass), `${where}: rowClass "${row.rowClass}" is in the closed set`);
49
+ assert.equal(typeof row.term, "string", `${where}: term is a string`);
50
+ assert.equal(typeof row.json, "string", `${where}: json is a string`);
51
+ }
52
+
53
+ const byRowKey = (rows) => new Map(rows.map((row) => [row.rowKey, row]));
54
+
55
+ /** One row per closed `rowClass` — including `bookkeeping` and `edge-group`
56
+ * — plus a second `fact` row on a distinct term, so every check below has
57
+ * something to round-trip, exclude, or filter by term. Individuals carry a
58
+ * made-up class name: `rowsToPayload` only special-cases the real Fact
59
+ * class for supersession derivation, which none of these checks exercise,
60
+ * so an arbitrary class string keeps this module free of any dependence on
61
+ * `core.mjs`'s individual shapes beyond what the wire-row contract itself
62
+ * needs. */
63
+ export function buildFixtureRows() {
64
+ const rows = [];
65
+ let ord = 0;
66
+ for (const rowClass of ROW_CLASSES) {
67
+ if (rowClass === BOOKKEEPING_ROW_CLASS) {
68
+ rows.push(bookkeepingRow(BOOKKEEPING_RESEARCH_QUEUE, "fixture", { note: "conformance fixture" }));
69
+ continue;
70
+ }
71
+ if (rowClass === "edge-group") {
72
+ rows.push({
73
+ rowKey: "edge-group:fixture:prop",
74
+ rowClass,
75
+ term: "",
76
+ json: JSON.stringify({ ord: ord++, group: { prop: "fixture:prop", examples: [] } }),
77
+ });
78
+ continue;
79
+ }
80
+ const term = rowClass === "fact" ? "alpha" : "";
81
+ rows.push({
82
+ rowKey: `fixture:${rowClass}:1`,
83
+ rowClass,
84
+ term,
85
+ json: JSON.stringify({ ord: ord++, individual: { id: `fixture:${rowClass}:1`, class: rowClass, label: rowClass, attributes: [] } }),
86
+ });
87
+ }
88
+ rows.push({
89
+ rowKey: "fixture:fact:2",
90
+ rowClass: "fact",
91
+ term: "beta",
92
+ json: JSON.stringify({ ord: ord++, individual: { id: "fixture:fact:2", class: "fact", label: "fact-2", attributes: [] } }),
93
+ });
94
+ return rows;
95
+ }
96
+
97
+ /** Wrap a real backend so one named row is refused by the WRAPPER itself,
98
+ * never reaching the backend's own `putRows` — the rest of the batch still
99
+ * goes through the real backend's own call. This is how the suite proves
100
+ * per-row atomicity without assuming anything about how a given backend's
101
+ * `putRows` behaves on invalid input: the wrapper is what rejects the
102
+ * poisoned row, and the check is whether the backend's OWN state still
103
+ * durably holds everything else. */
104
+ function poisonOneRow(backend, poisonRowKey) {
105
+ return {
106
+ ...backend,
107
+ async putRows(candidateRows) {
108
+ const rest = (candidateRows || []).filter((row) => row.rowKey !== poisonRowKey);
109
+ const poisoned = (candidateRows || []).some((row) => row.rowKey === poisonRowKey);
110
+ if (rest.length) await backend.putRows(rest);
111
+ if (poisoned) throw new BackendRejected(`poisoned row ${poisonRowKey}`, { rowKey: poisonRowKey });
112
+ },
113
+ };
114
+ }
115
+
116
+ export function runMemoryBackendConformance(name, makeBackend) {
117
+ test(`[${name}] advertises the row-backend contract`, () => {
118
+ const backend = makeBackend();
119
+ assert.equal(isRowBackend(backend), true, rowBackendProblems(backend).join("; "));
120
+ });
121
+
122
+ test(`[${name}] the exported failure classes carry stable names and codes`, () => {
123
+ const rejected = new BackendRejected("refused");
124
+ assert.ok(rejected instanceof Error);
125
+ assert.equal(rejected.name, "BackendRejected");
126
+ assert.equal(rejected.code, "TMCT_BACKEND_REJECTED");
127
+ const unavailable = new BackendUnavailable("unreachable");
128
+ assert.ok(unavailable instanceof Error);
129
+ assert.equal(unavailable.name, "BackendUnavailable");
130
+ assert.equal(unavailable.code, "TMCT_BACKEND_UNAVAILABLE");
131
+ });
132
+
133
+ test(`[${name}] every row class round-trips through putRows/readRows`, async () => {
134
+ const backend = makeBackend();
135
+ const fixture = buildFixtureRows();
136
+ await backend.putRows(fixture);
137
+ const got = byRowKey(await collectRows(backend.readRows()));
138
+ for (const row of fixture) {
139
+ const back = got.get(row.rowKey);
140
+ assert.ok(back, `${row.rowKey} did not come back`);
141
+ assertWireRow(back, row.rowKey);
142
+ assert.equal(back.rowClass, row.rowClass);
143
+ assert.equal(back.term, row.term);
144
+ assert.equal(back.json, row.json);
145
+ }
146
+ });
147
+
148
+ test(`[${name}] a bookkeeping row round-trips but never reaches the assembled answer`, async () => {
149
+ const backend = makeBackend();
150
+ const fixture = buildFixtureRows();
151
+ await backend.putRows(fixture);
152
+ const rows = await collectRows(backend.readRows());
153
+ const bookkeepingRows = rows.filter((row) => row.rowClass === BOOKKEEPING_ROW_CLASS);
154
+ assert.ok(bookkeepingRows.length > 0, "the fixture carries at least one bookkeeping row");
155
+ const payload = rowsToPayload(rows);
156
+ const answerFacingIds = new Set(payload.individuals.map((ind) => ind.id));
157
+ for (const row of bookkeepingRows) assert.equal(answerFacingIds.has(row.rowKey), false, `${row.rowKey} leaked into the answer`);
158
+ });
159
+
160
+ test(`[${name}] meta scalars round-trip, and an unset key reads null`, async () => {
161
+ const backend = makeBackend();
162
+ assert.equal(await backend.readMeta("memory"), null);
163
+ await backend.putMeta("memory", "chatty");
164
+ await backend.putMeta("prefixes", JSON.stringify({ mgx: "urn:mgx:" }));
165
+ assert.equal(await backend.readMeta("memory"), "chatty");
166
+ assert.equal(await backend.readMeta("prefixes"), JSON.stringify({ mgx: "urn:mgx:" }));
167
+ assert.equal(await backend.readMeta("neverSet"), null);
168
+ });
169
+
170
+ test(`[${name}] deleteRows leaves the deleted keys absent from every later read`, async () => {
171
+ const backend = makeBackend();
172
+ const fixture = buildFixtureRows();
173
+ await backend.putRows(fixture);
174
+ const [gone, ...kept] = fixture;
175
+ await backend.deleteRows([gone.rowKey]);
176
+ const rows = await collectRows(backend.readRows());
177
+ assert.equal(rows.some((row) => row.rowKey === gone.rowKey), false);
178
+ for (const row of kept) assert.ok(rows.some((r) => r.rowKey === row.rowKey), `${row.rowKey} should still be there`);
179
+ // A missing key is a no-op, not a failure.
180
+ await backend.deleteRows(["no-such-row-key"]);
181
+ });
182
+
183
+ test(`[${name}] deleteAll makes every row and meta entry absent`, async () => {
184
+ const backend = makeBackend();
185
+ await backend.putRows(buildFixtureRows());
186
+ await backend.putMeta("memory", "chatty");
187
+ await backend.putMeta("nodeId", "01890000-node");
188
+ await backend.deleteAll();
189
+ assert.deepEqual(await collectRows(backend.readRows()), []);
190
+ assert.equal(await backend.readMeta("memory"), null);
191
+ assert.equal(await backend.readMeta("nodeId"), null);
192
+ });
193
+
194
+ test(`[${name}] a batch carrying one refused row still leaves the good rows durable`, async () => {
195
+ const backend = makeBackend();
196
+ const [good1, good2, poison] = buildFixtureRows();
197
+ const wrapped = poisonOneRow(backend, poison.rowKey);
198
+ await assert.rejects(
199
+ wrapped.putRows([good1, poison, good2]),
200
+ (error) => {
201
+ assert.ok(error instanceof BackendRejected, "the wrapper's own rejection is a BackendRejected");
202
+ assert.equal(error.code, "TMCT_BACKEND_REJECTED");
203
+ return true;
204
+ },
205
+ );
206
+ const rows = await collectRows(backend.readRows());
207
+ assert.ok(rows.some((row) => row.rowKey === good1.rowKey), "the first good row is durable on the real backend");
208
+ assert.ok(rows.some((row) => row.rowKey === good2.rowKey), "the second good row is durable on the real backend");
209
+ assert.equal(rows.some((row) => row.rowKey === poison.rowKey), false, "the poisoned row never reached the real backend");
210
+ });
211
+
212
+ test(`[${name}] one row set fed in two arrival orders assembles to the same payload`, async () => {
213
+ const rows = buildFixtureRows();
214
+ const forward = makeBackend();
215
+ const backward = makeBackend();
216
+ await forward.putRows(rows);
217
+ await backward.putRows([...rows].reverse());
218
+
219
+ const forwardRows = await collectRows(forward.readRows());
220
+ const backwardRows = await collectRows(backward.readRows());
221
+ assert.deepEqual(
222
+ [...forwardRows].sort((a, b) => (a.rowKey < b.rowKey ? -1 : 1)),
223
+ [...backwardRows].sort((a, b) => (a.rowKey < b.rowKey ? -1 : 1)),
224
+ "the same row set, whatever order it arrived in, reads back as the same rows",
225
+ );
226
+ assert.deepStrictEqual(rowsToPayload(forwardRows), rowsToPayload(backwardRows));
227
+ });
228
+
229
+ test(`[${name}] readRowsByTerm, when implemented, answers exactly the rows on that term`, async () => {
230
+ const backend = makeBackend();
231
+ if (typeof backend.readRowsByTerm !== "function") return; // optional per the §3.1 contract
232
+ const rows = buildFixtureRows();
233
+ await backend.putRows(rows);
234
+ const expected = rows.filter((row) => row.term === "alpha").map((row) => row.rowKey).sort();
235
+ const got = (await collectRows(backend.readRowsByTerm("alpha"))).map((row) => row.rowKey).sort();
236
+ assert.deepEqual(got, expected);
237
+ });
238
+ }