@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.
Files changed (99) hide show
  1. package/README.md +12 -3
  2. package/bin/tmct.mjs +52 -3
  3. package/corpus/LICENSES.json +3 -3
  4. package/corpus/domains/code/LICENSE-NOTICE +43 -0
  5. package/corpus/{seon → domains/code}/README.md +22 -24
  6. package/corpus/domains/code/vocab.json +43 -0
  7. package/corpus/reference/manifest.json +126 -126
  8. package/corpus/reference/shards/ref-00.jsonl.gz +0 -0
  9. package/corpus/reference/shards/ref-01.jsonl.gz +0 -0
  10. package/corpus/reference/shards/ref-02.jsonl.gz +0 -0
  11. package/corpus/reference/shards/ref-03.jsonl.gz +0 -0
  12. package/corpus/reference/shards/ref-04.jsonl.gz +0 -0
  13. package/corpus/reference/shards/ref-05.jsonl.gz +0 -0
  14. package/corpus/reference/shards/ref-06.jsonl.gz +0 -0
  15. package/corpus/reference/shards/ref-07.jsonl.gz +0 -0
  16. package/corpus/reference/shards/ref-08.jsonl.gz +0 -0
  17. package/corpus/reference/shards/ref-09.jsonl.gz +0 -0
  18. package/corpus/reference/shards/ref-0a.jsonl.gz +0 -0
  19. package/corpus/reference/shards/ref-0b.jsonl.gz +0 -0
  20. package/corpus/reference/shards/ref-0c.jsonl.gz +0 -0
  21. package/corpus/reference/shards/ref-0d.jsonl.gz +0 -0
  22. package/corpus/reference/shards/ref-0e.jsonl.gz +0 -0
  23. package/corpus/reference/shards/ref-0f.jsonl.gz +0 -0
  24. package/corpus/reference/shards/ref-10.jsonl.gz +0 -0
  25. package/corpus/reference/shards/ref-11.jsonl.gz +0 -0
  26. package/corpus/reference/shards/ref-12.jsonl.gz +0 -0
  27. package/corpus/reference/shards/ref-13.jsonl.gz +0 -0
  28. package/corpus/reference/shards/ref-14.jsonl.gz +0 -0
  29. package/corpus/reference/shards/ref-15.jsonl.gz +0 -0
  30. package/corpus/reference/shards/ref-16.jsonl.gz +0 -0
  31. package/corpus/reference/shards/ref-17.jsonl.gz +0 -0
  32. package/corpus/reference/shards/ref-18.jsonl.gz +0 -0
  33. package/corpus/reference/shards/ref-19.jsonl.gz +0 -0
  34. package/corpus/reference/shards/ref-1a.jsonl.gz +0 -0
  35. package/corpus/reference/shards/ref-1b.jsonl.gz +0 -0
  36. package/corpus/reference/shards/ref-1c.jsonl.gz +0 -0
  37. package/corpus/reference/shards/ref-1d.jsonl.gz +0 -0
  38. package/corpus/reference/shards/ref-1e.jsonl.gz +0 -0
  39. package/corpus/reference/shards/ref-1f.jsonl.gz +0 -0
  40. package/corpus/reference/shards/ref-20.jsonl.gz +0 -0
  41. package/corpus/reference/shards/ref-21.jsonl.gz +0 -0
  42. package/corpus/reference/shards/ref-22.jsonl.gz +0 -0
  43. package/corpus/reference/shards/ref-23.jsonl.gz +0 -0
  44. package/corpus/reference/shards/ref-24.jsonl.gz +0 -0
  45. package/corpus/reference/shards/ref-25.jsonl.gz +0 -0
  46. package/corpus/reference/shards/ref-26.jsonl.gz +0 -0
  47. package/corpus/reference/shards/ref-27.jsonl.gz +0 -0
  48. package/corpus/reference/shards/ref-28.jsonl.gz +0 -0
  49. package/corpus/reference/shards/ref-29.jsonl.gz +0 -0
  50. package/corpus/reference/shards/ref-2a.jsonl.gz +0 -0
  51. package/corpus/reference/shards/ref-2b.jsonl.gz +0 -0
  52. package/corpus/reference/shards/ref-2c.jsonl.gz +0 -0
  53. package/corpus/reference/shards/ref-2d.jsonl.gz +0 -0
  54. package/corpus/reference/shards/ref-2e.jsonl.gz +0 -0
  55. package/corpus/reference/shards/ref-2f.jsonl.gz +0 -0
  56. package/corpus/reference/shards/ref-30.jsonl.gz +0 -0
  57. package/corpus/reference/shards/ref-31.jsonl.gz +0 -0
  58. package/corpus/reference/shards/ref-32.jsonl.gz +0 -0
  59. package/corpus/reference/shards/ref-33.jsonl.gz +0 -0
  60. package/corpus/reference/shards/ref-34.jsonl.gz +0 -0
  61. package/corpus/reference/shards/ref-35.jsonl.gz +0 -0
  62. package/corpus/reference/shards/ref-36.jsonl.gz +0 -0
  63. package/corpus/reference/shards/ref-37.jsonl.gz +0 -0
  64. package/corpus/reference/shards/ref-38.jsonl.gz +0 -0
  65. package/corpus/reference/shards/ref-39.jsonl.gz +0 -0
  66. package/corpus/reference/shards/ref-3a.jsonl.gz +0 -0
  67. package/corpus/reference/shards/ref-3b.jsonl.gz +0 -0
  68. package/corpus/reference/shards/ref-3c.jsonl.gz +0 -0
  69. package/corpus/reference/shards/ref-3d.jsonl.gz +0 -0
  70. package/corpus/reference/shards/ref-3e.jsonl.gz +0 -0
  71. package/corpus/reference/shards/ref-3f.jsonl.gz +0 -0
  72. package/corpus/tier2/vocab-empty.json +6 -0
  73. package/data/templates/responses.jsonl +3 -0
  74. package/package.json +19 -1
  75. package/src/adapters/corpus/conceptnet.mjs +7 -3
  76. package/src/adapters/corpus/courtesy.mjs +129 -0
  77. package/src/adapters/corpus/research-source.mjs +137 -0
  78. package/src/adapters/corpus/wikidata-live.mjs +262 -0
  79. package/src/adapters/corpus/wikipedia-live.mjs +83 -116
  80. package/src/domain/cli-verbs.mjs +2 -0
  81. package/src/domain/codegraph.mjs +10 -2
  82. package/src/domain/grammar/lexicon-core.json +1 -0
  83. package/src/domain/reference-pack.mjs +61 -9
  84. package/src/services/chat-page-viz.mjs +9 -6
  85. package/src/services/chat-session.mjs +65 -9
  86. package/src/services/chat.mjs +395 -121
  87. package/src/services/extensions.mjs +203 -3
  88. package/src/services/init.mjs +27 -6
  89. package/src/services/lane-vocab-data.mjs +56 -0
  90. package/src/services/research.mjs +36 -14
  91. package/src/surfaces/web/claims-browser-entry.mjs +26 -0
  92. package/src/surfaces/web/memory-ask-browser.bundle.js +130 -128
  93. package/src/surfaces/web/planner-instances.mjs +152 -0
  94. package/src/tools/handlers/tmct-untested.mjs +2 -2
  95. package/src/tools/server.mjs +9 -4
  96. package/corpus/seon/LICENSE-NOTICE +0 -37
  97. /package/corpus/{seon → domains/code}/concepts.jsonl +0 -0
  98. /package/corpus/{seon → domains/code}/definitions.jsonl +0 -0
  99. /package/corpus/{seon → domains/code}/relations.jsonl +0 -0
