@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 CHANGED
@@ -981,6 +981,18 @@ package or a bare user gets a working install in one command.
981
981
  > Install-size note: tmct depends on wink-nlp's deterministic English language
982
982
  > model (~3.8 MB installed). That model is a lookup table, not an LLM.
983
983
 
984
+ ### Custom memory backends
985
+
986
+ Memory — the facts you teach tmct — lives behind a pluggable adapter seam. The CLI and library come with three backends: in-memory (ephemeral), SQLite (the CLI's default), and DynamoDB (for hosted deployments). You can inject a custom backend and tmct will read and write through it instead. The backend is a small async row store scoped to one session key — it needs eight methods (read, write, delete, and a couple of scalar sidecars). The published conformance suite validates that a custom backend meets the contract. See `docs/adapter-contract.md` for the full interface and `src/adapters/memory/row-backend-memory.mjs` for the reference implementation. Wire it into a session:
987
+
988
+ ```js skip=illustrative-import
989
+ import { createSession } from "@polycode-projects/the-mechanical-code-talker";
990
+ import { createMyBackend } from "./my-backend.mjs";
991
+
992
+ const backend = createMyBackend(sessionKey, config);
993
+ const session = await createSession({ memoryBackend: backend });
994
+ ```
995
+
984
996
  ### Full command reference (`tmct --help`)
985
997
 
986
998
  `tmct --help` always prints the real, current flags. What follows is that
@@ -1194,6 +1206,21 @@ kill $SERVE_PID
1194
1206
  [--graph <path>] the same thing. --graph names the graph file outright
1195
1207
  [--config <path>] (repeatable), --config an alternate tmct.toml
1196
1208
  tmct cli digest '{…}' architecture map + per-module context bundles
1209
+ ```
1210
+
1211
+ `tmct corpus` loads a shared, read-only corpus band into a DynamoDB
1212
+ row-backend table, or clears one; the deployed turn service reads the loaded
1213
+ bands per query:
1214
+
1215
+ ```output:help:corpus
1216
+ tmct corpus load <band> [--table <name>] [--source <path>] [--dry-run] load a shared, read-only corpus band (wikidata-slice, wordnet-complete,
1217
+ [--table <name>] conceptnet-full) into a DynamoDB row-backend table from a jsonl of
1218
+ wire-row-shaped facts (default table from TMCT_DYNAMO_TABLE); a
1219
+ source whose digest already matches the band's manifest is a no-op
1220
+ [--source <path>] the band's jsonl (a scripts/corpus-bands/ build output, or any jsonl
1221
+ in the same wire-row shape)
1222
+ [--dry-run] report the row count and source digest without writing anything
1223
+ tmct corpus clear <band> [--table <name>] physically delete every row and the manifest for one band
1197
1224
  tmct --help show this help
