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

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 (36) hide show
  1. package/README.md +74 -11
  2. package/bin/tmct.mjs +81 -0
  3. package/package.json +6 -1
  4. package/src/adapters/corpus/courtesy.mjs +91 -28
  5. package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
  6. package/src/adapters/corpus/news-sources.mjs +436 -0
  7. package/src/adapters/corpus/research-source.mjs +16 -3
  8. package/src/adapters/corpus/wiktionary-live.mjs +158 -0
  9. package/src/adapters/news-store.mjs +87 -0
  10. package/src/adapters/toml-config.mjs +18 -0
  11. package/src/domain/ask.mjs +19 -6
  12. package/src/domain/choice-question.mjs +275 -0
  13. package/src/domain/cli-verbs.mjs +20 -0
  14. package/src/domain/codegraph.mjs +8 -1
  15. package/src/domain/dialogue-acts.mjs +1 -0
  16. package/src/domain/el-classify.mjs +569 -0
  17. package/src/domain/fact-phrase.mjs +70 -0
  18. package/src/domain/feed-normalize.mjs +224 -0
  19. package/src/domain/grammar/ace.mjs +223 -7
  20. package/src/domain/grammar/lexicon-core.json +2 -0
  21. package/src/domain/memory/trust.mjs +15 -0
  22. package/src/domain/news-feed.mjs +219 -0
  23. package/src/domain/reasoning-config.mjs +56 -0
  24. package/src/domain/sprite-animation.mjs +20 -2
  25. package/src/domain/tableau.mjs +1225 -0
  26. package/src/domain/term-ledger.mjs +118 -0
  27. package/src/services/chat.mjs +523 -20
  28. package/src/services/extract-facts.mjs +91 -1
  29. package/src/services/index.mjs +12 -0
  30. package/src/services/init.mjs +33 -0
  31. package/src/services/news-viz.mjs +489 -0
  32. package/src/services/news.mjs +918 -0
  33. package/src/services/sprite-catalog-viz.mjs +148 -78
  34. package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
  35. package/src/surfaces/web/news-browser-entry.mjs +384 -0
  36. package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