@@ -25,10 +25,24 @@
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 {
29
+ registerResearchSource,
30
+ researchSourceTag,
31
+ researchSources,
32
+ researchSourceNameFor,
33
+ normalizeResearchChoice,
34
+ } from "./research-source.mjs";
35
+ import { createCourtesyGate, DEFAULT_TIMEOUT_MS, DEFAULT_MIN_INTERVAL_MS, MAXLAG_SECONDS } from "./courtesy.mjs";
28
36
 
29
37
  export const WIKIPEDIA_LIVE_ORIGIN = "https://en.wikipedia.org";
30
38
  export const SIMPLE_WIKIPEDIA_ORIGIN = "https://simple.wikipedia.org";
31
39
 
40
+ /** The names these two providers go by as research SOURCES
41
+ * (research-source.mjs): the name segment of every provenance tag their facts
42
+ * carry, and the key each registers under. */
43
+ export const WIKIPEDIA_LIVE_SOURCE_NAME = "wikipedia-live";
44
+ export const SIMPLE_WIKIPEDIA_SOURCE_NAME = "simple-wikipedia";
45
+
32
46
  /** The identification string Wikimedia's robot policy asks API clients to
33
47
  * carry, pointing at this project's public site as the contact. Browsers
34
48
  * refuse to override the User-Agent request header, so the API-recognised
@@ -36,25 +50,20 @@ export const SIMPLE_WIKIPEDIA_ORIGIN = "https://simple.wikipedia.org";
36
50
  * sent. */
37
51
  export const WIKIMEDIA_USER_AGENT = "the-mechanical-code-talker (+https://tmct.polycode.co.uk/)";
38
52
 