1198
1225
  ```
1199
1226
 
package/bin/tmct.mjs CHANGED
@@ -1821,6 +1821,67 @@ async function main() {
1821
1821
  return;
1822
1822
  }
1823
1823
 
1824
+ if (mode === "corpus") {
1825
+ // `tmct corpus load|clear <band>` — the credentialed operator verb pair
1826
+ // over the shared, read-only corpus bands (src/adapters/memory/corpus-bands.mjs,
1827
+ // src/services/corpus-loader.mjs). Ambient AWS credentials only (a
1828
+ // profile locally, OIDC in CI) — this dispatch never embeds any.
1829
+ const rest = process.argv.slice(3);
1830
+ const subcommand = rest[0];
1831
+ if (subcommand !== "load" && subcommand !== "clear") {
1832
+ process.stderr.write("tmct corpus — name an action: `tmct corpus load <band>` or `tmct corpus clear <band>`\n");
1833
+ process.exitCode = 1;
1834
+ return;
1835
+ }
1836
+ const band = rest.slice(1).find((a) => !a.startsWith("-"));
1837
+ if (!band) {
1838
+ process.stderr.write(`tmct corpus ${subcommand} — name a band: \`tmct corpus ${subcommand} <band>\`\n`);
1839
+ process.exitCode = 1;
1840
+ return;
1841
+ }
1842
+ const { strFlag } = await import("../src/services/cli-args.mjs");
1843
+ const tableName = strFlag(rest, "--table") || process.env.TMCT_DYNAMO_TABLE;
1844
+ if (!tableName) {
1845
+ process.stderr.write("tmct corpus — no table name given (--table <name> or TMCT_DYNAMO_TABLE)\n");
1846
+ process.exitCode = 1;
1847
+ return;
1848
+ }
1849
+
1850
+ let DynamoDBClient;
1851
+ let DynamoDBDocument;
1852
+ try {
1853
+ ({ DynamoDBClient } = await import("@aws-sdk/client-dynamodb"));
1854
+ ({ DynamoDBDocument } = await import("@aws-sdk/lib-dynamodb"));
1855
+ } catch (cause) {
1856
+ process.stderr.write(
1857
+ "tmct corpus needs \"@aws-sdk/lib-dynamodb\" (>=3) installed alongside tmct; "
1858
+ + `run \`npm install @aws-sdk/lib-dynamodb\` and retry (${cause.message})\n`,
1859
+ );
1860
+ process.exitCode = 1;
1861
+ return;
1862
+ }
1863
+ const client = DynamoDBDocument.from(new DynamoDBClient({}));
1864
+
1865
+ if (subcommand === "load") {
1866
+ const source = strFlag(rest, "--source");
1867
+ if (!source) {
1868
+ process.stderr.write("tmct corpus load — name a source: `tmct corpus load <band> --source <path>`\n");
1869
+ process.exitCode = 1;
1870
+ return;
1871
+ }
1872
+ const { loadBand } = await import("../src/services/corpus-loader.mjs");
1873
+ const result = await loadBand({ client, tableName, band, source, dryRun: rest.includes("--dry-run") });
1874
+ const verb = { unchanged: "unchanged", loaded: "loaded", "dry-run": "would load" }[result.status];
1875
+ process.stdout.write(`tmct corpus load ${band}: ${verb} (${result.rowCount} row(s), source digest ${result.sourceDigest})\n`);
1876
+ return;
1877
+ }
1878
+
1879
+ const { clearBand } = await import("../src/services/corpus-loader.mjs");
1880
+ const result = await clearBand({ client, tableName, band });
1881
+ process.stdout.write(`tmct corpus clear ${band}: deleted ${result.deleted} item(s)\n`);
1882
+ return;
1883
+ }
1884
+
1824
1885
  // An unknown mode gets the instructive usage line and exit 2. (A bare invocation
1825
1886
  // never lands here — the argv splice above rewrote it to `chat`.)
1826
1887
  process.stderr.write(unknownInvocationMessage(process.argv.slice(2).join(" ")));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "6.0.0",
3
+ "version": "6.0.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -92,9 +92,13 @@
92
92
  "wink-nlp": "^2.4.0"
93
93
  },
94
94
  "peerDependencies": {
95
+ "@aws-sdk/client-lambda": ">=3",
95
96
  "@aws-sdk/lib-dynamodb": ">=3"
96
97
  },
