@polycode-projects/the-mechanical-code-talker 5.0.16 → 5.0.18

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
@@ -1325,6 +1325,7 @@ fanout_limit = 8 # links followed per page
1325
1325
  max_depth = 3 # hops from the starting topic
1326
1326
  max_topics = 40 # topics visited in one crawl
1327
1327
  min_interval_ms = 1000 # politeness delay between fetches
1328
+ source = "wikipedia" # wikipedia | wikidata — where "research <topic>" fetches from
1328
1329
 
1329
1330
  # Discourse record (src/domain/discourse.mjs).
1330
1331
  [discourse]
package/bin/tmct.mjs CHANGED
@@ -68,6 +68,10 @@ flag > TMCT_MEMORY_BACKEND env > tmct.toml [memory] backend > sqlite (the built-
68
68
  default, .tmct/memory/graph.sqlite); "memory" keeps the store in-process only. Set it
69
69
  once with \`tmct init --memory-backend <...>\` and every later \`tmct chat\` in that
70
70
  repo picks it up with no flag needed.
71
+
72
+ Research-source precedence (chat; see src/services/chat-session.mjs createSession):
73
+ /wikipedia|/wikidata in chat > --research-source flag > tmct.toml [research] source >
74
+ wikipedia.
71
75
  `;
72
76
 
73
77
  const argv = process.argv.slice(2);
@@ -342,6 +346,7 @@ async function readConfigForRewrite(repoRoot) {
342
346
  if (raw?.extensions !== undefined) cfg.extensions = raw.extensions;
343
347
  if (raw?.bias !== undefined) cfg.bias = raw.bias;
344
348
  if (raw?.memory?.backend !== undefined) cfg.memory = { ...cfg.memory, backend: raw.memory.backend };
349
+ if (raw?.research !== undefined) cfg.research = raw.research;
345
350
  return { raw, cfg };
346
351
  }
347
352
 