39
- const DEFAULT_TIMEOUT_MS = 4000;
40
- const DEFAULT_MIN_INTERVAL_MS = 2000;
41
- const RETRY_AFTER_FLOOR_MS = 5000;
42
- // Action-API requests carry maxlag so an overloaded replica set answers with
43
- // an error we back off from instead of adding to its load (Wikimedia's own
44
- // recommended default for non-interactive clients).
45
- const MAXLAG_SECONDS = 5;
46
-
47
53
  /**
48
54
  * A live-lookup provider: { lookup(normTerm) -> article row | null }, plus
49
55
  * the research fan-out surface: pageByTitle(title) fetches an exact title's
50
56
  * summary in ONE round trip (no opensearch — a linked title is already
51
57
  * exact), and linkedTitles(title) lists the namespace-0 articles the page's
52
- * LEAD section links to, in document order.
58
+ * LEAD section links to, in document order. It also carries the research
59
+ * source contract (research-source.mjs): `name`, `origin` and
60
+ * `provenanceTag(term)`.
53
61
  *
54
62
  * `fetchImpl` defaults to the global fetch; `origin` to en.wikipedia.org;
55
- * `lexicon` (optional) feeds the isa extraction. The row shape is the shipped
56
- * pack's own ({ term, title, text, summary, url, revid, isa? }), validated by
57
- * isReferenceArticleRow before it is ever returned.
63
+ * `sourceName` to the en.wikipedia source name; `lexicon` (optional) feeds the
64
+ * isa extraction. The row shape is the shipped pack's own ({ term, title,
65
+ * text, summary, url, revid, isa? }), validated by isReferenceArticleRow
66
+ * before it is ever returned.
58
67
  *
59
68
  * Throttle posture: every public method takes one "slot" gated by the
60
69
  * minimum interval, the single-flight guard and any open cool-off. By
@@ -71,76 +80,9 @@ export function createWikipediaLiveProvider({
71
80
  lexicon = null,
72
81
  userAgent = WIKIMEDIA_USER_AGENT,
73
82
  waitForSlot = false,
83
+ sourceName = WIKIPEDIA_LIVE_SOURCE_NAME,
74
84
  } = {}) {
75
- const doFetch = fetchImpl ?? ((...args) => globalThis.fetch(...args));
76
- const cache = new Map(); // key -> row | null (hits AND settled misses)
77
- let lastLookupAt = 0;
78
- let coolOffUntil = 0;
79
- let inFlight = false;
80
-
81
- const identifyingHeaders = () => {
82
- if (!userAgent) return null;
83
- const headers = { "Api-User-Agent": userAgent };
84
- // A browser strips User-Agent as a forbidden header; only set it where
85
- // no DOM says we are one (Node ships a global `navigator` these days, so
86
- // `document` is the discriminating global).
87
- if (typeof document === "undefined") headers["User-Agent"] = userAgent;
88
- return headers;
89
- };
90
-
91
- function openCoolOff(retryAfterSeconds) {
92
- const retryAfterMs = Number(retryAfterSeconds) * 1000;
93
- coolOffUntil = Date.now() + Math.max(retryAfterMs || 0, RETRY_AFTER_FLOOR_MS);
94
- }
95
-
96
- async function fetchJson(url) {
97
- const controller = typeof AbortController === "function" ? new AbortController() : null;
98
- const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
99
- try {
100
- const opts = {};
101
- if (controller) opts.signal = controller.signal;
102
- const headers = identifyingHeaders();
103
- if (headers) opts.headers = headers;
104
- const res = await doFetch(url, opts);
105
- if (res.status === 429) {
106
- openCoolOff(res.headers?.get?.("retry-after"));
107
- return null;
108
- }
109
- if (!res.ok) return null;
110
- const body = await res.json();
111
- // A maxlag rejection arrives as HTTP 200 with an error body (and a
112
- // Retry-After header) — back off exactly as a 429 asks.
113
- if (body?.error?.code === "maxlag") {
114
- openCoolOff(res.headers?.get?.("retry-after"));
115
- return null;
116
- }
117
- return body;
118
- } catch {
119
- return null;
120
- } finally {
121
- if (timer !== null) clearTimeout(timer);
122
- }
123
- }
124
-
125
- /** When the next network slot opens: past the cool-off, past the minimum
126
- * interval since the last taken slot. */
127
- const slotOpensAt = () => Math.max(coolOffUntil, lastLookupAt + minIntervalMs);
128
-
129
- /** Take the one network slot, or report it unavailable. Default posture
130
- * returns false immediately (the clean-miss hook's "null, never block");
131
- * `waitForSlot` sleeps until the slot opens instead. */
132
- async function takeSlot() {
133
- for (;;) {
134
- const now = Date.now();
135
- if (!inFlight && now >= slotOpensAt()) {
136
- lastLookupAt = now;
137
- inFlight = true;
138
- return true;
139
- }
140
- if (!waitForSlot) return false;
141
- await new Promise((resolve) => setTimeout(resolve, Math.max(slotOpensAt() - now, 25)));
142
- }
143
- }
85
+ const gate = createCourtesyGate({ fetchImpl, timeoutMs, minIntervalMs, userAgent, waitForSlot });
144
86
 
