@polycode-projects/the-mechanical-code-talker 6.0.0 → 6.0.2
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 +9 -2
- package/src/adapters/corpus/courtesy.mjs +67 -3
- package/src/adapters/corpus/dbpedia-lookup-live.mjs +8 -0
- package/src/adapters/corpus/wikidata-live.mjs +8 -0
- package/src/adapters/corpus/wikipedia-live.mjs +18 -0
- package/src/adapters/corpus/wiktionary-live.mjs +8 -0
- package/src/adapters/memory/core.mjs +522 -146
- package/src/adapters/memory/corpus-bands.mjs +155 -0
- package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
- package/src/adapters/memory/systemic-failure.mjs +28 -0
- package/src/domain/ask.mjs +341 -75
- package/src/domain/cli-verbs.mjs +17 -0
- package/src/domain/news-feed.mjs +42 -4
- package/src/domain/retrieval-marker.mjs +120 -0
- package/src/domain/retrieval-modes.mjs +13 -0
- package/src/domain/source-breaker.mjs +259 -0
- package/src/services/chat-session.mjs +13 -2
- package/src/services/chat.mjs +314 -92
- package/src/services/corpus-loader.mjs +222 -0
- package/src/services/news-viz.mjs +213 -348
- package/src/services/news.mjs +41 -7
- package/src/services/p2p-room.mjs +35 -21
- package/src/services/subgraph-retrieval.mjs +4 -33
- package/src/surfaces/web/http-row-backend.mjs +150 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +143 -140
- package/src/surfaces/web/news-browser-entry.mjs +204 -464
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// corpus-loader.mjs — load, clear and read the shared, read-only corpus
|
|
2
|
+
// bands (corpus-bands.mjs) over an injected DynamoDB-shaped document client:
|
|
3
|
+
// the AWS SDK's `DynamoDBDocument` convenience wrapper (`.put`/`.get`/
|
|
4
|
+
// `.delete`/`.query`, no Command objects), the same client shape
|
|
5
|
+
// `termQueryOverDocumentClient` (subgraph-retrieval.mjs) already reads. This
|
|
6
|
+
// module holds no credentials and imports no AWS package itself — the
|
|
7
|
+
// consumer constructs the client (a profile locally, OIDC in CI) and injects
|
|
8
|
+
// it, matching the shipped DynamoDB row backend's own discipline (§3.10).
|
|
9
|
+
//
|
|
10
|
+
// `queryBandTerm` lives here rather than in corpus-bands.mjs because it
|
|
11
|
+
// wraps subgraph-retrieval.mjs's `termQueryOverDocumentClient` — the one
|
|
12
|
+
// term-Query implementation this whole surface shares — and that module is
|
|
13
|
+
// services-layer; corpus-bands.mjs is adapters-layer and may not import
|
|
14
|
+
// upward into it (test/estate/import-layers.test.mjs).
|
|
15
|
+
//
|
|
16
|
+
// Load streams the source jsonl (wire-row-shaped facts, one per line),
|
|
17
|
+
// writes each with bounded concurrency, and writes the manifest row last —
|
|
18
|
+
// a run that dies mid-load leaves individually valid rows and a stale
|
|
19
|
+
// manifest, and re-running completes it, because every write is a content-
|
|
20
|
+
// addressed overwrite. Load is also a no-op when the source digest matches
|
|
21
|
+
// the manifest already on the band, which is what makes a CI job that runs
|
|
22
|
+
// this against every band on every deploy cheap.
|
|
23
|
+
//
|
|
24
|
+
// Clear queries the whole band partition and physically deletes every item
|
|
25
|
+
// it finds, manifest last. Physical, not the row service's soft delete: the
|
|
26
|
+
// loader holds AWS credentials on the operator's side of the trust line, not
|
|
27
|
+
// a public API caller's.
|
|
28
|
+
|
|
29
|
+
import { createReadStream } from "node:fs";
|
|
30
|
+
import { createInterface } from "node:readline";
|
|
31
|
+
import { createHash } from "node:crypto";
|
|
32
|
+
import {
|
|
33
|
+
bandPartitionKey, bandSortKeyForRow, buildBandManifest, bandLicenseInfo, MANIFEST_SORT_KEY,
|
|
34
|
+
} from "../adapters/memory/corpus-bands.mjs";
|
|
35
|
+
import { BackendRejected, BackendUnavailable, assertValidRow } from "../adapters/memory/row-backend.mjs";
|
|
36
|
+
import { termQueryOverDocumentClient } from "./subgraph-retrieval.mjs";
|
|
37
|
+
|
|
38
|
+
const DEFAULT_WRITE_CONCURRENCY = 25;
|
|
39
|
+
|
|
40
|
+
/** Runs `fn` over `items` with at most `limit` calls in flight, mirroring the
|
|
41
|
+
* DynamoDB row backend's own bounded-concurrency write loop. */
|
|
42
|
+
async function mapWithConcurrency(items, limit, fn) {
|
|
43
|
+
if (!items.length) return;
|
|
44
|
+
const workerCount = Math.max(1, Math.min(limit, items.length));
|
|
45
|
+
let cursor = 0;
|
|
46
|
+
async function worker() {
|
|
47
|
+
for (;;) {
|
|
48
|
+
const index = cursor++;
|
|
49
|
+
if (index >= items.length) return;
|
|
50
|
+
await fn(items[index], index);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
await Promise.all(Array.from({ length: workerCount }, worker));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Every store call funnels through here so a network failure or a
|
|
57
|
+
* 429/5xx-shaped rejection surfaces as `BackendUnavailable`, never a raw
|
|
58
|
+
* client error a caller would have to string-match. */
|
|
59
|
+
async function call(fn, label) {
|
|
60
|
+
try {
|
|
61
|
+
return await fn();
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof BackendRejected || error instanceof BackendUnavailable) throw error;
|
|
64
|
+
throw new BackendUnavailable(`corpus loader's ${label} call failed: ${error.message}`, { cause: error });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** sha256 of a file's bytes, streamed — the source digest the loader's
|
|
69
|
+
* no-op check compares against the manifest already on the band. */
|
|
70
|
+
export async function digestFile(path) {
|
|
71
|
+
const hash = createHash("sha256");
|
|
72
|
+
await new Promise((resolve, reject) => {
|
|
73
|
+
const stream = createReadStream(path);
|
|
74
|
+
stream.on("data", (chunk) => hash.update(chunk));
|
|
75
|
+
stream.on("end", resolve);
|
|
76
|
+
stream.on("error", reject);
|
|
77
|
+
});
|
|
78
|
+
return hash.digest("hex");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Stream a wire-row jsonl (one `{rowKey, rowClass, term, json}` per line),
|
|
82
|
+
* validating each row on the way in — a malformed source row is a
|
|
83
|
+
* `BackendRejected`, naming the line, before anything reaches the store. */
|
|
84
|
+
async function* readWireRows(path) {
|
|
85
|
+
const rl = createInterface({ input: createReadStream(path, "utf8"), crlfDelay: Infinity });
|
|
86
|
+
let lineNumber = 0;
|
|
87
|
+
for await (const raw of rl) {
|
|
88
|
+
lineNumber += 1;
|
|
89
|
+
const line = raw.trim();
|
|
90
|
+
if (!line) continue;
|
|
91
|
+
let row;
|
|
92
|
+
try {
|
|
93
|
+
row = JSON.parse(line);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw new BackendRejected(`${path}:${lineNumber}: not valid JSON: ${error.message}`);
|
|
96
|
+
}
|
|
97
|
+
assertValidRow(row);
|
|
98
|
+
yield row;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The manifest row for `band`, or null when the band has never been loaded. */
|
|
103
|
+
export async function bandStatus({ client, tableName, band }) {
|
|
104
|
+
const result = await call(
|
|
105
|
+
() => client.get({ TableName: tableName, Key: { pk: bandPartitionKey(band), sk: MANIFEST_SORT_KEY } }),
|
|
106
|
+
"get",
|
|
107
|
+
);
|
|
108
|
+
return result?.Item ? { ...result.Item } : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Every item (fact rows and the manifest, if present) under a band's
|
|
112
|
+
* partition, paginated. Shared by `clearBand` and any caller that wants a
|
|
113
|
+
* full inventory rather than one term's rows. */
|
|
114
|
+
async function queryWholePartition({ client, tableName, band }) {
|
|
115
|
+
const items = [];
|
|
116
|
+
let exclusiveStartKey;
|
|
117
|
+
do {
|
|
118
|
+
const response = await call(() => client.query({
|
|
119
|
+
TableName: tableName,
|
|
120
|
+
KeyConditionExpression: "pk = :pk",
|
|
121
|
+
ExpressionAttributeValues: { ":pk": bandPartitionKey(band) },
|
|
122
|
+
...(exclusiveStartKey ? { ExclusiveStartKey: exclusiveStartKey } : {}),
|
|
123
|
+
}), "query");
|
|
124
|
+
items.push(...(response?.Items || []));
|
|
125
|
+
exclusiveStartKey = response?.LastEvaluatedKey || null;
|
|
126
|
+
} while (exclusiveStartKey);
|
|
127
|
+
return items;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Load `band` from a jsonl source of wire rows. Resolves to
|
|
131
|
+
* `{status: "unchanged" | "loaded" | "dry-run", band, rowCount, sourceDigest}`.
|
|
132
|
+
* `dryRun` computes the digest and reports what would happen without
|
|
133
|
+
* writing anything. */
|
|
134
|
+
export async function loadBand({
|
|
135
|
+
client, tableName, band, source, dryRun = false,
|
|
136
|
+
writeConcurrency = DEFAULT_WRITE_CONCURRENCY, now = () => new Date().toISOString(),
|
|
137
|
+
}) {
|
|
138
|
+
if (!client) throw new TypeError("loadBand needs a client");
|
|
139
|
+
if (!tableName) throw new TypeError("loadBand needs a tableName");
|
|
140
|
+
if (!band) throw new TypeError("loadBand needs a band");
|
|
141
|
+
if (!source) throw new TypeError("loadBand needs a source path");
|
|
142
|
+
|
|
143
|
+
const sourceDigest = await digestFile(source);
|
|
144
|
+
const existing = await bandStatus({ client, tableName, band });
|
|
145
|
+
if (existing?.sourceDigest === sourceDigest) {
|
|
146
|
+
return { status: "unchanged", band, rowCount: existing.rowCount, sourceDigest };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const pk = bandPartitionKey(band);
|
|
150
|
+
let rowCount = 0;
|
|
151
|
+
const { license, notice } = bandLicenseInfo(band);
|
|
152
|
+
|
|
153
|
+
if (!dryRun) {
|
|
154
|
+
const rows = [];
|
|
155
|
+
for await (const row of readWireRows(source)) rows.push(row);
|
|
156
|
+
rowCount = rows.length;
|
|
157
|
+
await mapWithConcurrency(rows, writeConcurrency, async (row) => {
|
|
158
|
+
const item = {
|
|
159
|
+
pk, sk: bandSortKeyForRow(row.rowClass, row.term, row.rowKey),
|
|
160
|
+
rowKey: row.rowKey, rowClass: row.rowClass, term: row.term, json: row.json,
|
|
161
|
+
};
|
|
162
|
+
await call(() => client.put({ TableName: tableName, Item: item }), "put");
|
|
163
|
+
});
|
|
164
|
+
const manifest = buildBandManifest({
|
|
165
|
+
band, rowCount, loadedAt: now(), sourceDigest, license, notice,
|
|
166
|
+
});
|
|
167
|
+
await call(() => client.put({
|
|
168
|
+
TableName: tableName,
|
|
169
|
+
Item: { pk, sk: MANIFEST_SORT_KEY, ...manifest },
|
|
170
|
+
}), "put");
|
|
171
|
+
return { status: "loaded", band, rowCount, sourceDigest };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
for await (const _row of readWireRows(source)) rowCount += 1;
|
|
175
|
+
return { status: "dry-run", band, rowCount, sourceDigest };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Physically delete every item under `band`'s partition, manifest last.
|
|
179
|
+
* Idempotent: an empty partition (already cleared, or never loaded) is a
|
|
180
|
+
* no-op. Resolves to `{band, deleted}`. */
|
|
181
|
+
export async function clearBand({ client, tableName, band, writeConcurrency = DEFAULT_WRITE_CONCURRENCY }) {
|
|
182
|
+
if (!client) throw new TypeError("clearBand needs a client");
|
|
183
|
+
if (!tableName) throw new TypeError("clearBand needs a tableName");
|
|
184
|
+
if (!band) throw new TypeError("clearBand needs a band");
|
|
185
|
+
|
|
186
|
+
const items = await queryWholePartition({ client, tableName, band });
|
|
187
|
+
const facts = items.filter((item) => item.sk !== MANIFEST_SORT_KEY);
|
|
188
|
+
const manifestItem = items.find((item) => item.sk === MANIFEST_SORT_KEY);
|
|
189
|
+
|
|
190
|
+
await mapWithConcurrency(facts, writeConcurrency, async (item) => {
|
|
191
|
+
await call(() => client.delete({ TableName: tableName, Key: { pk: item.pk, sk: item.sk } }), "delete");
|
|
192
|
+
});
|
|
193
|
+
if (manifestItem) {
|
|
194
|
+
await call(() => client.delete({ TableName: tableName, Key: { pk: manifestItem.pk, sk: manifestItem.sk } }), "delete");
|
|
195
|
+
}
|
|
196
|
+
return { band, deleted: items.length };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const DEFAULT_BAND_QUERY_PAGE_SIZE = 200;
|
|
200
|
+
|
|
201
|
+
/** One term's rows from one band, fully paginated, wrapping
|
|
202
|
+
* subgraph-retrieval.mjs's `termQueryOverDocumentClient` — the one term
|
|
203
|
+
* Query this whole surface shares. `client` is the same convenience
|
|
204
|
+
* document client (`.query({...})` resolving to `{Items,
|
|
205
|
+
* LastEvaluatedKey}`) `loadBand`/`clearBand` already take. Returns plain
|
|
206
|
+
* wire rows (`{rowKey, rowClass, term, json}`), with the storage-only
|
|
207
|
+
* `pk`/`sk` stripped — the loader's own read-back checks and the read-only
|
|
208
|
+
* corpus route both call this rather than issuing their own Query. */
|
|
209
|
+
export async function queryBandTerm(client, tableName, band, term, { pageSize = DEFAULT_BAND_QUERY_PAGE_SIZE } = {}) {
|
|
210
|
+
const queryTerm = termQueryOverDocumentClient({ client, tableName, pageSize });
|
|
211
|
+
const rows = [];
|
|
212
|
+
let exclusiveStartKey;
|
|
213
|
+
for (;;) {
|
|
214
|
+
const response = await queryTerm({ band, term, exclusiveStartKey });
|
|
215
|
+
for (const item of response.rows) {
|
|
216
|
+
rows.push({ rowKey: item.rowKey, rowClass: item.rowClass, term: item.term, json: item.json });
|
|
217
|
+
}
|
|
218
|
+
exclusiveStartKey = response.lastEvaluatedKey;
|
|
219
|
+
if (!exclusiveStartKey) break;
|
|
220
|
+
}
|
|
221
|
+
return rows;
|
|
222
|
+
}
|