@@ -700,8 +705,14 @@ async function main() {
700
705
  // shared precedence order, resolved inside createSession itself). Omitted
701
706
  // when absent so the lower tiers still apply unchanged.
702
707
  let memoryBackend;
708
+ let researchSource;
703
709
  try {
704
710
  memoryBackend = enumFlag(rest, ["--memory-backend"], ["default", "memory", "sqlite"]);
711
+ // `--research-source <wikipedia|wikidata>`: the CLI's flag tier of the
712
+ // research lane's source precedence (below /wikipedia|/wikidata in chat,
713
+ // above tmct.toml's [research] source). Omitted when absent so the
714
+ // lower tiers still apply unchanged.
715
+ researchSource = enumFlag(rest, ["--research-source"], ["wikipedia", "wikidata"]);
705
716
  } catch (e) {
706
717
  process.stderr.write(`tmct: ${e?.message || e}\n`);
707
718
  process.exit(2);
@@ -710,6 +721,7 @@ async function main() {
710
721
  if (graphPaths.length) extra.graphPaths = graphPaths;
711
722
  if (configPath) extra.configPath = configPath;
712
723
  if (memoryBackend) extra.memoryBackend = memoryBackend;
724
+ if (researchSource) extra.researchSource = researchSource;
713
725
  // `--prompt "<text>"` — one-shot mode: each sentence of the prompt runs as
714
726
  // its own turn (state teaches first, the goal/solve trigger last), the
715
727
  // FINAL turn's answer prints to stdout, and the process exits. Piped stdin
@@ -874,6 +886,18 @@ async function main() {
874
886
  process.stderr.write(`tmct init: ${e?.message || e}\n`);
875
887
  process.exit(2);
876
888
  }
889
+
890
+ // `--research-source <wikipedia|wikidata>`: written into tmct.toml's
891
+ // `[research] source` (src/services/init.mjs's renderTomlConfig), the same
892
+ // flag name `tmct chat` reads at its own precedence tier — a repo set up
893
+ // once here needs no flag on a later `tmct chat` in it.
894
+ let researchSourceVal;
895
+ try {
896
+ researchSourceVal = enumFlag(rest, ["--research-source"], ["wikipedia", "wikidata"]);
897
+ } catch (e) {
898
+ process.stderr.write(`tmct init: ${e?.message || e}\n`);
899
+ process.exit(2);
900
+ }
877
901
  // `init` takes no positional argument at all, so a bare "sqlite"/"memory"/
878
902
  // "default" here almost always means `npm run init --memory-backend X`
879
903
  // was typed without the `--` separator npm needs — npm silently drops its
@@ -966,18 +990,19 @@ async function main() {
966
990
  // before initRepo/activation run, so this repo's re-seed (if any) and
967
991
  // any --corpus/--ontology/--lexicon activation below see it.
968
992
  const forceFlag = rest.includes("--force");
969
- if (memoryBackendVal) {
993
+ if (memoryBackendVal || researchSourceVal) {
970
994
  const { access } = await import("node:fs/promises");
971
995
  const tomlPath = resolvePath(repoRoot, "tmct.toml");
972
996
  const tomlAlreadyExists = await access(tomlPath).then(() => true, () => false);
973
997
  if (tomlAlreadyExists && !forceFlag) {
974
998
  const { cfg } = await readConfigForRewrite(repoRoot);
975
- cfg.memory = { ...(cfg.memory || {}), backend: memoryBackendVal };
999
+ if (memoryBackendVal) cfg.memory = { ...(cfg.memory || {}), backend: memoryBackendVal };
1000
+ if (researchSourceVal) cfg.research = { ...(cfg.research || {}), source: researchSourceVal };
976
1001
  await writeConfig(repoRoot, cfg);
977
1002
  }
978
1003
  }
979
1004
 
980
- const res = await initRepo(repoRoot, { force: forceFlag, persona: personaPreset, memoryBackend: memoryBackendVal });
1005
+ const res = await initRepo(repoRoot, { force: forceFlag, persona: personaPreset, memoryBackend: memoryBackendVal, researchSource: researchSourceVal });
981
1006
  process.stdout.write(res.message + "\n");
982
1007
 
983
1008
  // The cold tools carry no resident schema, so the initialized repo gets the catalog
@@ -1065,6 +1090,14 @@ async function main() {
1065
1090
  anyActivation = true;
1066
1091
  }
1067
1092
 
1093
+ // `--research-source <wikipedia|wikidata>`: already WRITTEN by now — either
1094
+ // just above (pre-existing tmct.toml) or inside initRepo() itself (a fresh
1095
+ // write, `researchSource` opt) — this just reports it.
1096
+ if (researchSourceVal) {
1097
+ process.stdout.write(`research source set in tmct.toml: ${researchSourceVal}\n`);
1098
+ anyActivation = true;
1099
+ }
1100
+
1068
1101
  if (anyActivation) return;
1069
1102
 
1070
1103
  if (rest.includes("--detect")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.16",
3
+ "version": "5.0.18",
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.",
@@ -169,7 +169,8 @@
169
169
  "claim:paraphrase": "node scripts/claims/claim-paraphrase.mjs",
170
170
  "claim:freshness": "node scripts/claims/claim-freshness.mjs",
171
171
  "claim:ground-gate": "node scripts/claims/claim-ground-gate.mjs",
172
- "claim:commonsense": "node scripts/claims/claim-commonsense.mjs",
172
+ "claim:definitions": "node scripts/claims/claim-definitions.mjs",
173
+ "claim:openbookqa": "node scripts/claims/claim-openbookqa.mjs",
173
174
  "claim:lexicon": "node scripts/claims/claim-lexicon.mjs",
174
175
  "claim:planner": "node scripts/claims/claim-planner.mjs",
175
176
  "roll": "node scripts/roll.mjs",
@@ -118,3 +118,20 @@ export function registerResearchSource(entry) {
118
118
  export function researchSources() {
119
119
  return [...sourceFactories.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
120
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
+ }
@@ -25,7 +25,13 @@
25
25
  import { normFactTerm } from "../../domain/hash.mjs";
26
26
  import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
27
27
  import { isReferenceArticleRow, sentencesUpTo, isaOf, SUMMARY_CHAR_CAP } from "../../domain/reference-pack.mjs";
28
- import { registerResearchSource, researchSourceTag } from "./research-source.mjs";
28
+ import {
29
+ registerResearchSource,
30
+ researchSourceTag,
31
+ researchSources,
32
+ researchSourceNameFor,
33
+ normalizeResearchChoice,
34
+ } from "./research-source.mjs";
29
35
  import { createCourtesyGate, DEFAULT_TIMEOUT_MS, DEFAULT_MIN_INTERVAL_MS, MAXLAG_SECONDS } from "./courtesy.mjs";
30
36
 
31
37
  export const WIKIPEDIA_LIVE_ORIGIN = "https://en.wikipedia.org";
@@ -210,14 +216,9 @@ export function registerResearchProvider(provider) {
210
216
  registeredResearchProvider = provider && typeof provider.lookup === "function" ? provider : null;
211
217
  }
212
218
 
213
- /** The research lane's active provider — the registered one, else one lazily
214
- * created singleton against simple.wikipedia.org with `waitForSlot` on: the
215
- * queue is paced turn-by-turn, so a throttled step WAITS for its polite slot
216
- * rather than reporting a false miss. `minIntervalMs` (first call only —
217
- * the singleton keeps its throttle clock) can only ever RAISE the interval;
218
- * the shipped minimum stays the floor. */
219
- export function getResearchProvider({ minIntervalMs } = {}) {
220
- if (registeredResearchProvider) return registeredResearchProvider;
219
+ const researchProvidersByChoice = new Map();
220
+
221
+ function defaultSimpleWikipediaProvider(minIntervalMs) {
221
222
  if (!defaultResearchProvider) {
222
223
  defaultResearchProvider = createSimpleWikipediaResearchSource({
223
224
  minIntervalMs: Math.max(DEFAULT_MIN_INTERVAL_MS, Number(minIntervalMs) || 0),
@@ -226,6 +227,28 @@ export function getResearchProvider({ minIntervalMs } = {}) {
226
227
  return defaultResearchProvider;
227
228
  }
228
229
 
230
+ /** The research lane's active provider — the registered one, else the source
231
+ * the config `source` choice names, each a lazily created singleton against
232
+ * its own origin with `waitForSlot` on: the queue is paced turn-by-turn, so a
233
+ * throttled step WAITS for its polite slot rather than reporting a false
234
+ * miss. `minIntervalMs` (first call only — the singleton keeps its throttle
235
+ * clock) can only ever RAISE the interval; the shipped minimum stays the
236
+ * floor. A registered provider (registerResearchProvider) wins outright,
237
+ * before any source resolution — every existing caller that never passes
238
+ * `source` keeps today's simple.wikipedia.org default unchanged. */
239
+ export function getResearchProvider({ minIntervalMs, source } = {}) {
240
+ if (registeredResearchProvider) return registeredResearchProvider;
241
+ const choice = normalizeResearchChoice(source);
242
+ if (choice === "wikipedia") return defaultSimpleWikipediaProvider(minIntervalMs);
243
+ if (researchProvidersByChoice.has(choice)) return researchProvidersByChoice.get(choice);
244
+ const entry = researchSources().find((e) => e.name === researchSourceNameFor(choice));
245
+ const provider = entry
246
+ ? entry.create({ minIntervalMs: Math.max(DEFAULT_MIN_INTERVAL_MS, Number(minIntervalMs) || 0) })
247
+ : defaultSimpleWikipediaProvider(minIntervalMs);
248
+ researchProvidersByChoice.set(choice, provider);
249
+ return provider;
250
+ }
251
+
229
252
  /** The Simple English Wikipedia research source: the same provider, named and
230
253
  * origin-pinned for the research-source registry, with `waitForSlot` on. Every
231
254
  * option the caller passes wins, so a test can hand it a stub transport and a
@@ -37,6 +37,7 @@ export const CLI_VERBS = [
37
37
  { flag: "[--live-wikipedia]", prose: ["start with the live Wikipedia supplement on — a question", "nothing local can answer also tries en.wikipedia.org,", "cited (network; also TMCT_LIVE_WIKIPEDIA=1 or tmct.toml", "corpus tier3; toggle mid-session with /wiki on|off)"] },
38
38
  { flag: "[--plain]", prose: ["force the plain readline shell (the default when", "stdin/stdout is not a terminal)"] },
39
39
  { flag: "[--memory-backend <default|memory|sqlite>]", prose: ["storage backend for taught facts this", "session (CLI flag > TMCT_MEMORY_BACKEND env > tmct.toml's", "[memory] backend > sqlite, .tmct/memory/graph.sqlite)"] },
40
+ { flag: "[--research-source <wikipedia|wikidata>]", prose: ["where \"research <topic>\" fetches from this session", "(/wikipedia|/wikidata in chat > this flag > tmct.toml's", "[research] source > wikipedia)"] },
40
41
  ],
41
42
  },
42
43
  {
@@ -66,6 +67,7 @@ export const CLI_VERBS = [
66
67
  { flag: "[--with-persona <name>]", prose: ["write an explicit [extensions]/[bias] preset into tmct.toml", "(\"code\" — today's implicit default, made explicit)"] },
67
68
  { flag: "[--persona-size <medium|large>]", prose: ["grow the default \"human\" persona's fact count", "beyond Small (the default): \"medium\" activates", "human-medium.jsonl (~1,608 facts total), \"large\" also", "activates human-large.jsonl (~13,600 facts total,", "with genuine multi-hop hypernym chains) — additive", "size tiers of the SAME bundle, not separate personas"] },
68
69
  { flag: "[--memory-backend <default|memory|sqlite>]", prose: ["write tmct.toml's [memory] backend", "(same flag name as `tmct chat`) — a later `tmct chat`", "in this repo picks it up with no flag needed"] },
70
+ { flag: "[--research-source <wikipedia|wikidata>]", prose: ["write tmct.toml's [research] source", "(same flag name as `tmct chat`) — a later `tmct chat`", "in this repo picks it up with no flag needed"] },
69
71
  ],
70
72
  },
71
73
  {
@@ -392,18 +392,21 @@ export function loadProgressLine(parts) {
392
392
  * The "researched this session" panel's own reading of a settled research
393
393
  * turn's answer — the passage it read and where it read it, straight off
394
394
  * research.mjs's own `renderResearchAnswer` shape (`term — summary (source:
395
- * research article "title", Simple English Wikipedia, CC BY-SA 4.0 — url)`),
396
- * never a second fetch: the citation text is already the retrieved passage,
397
- * this just pulls its pieces apart for display. Returns null on anything
398
- * else (a miss, a status/stop reply, or text that doesn't open this way) —
399
- * an honest "nothing to show" rather than a guessed passage.
395
+ * research article "title", <source>, <licence> — url)`, e.g. "Simple
396
+ * English Wikipedia, CC BY-SA 4.0" or "Wikidata, CC0 1.0"), never a second
397
+ * fetch: the citation text is already the retrieved passage, this just pulls
398
+ * its pieces apart for display. The source/licence segment itself is not
399
+ * pinned to one source, so a Wikidata-sourced research turn still parses.
400
+ * Returns null on anything else (a miss, a status/stop reply, or text that
401
+ * doesn't open this way) — an honest "nothing to show" rather than a
402
+ * guessed passage.
400
403
  *
401
404
  * Self-contained, `.toString()`-splice safe — the same discipline every
402
405
  * other pure export in this module holds.
403
406
  */
404
407
  export function parseResearchAnswer(answer) {
405
408
  const text = String(answer || "");
406
- const m = /^(.*?) — ([\s\S]*?) \(source: research article "([^"]+)", Simple English Wikipedia, CC BY-SA 4\.0 — (\S+)\)/.exec(text);
409
+ const m = /^(.*?) — ([\s\S]*?) \(source: research article "([^"]+)", [^,]+, [^—]+? — (\S+)\)/.exec(text);
407
410
  if (!m) return null;
408
411
  return { term: m[1], passage: m[2], title: m[3], url: m[4] };
409
412
  }
@@ -1496,6 +1499,9 @@ ${shareOverlayHtml({ withTape: true })}
1496
1499
  onRender: renderResearchControls,
1497
1500
  waitMs: RESEARCH_TICK_MS,
1498
1501
  });
1502
+ // A driver process can't atomically observe a browser-paced ticker from
1503
+ // outside, so tests read its state through here rather than racing it.
1504
+ window.tmct.page.researchTicker = researchTicker;
1499
1505
 
1500
1506
  function renderResearchControls(tickState) {
1501
1507
  const state = tickState || researchTicker.getState();
@@ -30,6 +30,7 @@ import { runTurn, hasSeededVocabulary, vocabExampleHint, codeDomainActive as cod
30
30
  import { resolveGameConfig } from "../domain/game-config.mjs";
31
31
  import { emptyRecord, resolveDiscourseConfig } from "../domain/discourse.mjs";
32
32
  import { resolveResearchConfig } from "./research.mjs";
33
+ import { normalizeResearchChoice } from "../adapters/corpus/research-source.mjs";
33
34
  import { sessionLogHeaderMarkdown, sessionLogTurnMarkdown, sessionLogEndMarkdown } from "./session-log-format.mjs";
34
35
 
35
36
  /** Where session logs live, relative to the target repo. `.tmct/` is the repo's
@@ -126,6 +127,12 @@ export async function createSession({
126
127
  ephemeral = false,
127
128
  narrate = false,
128
129
  liveReference = false,
130
+ // Which research source "research <topic>" fetches from: this session's
131
+ // starting value. Precedence — /wikipedia|/wikidata in chat (mutable,
132
+ // applied to session state by `turn()` below) > this param (`tmct chat
133
+ // --research-source`) > tmct.toml's [research] source > "wikipedia".
134
+ // Omitted (null) defers entirely to the toml/default tier.
135
+ researchSource = null,
129
136
  // The storage-backend seam: the default (empty or "default") resolves to
130
137
  // Backend C — the sqlite store at .tmct/memory/graph.sqlite, a live
131
138
  // node:sqlite connection lazily imported on open. The flat-file Backend A is
@@ -247,6 +254,11 @@ export async function createSession({
247
254
  // resolved once per session from the same tmct.toml, defaults filling
248
255
  // every unset key exactly as resolveGameConfig does above.
249
256
  const researchConfig = resolveResearchConfig(toml);
257
+ // This session's starting research source: the flag tier (`researchSource`,
258
+ // e.g. `tmct chat --research-source`) over the toml tier over the shipped
259
+ // default — /wikipedia|/wikidata in chat mutate this turn-to-turn below,
260
+ // exactly like narrateOn/liveReferenceOn.
261
+ let researchSourceOn = normalizeResearchChoice(researchSource || researchConfig.source);
250
262
 
251
263
  // tmct.toml's corpus tier3 opts the session into the live supplement too —
252
264
  // the flag/env tiers above stay authoritative when set.
@@ -493,6 +505,7 @@ export async function createSession({
493
505
  get turns() { return turns; },
494
506
  get narrate() { return narrateOn; },
495
507
  get liveReference() { return liveReferenceOn; },
508
+ get researchSource() { return researchSourceOn; },
496
509
  promptFor: () => promptFor(focus),
497
510
 
498
511
  /** One dispatched turn through the FULL sink sequencing (writeLog → writeSidecar
@@ -503,7 +516,7 @@ export async function createSession({
503
516
  async turn(line) {
504
517
  let result;
505
518
  try {
506
- result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, vocabHint, tel, biasByBundle, planState, gameConfig, researchState, researchConfig, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
519
+ result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, researchState, researchConfig, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
507
520
  } catch (e) {
508
521
  const ts = new Date().toISOString();
509
522
  const message = e instanceof Error ? e.message : String(e);
@@ -514,7 +527,7 @@ export async function createSession({
514
527
  turns += 1;
515
528
  return { answer: `Something went wrong answering that (${message}). Try rephrasing, or /help.`, end: false, prompt: promptFor(focus) };
516
529
  }
517
- const { record, focus: nextFocus, last: nextLast, end, narrate: nextNarrate, liveReference: nextLiveReference } = result;
530
+ const { record, focus: nextFocus, last: nextLast, end, narrate: nextNarrate, liveReference: nextLiveReference, researchSource: nextResearchSource } = result;
518
531
  // "noted — remembered" reports a durable write. In a session that keeps
519
532
  // nothing it is the last word on a fact that dies with the process, so
520
533
  // say where the fact actually went.
@@ -534,6 +547,7 @@ export async function createSession({
534
547
  // append a cited read-out under every grounded vocabulary answer), or
535
548
  // "always" (widen that to every grounded answer).
536
549
  if (typeof nextLiveReference === "boolean" || nextLiveReference === "supplement" || nextLiveReference === "always") liveReferenceOn = nextLiveReference;
550
+ if (typeof nextResearchSource === "string") researchSourceOn = nextResearchSource;
537
551
  await writeLog(sessionLogTurnMarkdown({ startedAt: record.ts, turnNumber: turns + 1, query: line, answer }));
538
552
  await writeSidecar(record);
539
553
  turnRecords.push(record);
@@ -589,6 +603,7 @@ export async function runChat({
589
603
  ephemeral = false,
590
604
  narrate = false,
591
605
  liveReference = false,
606
+ researchSource = null,
592
607
  memoryBackend = null,
593
608
  toolNamePrefix,
594
609
  actingSubject,
@@ -596,7 +611,7 @@ export async function runChat({
596
611
  // createSession's first-run seed (~2-3s) produces ZERO output until it fully
597
612
  // resolves, which otherwise reads as `npm run chat` hanging with total silence.
598
613
  output.write("tmct — starting…\n");
599
- const session = await createSession({ repoPath, graphPaths, configPath, source, env, cwd, gitRoot, ephemeral, narrate, liveReference, memoryBackend, toolNamePrefix, actingSubject });
614
+ const session = await createSession({ repoPath, graphPaths, configPath, source, env, cwd, gitRoot, ephemeral, narrate, liveReference, researchSource, memoryBackend, toolNamePrefix, actingSubject });
600
615
 
601
616
  const dim = (s) => (env.NO_COLOR || !output.isTTY ? s : `\x1b[2m${s}\x1b[0m`);
602
617
  for (const line of session.bannerLines) output.write(dim(line) + "\n");
@@ -54,7 +54,10 @@ import {
54
54
  } from "../domain/reference-pack.mjs";
55
55
  import { getReferencePackProvider } from "../adapters/corpus/reference-pack.mjs";
56
56
  import { getLiveReferenceProvider, getResearchProvider } from "../adapters/corpus/wikipedia-live.mjs";
57
- import { researchTurn, researchSnapshot, resolveResearchConfig, RESEARCH_DEFAULTS, parseResearchRequest } from "./research.mjs";
57
+ // Imported for its research-source registration side effect only, so
58
+ // getResearchProvider({ source: "wikidata" }) can find an entry to build.
59
+ import "../adapters/corpus/wikidata-live.mjs";
60
+ import { researchTurn, researchSnapshot, resolveResearchConfig, RESEARCH_DEFAULTS, parseResearchRequest, researchSourceLabel } from "./research.mjs";
58
61
  import { loadResearchQueue, saveResearchQueue } from "../adapters/research-queue-store.mjs";
59
62
  import { CHILD_PACK_NAME, childProvenanceTag } from "../domain/child-pack.mjs";
60
63
  import { getChildPackProvider } from "../adapters/corpus/child-pack.mjs";
@@ -7320,7 +7323,8 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7320
7323
  ["forget that <X> is a <Y>", "withdraw a fact you taught, and anything derived from it — the phrasing the retract lane reads"],
7321
7324
  ["/narrate on|off", "verbose developer/debug mode: decision points, matched pattern, results+sources, goal per turn"],
7322
7325
  ["/wiki on|off|supplement|always", "live Wikipedia (default off): on tries en.wikipedia.org when I can't answer (network), cited; supplement also adds a read-out under every grounded vocabulary answer; always widens that to every grounded answer"],
7323
- ["research <topic> [limit N] [depth D]", "fetch the topic from Simple English Wikipedia (the explicit ask is the network consent), store what it grounds, and queue its linked topics — \"research next\" steps the queue; also status/stop. limit N caps the links queued per topic, depth D how many hops the queue follows (1 by default); a run also stops at its total node budget"],
7326
+ ["/wikipedia | /wikidata", "which source \"research <topic>\" fetches from for the rest of the session: Simple English Wikipedia's prose (the default) or Wikidata's structured claims. tmct.toml's [research] source sets the starting value; tmct chat --research-source overrides it per invocation"],
7327
+ ["research <topic> [limit N] [depth D]", "fetch the topic from the session's research source (Simple English Wikipedia by default — /wikidata switches it) (the explicit ask is the network consent), store what it grounds, and queue its linked topics — \"research next\" steps the queue; also status/stop. limit N caps the links queued per topic, depth D how many hops the queue follows (1 by default); a run also stops at its total node budget"],
7324
7328
  ["/help", "this list"],
7325
7329
  ["/exit", "leave the session (also Ctrl+C / Ctrl+D)"],
7326
7330
  ];
@@ -12187,6 +12191,9 @@ async function ingestReferenceArticle(memoryDir, key, article, cache, tagFor = r
12187
12191
  if (subject && object && subject !== object && !seen.has(id)) { seen.add(id); facts.push({ subject, predicate, object, provenance }); }
12188
12192
  };
12189
12193
  if (article.isa) add(key, "rdfs:subClassOf", article.isa);
12194
+ if (Array.isArray(article.facts)) {
12195
+ for (const f of article.facts) add(f.subject, f.predicate, f.object);
12196
+ }
12190
12197
  try {
12191
12198
  const { optimisticTriples } = await import("./extract-facts.mjs");
12192
12199
  for (const sentence of splitSentences(article.summary || article.text || "")) {
@@ -15289,6 +15296,8 @@ const GOAL_BY_COMMAND = {
15289
15296
  capabilities: "see what /plan can plan over — built-in query tools and taught actions",
15290
15297
  syllogise: "materialize the entailed facts that follow from what's remembered about one term",
15291
15298
  wiki: "toggle the live Wikipedia supplement for questions nothing local can answer",
15299
+ wikipedia: "choose which source the research lane fetches from",
15300
+ wikidata: "choose which source the research lane fetches from",
15292
15301
  export: "write the memory store to a file, in the standard JSONL shape",
15293
15302
  ingest: "read a local text file and store every fact the recognizer grounds from it",
15294
15303
  };
@@ -15313,12 +15322,12 @@ function domainPackLine({ name, groundingKind, groundingAdapter, commandCount, c
15313
15322
  return parts.length ? `${name} — ${parts.join("; ")}` : String(name);
15314
15323
  }
15315
15324
 
15316
- async function runCommand(line, { config, source, graph, focus, memoryDir, trace, narrate = false, liveReference = false, tel = null, biasByBundle = {}, cache = null, codeDomainActive = false, laneVocab = null, domainPacks = null }) {
15325
+ async function runCommand(line, { config, source, graph, focus, memoryDir, trace, narrate = false, liveReference = false, researchSource = null, tel = null, biasByBundle = {}, cache = null, codeDomainActive = false, laneVocab = null, domainPacks = null }) {
15317
15326
  const ts = new Date().toISOString();
15318
15327
  const sp = line.indexOf(" ");
15319
15328
  const name = (sp === -1 ? line.slice(1) : line.slice(1, sp)).toLowerCase();
15320
15329
  const argText = (sp === -1 ? "" : line.slice(sp + 1)).trim();
15321
- const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext } = {}) => ({
15330
+ const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext, researchSourceNext } = {}) => ({
15322
15331
  answer,
15323
15332
  logLines: [ts, `> ${line}`, answer, ""],
15324
15333
  record: { type: "turn", ts, query: line, command: name, via: "command", resolvedIds, answeredIds: [], miss },
@@ -15326,6 +15335,7 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15326
15335
  goal: GOAL_BY_COMMAND[name] || "use a specific tool/command directly",
15327
15336
  ...(narrateNext !== undefined ? { narrate: narrateNext } : {}),
15328
15337
  ...(liveReferenceNext !== undefined ? { liveReference: liveReferenceNext } : {}),
15338
+ ...(researchSourceNext !== undefined ? { researchSource: researchSourceNext } : {}),
15329
15339
  });
15330
15340
 
15331
15341
  if (name === "help") { note(trace, "goal: get oriented / learn available commands"); return mk(await helpText(codeDomainActive, codeDomainActive ? laneVocab?.helpRows : [])); }
@@ -15364,15 +15374,34 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15364
15374
  const arg = argText.toLowerCase();
15365
15375
  const stateWord = (v) => (v === "always" ? "always" : v === "supplement" ? "supplement" : v ? "on" : "off");
15366
15376
  if (arg !== "on" && arg !== "off" && arg !== "supplement" && arg !== "always") {
15377
+ const activeResearchSource = researchSourceLabel(researchSource);
15367
15378
  return mk(`live Wikipedia supplement is ${stateWord(liveReference)} — /wiki on, /wiki off, /wiki supplement, or /wiki always. `
15368
15379
  + "When on, a question I can't answer also tries en.wikipedia.org (network); "
15369
15380
  + "supplement adds a cited Wikipedia read-out under every grounded vocabulary answer too; "
15370
- + "always widens that to every grounded answer.");
15381
+ + "always widens that to every grounded answer. "
15382
+ + `Research fetches currently go to ${activeResearchSource} — /wikipedia or /wikidata switches them.`);
15371
15383
  }
15372
15384
  const next = arg === "always" ? "always" : arg === "supplement" ? "supplement" : arg === "on";
15373
15385
  return mk(`live Wikipedia supplement ${stateWord(next)}.`, { liveReferenceNext: next });
15374
15386
  }
15375
15387
 
15388
+ // /wikipedia and /wikidata — which source the research lane fetches from for
15389
+ // the rest of the session (session-scoped, the /narrate and /wiki pattern:
15390
+ // the new state rides the turn RESULT as `researchSource`). tmct.toml's
15391
+ // [research] source sets the session's starting value; `tmct chat
15392
+ // --research-source` overrides that; these two override both, per session.
15393
+ // Neither name is slash-optional and neither goes in COMMANDS/COMMAND_WORDS
15394
+ // — a bare "wikipedia" or "wikidata" stays an ordinary question, exactly
15395
+ // like /wiki and /narrate.
15396
+ if (name === "wikipedia" || name === "wikidata") {
15397
+ return mk(
15398
+ name === "wikipedia"
15399
+ ? "research fetches go to Simple English Wikipedia (prose articles, CC BY-SA 4.0) for the rest of this session — /wikidata switches them to Wikidata."
15400
+ : "research fetches go to Wikidata (structured claims, CC0 1.0) for the rest of this session — /wikipedia switches them back to Simple English Wikipedia.",
15401
+ { researchSourceNext: name },
15402
+ );
15403
+ }
15404
+
15376
15405
  // /memory [verbose] — what tmct remembers, as text (the same renderer
15377
15406
  // serves the `tmct memory` CLI).
15378
15407
  if (name === "memory") {
@@ -16577,7 +16606,7 @@ export async function runTurn(input, options = {}) {
16577
16606
  return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
16578
16607
  }
16579
16608
 
16580
- async function dispatchTurn(input, { config, source = defaultSource, graph = null, focus = null, last = null, memoryDir = null, sessionId = "", env = process.env, lexicon = null, narrate = false, liveReference = false, onLiveLookup = null, vocabHint = null, tel = null, biasByBundle = {}, factRowsCache: injectedFactRowsCache = null, planState = null, gameConfig = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, researchState = null, researchConfig = null, discourse = null, _noSplit = false, actingSubject = "player", codeDomainActive = null, laneVocab = null, domainPacks = null } = {}) {
16609
+ async function dispatchTurn(input, { config, source = defaultSource, graph = null, focus = null, last = null, memoryDir = null, sessionId = "", env = process.env, lexicon = null, narrate = false, liveReference = false, researchSource = null, onLiveLookup = null, vocabHint = null, tel = null, biasByBundle = {}, factRowsCache: injectedFactRowsCache = null, planState = null, gameConfig = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, researchState = null, researchConfig = null, discourse = null, _noSplit = false, actingSubject = "player", codeDomainActive = null, laneVocab = null, domainPacks = null } = {}) {
16581
16610
  // Every game's tuning knobs (spider-fly's mass economy, guess-the-number's
16582
16611
  // bounds, the shared plan lane's search-depth cap) — a caller's own
16583
16612
  // gameConfig (chat-session.mjs resolves one per session from tmct.toml)
@@ -16669,7 +16698,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
16669
16698
  // an answer's typed content is in hand (runAsk, off the ask envelope's
16670
16699
  // `discourse` referents); the caller re-threads whatever comes back.
16671
16700
  const discourseHolder = { record: discourse ?? emptyDiscourseRecord() };
16672
- const ctx = { config, source, graph, focus, last, memoryDir, sessionId, templates, env, lexicon, trace, narrate, liveReference, onLiveLookup, vocabHint: resolvedVocabHint, tel, biasByBundle, cache: factRowsCache, vocabAntecedent, planHolder, discourseHolder, gameConfig: resolvedGameConfig, uiContext, synthesisBudget, codeDomainActive: domainActive, laneVocab: laneVocabValue, domainPacks: domainPacksValue };
16701
+ const ctx = { config, source, graph, focus, last, memoryDir, sessionId, templates, env, lexicon, trace, narrate, liveReference, researchSource, onLiveLookup, vocabHint: resolvedVocabHint, tel, biasByBundle, cache: factRowsCache, vocabAntecedent, planHolder, discourseHolder, gameConfig: resolvedGameConfig, uiContext, synthesisBudget, codeDomainActive: domainActive, laneVocab: laneVocabValue, domainPacks: domainPacksValue };
16673
16702
  // A DISPATCHED turn (count / slash-command / ask) becomes the new "last
16674
16703
  // answer" that why/say-more re-renders; a conversational turn does not.
16675
16704
  // Every dispatched turn's result passes through finish() here — the LAST
@@ -16867,12 +16896,13 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
16867
16896
  }
16868
16897
  const researchHolder = { state: priorResearchState };
16869
16898
  const resolvedResearchConfig = researchConfig ?? RESEARCH_DEFAULTS;
16899
+ const effectiveResearchSource = researchSource ?? resolvedResearchConfig.source;
16870
16900
  const rTurn = await researchTurn(workingLine, {
16871
16901
  holder: researchHolder,
16872
16902
  memoryDir,
16873
16903
  lexicon,
16874
- provider: getResearchProvider({ minIntervalMs: resolvedResearchConfig.minIntervalMs }),
16875
- config: resolvedResearchConfig,
16904
+ provider: getResearchProvider({ minIntervalMs: resolvedResearchConfig.minIntervalMs, source: effectiveResearchSource }),
16905
+ config: { ...resolvedResearchConfig, source: effectiveResearchSource },
16876
16906
  planActive: Boolean(planHolder.state && !planHolder.state.done),
16877
16907
  pagerActive: Boolean(Array.isArray(last?.detail?.pending?.items) && last.detail.pending.items.length),
16878
16908
  notify: onLiveLookup,
@@ -145,6 +145,19 @@ backend = ${JSON.stringify(config.memory.backend)}
145
145
  `;
146
146
  }
147
147
 
148
+ // [research] source — only emitted when a caller actually supplies it.
149
+ if (config.research && config.research.source !== undefined) {
150
+ out += `
151
+ [research]
152
+ # Which source "research <topic>" fetches from.
153
+ # Precedence: /wikipedia|/wikidata in chat > --research-source flag >
154
+ # this file > "wikipedia" (the built-in default).
155
+ # "wikipedia" — Simple English Wikipedia prose articles, CC BY-SA 4.0.
156
+ # "wikidata" — Wikidata's structured claims, CC0 1.0.
157
+ source = ${JSON.stringify(config.research.source)}
158
+ `;
159
+ }
160
+
148
161
  // Extension-pack / bias sections — only emitted when a caller supplies them.
149
162
  const extras = {};
150
163
  if (config.extensions !== undefined) extras.extensions = config.extensions;
@@ -184,13 +197,16 @@ function seedRequested({ optSeed, configEnabled, env }) {
184
197
  * @param {string} [opts.memoryBackend] "default" | "memory" | "sqlite" — merged into a
185
198
  * FRESH config's `[memory] backend`, and selects which backend the corpus seed writes
186
199
  * into (via src/adapters/memory/core.mjs's openMemoryBackend).
200
+ * @param {string} [opts.researchSource] "wikipedia" | "wikidata" — merged into a
201
+ * FRESH config's `[research] source`, the tmct.toml tier of the research lane's
202
+ * source precedence (src/services/chat-session.mjs createSession).
187
203
  * @returns {Promise<{
188
204
  * created: string[], config: object, seeded: boolean,
189
205
  * alreadyInitialized: boolean, seedResult: (object|null), message: string
190
206
  * }>} `created` lists the absolute paths this call brought into being. Never throws on
191
207
  * a benign re-init or a corpus failure.
192
208
  */
193
- export async function initRepo(dir, { force = false, seed, env = process.env, persona = null, memoryBackend = null } = {}) {
209
+ export async function initRepo(dir, { force = false, seed, env = process.env, persona = null, memoryBackend = null, researchSource = null } = {}) {
194
210
  const root = resolve(dir);
195
211
  const created = [];
196
212
  const paths = {
@@ -265,6 +281,7 @@ export async function initRepo(dir, { force = false, seed, env = process.env, pe
265
281
  if (persona.bias && Object.keys(persona.bias).length) config.bias = persona.bias;
266
282
  }
267
283
  if (memoryBackend) config.memory = { ...(config.memory || {}), backend: memoryBackend };
284
+ if (researchSource) config.research = { ...(config.research || {}), source: researchSource };
268
285
  const tomlPresent = await exists(paths.toml);
269
286
  if (!tomlPresent || force) {
270
287
  await writeFile(paths.toml, renderTomlConfig(config));
@@ -391,6 +408,9 @@ async function readWrittenConfig(tomlPath, base) {
391
408
  if (raw.memory && raw.memory.backend !== undefined) {
392
409
  cfg.memory = { ...cfg.memory, backend: raw.memory.backend };
393
410
  }
411
+ if (raw.research && raw.research.source !== undefined) {
412
+ cfg.research = { ...cfg.research, source: raw.research.source };
413
+ }
394
414
  return cfg;
395
415
  } catch {
396
416
  return base;