145
87
  /** The opensearch title whose normFactTerm fold equals or extends the key —
146
88
  * the topic-drift guard: "quasar" may resolve to "Quasar" or "Quasars",
@@ -155,7 +97,7 @@ export function createWikipediaLiveProvider({
155
97
  }
156
98
 
157
99
  async function summaryRow(key, title) {
158
- const summary = await fetchJson(
100
+ const summary = await gate.fetchJson(
159
101
  `${origin}/api/rest_v1/page/summary/${encodeURIComponent(title.replace(/ /g, "_"))}`,
160
102
  );
161
103
  if (!summary) return null;
@@ -177,7 +119,7 @@ export function createWikipediaLiveProvider({
177
119
  }
178
120
 
179
121
  async function roundTrips(key) {
180
- const search = await fetchJson(
122
+ const search = await gate.fetchJson(
181
123
  `${origin}/w/api.php?action=opensearch&format=json&origin=*&maxlag=${MAXLAG_SECONDS}&search=${encodeURIComponent(key)}&limit=3`,
182
124
  );
183
125
  const title = search ? matchingTitle(key, search) : null;
@@ -185,29 +127,21 @@ export function createWikipediaLiveProvider({
185
127
  return summaryRow(key, title);
186
128
  }
187
129
 
188
- /** One slot-gated, cached operation: cache first (a settled hit or miss is
189
- * never refetched), then the slot, then `work()`, with every failure
190
- * cached as null so it never costs a second round trip. */
191
- async function cachedFetch(cacheKey, work) {
192
- if (cache.has(cacheKey)) return cache.get(cacheKey);
193
- if (!(await takeSlot())) return null;
194
- let value = null;
195
- try {
196
- value = await work();
197
- } catch {
198
- value = null;
199
- } finally {
200
- inFlight = false;
201
- }
202
- cache.set(cacheKey, value);
203
- return value;
204
- }
205
-
206
130
  return {
131
+ name: sourceName,
132
+ origin,
133
+
134
+ /** The tag a fact gained through the research source contract carries. The
135
+ * research lane stamps its own `research:<topic>@<depth>` tag instead when
136
+ * it ingests, because only the lane knows how far its fan-out reached. */
137
+ provenanceTag(term) {
138
+ return researchSourceTag(sourceName, term);
139
+ },
140
+
207
141
  async lookup(normTerm) {
208
142
  const key = String(normTerm ?? "");
209
143
  if (!key) return null;
210
- return cachedFetch(key, () => roundTrips(key));
144
+ return gate.cachedFetch(key, () => roundTrips(key));
211
145
  },
212
146
 
213
147
  /** The summary for an EXACT title — one round trip, no opensearch. The
@@ -216,7 +150,7 @@ export function createWikipediaLiveProvider({
216
150
  async pageByTitle(title) {
217
151
  const t = String(title ?? "").trim();
218
152
  if (!t) return null;
219
- return cachedFetch(`title\0${normFactTerm(t)}`, () => summaryRow(normFactTerm(t), t));
153
+ return gate.cachedFetch(`title\0${normFactTerm(t)}`, () => summaryRow(normFactTerm(t), t));
220
154
  },
221
155
 
222
156
  /** The namespace-0 articles the page's LEAD section links to, in document
@@ -228,8 +162,8 @@ export function createWikipediaLiveProvider({
228
162
  async linkedTitles(title, { limit = 25 } = {}) {
229
163
  const t = String(title ?? "").trim();
230
164
  if (!t) return null;
231
- const listed = await cachedFetch(`links\0${normFactTerm(t)}`, async () => {
232
- const parsed = await fetchJson(
165
+ const listed = await gate.cachedFetch(`links\0${normFactTerm(t)}`, async () => {
166
+ const parsed = await gate.fetchJson(
233
167
  `${origin}/w/api.php?action=parse&format=json&formatversion=2&origin=*&maxlag=${MAXLAG_SECONDS}&prop=links&redirects=1&page=${encodeURIComponent(t)}&section=0`,
234
168
  );
235
169
  const links = parsed?.parse?.links;
@@ -282,20 +216,53 @@ export function registerResearchProvider(provider) {
282
216
  registeredResearchProvider = provider && typeof provider.lookup === "function" ? provider : null;
283
217
  }
284
218
 
285
- /** The research lane's active provider — the registered one, else one lazily
286
- * created singleton against simple.wikipedia.org with `waitForSlot` on: the
287
- * queue is paced turn-by-turn, so a throttled step WAITS for its polite slot
288
- * rather than reporting a false miss. `minIntervalMs` (first call only —
289
- * the singleton keeps its throttle clock) can only ever RAISE the interval;
290
- * the shipped minimum stays the floor. */
291
- export function getResearchProvider({ minIntervalMs } = {}) {
292
- if (registeredResearchProvider) return registeredResearchProvider;
219
+ const researchProvidersByChoice = new Map();
220
+
221
+ function defaultSimpleWikipediaProvider(minIntervalMs) {
293
222
  if (!defaultResearchProvider) {
294
- defaultResearchProvider = createWikipediaLiveProvider({
295
- origin: SIMPLE_WIKIPEDIA_ORIGIN,
296
- waitForSlot: true,
223
+ defaultResearchProvider = createSimpleWikipediaResearchSource({
297
224
  minIntervalMs: Math.max(DEFAULT_MIN_INTERVAL_MS, Number(minIntervalMs) || 0),
298
225
  });
299
226
  }
300
227
  return defaultResearchProvider;
301
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
+
252
+ /** The Simple English Wikipedia research source: the same provider, named and
253
+ * origin-pinned for the research-source registry, with `waitForSlot` on. Every
254
+ * option the caller passes wins, so a test can hand it a stub transport and a
255
+ * zero interval. */
256
+ export function createSimpleWikipediaResearchSource(options = {}) {
257
+ return createWikipediaLiveProvider({
258
+ origin: SIMPLE_WIKIPEDIA_ORIGIN,
259
+ sourceName: SIMPLE_WIKIPEDIA_SOURCE_NAME,
260
+ waitForSlot: true,
261
+ ...options,
262
+ });
263
+ }
264
+
265
+ registerResearchSource({
266
+ name: SIMPLE_WIKIPEDIA_SOURCE_NAME,
267
+ create: createSimpleWikipediaResearchSource,
268
+ });
@@ -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
  {
@@ -1370,8 +1370,15 @@ export function renderTestsFor(graph, ind) {
1370
1370
  * statements, so the empty survey has to say which one it means: with no
1371
1371
  * source module recorded there is no coverage claim to make at all, and the
1372
1372
  * full-coverage sentence would be an assertion about a repo this store has
1373
- * never seen. */
1374
- export function renderUntested(graph) {
1373
+ * never seen.
1374
+ *
1375
+ * `codeDomainActive` (the session-level predicate; omitted derives from the
1376
+ * graph alone, same fallback the chat layer's own gate uses) — with no code
1377
+ * domain active, the empty survey says nothing about a "code index" at all:
1378
+ * this is a slash command, not a miss the chat layer's own text-swap covers,
1379
+ * so the neutral wording has to live here. */
1380
+ export function renderUntested(graph, { codeDomainActive = null } = {}) {
1381
+ const domainActive = codeDomainActive ?? (moduleCountOf(graph) > 0);
1375
1382
  const covered = new Set();
1376
1383
  const testModules = new Set();
1377
1384
  for (const e of edgesOfKind(graph, "tests")) {
@@ -1384,6 +1391,7 @@ export function renderUntested(graph) {
1384
1391
  && !isTestPath(String(i.label).toLowerCase()),
1385
1392
  );
1386
1393
  if (!sourceModules.length) {
1394
+ if (!domainActive) return "this session holds no graph to check test coverage against.";
1387
1395
  return moduleCountOf(graph) === 0
1388
1396
  ? `no modules to check for test coverage in this index. ${NO_CODE_INDEX_NOTE}`
1389
1397
  : "no source modules to check for test coverage in this index — only test modules are recorded.";
@@ -389,6 +389,7 @@
389
389
  "plural": "mice"
390
390
  },
391
391
  "rabbit": {},
392
+ "rodent": {},
392
393
  "bear": {},
393
394
  "lion": {},
394
395
  "tiger": {},
@@ -157,7 +157,26 @@ export function sentencesUpTo(text, cap) {
157
157
  return out || String(text ?? "").slice(0, cap);
158
158
  }
159
159
 
160
- const ISA_RE = /^[A-Z][^.!?]{0,80}? (?:is|are) (?:(a|an|the) )?([a-z][a-z -]{1,60})/;
160
+ // The preamble before the copula is bounded only by the sentence itself
161
+ // (no "is"/"are" can cross a ".", "!" or "?"), not by a fixed character
162
+ // count — an appositive list ("also called cougars, mountain lions, …")
163
+ // can push the real copula well past what a short cap would reach.
164
+ const ISA_RE = /^[A-Z][^.!?]*? (?:is|are) (?:(a|an|the) )?([a-z][a-z -]{1,60})/;
165
+
166
+ // A "(…)" aside breaks the plain-lowercase word class ISA_RE's capture group
167
+ // matches against, and can itself push the real copula past any fixed cap —
168
+ // so every parenthetical is dropped before matching, not just accounted for
169
+ // in the cap. Applied to the whole string: a later sentence's own aside
170
+ // never reaches back to move the first sentence's boundary.
171
+ function withoutParentheticals(text) {
172
+ let out = text;
173
+ let prior;
174
+ do {
175
+ prior = out;
176
+ out = out.replace(/\s*\([^()]*\)/g, "");
177
+ } while (out !== prior);
178
+ return out;
179
+ }
161
180
 
162
181
  // Words that end the noun phrase: a relative clause or a trailing modifier
163
182
  // carries detail, not the category ("a place where ships shelter" → place).
@@ -178,18 +197,48 @@ const ISA_ARTICLES = new Set(["a", "an", "the"]);
178
197
  // The classifier heads an of-chain reads THROUGH to the real class ("a kind
179
198
  // of dog" → dog). Any other head before "of" keeps the outer phrase: "a body
180
199
  // of ice" states composition, and "a game of skill" is a game — neither
181
- // makes the of-object the class.
200
+ // makes the of-object the class. Partitive, collective and measure heads
201
+ // ("a group of animals", "a piece of matter", "an accumulation of vegetation")
202
+ // read through the same way — the of-object names the class, the head names
203
+ // only how much of it or how it is packaged. "member" and "body" are the
204
+ // deliberate exceptions: "a member of the cat family" and "a body of water"
205
+ // name membership or composition, not what the thing is, so they stay off
206
+ // this set and fall through to ISA_GENERIC_HEADS' null instead.
182
207
  const ISA_OF_READ_THROUGH = new Set([
183
208
  "type", "kind", "sort", "form", "class", "variety", "species", "breed", "genus",
209
+ "group", "part", "parts", "piece", "bunch", "bit", "name", "set", "way", "unit", "family",
210
+ "ability", "color", "series", "mammal", "practice", "list", "amount", "mass",
211
+ "reworking", "blockage", "goddess", "aura", "development", "consisting",
212
+ "announcement", "messengers", "subset", "carrying", "photograph", "adding",
213
+ "use", "science", "songbird", "symptom", "accumulation", "number", "suborder",
214
+ "falling", "management", "evaluation", "superorder", "activity", "interlacing",
215
+ "introduction",
184
216
  ]);
217
+ // A quantifier naming a share of a set ("either of two species", "one of
218
+ // several kinds") is never itself the class — it has no noun reading at all
219
+ // — so the of-chain reads through it the same way it reads through a
220
+ // classifier head, on to whatever the rest of the chain names.
221
+ const ISA_OF_QUANTIFIER = new Set(["either", "one", "each", "both", "any"]);
185
222
 
186
223
  /** The isa lemma of a lead's first sentence, or null. The copula must sit in
187
- * the first sentence; an of-chain resolves to its final noun ("a kind of
188
- * dog" → dog); a bare-plural predicate counts only when the head is an
189
- * inflected plural the lexicon folds ("are animals that…" → animal, but
190
- * "is light" stays null); a generic classifier head is no isa at all. */
224
+ * the first sentence; a parenthetical aside is skipped, not read as part of
225
+ * the class; an of-chain resolves to its final noun ("a kind of dog" →
226
+ * dog; "either of two species (…) of rodents" → rodent); a bare-plural
227
+ * predicate counts only when the head is an inflected plural the lexicon
228
+ * folds ("are animals that…" → animal, but "is light" stays null); a
229
+ * generic classifier head is no isa at all. */
230
+ // A classifier/quantifier/generic-head word can appear inflected ("kinds of
231
+ // dog", "sets of threads") — the sets above hold singular forms, so every
232
+ // membership check folds the word through the lexicon to its lemma first.
233
+ // An unresolvable word (the quantifiers are not nouns at all) falls back to
234
+ // itself unchanged, so the raw-string check still applies.
235
+ function classifierKeyFor(word, lexicon) {
236
+ const entry = lookupNoun(lexicon, word);
237
+ return entry ? normFactTerm(entry.lemma) : word;
238
+ }
239
+
191
240
  export function isaOf(plain, lexicon) {
192
- const m = String(plain ?? "").match(ISA_RE);
241
+ const m = withoutParentheticals(String(plain ?? "")).match(ISA_RE);
193
242
  if (!m) return null;
194
243
  const bare = !m[1];
195
244
  const window = [];
@@ -201,14 +250,17 @@ export function isaOf(plain, lexicon) {
201
250
  let headWords = window;
202
251
  for (let ofIdx = headWords.indexOf("of"); ofIdx > 0; ofIdx = headWords.indexOf("of")) {
203
252
  const outer = headWords[ofIdx - 1]?.split("-").pop();
204
- if (outer && ISA_OF_READ_THROUGH.has(outer)) { headWords = headWords.slice(ofIdx + 1); continue; }
253
+ const outerKey = outer && classifierKeyFor(outer, lexicon);
254
+ if (outerKey && (ISA_OF_READ_THROUGH.has(outerKey) || ISA_OF_QUANTIFIER.has(outerKey))) { headWords = headWords.slice(ofIdx + 1); continue; }
205
255
  headWords = headWords.slice(0, ofIdx);
206
256
  break;
207
257
  }
208
258
  while (headWords.length && ISA_ARTICLES.has(headWords[0])) headWords = headWords.slice(1);
209
259
  if (!headWords.length) return null;
210
260
  const headToken = headWords[headWords.length - 1].split("-").pop();
211
- if (!headToken || ISA_GENERIC_HEADS.has(headToken)) return null;
261
+ if (!headToken) return null;
262
+ const headKey = classifierKeyFor(headToken, lexicon);
263
+ if (ISA_GENERIC_HEADS.has(headToken) || ISA_GENERIC_HEADS.has(headKey)) return null;
212
264
  const entry = lookupNoun(lexicon, headToken);
213
265
  if (!entry) return null;
214
266
  const lemma = normFactTerm(entry.lemma);
@@ -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
  }
@@ -25,11 +25,12 @@ import { SESSIONS_DIR_REL, appendSessionToGraph } from "./sessions.mjs";
25
25
  import { uuidv7 } from "../adapters/uuid.mjs";
26
26
  import { createTelemetry } from "./telemetry.mjs";
27
27
  import * as defaultSource from "../adapters/source.mjs";
28
- import { resolveExtensions, mergedLexiconExtra } from "./extensions.mjs";
29
- import { runTurn, hasSeededVocabulary, vocabExampleHint } from "./chat.mjs";
28
+ import { resolveExtensions, mergedLexiconExtra, mergedLaneVocab, defaultCodeLaneVocab, activeDomainPacks, defaultCodeDomainPacks } from "./extensions.mjs";
29
+ import { runTurn, hasSeededVocabulary, vocabExampleHint, codeDomainActive as codeDomainActiveOf } from "./chat.mjs";
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.
@@ -281,6 +293,36 @@ export async function createSession({
281
293
  try { ({ entries: extEntries, biasByBundle } = await resolveExtensions(repo)); }
282
294
  catch { extEntries = null; biasByBundle = {}; }
283
295
 
296
+ // The code-domain predicate (chat.mjs): a loaded graph with modules, or a
297
+ // code-domain bundle active in this repo's tmct.toml/persona (the `code`
298
+ // pack, or a direct `seon` activation predating it) — computed ONCE per
299
+ // session and threaded into every turn, so every code-vocabulary surface
300
+ // (counts, misses, banner, greeting, orientation, help) reads the same
301
+ // answer all session long.
302
+ const codePackActive = Boolean(extEntries?.get("seon")?.active || extEntries?.get("code")?.active);
303
+ const domainActive = codeDomainActiveOf({ graph, seonActive: codePackActive });
304
+
305
+ // This session's merged lane vocabulary (count nouns/class labels/help rows/
306
+ // the miss-recovery pointer) — extensions.mjs's mergedLaneVocab over every
307
+ // active pack. A real code graph with no pack formally active (a fixture, a
308
+ // provider-supplied graph, a repo indexed before this pack existed) still
309
+ // needs the code vocabulary to render today's answers, so it falls back to
310
+ // the shipped code pack's own vocabulary — the same "a real graph is
311
+ // enough" rule domainActive itself applies, just above. Empty when the
312
+ // domain is inactive: a bare session imports nothing and carries none of it.
313
+ let laneVocab = extEntries
314
+ ? await mergedLaneVocab(extEntries, biasByBundle)
315
+ : { countNouns: {}, classLabels: {}, helpRows: [], missRecoveryPointer: "" };
316
+ if (domainActive && !Object.keys(laneVocab.countNouns).length) {
317
+ laneVocab = await defaultCodeLaneVocab();
318
+ }
319
+
320
+ // Which packs supplied that vocabulary, read from each pack's own
321
+ // declaration — what /capabilities names as this session's loaded domains.
322
+ // Same "a real graph is enough" fallback as the vocabulary itself.
323
+ let domainPacks = extEntries ? await activeDomainPacks(extEntries, biasByBundle) : [];
324
+ if (domainActive && !domainPacks.length) domainPacks = await defaultCodeDomainPacks();
325
+
284
326
  // Load this handle's lexicon once, MERGED with any active lexicon/pack
285
327
  // extension entries (ascending-bias merge order so a higher-bias bundle's
286
328
  // same-lemma entry wins deterministically). Failure-tolerated — a broken
@@ -403,8 +445,13 @@ export async function createSession({
403
445
  const bannerLines = [
404
446
  noCodeGraph
405
447
  // No code graph: honest, orienting messaging — never an error before the prompt.
406
- ? `tmct chat — ${readRepo} — no code graph loaded — ${empty ? "starting empty" : "graph has no code entities"}; ` +
407
- `${whereItGoes}`
448
+ // domainActive here means the seon bundle is active without an index yet
449
+ // (e.g. --with-persona code, before `tmct index` runs) — same code-graph
450
+ // framing as today. With no code domain at all, naming "no code graph" would
451
+ // itself be a code-domain leak, so a bare install gets a neutral line instead.
452
+ ? (domainActive
453
+ ? `tmct chat — ${readRepo} — no code graph loaded — ${empty ? "starting empty" : "graph has no code entities"}; ${whereItGoes}`
454
+ : `tmct chat — ${readRepo} — ${whereItGoes}`)
408
455
  : `tmct chat — ${readRepo} — ${moduleCount} module(s) — `
409
456
  + (discardsWrites ? `${whereItGoes}` : `log ${logFile}`),
410
457
  // the honest seed line appears ONLY on the run that actually seeded — the count
@@ -415,8 +462,14 @@ export async function createSession({
415
462
  // example), and at what IS answerable now — `vocabHint` is only ever a term
416
463
  // confirmed to resolve in THIS session's actual seed state (see vocabExampleHint),
417
464
  // never a hardcoded example that might not have been seeded. tmct can index a
418
- // repo itself (`tmct index`) or read a graph any other producer wrote.
419
- ...(noCodeGraph ? [`for code structure, index this repo with \`tmct index\`, or point me at a .tmct/graph.json with --repo <path> (or try \`npm run example:mini\`). ${vocabHint}`] : []),
465
+ // repo itself (`tmct index`) or read a graph any other producer wrote. With no
466
+ // code domain active, the code-structure pointer has nothing to point at, so
467
+ // this line carries just the teach/vocabulary hint. The pointer text itself
468
+ // is the active code pack's own miss-recovery clause (laneVocab, above) —
469
+ // never a chat-session.mjs literal, so a host pack can carry its own.
470
+ ...(noCodeGraph ? [domainActive
471
+ ? `${laneVocab.missRecoveryPointer} ${vocabHint}`
472
+ : vocabHint] : []),
420
473
  "pass --repo <path> to target a different repo",
421
474
  "ask a question, or /help for commands (/stats for an overview) — /exit to leave",
422
475
  ];
@@ -452,6 +505,7 @@ export async function createSession({
452
505
  get turns() { return turns; },
453
506
  get narrate() { return narrateOn; },
454
507
  get liveReference() { return liveReferenceOn; },
508
+ get researchSource() { return researchSourceOn; },
455
509
  promptFor: () => promptFor(focus),
456
510
 
457
511
  /** One dispatched turn through the FULL sink sequencing (writeLog → writeSidecar
@@ -462,7 +516,7 @@ export async function createSession({
462
516
  async turn(line) {
463
517
  let result;
464
518
  try {
465
- 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 });
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 });
466
520
  } catch (e) {
467
521
  const ts = new Date().toISOString();
468
522
  const message = e instanceof Error ? e.message : String(e);
@@ -473,7 +527,7 @@ export async function createSession({
473
527
  turns += 1;
474
528
  return { answer: `Something went wrong answering that (${message}). Try rephrasing, or /help.`, end: false, prompt: promptFor(focus) };
475
529
  }
476
- 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;
477
531
  // "noted — remembered" reports a durable write. In a session that keeps
478
532
  // nothing it is the last word on a fact that dies with the process, so
479
533
  // say where the fact actually went.
@@ -493,6 +547,7 @@ export async function createSession({
493
547
  // append a cited read-out under every grounded vocabulary answer), or
494
548
  // "always" (widen that to every grounded answer).
495
549
  if (typeof nextLiveReference === "boolean" || nextLiveReference === "supplement" || nextLiveReference === "always") liveReferenceOn = nextLiveReference;
550
+ if (typeof nextResearchSource === "string") researchSourceOn = nextResearchSource;
496
551
  await writeLog(sessionLogTurnMarkdown({ startedAt: record.ts, turnNumber: turns + 1, query: line, answer }));
497
552
  await writeSidecar(record);
498
553
  turnRecords.push(record);
@@ -548,6 +603,7 @@ export async function runChat({
548
603
  ephemeral = false,
549
604
  narrate = false,
550
605
  liveReference = false,
606
+ researchSource = null,
551
607
  memoryBackend = null,
552
608
  toolNamePrefix,
553
609
  actingSubject,
@@ -555,7 +611,7 @@ export async function runChat({
555
611
  // createSession's first-run seed (~2-3s) produces ZERO output until it fully
556
612
  // resolves, which otherwise reads as `npm run chat` hanging with total silence.
557
613
  output.write("tmct — starting…\n");
558
- 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 });
559
615
 
560
616
  const dim = (s) => (env.NO_COLOR || !output.isTTY ? s : `\x1b[2m${s}\x1b[0m`);
561
617
  for (const line of session.bannerLines) output.write(dim(line) + "\n");