@polycode-projects/the-mechanical-code-talker 5.0.25 → 5.0.26

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
@@ -123,7 +123,7 @@ derive by rule from both. Every answer is either grounded or an honest miss.
123
123
  | `reports/` | benchmark write-ups (`BENCHMARK_*.md`) and `PAGE_WEIGHTS.md` — see the root `STATUS.md` for the one-page summary these feed |
124
124
  | `playtests/` | numbered playtest session logs, one edge found and fixed per entry |
125
125
  | `archive/` | delivered `PLAN_*.md`/`BENCHMARK_*.md` docs, kept for history |
126
- | `public/` | the demo site: the hand-written home page, the six about pages, the shared stylesheet and the model/screenshot assets. The demo pages and browser bundles beside them are gitignored build outputs of `npm run demo:build` |
126
+ | `public/` | the demo site: the hand-written home page, `help.html`, the six about pages, `receipts.html`, `claims.html`, the shared stylesheet and the model/screenshot assets. The demo pages and browser bundles beside them are gitignored build outputs of `npm run demo:build` |
127
127
 
128
128
  `node_modules/` (dependencies) and dotfiles/hidden tooling directories are omitted above.
129
129
 
@@ -417,10 +417,30 @@ own domain: a full chat seeded with 63,470 facts (the same nine bands as
417
417
  **memory ledger** (every fact as a readable sentence; drill by clicking the
418
418
  terms inside), and a Towers-of-Hanoi **plan** replayed move by move. A 3D
419
419
  **town square** has a fox and goblins each plan their own move from what
420
- they've personally seen. The rest are the text-adventure game and a
421
- **sprite gallery** whose chat dock answers from 1,480 generated sprite
422
- facts. The chat page and the ledger take the same paste-or-drop text in
420
+ they've personally seen; the same game also opens onto a market day in the
421
+ square and a chapel corner where two foxes hunt, each its own closed-opener
422
+ scene. The text-adventure page renders its household staff (butler, cook,
423
+ gardener, housekeeper) as turning, walking sprites on their own schedule,
424
+ skipped entirely if you have reduced motion set. The rest are the
425
+ text-adventure game and a **sprite gallery** whose chat dock answers from
426
+ 1,480 generated sprite facts: hover a tile to flip it between its static and
427
+ moving frame, click one to start it turning and click again to cycle its
428
+ emotions, hit "random scene" to compose a sentence from the graph's own
429
+ vocabulary (colours, emotions, roles, rooms), or open an ontology tree to see
430
+ every class's `rdfs:subClassOf` parent drawn as a connector line rather than
431
+ listed. The chat page and the ledger take the same paste-or-drop text in
423
432
  place; every page that holds a fact store exports it as JSONL.
433
+
434
+ Two browsers can also link directly, no server in between: chat's share
435
+ overlay walks a five-step WebRTC handshake (mint an invite, send it, create
436
+ the reply, send that back, paste it to connect), and the mesh grows past a pair — three peers converge
437
+ on the same fact store through a deterministic merge, real browsers driving
438
+ real WebRTC in CI, not a mock. `help.html` walks asking, teaching, sharing,
439
+ and what to do when something goes wrong. `receipts.html` and `claims.html`
440
+ carry the site's own numbers and claims, each figure naming the committed
441
+ file it was measured or rendered from, including the ones that don't flatter
442
+ tmct.
443
+
424
444
  The site hosts its own copy of wink-nlp, ships its assets precompressed,
425
445
  and a service worker precaches the big ones, so a second visit works
426
446
  offline. `tmct chat --render spider-fly|adventure|sprites [--output <path>]`
@@ -480,6 +500,16 @@ resolves to a real graph traversal or declines cleanly:
480
500
  entities' real edges side by side, never a hand-written diff;
481
501
  - list follow-ups: after "which modules import src/core/model.mjs",
482
502
  "which of those are tested" resolves against that list;
503
+ - follow-up context more broadly: "it", "that", and "those" bind to whatever
504
+ you just asked about or were told, so a listed set survives a count ("which
505
+ modules import http.mjs", then "how many of those are tested" — and "those"
506
+ still means that same list on the turn after the count), and a
507
+ genuine tie — "that" fitting two things said in the same turn — declines
508
+ and lists both candidates rather than guessing which one you meant;
509
+ - filler-clause openers: "oh nice. um what about cats" answers like its
510
+ clean form underneath, but only when the opener matches a closed inventory
511
+ of fillers and what's left still grounds; a stripped remainder can never
512
+ reach the teach lane, so a filler-topped teach attempt still declines;
483
513
  - curated synonyms plus a filtered ConceptNet slice, clause openers
484
514
  (*because/although/while*), conditionals, and false-premise flags ("why
485
515
  does X still import Y" when it no longer does).
@@ -627,6 +657,16 @@ proof chain, composed answer) for a caller that wants to consume this
627
657
  programmatically rather than read the report. `tmct plan --help` has the full
628
658
  flag reference.
629
659
 
660
+ `/goals` (or `tmct plan --goals` on the command line) lists what a trace can
661
+ be recognized against: the maintenance invariants above, one goal per
662
+ declared tool, this world's own objective, and whatever you've taught as an
663
+ action rule. Inside the text adventure, ask "what am I doing" or "what is
664
+ the butler doing" and tmct reads the moves actually taken and names the
665
+ declared goal they fit, by containment. A trace that fits two goals equally
666
+ well declines and lists both rather than picking one, and a trace that fits
667
+ none is told so plainly, pointed at the goal set it didn't match — the same
668
+ honest-miss rule the rest of tmct runs on.
669
+
630
670
  ## Teach it a game, then ask it to plan
631
671
 
632
672
  The planner above works over a fixed toolset. This one works over rules you
@@ -670,6 +710,14 @@ asserts the plan is exactly 2^n − 1 moves every time, and a second game
670
710
  conjunction) solves with zero interpreter changes. `--render blocks` writes