97
98
  "peerDependenciesMeta": {
99
+ "@aws-sdk/client-lambda": {
100
+ "optional": true
101
+ },
98
102
  "@aws-sdk/lib-dynamodb": {
99
103
  "optional": true
100
104
  }
@@ -183,7 +187,10 @@
183
187
  "claim:news": "node scripts/news-rig.mjs",
184
188
  "roll": "node scripts/roll.mjs",
185
189
  "build:ask-bundle": "node scripts/build-ask-bundle.mjs",
186
- "build:row-service": "esbuild server/row-service/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --outfile=server/row-service/dist/handler.js",
190
+ "build:row-service": "esbuild server/row-service/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --external:@aws-sdk/client-lambda --outfile=server/row-service/dist/handler.js",
191
+ "build:turn-service": "esbuild server/turn-service/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --external:@aws-sdk/client-lambda --outfile=server/turn-service/dist/handler.js",
192
+ "build:turn-seed": "node server/turn-service/build-seed.mjs",
193
+ "build:news-worker": "esbuild server/news-worker/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --external:@aws-sdk/client-lambda --outfile=server/news-worker/dist/handler.js",
187
194
  "build:chat-bundle": "node scripts/build-chat-bundle.mjs",
188
195
  "build:spider-fly-bundle": "node scripts/build-spider-fly-bundle.mjs",
189
196
  "build:plan-bundle": "node scripts/build-plan-bundle.mjs",
@@ -8,12 +8,28 @@
8
8
  // keeps hits AND misses so a term is never asked twice. Every failure of any
9
9
  // kind reads as null, so the caller's honest miss stands.
10
10
  //
11
+ // The gate also counts what its fetches cost and what they hit: how many round
12
+ // trips a turn has spent, and how many of its failures said the source itself
13
+ // is struggling. The first bounds a turn (`beginTurn` opens the budget window,
14
+ // and a turn past its cap stops fetching and misses honestly); the second is
15
+ // what a source's circuit breaker reads through `stats()`, so an empty answer
16
+ // and a timing-out source never look alike to it.
17
+ //
11
18
  // No node builtins — this module ships in the browser bundles unchanged; the
12
19
  // only I/O is fetch.
13
20
 
21
+ import { isSystemicSourceStatus } from "../../domain/source-breaker.mjs";
22
+
23
+ /** The abort timeout on every single fetch: one source's slowness costs a turn
24
+ * this much and no more. */
14
25
  export const DEFAULT_TIMEOUT_MS = 4000;
15
26
  export const DEFAULT_MIN_INTERVAL_MS = 2000;
16
27
  export const RETRY_AFTER_FLOOR_MS = 5000;
28
+ /** How many round trips one turn may spend on a single source. A live
29
+ * reference lookup costs two (search, then read), a research step three at
30
+ * most, so the cap sits above what an honest turn needs and below what a
31
+ * retrying loop could spend. Only counted once a caller declares a turn. */
32
+ export const DEFAULT_MAX_FETCHES_PER_TURN = 6;
17
33
  // Action-API requests carry maxlag so an overloaded replica set answers with
18
34
  // an error we back off from instead of adding to its load (Wikimedia's own
19
35
  // recommended default for non-interactive clients).
@@ -43,6 +59,7 @@ export function createCourtesyGate({
43
59
  timeoutMs = DEFAULT_TIMEOUT_MS,
44
60
  minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
45
61
  retryAfterFloorMs = RETRY_AFTER_FLOOR_MS,
62
+ maxFetchesPerTurn = DEFAULT_MAX_FETCHES_PER_TURN,
46
63
  userAgent,
47
64
  waitForSlot = false,
48
65
  validators = null,
@@ -52,6 +69,11 @@ export function createCourtesyGate({
52
69
  let lastLookupAt = 0;
53
70
  let coolOffUntil = 0;
54
71
  let inFlight = false;
72
+ let fetches = 0;
73
+ let systemicFailures = 0;
74
+ let fetchesThisTurn = 0;
75
+ let turnBudgetOpen = false;
76
+ let budgetExhausted = false;
55
77
 
56
78
  const identifyingHeaders = () => {
57
79
  if (!userAgent) return null;
@@ -98,6 +120,12 @@ export function createCourtesyGate({
98
120
  * else could have earned a 304 in the first place). `asJson` picks the
99
121
  * body shape: parsed JSON (with the maxlag check) or raw text. */
100
122
  async function fetchRaw(url, { asJson }) {
123
+ if (turnBudgetOpen && fetchesThisTurn >= maxFetchesPerTurn) {
124
+ budgetExhausted = true;
125
+ return null;
126
+ }
127
+ fetches += 1;
128
+ fetchesThisTurn += 1;
101
129
  const controller = typeof AbortController === "function" ? new AbortController() : null;
102
130
  const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
103
131
  try {
@@ -105,13 +133,27 @@ export function createCourtesyGate({
105
133
  if (controller) opts.signal = controller.signal;
106
134
  const headers = { ...(identifyingHeaders() ?? {}), ...(conditionalHeaders(url) ?? {}) };
107
135
  if (Object.keys(headers).length) opts.headers = headers;
108
- const res = await doFetch(url, opts);
136
+ let res;
137
+ try {
138
+ res = await doFetch(url, opts);
139
+ } catch {
140
+ // Nothing came back at all: a dropped connection, a refused host, or
141
+ // this fetch's own abort timer. Every one of those is the source
142
+ // failing, not answering.
143
+ systemicFailures += 1;
144
+ return null;
145
+ }
109
146
  if (res.status === 429) {
110
147
  openCoolOff(res.headers?.get?.("retry-after"));
148
+ systemicFailures += 1;
111
149
  return null;
112
150
  }
113
151
  if (res.status === 304) return validators ? { notModified: true } : null;
114
- if (!res.ok) return null;
152
+ if (!res.ok) {
153
+ // A 404 for a term nobody wrote about is an answer; a 5xx is not.
154
+ if (isSystemicSourceStatus(res.status)) systemicFailures += 1;
155
+ return null;
156
+ }
115
157
  rememberValidators(url, res);
116
158
  if (asJson) {
117
159
  const body = await res.json();
@@ -119,12 +161,17 @@ export function createCourtesyGate({
119
161
  // Retry-After header — back off exactly as a 429 asks.
120
162
  if (body?.error?.code === "maxlag") {
121
163
  openCoolOff(res.headers?.get?.("retry-after"));
164
+ systemicFailures += 1;
122
165
  return null;
123
166
  }
124
167
  return body;
125
168
  }
126
169
  return await res.text();
127
170
  } catch {
171
+ // The response arrived and its body did not. A body cut off by this
172
+ // fetch's own timer is the source failing; an unparseable one is just
173
+ // an answer we cannot use.
174
+ if (controller?.signal?.aborted) systemicFailures += 1;
128
175
  return null;
129
176
  } finally {
130
177
  if (timer !== null) clearTimeout(timer);
@@ -188,5 +235,22 @@ export function createCourtesyGate({
188
235
  return value;
189
236
  }
190
237
 
191
- return { fetchJson, fetchText, cachedFetch };
238
+ /** Opens this gate's per-turn fetch budget and resets its count. A caller
239
+ * that never calls this spends no budget at all — a library consumer with
240
+ * no turn boundary keeps today's behaviour, and the cap applies exactly
241
+ * where a turn declares itself. */
242
+ function beginTurn() {
243
+ turnBudgetOpen = true;
244
+ fetchesThisTurn = 0;
245
+ budgetExhausted = false;
246
+ }
247
+
248
+ /** What this gate has spent and hit since it was created. `fetches` and
249
+ * `systemicFailures` only ever climb, so a caller reads them either side of
250
+ * one lookup and takes the difference. */
251
+ function stats() {
252
+ return { fetches, systemicFailures, fetchesThisTurn, budgetExhausted };
253
+ }
254
+
255
+ return { fetchJson, fetchText, cachedFetch, beginTurn, stats };
192
256
  }
@@ -89,6 +89,14 @@ export function createDbpediaLookupLiveProvider({
89
89
  return {
90
90
  name: sourceName,
91
91
  origin,
92
+ label: DBPEDIA_LOOKUP_SOURCE_LABEL,
93
+
94
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). */
95
+ beginTurn() { gate.beginTurn(); },
96
+
97
+ /** The source's own running totals, including the failures that said the
98
+ * source itself is struggling — what a circuit breaker reads. */
99
+ stats() { return gate.stats(); },
92
100
 
93
101
  provenanceTag(term) {
94
102
  return researchSourceTag(sourceName, term);
@@ -231,6 +231,14 @@ export function createWikidataLiveProvider({
231
231
  return {
232
232
  name: sourceName,
233
233
  origin,
234
+ label: WIKIDATA_SOURCE_LABEL,
235
+
236
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). */
237
+ beginTurn() { gate.beginTurn(); },
238
+
239
+ /** The source's own running totals, including the failures that said the
240
+ * source itself is struggling — what a circuit breaker reads. */
241
+ stats() { return gate.stats(); },
234
242
 
235
243
  /** The tag every fact this source contributes carries. */
236
244
  provenanceTag(term) {
@@ -43,6 +43,11 @@ export const SIMPLE_WIKIPEDIA_ORIGIN = "https://simple.wikipedia.org";
43
43
  export const WIKIPEDIA_LIVE_SOURCE_NAME = "wikipedia-live";
44
44
  export const SIMPLE_WIKIPEDIA_SOURCE_NAME = "simple-wikipedia";
45
45
 
46
+ /** What each of the two goes by in prose a reader sees, the same names their
47
+ * citations already carry. */
48
+ export const WIKIPEDIA_SOURCE_LABEL = "Wikipedia";
49
+ export const SIMPLE_WIKIPEDIA_SOURCE_LABEL = "Simple English Wikipedia";
50
+
46
51
  /** The identification string Wikimedia's robot policy asks API clients to
47
52
  * carry, pointing at this project's public site as the contact. Browsers
48
53
  * refuse to override the User-Agent request header, so the API-recognised
@@ -81,6 +86,7 @@ export function createWikipediaLiveProvider({
81
86
  userAgent = WIKIMEDIA_USER_AGENT,
82
87
  waitForSlot = false,
83
88
  sourceName = WIKIPEDIA_LIVE_SOURCE_NAME,
89
+ label = WIKIPEDIA_SOURCE_LABEL,
84
90
  } = {}) {
85
91
  const gate = createCourtesyGate({ fetchImpl, timeoutMs, minIntervalMs, userAgent, waitForSlot });
86
92
 
@@ -130,6 +136,17 @@ export function createWikipediaLiveProvider({
130
136
  return {
131
137
  name: sourceName,
132
138
  origin,
139
+ label,
140
+
141
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). A caller with
142
+ * a turn boundary calls it once at the top of the turn; one that has none
143
+ * never calls it and spends no budget. */
144
+ beginTurn() { gate.beginTurn(); },
145
+
146
+ /** The source's own running totals, including how many of its failures
147
+ * said the source itself is struggling — what a circuit breaker reads to
148
+ * tell a timing-out source from one that simply has no article. */
149
+ stats() { return gate.stats(); },
133
150
 
134
151
  /** The tag a fact gained through the research source contract carries. The
135
152
  * research lane stamps its own `research:<topic>@<depth>` tag instead when
@@ -257,6 +274,7 @@ export function createSimpleWikipediaResearchSource(options = {}) {
257
274
  return createWikipediaLiveProvider({
258
275
  origin: SIMPLE_WIKIPEDIA_ORIGIN,
259
276
  sourceName: SIMPLE_WIKIPEDIA_SOURCE_NAME,
277
+ label: SIMPLE_WIKIPEDIA_SOURCE_LABEL,
260
278
  waitForSlot: true,
261
279
  ...options,
262
280
  });
@@ -131,6 +131,14 @@ export function createWiktionaryLiveProvider({
131
131
  return {
132
132
  name: sourceName,
133
133
  origin,
134
+ label: WIKTIONARY_SOURCE_LABEL,
135
+
136
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). */
137
+ beginTurn() { gate.beginTurn(); },
138
+
139
+ /** The source's own running totals, including the failures that said the
140
+ * source itself is struggling — what a circuit breaker reads. */
141
+ stats() { return gate.stats(); },
134
142
 
135
143
  provenanceTag(term) {
136
144
  return researchSourceTag(sourceName, term);