@@ -0,0 +1,87 @@
1
+ // news-store.mjs — persists the news capability's whole runtime state (feed
2
+ // snapshots, the fact-ungrounded-term ledger, per-source health, the request
3
+ // log, cycle metrics) as one JSON file under the repo's .tmct/
4
+ // (news-state.json, beside the memory dir and research-queue.json), mirroring
5
+ // research-queue-store.mjs exactly: a Node CLI session's poll history and
6
+ // enrichment ledger survive a restart, while a browser session persists the
7
+ // same state object inside its own IndexedDB snapshot instead.
8
+ //
9
+ // The seam is the memoryDir backend token runTurn already carries:
10
+ // - a repo-path string (Backend A): the state file is <repo>/.tmct/…;
11
+ // - a sqlite handle carrying dbPath (Backend C, the CLI default): the state
12
+ // file is the dbPath's .tmct/ sibling;
13
+ // - an in-memory handle (Backend B) or null (the browser session): no
14
+ // path, so persistence is a silent no-op.
15
+ //
16
+ // Fail closed: an absent, unreadable, or invalid file reads as "no state" —
17
+ // never a crash, never a fabricated one.
18
+
19
+ import { readFile, writeFile, mkdir, unlink } from "node:fs/promises";
20
+ import { dirname, join } from "node:path";
21
+
22
+ const STATE_FILE = "news-state.json";
23
+
24
+ // requestLog is newest-first (PLAN_NEWS_FEED.md section 9.4); capping here,
25
+ // at the point of persistence, keeps the file bounded regardless of how much
26
+ // a caller appended to it in memory during one run.
27
+ const REQUEST_LOG_CAP = 200;
28
+
29
+ /** The on-disk path for `memoryDir`'s news state file, or null when this
30
+ * session has nowhere to persist — the same resolution research-queue-store
31
+ * uses for research-queue.json. */
32
+ function newsStatePath(memoryDir) {
33
+ if (!memoryDir) return null;
34
+ if (typeof memoryDir === "string") return join(memoryDir, ".tmct", STATE_FILE);
35
+ if (typeof memoryDir.dbPath === "string") return join(dirname(dirname(memoryDir.dbPath)), STATE_FILE);
36
+ return null;
37
+ }
38
+
39
+ /** A parsed value is a resumable news state only if it carries the five
40
+ * lists/objects every reader and writer below expects. Anything else fails
41
+ * closed to null. */
42
+ function isNewsState(state) {
43
+ return !!state && typeof state === "object"
44
+ && Array.isArray(state.items)
45
+ && !!state.ledger && typeof state.ledger === "object" && Array.isArray(state.ledger.terms)
46
+ && Array.isArray(state.health)
47
+ && Array.isArray(state.requestLog)
48
+ && Array.isArray(state.metrics);
49
+ }
50
+
51
+ /** The persisted news state for `memoryDir`, or null when none is stored,
52
+ * the store cannot persist, or the file is missing/corrupt/ill-shaped. */
53
+ export async function loadNewsState(memoryDir) {
54
+ const path = newsStatePath(memoryDir);
55
+ if (!path) return null;
56
+ let raw;
57
+ try { raw = await readFile(path, "utf8"); } catch { return null; }
58
+ let state;
59
+ try { state = JSON.parse(raw); } catch { return null; }
60
+ return isNewsState(state) ? state : null;
61
+ }
62
+
63
+ /** Write-through the current state, capping requestLog to its newest
64
+ * REQUEST_LOG_CAP rows on the way out. A null/absent state clears the file.
65
+ * A store with no path is a no-op. A write that fails leaves the in-memory
66
+ * state standing. */
67
+ export async function saveNewsState(memoryDir, state) {
68
+ const path = newsStatePath(memoryDir);
69
+ if (!path) return;
70
+ if (!state) { await clearNewsState(memoryDir); return; }
71
+ const capped = {
72
+ ...state,
73
+ requestLog: Array.isArray(state.requestLog) ? state.requestLog.slice(0, REQUEST_LOG_CAP) : [],
74
+ };
75
+ try {
76
+ await mkdir(dirname(path), { recursive: true });
77
+ await writeFile(path, JSON.stringify(capped), "utf8");
78
+ } catch { /* a state we can't persist stays in memory for this session */ }
79
+ }
80
+
81
+ /** Delete the persisted news state file (idempotent). A store with no path
82
+ * is a no-op. */
83
+ export async function clearNewsState(memoryDir) {
84
+ const path = newsStatePath(memoryDir);
85
+ if (!path) return;
86
+ try { await unlink(path); } catch { /* already gone */ }
87
+ }
@@ -142,6 +142,15 @@ export async function normalizeConfig(raw, { configDir } = {}) {
142
142
  // resolveResearchConfig's job.
143
143
  if (src.research !== undefined) cfg.research = src.research;
144
144
 
145
+ // News-capability knobs (src/services/news.mjs): sparse PASS-THROUGH, same
146
+ // discipline as [research] — the raw `[news]` table (sources / kb_sources /
147
+ // extra_sources / poll_minutes / enrich_minutes / enrich_terms_per_cycle /
148
+ // negative_cache_ttl_hours / syllogisms_per_ingest / item_cap /
149
+ // news_fact_cap / feed_top / window_hours / min_interval_ms, snake_case)
150
+ // rides through unmodified; clamping and default-filling is
151
+ // resolveNewsConfig's job.
152
+ if (src.news !== undefined) cfg.news = src.news;
153
+
145
154
  // Discourse-record knob (src/domain/discourse.mjs): sparse PASS-THROUGH,
146
155
  // same discipline — the raw `[discourse]` table (max_referents) rides
147
156
  // through; default-filling is resolveDiscourseConfig's job.
@@ -152,6 +161,15 @@ export async function normalizeConfig(raw, { configDir } = {}) {
152
161
  // is resolveRecognitionConfig's job.
153
162
  if (src.recognition !== undefined) cfg.recognition = src.recognition;
154
163
 
164
+ // Reasoning-lane knobs (src/domain/reasoning-config.mjs): sparse
165
+ // PASS-THROUGH, same discipline as [games.*]/[research]/[recognition] —
166
+ // the raw `[reasoning]` table (syllogise_budget/syllogise_depth/
167
+ // classify_budget/classify_rounds/max_environments/prove_steps/
168
+ // prove_branches/prove_nodes, snake_case) rides through unmodified;
169
+ // mapping onto the internal camelCase shape and default-filling is
170
+ // resolveReasoningConfig's job.
171
+ if (src.reasoning !== undefined) cfg.reasoning = src.reasoning;
172
+
155
173
  const idx = src.index || {};
156
174
  const index = {};
157
175
  if (idx.languages !== undefined) index.languages = idx.languages;
@@ -3040,17 +3040,17 @@ function modifierIsWired(shape, kind, entityType) {
3040
3040
  }
3041
3041
  const TRANSITIVE_MAX_DEPTH = 8; // matches renderImpact's own default (codegraph.mjs)
3042
3042
 
3043
- /** A graph's own vocabulary nodes carry their definition text under this
3044
- * property. A code entity's docstring rides `seon:hasDoc` and shares the
3045
- * plain `doc` key, so the PROP is what separates the two. */
3046
- const SCHEMA_DOC_PROP = "mgx:schemaDoc";
3043
+ /** A graph's own vocabulary nodes carry their definition text under one of
3044
+ * these properties. A code entity's docstring rides `seon:hasDoc` and shares
3045
+ * the plain `doc` key, so this set is what separates the two. */
3046
+ const SCHEMA_DOC_PROPS = new Set(["mgx:schemaDoc", "mgx:lexiconDoc"]);
3047
3047
 
3048
3048
  /** The definition text an individual publishes about itself, or null. Reading
3049
3049
  * the meta lane off this attribute rather than a fixed class-name list lets a
3050
3050
  * graph declare its own documented individual class (a glossary term, say)
3051
3051
  * and have "what is X" answer for it like any other vocabulary node. */
3052
3052
  function schemaDefinitionOf(ind) {
3053
- return (ind?.attributes || []).find((a) => a.prop === SCHEMA_DOC_PROP)?.value || null;
3053
+ return (ind?.attributes || []).find((a) => SCHEMA_DOC_PROPS.has(a.prop))?.value || null;
3054
3054
  }
3055
3055
 
3056
3056
  function schemaKindWordFor(cls) {
@@ -4055,7 +4055,20 @@ function renderCore(parsed, result, graph) {
4055
4055
  miss: true, ambiguous: false,
4056
4056
  };
4057
4057
  }
4058
- const entityWord = nounFor(parsed.entityType || "Module", 2);
4058
+ // No entity type was parsed (a bare "what denotes X" names no grain), so the
4059
+ // word for what was searched comes off the kind's own object classes in the
4060
+ // loaded graph rather than defaulting to "modules" — a kind like `denotes`
4061
+ // never targets a module at all, and saying so would misname what was searched.
4062
+ // When the graph holds no edges of this kind at all, there is nothing to
4063
+ // read a class from, and "Module" stays the plain default.
4064
+ const entityWord = parsed.entityType
4065
+ ? nounFor(parsed.entityType, 2)
4066
+ : (() => {
4067
+ const kindClasses = [...classesForKinds(graph, kindsFor(parsed.kind))];
4068
+ if (kindClasses.length === 1) return nounFor(kindClasses[0], 2);
4069
+ if (kindClasses.length > 1) return kindClasses.map((c) => nounFor(c, 2)).join(" or ");
4070
+ return nounFor("Module", 2);
4071
+ })();
4059
4072
  // Name the resolved antecedent, not the raw pronoun: "who touched it" that
4060
4073
  // bound "it" to fnAlpha must say so, or the receipt reads as though nothing
4061
4074
  // was resolved at all. Scoped to a context pronoun so a typed term keeps the
@@ -0,0 +1,275 @@
1
+ // choice-question.mjs — splits a closed multiple-choice question into its
2
+ // stem and its options. Pure, closed-set, no graph and no store: the same
3
+ // house style as ask-vocab.mjs's phrasing tables, not a general parser.
4
+ //
5
+ // Two shapes. Inline ("is a whale a fish or a mammal") is recognized by a
6
+ // small set of hand-authored sentence templates, tried most-specific-first
7
+ // so a relational source clause ("the capital of france") never gets read
8
+ // as a one-word source with the wrong option boundary. Enumerated ("A) ...
9
+ // B) ...") is recognized structurally: either explicit A/B/C labels in
10
+ // strict sequence, or — when no labels are found — a stem line followed by
11
+ // two or more bare option lines.
12
+ //
13
+ // The write-boundary brief this module exists for: "every pet is a cat or
14
+ // a dog" must keep teaching, never be swallowed as a choice question. That
15
+ // case (and the rest of the negative set) is handled by requiring an
16
+ // interrogative lead — reusing leadsInterrogative/QUESTION_LEAD_RE rather
17
+ // than inventing a second notion of "looks like a question" — plus a guard
18
+ // that declines whenever a candidate option itself reads as a second,
19
+ // embedded question ("is it a bird or is it a plane").
20
+ import { leadsInterrogative, QUESTION_LEAD_RE } from "./interpret/normalize.mjs";
21
+
22
+ /** The recognized shapes. Frozen so a caller can switch on the value
23
+ * without inventing its own string. */
24
+ export const CHOICE_SHAPES = Object.freeze({ inline: "inline", enumerated: "enumerated" });
25
+
26
+ /** Minimum and maximum alternatives a choice question may carry. Two is the
27
+ * smallest set that is a choice at all. Six is one above CommonsenseQA's
28
+ * five, which leaves the fixture room and still keeps the refusal list short
29
+ * enough to read in one line. A longer list is a set question, which the ask
30
+ * engine already answers, so the lane declines and falls through. */
31
+ export const CHOICE_MIN_OPTIONS = 2;
32
+ export const CHOICE_MAX_OPTIONS = 6;
33
+
34
+ const NEGATION_TAIL_WORDS = new Set(["not", "never", "no"]);
35
+ const PREP_WORDS = new Set(["in", "on", "at", "for", "with", "from", "of", "into", "onto"]);
36
+
37
+ const stripLeadingArticle = (phrase) => phrase.replace(/^(?:an?|the)\s+/i, "").trim();
38
+
39
+ function stripTrailingPreposition(phrase) {
40
+ const words = phrase.trim().split(/\s+/);
41
+ if (words.length > 1 && PREP_WORDS.has(words[words.length - 1].toLowerCase())) words.pop();
42
+ return words.join(" ");
43
+ }
44
+
45
+ function normalizeOptionText(text) {
46
+ return String(text).toLowerCase().replace(/[^\w\s'-]/g, "").replace(/\s+/g, " ").trim();
47
+ }
48
+
49
+ // ---- the "or"-list splitter — the machinery this module adds, cited in the
50
+ // design survey as absent everywhere else under src/domain/ ----
51
+
52
+ /** Splits an option-list tail ("a fish or a mammal", "paris, lyon or
53
+ * marseille") on its final standalone "or", then the comma-separated
54
+ * options ahead of it. Returns an ordered array of option text, or null
55
+ * when no standalone "or" is present at all — the signal a caller reads as
56
+ * "this was not an alternation". */
57
+ function splitOrList(text) {
58
+ const cleaned = String(text).replace(/[?.!]+\s*$/, "").trim();
59
+ const orRe = /\bor\b/gi;
60
+ let lastIndex = -1;
61
+ let lastLength = 0;
62
+ let match;
63
+ while ((match = orRe.exec(cleaned))) {
64
+ lastIndex = match.index;
65
+ lastLength = match[0].length;
66
+ }
67
+ if (lastIndex === -1) return null;
68
+ const before = cleaned.slice(0, lastIndex).trim().replace(/,\s*$/, "");
69
+ const last = cleaned.slice(lastIndex + lastLength).trim();
70
+ if (!before || !last) return null;
71
+ const earlier = before.split(",").map((s) => s.trim()).filter(Boolean);
72
+ return [...earlier, last];
73
+ }
74
+
75
+ // ---- shape A: natural inline phrasing ----
76
+ //
77
+ // Tried in this order deliberately: the comma-anchored and "of"-clause
78
+ // templates are more specific than the bare "is/are <source> <options>"
79
+ // template, which would otherwise shadow them (its source-clause capture is
80
+ // happy to stop after one word, so "is the capital of france ..." would
81
+ // mis-split into source "the capital" and a leading option "of france ...").
82
+
83
+ const INLINE_TEMPLATES = [
84
+ // "which is <source clause>, <option list>?" — the one inline shape with
85
+ // an explicit comma boundary between the source clause and its options.
86
+ {
87
+ re: /^which\s+is\s+((?:an?|the)\s+[a-z][\w'-]*(?:\s+[a-z][\w'-]*)?),\s*(.+?)[?.!]*$/i,
88
+ build: (m) => ({
89
+ stem: `which is ${m[1].trim()}?`,
90
+ optionsText: m[2],
91
+ sourceTerm: stripTrailingPreposition(stripLeadingArticle(m[1].trim())),
92
+ }),
93
+ },
94
+ // "does/do/did <source clause> <verb preposition> <option list>?" — the
95
+ // verb phrase is closed to a bare verb plus one of a curated preposition
96
+ // set, never a general parse of the predicate.
97
+ {
98
+ re: /^(does|do|did)\s+((?:an?|the)\s+[a-z][\w'-]*)\s+([a-z]+\s+(?:in|on|at|of|with|for|from))\s+(.+?)[?.!]*$/i,
99
+ build: (m) => ({
100
+ stem: `${m[1].toLowerCase()} ${m[2].trim()} ${m[3].trim()}?`,
101
+ optionsText: m[4],
102
+ sourceTerm: stripLeadingArticle(m[2].trim()),
103
+ }),
104
+ },
105
+ // "is <the X of Y> <option list>?" — a relational source clause with its
106
+ // own internal "of", so the option list needs no linking word to start.
107
+ {
108
+ re: /^is\s+(the\s+[a-z][\w'-]*\s+of\s+[a-z][\w'-]*)\s+(.+?)[?.!]*$/i,
109
+ build: (m) => ({
110
+ stem: `is ${m[1].trim()}?`,
111
+ optionsText: m[2],
112
+ sourceTerm: stripLeadingArticle(m[1].trim()),
113
+ }),
114
+ },
115
+ // "is/are/was/were <a/the source> <option list>?" — the bare-juxtaposition
116
+ // form, tried last because it is the most general "is"-lead shape.
117
+ {
118
+ re: /^(is|are|was|were)\s+((?:an?|the)\s+[a-z][\w'-]*)\s+(.+?)[?.!]*$/i,
119
+ build: (m) => ({
120
+ stem: `${m[1].toLowerCase()} ${m[2].trim()}?`,
121
+ optionsText: m[3],
122
+ sourceTerm: stripLeadingArticle(m[2].trim()),
123
+ }),
124
+ },
125
+ ];
126
+
127
+ /** Tries each inline template in order. Returns null when no template's
128
+ * sentence shape matches at all. When a template's shape matches but its
129
+ * option-list tail has no standalone "or" ("is a whale a fish?"), returns
130
+ * { stem, options: null, sourceTerm } — recognized shape, no alternation —
131
+ * so the caller can report that precisely rather than trying every other
132
+ * template in turn. */
133
+ function parseInline(text) {
134
+ for (const template of INLINE_TEMPLATES) {
135
+ const m = template.re.exec(text);
136
+ if (!m) continue;
137
+ const built = template.build(m);
138
+ const rawOptions = splitOrList(built.optionsText);
139
+ if (!rawOptions) return { stem: built.stem, options: null, sourceTerm: built.sourceTerm };
140
+ const options = rawOptions.map((t, i) => ({ label: String(i + 1), text: t }));
141
+ return { stem: built.stem, options, sourceTerm: built.sourceTerm };
142
+ }
143
+ return null;
144
+ }
145
+
146
+ // ---- shape B: enumerated options ----
147
+
148
+ // A label marker is "(A)", "A)", "A.", or "A:" — any letter, so a run past
149
+ // CHOICE_MAX_OPTIONS (an eight-option "A) ... H) ...") is still recognized
150
+ // as enumerated and declines on the option count, rather than the marker
151
+ // regex itself silently stopping short and truncating the list.
152
+ const LABEL_MARKER_RE = /\(([A-Za-z])\)|\b([A-Za-z])[.):]/g;
153
+
154
+ /** The longest run of label markers found in strict A, B, C, ... sequence.
155
+ * A marker that does not match the next expected letter is skipped rather
156
+ * than resetting the search, so one stray match elsewhere in the stem
157
+ * cannot break a real label sequence that follows it. */
158
+ function findAcceptedLabelSequence(text) {
159
+ const accepted = [];
160
+ let expected = 0;
161
+ LABEL_MARKER_RE.lastIndex = 0;
162
+ let m;
163
+ while ((m = LABEL_MARKER_RE.exec(text))) {
164
+ const letter = (m[1] || m[2]).toUpperCase();
165
+ if (letter === String.fromCharCode(65 + expected)) {
166
+ accepted.push({ letter, start: m.index, end: LABEL_MARKER_RE.lastIndex });
167
+ expected += 1;
168
+ }
169
+ }
170
+ return accepted;
171
+ }
172
+
173
+ // The one closed frame this module extracts a source term from directly:
174
+ // "where would you find/see/keep/put/store/place X ..." — the shape the
175
+ // rig's own enumerated stems take. Anything else yields "", which the
176
+ // contract states is a valid outcome, not a failure.
177
+ const PLACEMENT_VERB_RE = /\b(?:find|see|keep|put|store|place)\s+([a-z][\w'-]*)/i;
178
+
179
+ const extractStemSourceTerm = (stem) => PLACEMENT_VERB_RE.exec(stem)?.[1]?.toLowerCase() ?? "";
180
+
181
+ function parseLabelledEnumerated(text) {
182
+ const accepted = findAcceptedLabelSequence(text);
183
+ if (accepted.length < 1) return null;
184
+ const stem = text.slice(0, accepted[0].start).trim();
185
+ if (!stem) return null;
186
+ const options = accepted.map((marker, i) => {
187
+ const end = i + 1 < accepted.length ? accepted[i + 1].start : text.length;
188
+ return { label: marker.letter, text: text.slice(marker.end, end).trim() };
189
+ });
190
+ return { stem, options, sourceTerm: extractStemSourceTerm(stem) };
191
+ }
192
+
193
+ /** The unlabelled fallback: a stem line followed by two or more option
194
+ * lines, one per line, no markers at all. */
195
+ function parseBareNewlineEnumerated(text) {
196
+ const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
197
+ if (lines.length < 3) return null;
198
+ const [stem, ...optionLines] = lines;
199
+ const options = optionLines.map((line, i) => ({ label: String.fromCharCode(65 + i), text: line }));
200
+ return { stem, options, sourceTerm: extractStemSourceTerm(stem) };
201
+ }
202
+
203
+ const parseEnumerated = (text) => parseLabelledEnumerated(text) ?? parseBareNewlineEnumerated(text);
204
+
205
+ // ---- shared finalization ----
206
+
207
+ function finalize(shape, stem, rawOptions, sourceTerm) {
208
+ if (!rawOptions) return { result: null, reason: "no-alternation" };
209
+ const options = rawOptions.map((o) => ({
210
+ label: o.label,
211
+ text: o.text.trim(),
212
+ normalized: normalizeOptionText(o.text),
213
+ }));
214
+
215
+ if (options.some((o) => !o.text)) return { result: null, reason: "option-empty" };
216
+ // An option that itself opens like a question is a second, separate
217
+ // question riding along ("is it a bird or is it a plane"), not a real
218
+ // alternative — decline rather than misread the pair as one choice.
219
+ if (options.some((o) => QUESTION_LEAD_RE.test(o.text))) return { result: null, reason: "no-alternation" };
220
+ // "or not" is a negated tail on a polar question, not a second option.
221
+ if (options.some((o) => NEGATION_TAIL_WORDS.has(o.normalized))) return { result: null, reason: "no-alternation" };
222
+ if (options.length < CHOICE_MIN_OPTIONS) return { result: null, reason: "too-few-options" };
223
+ if (options.length > CHOICE_MAX_OPTIONS) return { result: null, reason: "too-many-options" };
224
+
225
+ const seen = new Set();
226
+ for (const o of options) {
227
+ if (seen.has(o.normalized)) return { result: null, reason: "duplicate-options" };
228
+ seen.add(o.normalized);
229
+ }
230
+
231
+ return { result: { shape, stem, options, sourceTerm }, reason: "" };
232
+ }
233
+
234
+ function coreParse(text) {
235
+ const trimmed = String(text ?? "").trim();
236
+ if (!trimmed || !leadsInterrogative(trimmed)) return { result: null, reason: "not-a-question" };
237
+
238
+ const enumerated = parseEnumerated(trimmed);
239
+ if (enumerated) return finalize(CHOICE_SHAPES.enumerated, enumerated.stem, enumerated.options, enumerated.sourceTerm);
240
+
241
+ const inline = parseInline(trimmed);
242
+ if (inline) return finalize(CHOICE_SHAPES.inline, inline.stem, inline.options, inline.sourceTerm);
243
+
244
+ return { result: null, reason: "no-alternation" };
245
+ }
246
+
247
+ /**
248
+ * Splits a closed multiple-choice question into its stem and its options.
249
+ * Returns null for anything that is not one, which is the fall-through
250
+ * signal every caller relies on.
251
+ *
252
+ * @param {string} text
253
+ * @returns {null | {
254
+ * shape: "inline" | "enumerated",
255
+ * stem: string,
256
+ * options: Array<{ label: string, text: string, normalized: string }>,
257
+ * sourceTerm: string,
258
+ * }}
259
+ */
260
+ export function splitChoiceQuestion(text) {
261
+ return coreParse(text).result;
262
+ }
263
+
264
+ /** True when `text` reads as a choice question. Sugar over splitChoiceQuestion
265
+ * for a recognizer that does not need the parts. */
266
+ export function isChoiceQuestion(text) {
267
+ return coreParse(text).result !== null;
268
+ }
269
+
270
+ /** The reason splitChoiceQuestion declined, for a trace note. One of:
271
+ * "not-a-question", "no-alternation", "too-few-options", "too-many-options",
272
+ * "duplicate-options", "option-empty". Returns "" when it did not decline. */
273
+ export function choiceDeclineReason(text) {
274
+ return coreParse(text).reason;
275
+ }
@@ -126,6 +126,26 @@ export const CLI_VERBS = [
126
126
  { flag: "[--config <path>]", prose: ["(the classical syllogism among them), writing bounded, low-trust,", "retractable entailed facts (never on the chat path)"] },
127
127
  ],
128
128
  },
129
+ {
130
+ mode: "classify",
131
+ errorLabel: "classify",
132
+ usage: "tmct classify [--repo <abs>]",
133
+ prose: ["EL classification (offline maintenance job): saturation-based TBox"],
134
+ flags: [
135
+ { flag: "[--budget <n>] [--rounds <n>]", prose: ["classification that reaches class expressions the graph never"] },
136
+ { flag: "[--config <path>]", prose: ["declared as nodes, writing bounded, low-trust, retractable", "entailed facts (never on the chat path)"] },
137
+ ],
138
+ },
139
+ {
140
+ mode: "news",
141
+ errorLabel: "news",
142
+ usage: "tmct news [poll|rank|enrich|sources] [--repo <abs>]",
143
+ prose: ["the news feed over this graph: a contemporary sources dashboard,"],
144
+ flags: [
145
+ { flag: "[--limit <n>]", prose: ["grounding-driven enrichment loop, and a ranked list of", "candidate facts waiting to be learned"] },
146
+ { flag: "[--config <path>]", prose: [] },
147
+ ],
148
+ },
129
149
  {
130
150
  mode: "viz",
131
151
  errorLabel: "viz",
@@ -119,6 +119,8 @@ export function relationKind(group) {
119
119
  if (/\b(touch|chang|modif)/.test(pred)) return "touches";
120
120
  if (/\bcontain/.test(pred)) return "contains";
121
121
  if (/\b(inherit|subclass|extend|specializ)/.test(pred)) return "inherits";
122
+ if (/denot/.test(pred)) return "denotes";
123
+ if (/\bserve/.test(pred)) return "serves";
122
124
  return null;
123
125
  }
124
126
 
@@ -386,6 +388,11 @@ export function impactClosure(graph, ind, { maxDepth = 8 } = {}) {
386
388
  if (!coveredBy.has(e.object)) coveredBy.set(e.object, []);
387
389
  coveredBy.get(e.object).push(e.subjectLabel || e.subject);
388
390
  }
391
+ } else if (kind === "serves") {
392
+ // serves runs subject-provides-object (a handler serves a route), the
393
+ // opposite of imports/calls' subject-depends-on-object — so the
394
+ // dependent here is the OBJECT, not the subject.
395
+ for (const e of g.edges) addDependent(e.subject, e.object, e.objectLabel || e.object, g.predicate);
389
396
  }
390
397
  }
391
398
 
@@ -435,7 +442,7 @@ export function renderImpact(graph, ind, { maxDepth = 8 } = {}) {
435
442
  });
436
443
  const truncatedStructural = graph.truncated.filter((t) => {
437
444
  const kind = relationKind({ predicate: t.predicate });
438
- return kind === "imports" || kind === "calls" || kind === "callsSymbol" || kind === "tests";
445
+ return kind === "imports" || kind === "calls" || kind === "callsSymbol" || kind === "tests" || kind === "serves";
439
446
  });
440
447
  if (truncatedStructural.length) {
441
448
  lines.push(
@@ -136,6 +136,7 @@ export const LANE_DIALOGUE_ACTS = Object.freeze({
136
136
  teach: "inform",
137
137
  "ask-set": "setQuestion",
138
138
  "ask-propositional": "propositionalQuestion",
139
+ "ask-choice": "choiceQuestion",
139
140
  goal: "request",
140
141
  imperative: "instruct",
141
142
  "honest-miss": "autoNegative",