671
711
  the plan as a self-contained animated page (see "Two more surfaces" above).
672
712
 
713
+ Once a plan is found, you can question it without re-solving for real. "what
714
+ if disk-1 started on peg-c instead?" re-solves the hypothetical board and
715
+ reports its own move count, leaving the held plan, its cursor, and its move
716
+ count untouched. "why did you move disk-1 first instead of disk-2?" (or "why
717
+ not move disk-2 first?", the same answer) forces the alternative first move
718
+ and names either the extra cost against the plan found or the taught
719
+ precondition that blocks it outright.
720
+
673
721
  ## Play a game with it
674
722
 
675
723
  Three games run inside an ordinary chat session, no setup.
@@ -742,6 +790,15 @@ the curated revision-pinned pack (`reference`, 0.6). A fact fetched live never
742
790
  outranks the shipped article on the same term, and a fact you teach outranks
743
791
  both.
744
792
 
793
+ That miss-time rescue is passive. `research <topic>` is the deliberate
794
+ version: say `research owls` and tmct fetches the article, ingests it as
795
+ graph facts, and queues the topics its lead section links to, one per
796
+ `research next` (the chat page's own play button submits that for you).
797
+ Asking by name is its own consent for the fetch: unlike the miss-time
798
+ rescue, it needs no `/wiki on`. A topic that fails to fetch or ground
799
+ reports the miss plainly and moves the queue on rather than faking a result.
800
+ `research stop` clears the queue.
801
+
745
802
  ## How it remembers
746
803
 
747
804
  tmct's memory has two layers, both fed by every parsed request and response and
@@ -808,7 +865,10 @@ built-in lexicon, as long as one side of the sentence is already grounded.
808
865
  tmct never mints a fact between two totally ungrounded terms; it declines and
809
866
  nudges you to ground one side first. Quantified teaching stores the
810
867
  quantifier ("some functions are risky" … "how many functions are risky" →
811
- "A few."), and "how many facts are there" counts the store back.
868
+ "A few."), and "how many facts are there" counts the store back. A
869
+ quantified subject over a locative works the same way: "every disk rests on
870
+ peg-a" teaches, so does "one more disk rests on peg-a", and the read-back
871
+ answers either shape ("does every disk rest on peg-a" → "yes — …").
812
872
 
813
873
  The store answers about its own contents directly. "list facts" and "list
814
874
  utterances" enumerate what it holds; "how many sessions are there", "how many
@@ -1558,9 +1618,9 @@ npm run chatbench:judge -- --product /tmp/chatbench-smoke/product.jsonl
1558
1618
  tmct is $0 to run and meant to be trusted offline, so the supply chain is
1559
1619
  hardened:
1560
1620
 
1561
- - CI runs **SAST and secret detection**.
1562
- - A nightly **`npm audit` + OSV-Scanner** job watches dependencies.
1563
- - Releases are published with **npm provenance** (`--provenance`).
1621
+ - CI runs **SAST (semgrep) and secret detection** on every pipeline.
1622
+ - Releases are published with **provenance-signed** npm publishing (`--provenance`).
1623
+ - `npm run audit` runs a local `npm audit` check on demand; nothing schedules it.
1564
1624
 
1565
1625
  The npm tarball carries Sigstore-signed provenance naming the GitLab pipeline
1566
1626
  that built it. Every published version also gets a GitLab release tag pinned to
@@ -1642,9 +1702,12 @@ edition, the retrieval date, the terms tmct uses, and what could not be verified
1642
1702
  `owl:disjointWith` would over-claim, since "john is not a man" denies one membership rather than
1643
1703
  a class axiom, and OWL 2's `negativePropertyAssertion` needs a reified shape the flat JSON store
1644
1704
  has no room for.
1645
- - **Dialogue acts.** tmct has no intent vocabulary. ISO 24617-2 (SemAF) is the standard for one, and
1646
- `docs/references/schemas/iso-24617-2-dialogue-acts.md` maps tmct's behaviour onto it so that if
1647
- one is built it uses the standard's names.
1705
+ - **Dialogue acts.** ISO 24617-2 (SemAF) is the standard for tagging a turn's own speech act
1706
+ (question, assertion, request), and tmct has no such taxonomy.
1707
+ `docs/references/schemas/iso-24617-2-dialogue-acts.md` maps tmct's behaviour onto the standard's
1708
+ names, in case one gets built. Goal recognition is a separate, shipped capability: `/goals` and
1709
+ `tmct plan --goals` list the goals a trace can be checked against, and the recognizer matches an
1710
+ observed trace to one of them by containment, refusing when nothing fits.
1648
1711
 
1649
1712
  ## Licensing
1650
1713
 
package/bin/tmct.mjs CHANGED
@@ -1375,6 +1375,87 @@ async function main() {
1375
1375
  return;
1376
1376
  }
1377
1377
 
1378
+ if (mode === "classify") {
1379
+ // `tmct classify` — the explicit EL saturation batch (never on the chat hot
1380
+ // path): normalize the stored TBox to EL normal forms and forward-chain the
1381
+ // seven completion rules into bounded, low-trust, retractable entailed
1382
+ // facts. Same repo resolution as `syllogise` — resolveRuntimeConfig
1383
+ // (src/services/cli-args.mjs): --repo > git root > cwd. Also accepts
1384
+ // `--config` for symmetry (classify reads no code graph either).
1385
+ const rest = process.argv.slice(3);
1386
+ const numFlag = (name, dflt) => {
1387
+ const j = rest.indexOf(name);
1388
+ const v = j !== -1 ? Number(rest[j + 1]) : NaN;
1389
+ return Number.isFinite(v) ? v : dflt;
1390
+ };
1391
+ const { resolveRuntimeConfig } = await import("../src/services/cli-args.mjs");
1392
+ const { classifyEl, DEFAULT_EL_BUDGET, DEFAULT_EL_ROUNDS } = await import("../src/domain/el-classify.mjs");
1393
+ const { resolveReasoningConfig } = await import("../src/domain/reasoning-config.mjs");
1394
+ const { loadMemory, readFactRows, appendFacts, openMemoryBackend } = await import("../src/adapters/memory/core.mjs");
1395
+ const { repo, toml } = await resolveRuntimeConfig({ argv: rest });
1396
+ // Same env > tmct.toml > default backend resolution as `tmct syllogise` —
1397
+ // the entailed facts must land in the store chat reads back.
1398
+ const backendChoice = String(process.env.TMCT_MEMORY_BACKEND || toml?.memory?.backend || "").trim().toLowerCase();
1399
+ const { dir: memoryDir, close: closeMemoryStore } = await openMemoryBackend(repo, backendChoice);
1400
+ const reasoning = resolveReasoningConfig(toml);
1401
+ let res;
1402
+ try {
1403
+ res = await classifyEl(memoryDir, {
1404
+ budget: numFlag("--budget", reasoning.classifyBudget ?? DEFAULT_EL_BUDGET),
1405
+ rounds: numFlag("--rounds", reasoning.classifyRounds ?? DEFAULT_EL_ROUNDS),
1406
+ store: { loadMemory, readFactRows, appendFacts },
1407
+ });
1408
+ } finally {
1409
+ await closeMemoryStore();
1410
+ }
1411
+ process.stdout.write(
1412
+ `tmct classify — derived ${res.count} entailed fact(s) (rounds ${res.rounds}, budget ${res.budget})`
1413
+ + (res.unsatisfiable.length ? `, ${res.unsatisfiable.length} unsatisfiable class(es): ${res.unsatisfiable.join(", ")}` : "")
1414
+ + (res.truncated ? ` — budget reached, more may follow; run \`tmct classify --budget <n>\` for a wider pass` : "") + "\n",
1415
+ );
1416
+ return;
1417
+ }
1418
+
1419
+ if (mode === "news") {
1420
+ // `tmct news` — the news feed over this graph: poll contemporary sources,
1421
+ // rank ungrounded terms, enrich the top terms through knowledge-base sources,
1422
+ // and build a feed of what changed. Same repo resolution as `memory`/
1423
+ // `syllogise` — resolveRuntimeConfig (src/services/cli-args.mjs): --repo >
1424
+ // git root > cwd. Also accepts `--config` for symmetry.
1425
+ const rest = process.argv.slice(3);
1426
+ const { resolveRuntimeConfig, strFlag } = await import("../src/services/cli-args.mjs");
1427
+ const { newsTurn, resolveNewsConfig, createNewsState } = await import("../src/services/news.mjs");
1428
+ const { loadMemory, readFactRows, appendFacts, openMemoryBackend } = await import("../src/adapters/memory/core.mjs");
1429
+ const { loadTomlConfig } = await import("../src/adapters/toml-config.mjs");
1430
+ const { repo, toml } = await resolveRuntimeConfig({ argv: rest });
1431
+ // Same env > tmct.toml > default backend resolution as `tmct memory` — the
1432
+ // news facts must land in the store chat reads back.
1433
+ const backendChoice = String(process.env.TMCT_MEMORY_BACKEND || toml?.memory?.backend || "").trim().toLowerCase();
1434
+ const { dir: memoryDir, close: closeMemoryStore } = await openMemoryBackend(repo, backendChoice);
1435
+ const store = { loadMemory, readFactRows, appendFacts };
1436
+ const memory = await loadMemory(memoryDir);
1437
+ const rows = readFactRows(memory);
1438
+ const config = resolveNewsConfig(toml?.news);
1439
+ const state = createNewsState();
1440
+ let res;
1441
+ try {
1442
+ const line = rest.join(" ").trim();
1443
+ // Prepend `/news` to make parseNewsRequest recognize the subcommand.
1444
+ const newsLine = line ? `/news ${line}` : "/news poll";
1445
+ res = await newsTurn(newsLine, {
1446
+ memoryDir, rows, store, config, state, now: () => new Date().toISOString(),
1447
+ });
1448
+ } finally {
1449
+ await closeMemoryStore();
1450
+ }
1451
+ if (res) {
1452
+ process.stdout.write(res.text + "\n");
1453
+ } else {
1454
+ process.stdout.write("(no response)\n");
1455
+ }
1456
+ return;
1457
+ }
1458
+
1378
1459
  if (mode === "extract") {
1379
1460
  // `tmct extract` — run a text file's sentences through the chat's own teach
1380
1461
  // recognizer and keep what it grounds. Lazily imported: it pulls the whole
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.25",
3
+ "version": "5.0.26",
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.",
@@ -98,6 +98,7 @@
98
98
  "capture:hero": "node --disable-warning=ExperimentalWarning test-capture/hero-mudiii.capture.mjs",
99
99
  "gen:screenshots": "node scripts/gen-screenshots.mjs",
100
100
  "gen:og-images": "node scripts/gen-og-images.mjs",
101
+ "probe:news-sources": "node scripts/probe-news-sources.mjs",
101
102
  "check:links": "node scripts/check-links.mjs",
102
103
  "check:pii": "node scripts/pii-lint.mjs",
103
104
  "check:pack": "node scripts/check-pack-manifest.mjs",
@@ -127,6 +128,8 @@
127
128
  "memory": "node --disable-warning=ExperimentalWarning bin/tmct.mjs memory",
128
129
  "memory:verbose": "node --disable-warning=ExperimentalWarning bin/tmct.mjs memory --verbose",
129
130
  "syllogise": "node --disable-warning=ExperimentalWarning bin/tmct.mjs syllogise",
131
+ "classify": "node --disable-warning=ExperimentalWarning bin/tmct.mjs classify",
132
+ "news": "node --disable-warning=ExperimentalWarning bin/tmct.mjs news",
130
133
  "viz": "node --disable-warning=ExperimentalWarning bin/tmct.mjs viz",
131
134
  "viz:term": "node --disable-warning=ExperimentalWarning bin/tmct.mjs viz --term",
132
135
  "plan": "node --disable-warning=ExperimentalWarning bin/tmct.mjs plan",
@@ -160,6 +163,7 @@
160
163
  "claims": "node scripts/claims/run-all.mjs",
161
164
  "claim:prose-band": "node scripts/claims/claim-prose-band.mjs",
162
165
  "claim:openbookqa": "node scripts/claims/claim-openbookqa.mjs",
166
+ "claim:commonsenseqa": "node scripts/claims/claim-commonsenseqa.mjs",
163
167
  "claim:planner": "node scripts/claims/claim-planner.mjs",
164
168
  "roll": "node scripts/roll.mjs",
165
169
  "build:ask-bundle": "node scripts/build-ask-bundle.mjs",
@@ -1,10 +1,12 @@
1
1
  // corpus/courtesy.mjs — the throttle, cool-off and cache machinery shared by
2
- // every live research adapter that talks to a Wikimedia API (wikipedia-live.mjs,
3
- // wikidata-live.mjs): one in-flight fetch at a time, a minimum interval between
4
- // round trips, a 429/maxlag cool-off honouring Retry-After, an abort timeout on
5
- // every fetch, and a cache that keeps hits AND misses so a term is never asked
6
- // twice. Every failure of any kind reads as null, so the caller's honest miss
7
- // stands.
2
+ // every live adapter that fetches a third party: the research sources
3
+ // (wikipedia-live.mjs, wikidata-live.mjs, wiktionary-live.mjs,
4
+ // dbpedia-lookup-live.mjs) and the news sources (news-sources.mjs). One
5
+ // in-flight fetch at a time, a minimum interval between round trips, a
6
+ // 429/maxlag cool-off honouring Retry-After, an abort timeout on every fetch,
7
+ // optional ETag/Last-Modified conditional-request memory, and a cache that
8
+ // keeps hits AND misses so a term is never asked twice. Every failure of any
9
+ // kind reads as null, so the caller's honest miss stands.
8
10
  //
9
11
  // No node builtins — this module ships in the browser bundles unchanged; the
10
12
  // only I/O is fetch.
@@ -18,13 +20,23 @@ export const RETRY_AFTER_FLOOR_MS = 5000;
18
20
  export const MAXLAG_SECONDS = 5;
19
21
 
20
22
  /**
21
- * One adapter instance's courtesy state: `{ fetchJson(url), cachedFetch(key,
22
- * work) }`. Every option a caller passes wins, so a test can hand it a zero
23
- * interval and a stub transport.
23
+ * One adapter instance's courtesy state: `{ fetchJson(url), fetchText(url),
24
+ * cachedFetch(key, work) }`. Every option a caller passes wins, so a test can
25
+ * hand it a zero interval and a stub transport.
24
26
  *
25
27
  * `waitForSlot` picks the throttle posture: false answers null the moment a
26
28
  * slot is unavailable (never block a chat turn), true waits for it (a queue
27
29
  * paced turn-by-turn, where a false miss would be dishonest).
30
+ *
31
+ * `validators`, when given, is a Map the CALLER owns (keyed by URL) that this
32
+ * gate reads an `{ etag, lastModified }` entry from before every request —
33
+ * sent as `If-None-Match` / `If-Modified-Since` — and writes back to after
34
+ * every 2xx response that carries an ETag or Last-Modified header. A 304
35
+ * answers `{ notModified: true }` instead of the usual body, so a caller can
36
+ * tell "nothing changed" apart from "the source failed" apart from "here is
37
+ * the new body". Without `validators` this is all inert: no conditional
38
+ * headers go out, and a 304 (which no server sends without them) falls
39
+ * through the ordinary `!res.ok` path to null exactly as before.
28
40
  */
29
41
  export function createCourtesyGate({
30
42
  fetchImpl,
@@ -33,6 +45,7 @@ export function createCourtesyGate({
33
45
  retryAfterFloorMs = RETRY_AFTER_FLOOR_MS,
34
46
  userAgent,
35
47
  waitForSlot = false,
48
+ validators = null,
36
49
  } = {}) {
37
50
  const doFetch = fetchImpl ?? ((...args) => globalThis.fetch(...args));
38
51
  const cache = new Map(); // key -> value | null (hits AND settled misses)
@@ -55,31 +68,62 @@ export function createCourtesyGate({
55
68
  coolOffUntil = Date.now() + Math.max(retryAfterMs || 0, retryAfterFloorMs);
56
69
  }
57
70
 
58
- /** One GET, JSON-parsed, with the abort timeout and the 429/maxlag cool-off
59
- * wired in. Any failure of any kind — network, non-2xx, unparseable body —
60
- * reads as null. */
61
- async function fetchJson(url) {
71
+ /** The conditional-request headers this URL's remembered validator earns,
72
+ * or null when there is none yet (first fetch of this URL, or no
73
+ * `validators` map at all). */
74
+ function conditionalHeaders(url) {
75
+ const entry = validators?.get(url);
76
+ if (!entry) return null;
77
+ const headers = {};
78
+ if (entry.etag) headers["If-None-Match"] = entry.etag;
79
+ if (entry.lastModified) headers["If-Modified-Since"] = entry.lastModified;
80
+ return Object.keys(headers).length ? headers : null;
81
+ }
82
+
83
+ /** Remember this URL's validator off a 2xx response, so the NEXT fetch of
84
+ * it can ask "did this change" instead of paying for the whole body. */
85
+ function rememberValidators(url, res) {
86
+ if (!validators) return;
87
+ const etag = res.headers?.get?.("etag") ?? "";
88
+ const lastModified = res.headers?.get?.("last-modified") ?? "";
89
+ if (!etag && !lastModified) return;
90
+ const prior = validators.get(url) ?? {};
91
+ validators.set(url, { etag: etag || prior.etag || "", lastModified: lastModified || prior.lastModified || "" });
92
+ }
93
+
94
+ /** One GET, with the abort timeout, the 429/maxlag cool-off and the
95
+ * conditional-request dance all wired in. Any failure of any kind —
96
+ * network, non-2xx, unparseable body — reads as null; a 304 reads as
97
+ * `{ notModified: true }`, but only when `validators` is in play (nothing
98
+ * else could have earned a 304 in the first place). `asJson` picks the
99
+ * body shape: parsed JSON (with the maxlag check) or raw text. */
100
+ async function fetchRaw(url, { asJson }) {
62
101
  const controller = typeof AbortController === "function" ? new AbortController() : null;
63
102
  const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
64
103
  try {
65
104
  const opts = {};
66
105
  if (controller) opts.signal = controller.signal;
67
- const headers = identifyingHeaders();
68
- if (headers) opts.headers = headers;
106
+ const headers = { ...(identifyingHeaders() ?? {}), ...(conditionalHeaders(url) ?? {}) };
107
+ if (Object.keys(headers).length) opts.headers = headers;
69
108
  const res = await doFetch(url, opts);
70
109
  if (res.status === 429) {
71
110
  openCoolOff(res.headers?.get?.("retry-after"));
72
111
  return null;
73
112
  }
113
+ if (res.status === 304) return validators ? { notModified: true } : null;
74
114
  if (!res.ok) return null;
75
- const body = await res.json();
76
- // A maxlag rejection arrives as HTTP 200 with an error body and a
77
- // Retry-After header — back off exactly as a 429 asks.
78
- if (body?.error?.code === "maxlag") {
79
- openCoolOff(res.headers?.get?.("retry-after"));
80
- return null;
115
+ rememberValidators(url, res);
116
+ if (asJson) {
117
+ const body = await res.json();
118
+ // A maxlag rejection arrives as HTTP 200 with an error body and a
119
+ // Retry-After header — back off exactly as a 429 asks.
120
+ if (body?.error?.code === "maxlag") {
121
+ openCoolOff(res.headers?.get?.("retry-after"));
122
+ return null;
123
+ }
124
+ return body;
81
125
  }
82
- return body;
126
+ return await res.text();
83
127
  } catch {
84
128
  return null;
85
129
  } finally {
@@ -87,6 +131,18 @@ export function createCourtesyGate({
87
131
  }
88
132
  }
89
133
 
134
+ async function fetchJson(url) {
135
+ return fetchRaw(url, { asJson: true });
136
+ }
137
+
138
+ /** Same slot, cool-off, timeout and conditional-request handling as
139
+ * fetchJson, returning the raw body text instead of a parsed object — what
140
+ * every feed format (RSS/Atom/JSON Feed) needs, since JSON Feed is the only
141
+ * one of the three worth parsing before this layer hands it over. */
142
+ async function fetchText(url) {
143
+ return fetchRaw(url, { asJson: false });
144
+ }
145
+
90
146
  /** When the next network slot opens: past the cool-off, past the minimum
91
147
  * interval since the last taken slot. */
92
148
  const slotOpensAt = () => Math.max(coolOffUntil, lastLookupAt + minIntervalMs);
@@ -107,10 +163,17 @@ export function createCourtesyGate({
107
163
  }
108
164
  }
109
165
 
110
- /** One slot-gated, cached operation: cache first (a settled hit or miss is
111
- * never refetched), then the slot, then `work()`, with every failure
112
- * cached as null so it never costs a second round trip. */
113
- async function cachedFetch(cacheKey, work) {
166
+ /** One slot-gated operation: cache first (a settled hit or miss is never
167
+ * refetched), then the slot, then `work()`, with every failure cached as
168
+ * null so it never costs a second round trip.
169
+ *
170
+ * `remember: false` skips the cache write (the poll loop's use: a live
171
+ * feed must re-fetch every cycle, never answer from a stale hit), while
172
+ * still gating `work()` behind the slot — so a caller that needs "paced,
173
+ * but never stale" (every feed poller in news-sources.mjs) still gets the
174
+ * minInterval spacing between successive calls, just without the
175
+ * answer-forever memory a term lookup wants. */
176
+ async function cachedFetch(cacheKey, work, { remember = true } = {}) {
114
177
  if (cache.has(cacheKey)) return cache.get(cacheKey);
115
178
  if (!(await takeSlot())) return null;
116
179
  let value = null;
@@ -121,9 +184,9 @@ export function createCourtesyGate({
121
184
  } finally {
122
185
  inFlight = false;
123
186
  }
124
- cache.set(cacheKey, value);
187
+ if (remember) cache.set(cacheKey, value);
125
188
  return value;
126
189
  }
127
190
 
128
- return { fetchJson, cachedFetch };
191
+ return { fetchJson, fetchText, cachedFetch };
129
192
  }
@@ -0,0 +1,116 @@
1
+ // corpus/dbpedia-lookup-live.mjs — the live DBpedia Lookup research source:
2
+ // one GET against lookup.dbpedia.org's ranked entity search, mapped into the
3
+ // shipped reference-pack article-row shape. The top hit's own category is the
4
+ // isa: DBpedia categories are DBpedia's OWN classification of the resource
5
+ // (not free text to parse), so there is no sentence to read a genus out of —
6
+ // unlike wiktionary-live.mjs, whose definitions are prose.
7
+ //
8
+ // Courtesy is structural, mirroring the other live research sources: one
9
+ // in-flight lookup at a time, a minimum interval between round trips, a 429
10
+ // cool-off honouring Retry-After, an abort timeout on every fetch, and a
11
+ // cache that keeps hits AND misses so a term is never asked twice. Every
12
+ // failure of any kind reads as null, so the caller's honest miss stands.
13
+ //
14
+ // No node builtins — this module ships in the browser bundles unchanged; the
15
+ // only I/O is fetch.
16
+
17
+ import { normFactTerm } from "../../domain/hash.mjs";
18
+ import { stripMarkup } from "../../domain/feed-normalize.mjs";
19
+ import { sentencesUpTo, SUMMARY_CHAR_CAP } from "../../domain/reference-pack.mjs";
20
+ import { isResearchSourceRow, registerResearchSource, researchSourceTag } from "./research-source.mjs";
21
+ import { createCourtesyGate, DEFAULT_TIMEOUT_MS, DEFAULT_MIN_INTERVAL_MS } from "./courtesy.mjs";
22
+
23
+ export const DBPEDIA_LOOKUP_ORIGIN = "https://lookup.dbpedia.org";
24
+ export const DBPEDIA_LOOKUP_SOURCE_NAME = "dbpedia-lookup";
25
+ export const DBPEDIA_LOOKUP_SOURCE_LABEL = "DBpedia";
26
+ export const DBPEDIA_LOOKUP_LICENCE = "CC BY-SA 3.0";
27
+
28
+ export const DBPEDIA_LOOKUP_USER_AGENT = "the-mechanical-code-talker (+https://tmct.polycode.co.uk/)";
29
+
30
+ // Lookup's search results carry no revision id of their own; the row shape
31
+ // needs a positive integer regardless, so every DBpedia row cites this fixed
32
+ // placeholder rather than a real revision.
33
+ const NO_REVISION_ID = 1;
34
+ const MAX_RESULTS = 5;
35
+
36
+ /** A category resource URI's local name, spaced and folded to a fact term:
37
+ * ".../resource/Category:Cardiac_anatomy" -> "cardiac anatomy". */
38
+ function categoryTerm(categoryUrl) {
39
+ const local = String(categoryUrl ?? "").split("/").pop() ?? "";
40
+ const name = local.replace(/^Category:/, "").replace(/_/g, " ").trim();
41
+ return name ? normFactTerm(name) : null;
42
+ }
43
+
44
+ /**
45
+ * A live DBpedia Lookup research source: { name, origin, lookup(term),
46
+ * provenanceTag(term) } — the research-source.mjs contract.
47
+ *
48
+ * `fetchImpl` defaults to the global fetch. `waitForSlot` picks the throttle
49
+ * posture: false answers null the moment a slot is unavailable (never block a
50
+ * chat turn), true waits for it (the research queue and the news enrichment
51
+ * loop, both paced turn-by-turn, where a false miss would be dishonest).
52
+ */
53
+ export function createDbpediaLookupLiveProvider({
54
+ fetchImpl,
55
+ origin = DBPEDIA_LOOKUP_ORIGIN,
56
+ timeoutMs = DEFAULT_TIMEOUT_MS,
57
+ minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
58
+ userAgent = DBPEDIA_LOOKUP_USER_AGENT,
59
+ waitForSlot = false,
60
+ sourceName = DBPEDIA_LOOKUP_SOURCE_NAME,
61
+ } = {}) {
62
+ const gate = createCourtesyGate({ fetchImpl, timeoutMs, minIntervalMs, userAgent, waitForSlot });
63
+
64
+ async function roundTrip(key) {
65
+ const body = await gate.fetchJson(
66
+ `${origin}/api/search?query=${encodeURIComponent(key)}&maxResults=${MAX_RESULTS}&format=json`,
67
+ );
68
+ const doc = Array.isArray(body?.docs) ? body.docs[0] : null;
69
+ if (!doc) return null;
70
+ const label = stripMarkup(String(doc.label?.[0] ?? ""));
71
+ const comment = stripMarkup(String(doc.comment?.[0] ?? ""));
72
+ const resourceUrl = String(doc.resource?.[0] ?? "");
73
+ if (!label || !comment || !resourceUrl) return null;
74
+ const row = {
75
+ term: key,
76
+ title: label,
77
+ text: comment,
78
+ summary: sentencesUpTo(comment, SUMMARY_CHAR_CAP),
79
+ url: resourceUrl,
80
+ revid: NO_REVISION_ID,
81
+ source: DBPEDIA_LOOKUP_SOURCE_LABEL,
82
+ licence: DBPEDIA_LOOKUP_LICENCE,
83
+ };
84
+ const isa = categoryTerm(Array.isArray(doc.category) ? doc.category[0] : null);
85
+ if (isa && isa !== key) row.isa = isa;
86
+ return isResearchSourceRow(row) ? row : null;
87
+ }
88
+
89
+ return {
90
+ name: sourceName,
91
+ origin,
92
+
93
+ provenanceTag(term) {
94
+ return researchSourceTag(sourceName, term);
95
+ },
96
+
97
+ async lookup(term) {
98
+ const key = normFactTerm(term ?? "");
99
+ if (!key) return null;
100
+ return gate.cachedFetch(key, () => roundTrip(key));
101
+ },
102
+ };
103
+ }
104
+
105
+ /** The DBpedia Lookup research source with `waitForSlot` on: paced callers
106
+ * (the research queue, the news enrichment loop) wait for their polite slot
107
+ * rather than reporting a false miss. Every option the caller passes wins,
108
+ * so a test can hand it a stub transport and a zero interval. */
109
+ export function createDbpediaLookupResearchSource(options = {}) {
110
+ return createDbpediaLookupLiveProvider({ waitForSlot: true, ...options });
111
+ }
112
+
113
+ registerResearchSource({
114
+ name: DBPEDIA_LOOKUP_SOURCE_NAME,
115
+ create: createDbpediaLookupResearchSource,
116
+ });