@polycode-projects/the-mechanical-code-talker 5.0.15 → 5.0.17
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 +12 -3
- package/bin/tmct.mjs +52 -3
- package/corpus/LICENSES.json +3 -3
- package/corpus/domains/code/LICENSE-NOTICE +43 -0
- package/corpus/{seon → domains/code}/README.md +22 -24
- package/corpus/domains/code/vocab.json +43 -0
- package/corpus/reference/manifest.json +126 -126
- package/corpus/reference/shards/ref-00.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-01.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-02.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-03.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-04.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-05.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-06.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-07.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-08.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-09.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-0a.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-0b.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-0c.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-0d.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-0e.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-0f.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-10.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-11.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-12.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-13.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-14.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-15.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-16.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-17.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-18.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-19.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-1a.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-1b.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-1c.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-1d.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-1e.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-1f.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-20.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-21.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-22.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-23.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-24.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-25.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-26.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-27.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-28.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-29.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-2a.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-2b.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-2c.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-2d.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-2e.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-2f.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-30.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-31.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-32.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-33.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-34.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-35.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-36.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-37.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-38.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-39.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-3a.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-3b.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-3c.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-3d.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-3e.jsonl.gz +0 -0
- package/corpus/reference/shards/ref-3f.jsonl.gz +0 -0
- package/corpus/tier2/vocab-empty.json +6 -0
- package/data/templates/responses.jsonl +3 -0
- package/package.json +19 -1
- package/src/adapters/corpus/conceptnet.mjs +7 -3
- package/src/adapters/corpus/courtesy.mjs +129 -0
- package/src/adapters/corpus/research-source.mjs +137 -0
- package/src/adapters/corpus/wikidata-live.mjs +262 -0
- package/src/adapters/corpus/wikipedia-live.mjs +83 -116
- package/src/domain/cli-verbs.mjs +2 -0
- package/src/domain/codegraph.mjs +10 -2
- package/src/domain/grammar/lexicon-core.json +1 -0
- package/src/domain/reference-pack.mjs +61 -9
- package/src/services/chat-page-viz.mjs +9 -6
- package/src/services/chat-session.mjs +65 -9
- package/src/services/chat.mjs +395 -121
- package/src/services/extensions.mjs +203 -3
- package/src/services/init.mjs +27 -6
- package/src/services/lane-vocab-data.mjs +56 -0
- package/src/services/research.mjs +36 -14
- package/src/surfaces/web/claims-browser-entry.mjs +26 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +130 -128
- package/src/surfaces/web/planner-instances.mjs +152 -0
- package/src/tools/handlers/tmct-untested.mjs +2 -2
- package/src/tools/server.mjs +9 -4
- package/corpus/seon/LICENSE-NOTICE +0 -37
- /package/corpus/{seon → domains/code}/concepts.jsonl +0 -0
- /package/corpus/{seon → domains/code}/definitions.jsonl +0 -0
- /package/corpus/{seon → domains/code}/relations.jsonl +0 -0
|
@@ -65,10 +65,13 @@
|
|
|
65
65
|
{"id":"miss-no-previous-answer","class":"miss","register":"friendly","template":"No previous answer to expand yet — ask me a question first, then say \"why\" or \"say more\"."}
|
|
66
66
|
{"id":"conversational-greeting-empty","class":"conversational","register":"friendly","template":"Hi. I'm tmct. {vocabHint} Point me at a repo with `--repo <path>` for code-structure questions too (imports, calls, definitions). /help for commands."}
|
|
67
67
|
{"id":"conversational-greeting-empty-browser","class":"conversational","register":"friendly","template":"Hi. I'm tmct. {vocabHint} /help for commands."}
|
|
68
|
+
{"id":"conversational-greeting-empty-neutral","class":"conversational","register":"friendly","template":"Hi. I'm tmct. {vocabHint} /help for commands."}
|
|
68
69
|
{"id":"orientation-empty","class":"orientation","register":"friendly","template":"I'm tmct — a deterministic, offline chat assistant (no LLM). {vocabHint} /memory for what I remember.\nFor code structure (imports, calls, definitions) point me at a repo: `--repo <path>`, or try the shipped example `npm run example:mini`. tmct reads graphs; it doesn't index code itself.\n/help for commands."}
|
|
69
70
|
{"id":"orientation-empty-browser","class":"orientation","register":"friendly","template":"I'm tmct — a deterministic, offline chat assistant (no LLM). {vocabHint} /memory for what I remember, or ask about what's already loaded.\n/help for commands."}
|
|
71
|
+
{"id":"orientation-empty-neutral","class":"orientation","register":"friendly","template":"I'm tmct — a deterministic, offline chat assistant (no LLM). {vocabHint} /memory for what I remember.\n/help for commands."}
|
|
70
72
|
{"id":"identity-self","class":"conversational","register":"friendly","template":"I'm tmct — a deterministic, offline chat assistant. No LLM: wink-nlp parsing over a seeded ontology/lexicon, plus a code graph when you point me at a repo with `--repo <path>`. /help for commands, /stats for an overview."}
|
|
71
73
|
{"id":"identity-self-browser","class":"conversational","register":"friendly","template":"I'm tmct — a deterministic, offline chat assistant. No LLM: wink-nlp parsing over a seeded ontology/lexicon, plus a code graph when one is loaded. {vocabHint} /help for commands, /stats for an overview."}
|
|
74
|
+
{"id":"identity-self-neutral","class":"conversational","register":"friendly","template":"I'm tmct — a deterministic, offline chat assistant. No LLM: wink-nlp parsing over a seeded ontology/lexicon. {vocabHint} /help for commands, /stats for an overview."}
|
|
72
75
|
{"id":"identity-not-an-llm","class":"conversational","register":"friendly","template":"No — no LLM involved. tmct is deterministic: wink-nlp parsing over a graph/ontology, not a language model. /help for commands."}
|
|
73
76
|
{"id":"identity-no-feelings","class":"conversational","register":"friendly","template":"No — I don't have feelings, opinions, or consciousness. tmct is deterministic: wink-nlp parsing over a graph/ontology, not a mind. /help for commands."}
|
|
74
77
|
{"id":"identity-honest-miss","class":"conversational","register":"friendly","template":"No — I never make up an answer. If a question doesn't ground to a taught fact or a real graph entity, I say so plainly instead of guessing. /help for commands."}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@polycode-projects/the-mechanical-code-talker",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.17",
|
|
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.",
|
|
@@ -157,11 +157,29 @@
|
|
|
157
157
|
"audit:fix": "npm audit fix",
|
|
158
158
|
"demo:build": "node scripts/build-demo-site.mjs",
|
|
159
159
|
"bench:receipts": "node scripts/bench-receipts.mjs",
|
|
160
|
+
"claim:index-fabrication": "node scripts/claims/claim-index-fabrication.mjs",
|
|
161
|
+
"claim:latency": "node scripts/claims/claim-latency.mjs",
|
|
162
|
+
"claims": "node scripts/claims/run-all.mjs",
|
|
163
|
+
"claim:offline": "node scripts/claims/claim-offline.mjs",
|
|
164
|
+
"claim:cite": "node scripts/claims/claim-cite.mjs",
|
|
165
|
+
"claim:determinism": "node scripts/claims/claim-determinism.mjs",
|
|
166
|
+
"claim:research-sources": "node scripts/claims/claim-research-sources.mjs",
|
|
167
|
+
"claim:teach": "node scripts/claims/claim-teach.mjs",
|
|
168
|
+
"claim:prose-band": "node scripts/claims/claim-prose-band.mjs",
|
|
169
|
+
"claim:paraphrase": "node scripts/claims/claim-paraphrase.mjs",
|
|
170
|
+
"claim:freshness": "node scripts/claims/claim-freshness.mjs",
|
|
171
|
+
"claim:ground-gate": "node scripts/claims/claim-ground-gate.mjs",
|
|
172
|
+
"claim:commonsense": "node scripts/claims/claim-commonsense.mjs",
|
|
173
|
+
"claim:definitions": "node scripts/claims/claim-definitions.mjs",
|
|
174
|
+
"claim:openbookqa": "node scripts/claims/claim-openbookqa.mjs",
|
|
175
|
+
"claim:lexicon": "node scripts/claims/claim-lexicon.mjs",
|
|
176
|
+
"claim:planner": "node scripts/claims/claim-planner.mjs",
|
|
160
177
|
"roll": "node scripts/roll.mjs",
|
|
161
178
|
"build:ask-bundle": "node scripts/build-ask-bundle.mjs",
|
|
162
179
|
"build:chat-bundle": "node scripts/build-chat-bundle.mjs",
|
|
163
180
|
"build:spider-fly-bundle": "node scripts/build-spider-fly-bundle.mjs",
|
|
164
181
|
"build:plan-bundle": "node scripts/build-plan-bundle.mjs",
|
|
182
|
+
"build:claims-bundle": "node scripts/build-claims-bundle.mjs",
|
|
165
183
|
"build:ledger-bundle": "node scripts/build-ledger-bundle.mjs",
|
|
166
184
|
"build:ingest-bundle": "node scripts/build-ingest-bundle.mjs",
|
|
167
185
|
"build:research-bundle": "node scripts/build-research-bundle.mjs",
|
|
@@ -25,9 +25,13 @@ export const MAP_FILE = join(PKG_ROOT, "src", "adapters", "corpus", "conceptnet-
|
|
|
25
25
|
// The tier-1 curated Software-Engineering ontology (SEON): concepts.jsonl shares
|
|
26
26
|
// ConceptNet's slice shape and loads through the same loadSlice/loadMap/toFacts path.
|
|
27
27
|
// definitions.jsonl is a separate {term, definition, sense} list for lexicon lookups.
|
|
28
|
-
// Tier-2 corpuses (aws/python/java) share the slice shape too.
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
// Tier-2 corpuses (aws/python/java) share the slice shape too. The data lives under
|
|
29
|
+
// corpus/domains/code/ (the code domain pack's own directory); the bundle name
|
|
30
|
+
// "seon" and its "corpus:seon" provenance prefix are unchanged by the move —
|
|
31
|
+
// both are declared literally in src/services/extensions.mjs, not derived from
|
|
32
|
+
// this path.
|
|
33
|
+
export const SEON_CONCEPTS_FILE = join(PKG_ROOT, "corpus", "domains", "code", "concepts.jsonl");
|
|
34
|
+
export const SEON_DEFINITIONS_FILE = join(PKG_ROOT, "corpus", "domains", "code", "definitions.jsonl");
|
|
31
35
|
export const TIER2_DIR = join(PKG_ROOT, "corpus", "tier2");
|
|
32
36
|
export const TIER2_MANIFEST_FILE = join(TIER2_DIR, "manifest.json");
|
|
33
37
|
|
|
@@ -0,0 +1,129 @@
|
|
|
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.
|
|
8
|
+
//
|
|
9
|
+
// No node builtins — this module ships in the browser bundles unchanged; the
|
|
10
|
+
// only I/O is fetch.
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_TIMEOUT_MS = 4000;
|
|
13
|
+
export const DEFAULT_MIN_INTERVAL_MS = 2000;
|
|
14
|
+
export const RETRY_AFTER_FLOOR_MS = 5000;
|
|
15
|
+
// Action-API requests carry maxlag so an overloaded replica set answers with
|
|
16
|
+
// an error we back off from instead of adding to its load (Wikimedia's own
|
|
17
|
+
// recommended default for non-interactive clients).
|
|
18
|
+
export const MAXLAG_SECONDS = 5;
|
|
19
|
+
|
|
20
|
+
/**
|
|
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.
|
|
24
|
+
*
|
|
25
|
+
* `waitForSlot` picks the throttle posture: false answers null the moment a
|
|
26
|
+
* slot is unavailable (never block a chat turn), true waits for it (a queue
|
|
27
|
+
* paced turn-by-turn, where a false miss would be dishonest).
|
|
28
|
+
*/
|
|
29
|
+
export function createCourtesyGate({
|
|
30
|
+
fetchImpl,
|
|
31
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
32
|
+
minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
|
|
33
|
+
retryAfterFloorMs = RETRY_AFTER_FLOOR_MS,
|
|
34
|
+
userAgent,
|
|
35
|
+
waitForSlot = false,
|
|
36
|
+
} = {}) {
|
|
37
|
+
const doFetch = fetchImpl ?? ((...args) => globalThis.fetch(...args));
|
|
38
|
+
const cache = new Map(); // key -> value | null (hits AND settled misses)
|
|
39
|
+
let lastLookupAt = 0;
|
|
40
|
+
let coolOffUntil = 0;
|
|
41
|
+
let inFlight = false;
|
|
42
|
+
|
|
43
|
+
const identifyingHeaders = () => {
|
|
44
|
+
if (!userAgent) return null;
|
|
45
|
+
const headers = { "Api-User-Agent": userAgent };
|
|
46
|
+
// A browser strips User-Agent as a forbidden header; only set it where no
|
|
47
|
+
// DOM says we are one (Node ships a global `navigator` these days, so
|
|
48
|
+
// `document` is the discriminating global).
|
|
49
|
+
if (typeof document === "undefined") headers["User-Agent"] = userAgent;
|
|
50
|
+
return headers;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
function openCoolOff(retryAfterSeconds) {
|
|
54
|
+
const retryAfterMs = Number(retryAfterSeconds) * 1000;
|
|
55
|
+
coolOffUntil = Date.now() + Math.max(retryAfterMs || 0, retryAfterFloorMs);
|
|
56
|
+
}
|
|
57
|
+
|
|
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) {
|
|
62
|
+
const controller = typeof AbortController === "function" ? new AbortController() : null;
|
|
63
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
64
|
+
try {
|
|
65
|
+
const opts = {};
|
|
66
|
+
if (controller) opts.signal = controller.signal;
|
|
67
|
+
const headers = identifyingHeaders();
|
|
68
|
+
if (headers) opts.headers = headers;
|
|
69
|
+
const res = await doFetch(url, opts);
|
|
70
|
+
if (res.status === 429) {
|
|
71
|
+
openCoolOff(res.headers?.get?.("retry-after"));
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
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;
|
|
81
|
+
}
|
|
82
|
+
return body;
|
|
83
|
+
} catch {
|
|
84
|
+
return null;
|
|
85
|
+
} finally {
|
|
86
|
+
if (timer !== null) clearTimeout(timer);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** When the next network slot opens: past the cool-off, past the minimum
|
|
91
|
+
* interval since the last taken slot. */
|
|
92
|
+
const slotOpensAt = () => Math.max(coolOffUntil, lastLookupAt + minIntervalMs);
|
|
93
|
+
|
|
94
|
+
/** Take the one network slot, or report it unavailable. Default posture
|
|
95
|
+
* returns false immediately; `waitForSlot` sleeps until the slot opens
|
|
96
|
+
* instead. */
|
|
97
|
+
async function takeSlot() {
|
|
98
|
+
for (;;) {
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
if (!inFlight && now >= slotOpensAt()) {
|
|
101
|
+
lastLookupAt = now;
|
|
102
|
+
inFlight = true;
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
if (!waitForSlot) return false;
|
|
106
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(slotOpensAt() - now, 25)));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
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) {
|
|
114
|
+
if (cache.has(cacheKey)) return cache.get(cacheKey);
|
|
115
|
+
if (!(await takeSlot())) return null;
|
|
116
|
+
let value = null;
|
|
117
|
+
try {
|
|
118
|
+
value = await work();
|
|
119
|
+
} catch {
|
|
120
|
+
value = null;
|
|
121
|
+
} finally {
|
|
122
|
+
inFlight = false;
|
|
123
|
+
}
|
|
124
|
+
cache.set(cacheKey, value);
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { fetchJson, cachedFetch };
|
|
129
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// corpus/research-source.mjs — the contract a research SOURCE adapter meets,
|
|
2
|
+
// written down from the seam that already exists rather than beside it.
|
|
3
|
+
//
|
|
4
|
+
// The research lane (src/services/research.mjs) talks to one provider behind
|
|
5
|
+
// registerResearchProvider/getResearchProvider in wikipedia-live.mjs. What the
|
|
6
|
+
// lane reads off that provider is `lookup(term)` returning a reference-pack
|
|
7
|
+
// article row (or null), plus two optional fan-out reads it feature-tests
|
|
8
|
+
// before calling. This module writes that shape down. It adds the two things a
|
|
9
|
+
// source says about itself, its name and the origin it fetches from, and names
|
|
10
|
+
// the provenance tag its facts carry.
|
|
11
|
+
//
|
|
12
|
+
// It also holds the registry the contract test and the claims rig walk. An
|
|
13
|
+
// adapter registers a factory here. A caller builds one source from that entry
|
|
14
|
+
// against a stub transport (the test) or against the live endpoint (the rig).
|
|
15
|
+
//
|
|
16
|
+
// No node builtins: the browser bundles import the adapters that import this.
|
|
17
|
+
|
|
18
|
+
import { normFactTerm } from "../../domain/hash.mjs";
|
|
19
|
+
import { isReferenceArticleRow } from "../../domain/reference-pack.mjs";
|
|
20
|
+
|
|
21
|
+
/** The closed predicate set a research source may map onto: the seed ontology's
|
|
22
|
+
* own relation vocabulary (src/services/init.mjs SEED_PREFER, and the tmct
|
|
23
|
+
* predicates src/adapters/corpus/conceptnet-map.toml emits). A source that
|
|
24
|
+
* needs a relation missing here adds it to this list first. That keeps every
|
|
25
|
+
* alignment decision visible in one place instead of spread through the
|
|
26
|
+
* adapters. */
|
|
27
|
+
export const RESEARCH_SOURCE_RELATIONS = Object.freeze([
|
|
28
|
+
"rdf:type",
|
|
29
|
+
"rdfs:subClassOf",
|
|
30
|
+
"mgx:partOf",
|
|
31
|
+
"mgx:hasA",
|
|
32
|
+
"mgx:usedFor",
|
|
33
|
+
"mgx:capableOf",
|
|
34
|
+
"mgx:atLocation",
|
|
35
|
+
"mgx:causes",
|
|
36
|
+
"mgx:madeOf",
|
|
37
|
+
"mgx:createdBy",
|
|
38
|
+
"mgx:locatedNear",
|
|
39
|
+
"mgx:hasProperty",
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
/** One fact a source contributes: {subject, predicate, object, provenance},
|
|
43
|
+
* every field a non-empty string, the predicate one of
|
|
44
|
+
* RESEARCH_SOURCE_RELATIONS. The provenance field is required here and not
|
|
45
|
+
* optional anywhere: a fact with no tag has no way into the graph. */
|
|
46
|
+
export function isResearchFact(fact) {
|
|
47
|
+
if (!fact || typeof fact !== "object") return false;
|
|
48
|
+
for (const field of ["subject", "predicate", "object", "provenance"]) {
|
|
49
|
+
if (typeof fact[field] !== "string" || !fact[field]) return false;
|
|
50
|
+
}
|
|
51
|
+
return RESEARCH_SOURCE_RELATIONS.includes(fact.predicate);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What `lookup(term)` resolves to: the shipped reference pack's own article
|
|
55
|
+
* row ({term, title, text, summary, url, revid, isa?, source?, licence?}),
|
|
56
|
+
* optionally carrying `facts` — the triples a source that reads STRUCTURED
|
|
57
|
+
* data mapped at its own boundary. A prose source carries no `facts` and
|
|
58
|
+
* licenses its isa instead. */
|
|
59
|
+
export function isResearchSourceRow(row) {
|
|
60
|
+
if (!isReferenceArticleRow(row)) return false;
|
|
61
|
+
if (row.facts === undefined) return true;
|
|
62
|
+
return Array.isArray(row.facts) && row.facts.length > 0 && row.facts.every(isResearchFact);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The adapter interface: a `name` it goes by, the `origin` it fetches from,
|
|
66
|
+
* `lookup(term)` and `provenanceTag(term)`. `pageByTitle`/`linkedTitles` stay
|
|
67
|
+
* optional, because the lane feature-tests both before calling either. */
|
|
68
|
+
export function isResearchSource(source) {
|
|
69
|
+
return !!source && typeof source === "object"
|
|
70
|
+
&& typeof source.name === "string" && source.name.length > 0
|
|
71
|
+
&& typeof source.origin === "string" && source.origin.startsWith("https://")
|
|
72
|
+
&& typeof source.lookup === "function"
|
|
73
|
+
&& typeof source.provenanceTag === "function";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The provenance tag every fact gained through a research source carries:
|
|
77
|
+
* `research:<source>:<folded term>`. memory/trust.mjs reads the `research:`
|
|
78
|
+
* prefix back as a referenceLive Source, so a live-fetched fact scores below
|
|
79
|
+
* every curated pack, and the source segment keeps which adapter fetched it
|
|
80
|
+
* readable off the fact itself. */
|
|
81
|
+
export function researchSourceTag(sourceName, term) {
|
|
82
|
+
return `research:${sourceName}:${normFactTerm(term)}`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The facts a looked-up row licenses, each stamped with the source's own tag.
|
|
86
|
+
* A structured source mapped its claims at its adapter boundary and carries
|
|
87
|
+
* them on `facts`; a prose source licenses its first-sentence isa as one
|
|
88
|
+
* subClassOf edge, the same edge the chat ingest reads off the row. A null row
|
|
89
|
+
* licenses nothing, so a miss stays a miss. */
|
|
90
|
+
export function researchFacts(source, term, row) {
|
|
91
|
+
if (!row) return [];
|
|
92
|
+
const provenance = source.provenanceTag(term);
|
|
93
|
+
if (Array.isArray(row.facts)) {
|
|
94
|
+
return row.facts.map(({ subject, predicate, object }) => ({ subject, predicate, object, provenance }));
|
|
95
|
+
}
|
|
96
|
+
if (row.isa && row.term && row.isa !== row.term) {
|
|
97
|
+
return [{ subject: row.term, predicate: "rdfs:subClassOf", object: row.isa, provenance }];
|
|
98
|
+
}
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const sourceFactories = new Map();
|
|
103
|
+
|
|
104
|
+
/** Register a source adapter's factory: `{ name, create(options) -> source }`.
|
|
105
|
+
* The factory takes the same option bag the adapter's own constructor does, so
|
|
106
|
+
* a caller can hand it a stub transport. Re-registering a name replaces the
|
|
107
|
+
* entry, which keeps a module-scope registration idempotent. */
|
|
108
|
+
export function registerResearchSource(entry) {
|
|
109
|
+
if (!entry || typeof entry.name !== "string" || !entry.name || typeof entry.create !== "function") {
|
|
110
|
+
throw new Error("registerResearchSource: expected { name, create(options) }");
|
|
111
|
+
}
|
|
112
|
+
sourceFactories.set(entry.name, { name: entry.name, create: entry.create });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Every registered source factory, name-sorted so a caller that walks them
|
|
116
|
+
* reads them in the same order every run. An adapter module registers on
|
|
117
|
+
* import, so this lists exactly the adapters the caller imported. */
|
|
118
|
+
export function researchSources() {
|
|
119
|
+
return [...sourceFactories.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The config-facing choice words a user, tmct.toml or a CLI flag may name. */
|
|
123
|
+
export const RESEARCH_SOURCE_CHOICES = Object.freeze(["wikipedia", "wikidata"]);
|
|
124
|
+
export const DEFAULT_RESEARCH_SOURCE_CHOICE = "wikipedia";
|
|
125
|
+
|
|
126
|
+
const CHOICE_TO_SOURCE_NAME = Object.freeze({ wikipedia: "simple-wikipedia", wikidata: "wikidata" });
|
|
127
|
+
|
|
128
|
+
/** The config-facing choice folded to a known one — an absent, empty or
|
|
129
|
+
* unrecognized value reads as the default. */
|
|
130
|
+
export function normalizeResearchChoice(choice) {
|
|
131
|
+
return RESEARCH_SOURCE_CHOICES.includes(choice) ? choice : DEFAULT_RESEARCH_SOURCE_CHOICE;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The registered SOURCE NAME a choice selects ("wikipedia" → "simple-wikipedia"). */
|
|
135
|
+
export function researchSourceNameFor(choice) {
|
|
136
|
+
return CHOICE_TO_SOURCE_NAME[normalizeResearchChoice(choice)];
|
|
137
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
// corpus/wikidata-live.mjs — the live Wikidata research source. Three small
|
|
2
|
+
// GET round trips against www.wikidata.org's Action API, mapped onto tmct's
|
|
3
|
+
// seed-ontology relations at THIS boundary and nowhere else: everything
|
|
4
|
+
// downstream reads ordinary tmct facts and never learns the word "Wikidata".
|
|
5
|
+
//
|
|
6
|
+
// Why the Action API rather than the SPARQL query service: wbsearchentities
|
|
7
|
+
// then wbgetentities is the same two-step shape wikipedia-live.mjs already
|
|
8
|
+
// uses (find the item, then read it). It answers in plain JSON, with no query
|
|
9
|
+
// language to escape per lookup, and it carries maxlag like every other
|
|
10
|
+
// Wikimedia action request. The query service would need its own endpoint, its
|
|
11
|
+
// own rate policy and a SPARQL string built per term.
|
|
12
|
+
//
|
|
13
|
+
// The round trips:
|
|
14
|
+
// 1. wbsearchentities — the item whose English label matches the term.
|
|
15
|
+
// 2. wbgetentities — that item's label, description, revision, claims.
|
|
16
|
+
// 3. wbgetentities — the English labels of the mapped claims' object
|
|
17
|
+
// items, batched into ONE request. A claim's value is
|
|
18
|
+
// a Q-id, and a stored fact's object has to be a human
|
|
19
|
+
// term. Skipped when nothing mapped.
|
|
20
|
+
//
|
|
21
|
+
// Courtesy is structural, mirroring wikipedia-live.mjs: one in-flight lookup
|
|
22
|
+
// at a time, a minimum interval between round trips, a 429/maxlag cool-off
|
|
23
|
+
// honouring Retry-After, an abort timeout on every fetch, and a cache that
|
|
24
|
+
// keeps hits AND misses so a term is never asked twice. Every failure of any
|
|
25
|
+
// kind reads as null, so the caller's honest miss stands.
|
|
26
|
+
//
|
|
27
|
+
// No node builtins — this module ships in the browser bundles unchanged; the
|
|
28
|
+
// only I/O is fetch.
|
|
29
|
+
|
|
30
|
+
import { normFactTerm } from "../../domain/hash.mjs";
|
|
31
|
+
import { sentencesUpTo, SUMMARY_CHAR_CAP } from "../../domain/reference-pack.mjs";
|
|
32
|
+
import { isResearchSourceRow, registerResearchSource, researchSourceTag } from "./research-source.mjs";
|
|
33
|
+
import { createCourtesyGate, DEFAULT_TIMEOUT_MS, DEFAULT_MIN_INTERVAL_MS, MAXLAG_SECONDS } from "./courtesy.mjs";
|
|
34
|
+
|
|
35
|
+
export const WIKIDATA_LIVE_ORIGIN = "https://www.wikidata.org";
|
|
36
|
+
export const WIKIDATA_SOURCE_NAME = "wikidata";
|
|
37
|
+
|
|
38
|
+
/** The citation this source's rows carry, overriding the reference pack's
|
|
39
|
+
* Wikipedia defaults (isReferenceArticleRow's optional source/licence fields,
|
|
40
|
+
* which renderReferenceAnswer reads). Wikidata publishes its statements under
|
|
41
|
+
* CC0, not the CC BY-SA the encyclopedia text uses. */
|
|
42
|
+
export const WIKIDATA_SOURCE_LABEL = "Wikidata";
|
|
43
|
+
export const WIKIDATA_LICENCE = "CC0 1.0";
|
|
44
|
+
|
|
45
|
+
/** The identification string Wikimedia's robot policy asks API clients to
|
|
46
|
+
* carry. Browsers refuse to override User-Agent, so the API-recognised
|
|
47
|
+
* Api-User-Agent header carries the same string there. */
|
|
48
|
+
export const WIKIDATA_USER_AGENT = "the-mechanical-code-talker (+https://tmct.polycode.co.uk/)";
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The Wikidata property → tmct relation map: the ONE place this adapter aligns
|
|
52
|
+
* Wikidata with the seed ontology. A property with no row here is not read at
|
|
53
|
+
* all, and adding a row is the whole change needed to gain a relation. So the
|
|
54
|
+
* alignment reads as a table rather than scattered through the parser. Every
|
|
55
|
+
* target is a member of RESEARCH_SOURCE_RELATIONS.
|
|
56
|
+
*/
|
|
57
|
+
export const WIKIDATA_PROPERTY_RELATIONS = Object.freeze({
|
|
58
|
+
P31: "rdf:type", // instance of
|
|
59
|
+
P279: "rdfs:subClassOf", // subclass of
|
|
60
|
+
P361: "mgx:partOf", // part of
|
|
61
|
+
P527: "mgx:hasA", // has part(s)
|
|
62
|
+
P186: "mgx:madeOf", // made from material
|
|
63
|
+
P366: "mgx:usedFor", // has use
|
|
64
|
+
P276: "mgx:atLocation", // location
|
|
65
|
+
P1542: "mgx:causes", // has effect
|
|
66
|
+
P170: "mgx:createdBy", // creator
|
|
67
|
+
P2670: "mgx:hasA", // has part(s) of the class
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// The properties whose object is the item's own category, best first: what
|
|
71
|
+
// row.isa reads off, so the chat ingest path stores the same subClassOf edge
|
|
72
|
+
// it would store from a prose lead sentence.
|
|
73
|
+
const ISA_PROPERTIES = ["P279", "P31"];
|
|
74
|
+
|
|
75
|
+
// How much of one item a single lookup reads: at most this many object values
|
|
76
|
+
// per property, and this many facts in total. A busy item like "human" carries
|
|
77
|
+
// hundreds of statements, and a research lookup wants the shape of the thing,
|
|
78
|
+
// not its whole record.
|
|
79
|
+
const MAX_VALUES_PER_PROPERTY = 3;
|
|
80
|
+
const MAX_FACTS_PER_ITEM = 12;
|
|
81
|
+
|
|
82
|
+
const ITEM_ID_RE = /^Q[1-9][0-9]*$/;
|
|
83
|
+
|
|
84
|
+
/** The searched item whose English label folds onto the key, or null — the
|
|
85
|
+
* topic-drift guard, matching wikipedia-live.mjs's: "quasar" may resolve to
|
|
86
|
+
* "quasar" or "quasars", never to the first suggestion about something else.
|
|
87
|
+
* An exact fold beats a prefix fold wherever it appears in the result list,
|
|
88
|
+
* so a search that ranks "Quasars (album)" above "quasar" still lands on the
|
|
89
|
+
* term the caller asked for. */
|
|
90
|
+
function matchingItemId(key, body) {
|
|
91
|
+
const results = Array.isArray(body?.search) ? body.search : [];
|
|
92
|
+
let prefixMatch = null;
|
|
93
|
+
for (const hit of results) {
|
|
94
|
+
const id = String(hit?.id ?? "");
|
|
95
|
+
if (!ITEM_ID_RE.test(id)) continue;
|
|
96
|
+
const folded = normFactTerm(hit?.label ?? "");
|
|
97
|
+
if (folded === key) return id;
|
|
98
|
+
if (prefixMatch === null && folded.startsWith(key)) prefixMatch = id;
|
|
99
|
+
}
|
|
100
|
+
return prefixMatch;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Every mapped claim on an entity as {predicate, id} pairs, capped per
|
|
104
|
+
* property and in total. Only item-valued statements are read: a claim whose
|
|
105
|
+
* value is a date, a quantity or a string has no object term to store. */
|
|
106
|
+
function mappedClaims(entity) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const [property, predicate] of Object.entries(WIKIDATA_PROPERTY_RELATIONS)) {
|
|
109
|
+
const statements = entity?.claims?.[property];
|
|
110
|
+
if (!Array.isArray(statements)) continue;
|
|
111
|
+
let taken = 0;
|
|
112
|
+
for (const statement of statements) {
|
|
113
|
+
if (out.length >= MAX_FACTS_PER_ITEM) return out;
|
|
114
|
+
if (taken >= MAX_VALUES_PER_PROPERTY) break;
|
|
115
|
+
const snak = statement?.mainsnak;
|
|
116
|
+
if (snak?.snaktype !== "value") continue;
|
|
117
|
+
const id = String(snak?.datavalue?.value?.id ?? "");
|
|
118
|
+
if (!ITEM_ID_RE.test(id)) continue;
|
|
119
|
+
out.push({ property, predicate, id });
|
|
120
|
+
taken += 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The item's own category term, read off the first subclass-of (else
|
|
127
|
+
* instance-of) claim whose object label resolved. Null when neither did. */
|
|
128
|
+
function isaFrom(claims, termById, subject) {
|
|
129
|
+
for (const property of ISA_PROPERTIES) {
|
|
130
|
+
for (const claim of claims) {
|
|
131
|
+
if (claim.property !== property) continue;
|
|
132
|
+
const term = termById.get(claim.id);
|
|
133
|
+
if (term && term !== subject) return term;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* A live Wikidata research source: { name, origin, lookup(term),
|
|
141
|
+
* provenanceTag(term) } — the research-source.mjs contract.
|
|
142
|
+
*
|
|
143
|
+
* `fetchImpl` defaults to the global fetch. `waitForSlot` picks the throttle
|
|
144
|
+
* posture: false answers null the moment a slot is unavailable (never block a
|
|
145
|
+
* chat turn), true waits for it (the research queue, which is paced
|
|
146
|
+
* turn-by-turn and where a false miss would be dishonest).
|
|
147
|
+
*/
|
|
148
|
+
export function createWikidataLiveProvider({
|
|
149
|
+
fetchImpl,
|
|
150
|
+
origin = WIKIDATA_LIVE_ORIGIN,
|
|
151
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
152
|
+
minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
|
|
153
|
+
userAgent = WIKIDATA_USER_AGENT,
|
|
154
|
+
waitForSlot = false,
|
|
155
|
+
sourceName = WIKIDATA_SOURCE_NAME,
|
|
156
|
+
} = {}) {
|
|
157
|
+
const gate = createCourtesyGate({ fetchImpl, timeoutMs, minIntervalMs, userAgent, waitForSlot });
|
|
158
|
+
|
|
159
|
+
const actionUrl = (params) =>
|
|
160
|
+
`${origin}/w/api.php?${new URLSearchParams({ format: "json", origin: "*", maxlag: String(MAXLAG_SECONDS), ...params })}`;
|
|
161
|
+
|
|
162
|
+
/** The English labels of a batch of item ids, folded to fact terms, in one
|
|
163
|
+
* round trip. An id whose label is missing simply drops out of the map, and
|
|
164
|
+
* the claim that named it drops with it. */
|
|
165
|
+
async function termsForIds(ids) {
|
|
166
|
+
const termById = new Map();
|
|
167
|
+
if (!ids.length) return termById;
|
|
168
|
+
const body = await gate.fetchJson(actionUrl({
|
|
169
|
+
action: "wbgetentities",
|
|
170
|
+
languages: "en",
|
|
171
|
+
props: "labels",
|
|
172
|
+
ids: ids.join("|"),
|
|
173
|
+
}));
|
|
174
|
+
for (const [id, entity] of Object.entries(body?.entities ?? {})) {
|
|
175
|
+
const term = normFactTerm(entity?.labels?.en?.value ?? "");
|
|
176
|
+
if (term) termById.set(id, term);
|
|
177
|
+
}
|
|
178
|
+
return termById;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function roundTrips(key) {
|
|
182
|
+
const search = await gate.fetchJson(actionUrl({
|
|
183
|
+
action: "wbsearchentities",
|
|
184
|
+
language: "en",
|
|
185
|
+
uselang: "en",
|
|
186
|
+
type: "item",
|
|
187
|
+
limit: "5",
|
|
188
|
+
search: key,
|
|
189
|
+
}));
|
|
190
|
+
const id = search ? matchingItemId(key, search) : null;
|
|
191
|
+
if (!id) return null;
|
|
192
|
+
|
|
193
|
+
const read = await gate.fetchJson(actionUrl({
|
|
194
|
+
action: "wbgetentities",
|
|
195
|
+
languages: "en",
|
|
196
|
+
props: "labels|descriptions|claims|info",
|
|
197
|
+
ids: id,
|
|
198
|
+
}));
|
|
199
|
+
const entity = read?.entities?.[id];
|
|
200
|
+
if (!entity) return null;
|
|
201
|
+
|
|
202
|
+
const claims = mappedClaims(entity);
|
|
203
|
+
const termById = await termsForIds(claims.map((c) => c.id));
|
|
204
|
+
const provenance = researchSourceTag(sourceName, key);
|
|
205
|
+
const facts = [];
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
for (const claim of claims) {
|
|
208
|
+
const object = termById.get(claim.id);
|
|
209
|
+
if (!object || object === key || seen.has(`${claim.predicate}\0${object}`)) continue;
|
|
210
|
+
seen.add(`${claim.predicate}\0${object}`);
|
|
211
|
+
facts.push({ subject: key, predicate: claim.predicate, object, provenance });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const description = String(entity.descriptions?.en?.value ?? "");
|
|
215
|
+
const row = {
|
|
216
|
+
term: key,
|
|
217
|
+
title: String(entity.labels?.en?.value ?? ""),
|
|
218
|
+
text: description,
|
|
219
|
+
summary: sentencesUpTo(description, SUMMARY_CHAR_CAP),
|
|
220
|
+
url: `${origin}/wiki/${id}`,
|
|
221
|
+
revid: Number(entity.lastrevid),
|
|
222
|
+
source: WIKIDATA_SOURCE_LABEL,
|
|
223
|
+
licence: WIKIDATA_LICENCE,
|
|
224
|
+
};
|
|
225
|
+
const isa = isaFrom(claims, termById, key);
|
|
226
|
+
if (isa) row.isa = isa;
|
|
227
|
+
if (facts.length) row.facts = facts;
|
|
228
|
+
return isResearchSourceRow(row) ? row : null;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
name: sourceName,
|
|
233
|
+
origin,
|
|
234
|
+
|
|
235
|
+
/** The tag every fact this source contributes carries. */
|
|
236
|
+
provenanceTag(term) {
|
|
237
|
+
return researchSourceTag(sourceName, term);
|
|
238
|
+
},
|
|
239
|
+
|
|
240
|
+
/** One term's item as an article row, or null. Cache first (a settled hit
|
|
241
|
+
* or miss is never refetched), then the courtesy slot, then the round
|
|
242
|
+
* trips, with every failure cached as null so it costs one attempt. */
|
|
243
|
+
async lookup(term) {
|
|
244
|
+
const key = normFactTerm(term ?? "");
|
|
245
|
+
if (!key) return null;
|
|
246
|
+
return gate.cachedFetch(key, () => roundTrips(key));
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The Wikidata research source with `waitForSlot` on: the research queue is
|
|
252
|
+
* paced turn-by-turn, so a throttled step waits for its polite slot rather
|
|
253
|
+
* than reporting a false miss. Every option the caller passes wins, so a test
|
|
254
|
+
* can hand it a stub transport and a zero interval. */
|
|
255
|
+
export function createWikidataResearchSource(options = {}) {
|
|
256
|
+
return createWikidataLiveProvider({ waitForSlot: true, ...options });
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
registerResearchSource({
|
|
260
|
+
name: WIKIDATA_SOURCE_NAME,
|
|
261
|
+
create: createWikidataResearchSource,
|
|
262
|
+
});
|