@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
@@ -46,7 +46,7 @@ import { setConstructionBanks } from "../domain/interpret/strategies/constructio
46
46
  import { nlpAdapter } from "../adapters/ask-nlp.mjs";
47
47
  import { readConstructionFiles } from "../adapters/corpus/construction-banks.mjs";
48
48
  import { fuzzyMatchInSet, fuzzyBound } from "../domain/interpret/fuzzy.mjs";
49
- import { loadLexicon, lookupNoun, readsAsIndividualName } from "../domain/grammar/lexicon.mjs";
49
+ import { loadLexicon, lookupNoun, lookupVerb, lookupAdjective, lookupProperName, readsAsIndividualName } from "../domain/grammar/lexicon.mjs";
50
50
  import { pickPhrase } from "../domain/answer-variants.mjs";
51
51
  import {
52
52
  REFERENCE_PACK_NAME, cleanMissReferenceTerm, renderReferenceAnswer, referenceProvenanceTag,
@@ -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";
@@ -461,28 +464,11 @@ export function asBareCommand(line) {
461
464
  // header (individuals grouped by class, relation groups by predicate), not by
462
465
  // dispatching to the ask engine. Deterministic, fully in-ethos. ----
463
466
 
464
- /** singular+plural nouns a user might count → the individual `class` they map to. */
465
- const COUNT_NOUNS = {
466
- class: "Class", classes: "Class",
467
- function: "Function", functions: "Function", func: "Function", funcs: "Function",
468
- module: "Module", modules: "Module", file: "Module", files: "Module",
469
- package: "Package", packages: "Package",
470
- method: "Method", methods: "Method",
471
- attribute: "Attribute", attributes: "Attribute",
472
- variable: "GlobalVariable", variables: "GlobalVariable", global: "GlobalVariable", globals: "GlobalVariable",
473
- commit: "Commit", commits: "Commit",
474
- session: "Session", sessions: "Session",
475
- };
476
-
477
- /** class → [singular, plural] display noun, for echoing a count back in English. */
478
- const CLASS_LABELS = {
479
- Class: ["class", "classes"], Function: ["function", "functions"],
480
- Module: ["module", "modules"], Package: ["package", "packages"],
481
- Method: ["method", "methods"],
482
- Attribute: ["attribute", "attributes"], GlobalVariable: ["variable", "variables"],
483
- Commit: ["commit", "commits"], Session: ["session", "sessions"],
484
- };
485
- const classNoun = (cls, n) => { const [s, p] = CLASS_LABELS[cls] || [cls, `${cls}s`]; return n === 1 ? s : p; };
467
+ /** class → [singular, plural] display noun, for echoing a count back in English.
468
+ * `classLabels` comes from the active session's merged lane vocabulary (empty
469
+ * by default — see resolveLaneVocab/mergedLaneVocab, extensions.mjs); a
470
+ * session with no code pack active never falls back to a hardcoded table. */
471
+ const classNoun = (cls, n, classLabels) => { const [s, p] = classLabels[cls] || [cls, `${cls}s`]; return n === 1 ? s : p; };
486
472
 
487
473
  /** Count individuals of a class in the loaded graph (live, not the header field).
488
474
  * No individual is ever stored with class "Package" — packages are the
@@ -494,14 +480,29 @@ const countClass = (graph, cls) => (cls === "Package"
494
480
 
495
481
  /** Every kind the counter answers to, as a human list — what it can count once a
496
482
  * graph is loaded, as opposed to countableKinds, which is what THIS graph holds. */
497
- const COUNTABLE_KIND_WORDS = [...new Set(Object.values(COUNT_NOUNS))]
498
- .map((cls) => CLASS_LABELS[cls]?.[1] ?? `${cls}s`);
483
+ const countableKindWords = (countNouns, classLabels) => [...new Set(Object.values(countNouns))]
484
+ .map((cls) => classLabels[cls]?.[1] ?? `${cls}s`);
499
485
 
500
486
  /** The classes this graph can actually count, as a human list ("classes, functions, …"). */
501
- function countableKinds(graph) {
487
+ function countableKinds(graph, classLabels) {
502
488
  const present = new Set(graph.individuals.map((i) => i.class).filter(Boolean));
503
489
  if (present.has("Module")) present.add("Package");
504
- return Object.keys(CLASS_LABELS).filter((c) => present.has(c)).map((c) => CLASS_LABELS[c][1]);
490
+ return Object.keys(classLabels).filter((c) => present.has(c)).map((c) => classLabels[c][1]);
491
+ }
492
+
493
+ /** The shipped code pack's own count-noun table (extensions.mjs's
494
+ * defaultCodeLaneVocab, memoized), loaded unconditionally — the PRECEDENCE
495
+ * guard a handful of taught-fact lanes use to defer to the graph-count lanes
496
+ * for a word like "class"/"function" ("answerCount owns this noun, don't
497
+ * answer it as a taught fact instead"). Every caller of this guard already
498
+ * runs only once the code domain is active (either directly gated, or
499
+ * reached only after answerCount itself returned a real count), so reading
500
+ * the shipped default here — rather than threading the session's own merge
501
+ * through each one — reproduces today's precedence exactly, with the noun
502
+ * table itself no longer duplicated as a chat.mjs literal. */
503
+ async function codeCountNouns() {
504
+ const { defaultCodeLaneVocab } = await import("./extensions.mjs");
505
+ return (await defaultCodeLaneVocab()).countNouns;
505
506
  }
506
507
 
507
508
  /** A discourse-anaphoric count/list head — "how many [of] those/them/these",
@@ -599,9 +600,24 @@ const RESTRICTOR_VERB_RE = new RegExp(
599
600
  *
600
601
  * `uiContext` picks the empty-graph remedy: only a terminal session can run
601
602
  * the index/--repo commands, so a page names what it can actually offer
602
- * instead (see vocabExampleHint's own split). */
603
- export function answerCount(graph, query, { uiContext = "cli" } = {}) {
603
+ * instead (see vocabExampleHint's own split).
604
+ *
605
+ * `codeDomainActive` (the session-level predicate, see below) gates the
606
+ * whole lane: with no code domain active, this returns null unconditionally
607
+ * so a bare "how many classes are there" falls through to the taught-class
608
+ * count and the ordinary miss instead of a code-graph-flavored decline (or,
609
+ * worse, "0 classes." for a class nothing here actually holds). Omitted
610
+ * (null), it derives from the graph alone — every existing caller that
611
+ * passes a real code graph keeps its answer unchanged.
612
+ *
613
+ * `countNouns`/`classLabels` are this session's merged lane vocabulary
614
+ * (chat-session.mjs's resolveLaneVocab, threaded via ctx.laneVocab) — empty
615
+ * by default, so a caller that omits them alongside an inactive domain never
616
+ * sees code-graph vocabulary. */
617
+ export function answerCount(graph, query, { uiContext = "cli", codeDomainActive = null, countNouns = {}, classLabels = {} } = {}) {
604
618
  if (!graph) return null;
619
+ const domainActive = codeDomainActive ?? (moduleCountOf(graph) > 0);
620
+ if (!domainActive) return null;
605
621
  // ANAPHORIC counts ("how many of those are tested", "count them", "how many of
606
622
  // them") count the PREVIOUS answer's set, not a graph kind — decline so the turn
607
623
  // falls through to the ask engine's anaphora node (which threads `prev`). Without
@@ -615,14 +631,14 @@ export function answerCount(graph, query, { uiContext = "cli" } = {}) {
615
631
  const m = String(query).match(/\b(?:how many|number of|count(?:\s+the)?)\s+([a-z]+)\b/i);
616
632
  if (!m) return null;
617
633
  const noun = m[1].toLowerCase();
618
- const cls = COUNT_NOUNS[noun];
634
+ const cls = countNouns[noun];
619
635
  if (cls) {
620
636
  const tail = String(query).slice(m.index + m[0].length);
621
637
  if (RESTRICTOR_VERB_RE.test(tail)) return null;
622
638
  if (countTailIsUnhandledRestrictor(tail)) return null;
623
639
  }
624
640
  if (!cls) {
625
- const kinds = countableKinds(graph);
641
+ const kinds = countableKinds(graph, classLabels);
626
642
  // When no code graph is loaded, countableKinds(graph) is genuinely
627
643
  // empty — an honest, non-dangling message pointing at how to load one.
628
644
  if (!kinds.length) {
@@ -635,7 +651,7 @@ export function answerCount(graph, query, { uiContext = "cli" } = {}) {
635
651
  // promise that indexing would let it count moons. The REMEDY is about the
636
652
  // session, and a terminal can act on it, so it stays — worded as its own
637
653
  // fact rather than as the answer to what was asked.
638
- return `I can't count "${noun}" — I count the kinds a code graph holds: ${COUNTABLE_KIND_WORDS.join(", ")}. `
654
+ return `I can't count "${noun}" — I count the kinds a code graph holds: ${countableKindWords(countNouns, classLabels).join(", ")}. `
639
655
  + `This session has no code graph loaded either — index this repo with "tmct index", `
640
656
  + `point me at another with --repo, or run "npm run example:mini".`;
641
657
  }
@@ -643,15 +659,15 @@ export function answerCount(graph, query, { uiContext = "cli" } = {}) {
643
659
  `Try "how many classes are there".`;
644
660
  }
645
661
  const n = countClass(graph, cls);
646
- return `${n} ${classNoun(cls, n)}.`;
662
+ return `${n} ${classNoun(cls, n, classLabels)}.`;
647
663
  }
648
664
 
649
665
  /** singular+plural display forms for the edge-nominalized nouns answerEdgeCount
650
666
  * (below) actually answers — a small subset of EDGE_NOUN_TO_METRIC's keys, the
651
667
  * ones that read as a real countable noun ("3 callers.") rather than a
652
668
  * participle only natural in a superlative ("most USED", not "how many used").
653
- * A key with no entry here echoes the user's own word unchanged (safe default,
654
- * same fallback CLASS_LABELS/classNoun use above). */
669
+ * A key with no entry here echoes the user's own word unchanged (the same
670
+ * safe-default shape classNoun's own fallback uses above). */
655
671
  const EDGE_NOUN_LABELS = {
656
672
  test: ["test", "tests"], tests: ["test", "tests"],
657
673
  importers: ["importer", "importers"], dependents: ["dependent", "dependents"],
@@ -702,8 +718,8 @@ function extractEdgeCountEntity(tail, metric) {
702
718
 
703
719
  /** Bare "how many <edge-noun> <verb> <entity>" / "how many <edge-noun> does
704
720
  * <entity> have" — "how many tests cover X", "how many importers does X
705
- * have", "how many callers does X have". answerCount's own COUNT_NOUNS
706
- * table only maps a counted noun to a graph INDIVIDUAL CLASS (Module/Class/…);
721
+ * have", "how many callers does X have". answerCount's own count-noun table
722
+ * only maps a counted noun to a graph INDIVIDUAL CLASS (Module/Class/…);
707
723
  * an edge-nominalized noun like "tests"/"importers"/"callers" names an EDGE
708
724
  * KIND instead — ask-vocab.mjs's EDGE_NOUN_TO_METRIC, the SAME table the
709
725
  * superlative lane ("which module has the most tests") reads. This reuses
@@ -714,8 +730,8 @@ function extractEdgeCountEntity(tail, metric) {
714
730
  *
715
731
  * Checked BEFORE answerCount in runTurn so it gets first look; declines
716
732
  * (returns null, letting answerCount's existing message stand) whenever:
717
- * - the noun isn't edge-nominalized at all (a COUNT_NOUNS class, or truly
718
- * unknown), or
733
+ * - the noun isn't edge-nominalized at all (a real graph-countable class, or
734
+ * truly unknown), or
719
735
  * - no entity term could be extracted from the tail
720
736
  * (extractEdgeCountEntity), or
721
737
  * - the extracted term doesn't resolve to exactly one graph entity.
@@ -724,15 +740,23 @@ function extractEdgeCountEntity(tail, metric) {
724
740
  * named entity in the tail) declines here and keeps answerCount's existing
725
741
  * "I can't count 'tests'" honest miss — what a GLOBAL edge count would even
726
742
  * mean (every test edge in the graph? distinct test modules? distinct tested
727
- * modules?) is a genuine, undecided design question. */
728
- async function answerEdgeCount(graph, query) {
743
+ * modules?) is a genuine, undecided design question.
744
+ *
745
+ * `codeDomainActive`: same gate as answerCount's own — with no code domain
746
+ * active, this declines unconditionally rather than reading an edge kind off
747
+ * a graph nothing here actually indexed. `countNouns` is the session's merged
748
+ * lane vocabulary (see answerCount's own docblock) — the same table, so this
749
+ * lane defers to answerCount for exactly the nouns answerCount owns. */
750
+ async function answerEdgeCount(graph, query, { codeDomainActive = null, countNouns = {} } = {}) {
729
751
  if (!graph) return null;
752
+ const domainActive = codeDomainActive ?? (moduleCountOf(graph) > 0);
753
+ if (!domainActive) return null;
730
754
  const q = String(query);
731
755
  if (ANAPHORA_COUNT_RE.test(q) || IMPLICIT_ANAPHORA_COUNT_RE.test(q.trim())) return null;
732
756
  const m = q.match(/\b(?:how many|number of|count(?:\s+the)?)\s+([a-z]+)\b/i);
733
757
  if (!m) return null;
734
758
  const noun = m[1].toLowerCase();
735
- if (COUNT_NOUNS[noun]) return null; // a real graph class — answerCount owns it
759
+ if (countNouns[noun]) return null; // a real graph class — answerCount owns it
736
760
  const metric = EDGE_NOUN_TO_METRIC[noun];
737
761
  if (!metric) return null; // not edge-nominalized either — answerCount's "I can't count" stands
738
762
  const term = extractEdgeCountEntity(q.slice(m.index + m[0].length), metric);
@@ -758,7 +782,8 @@ async function countFromFacts(graph, memoryDir, query, biasByBundle = {}, cache
758
782
  const m = String(query).match(/\b(?:how many|number of|count(?:\s+the)?)\s+([a-z]+)\b/i);
759
783
  if (!m) return null;
760
784
  const asked = m[1].toLowerCase();
761
- if (COUNT_NOUNS[asked]) return null; // a real graph kind — answerCount owns it
785
+ const countNouns = await codeCountNouns();
786
+ if (countNouns[asked]) return null; // a real graph kind — answerCount owns it
762
787
  let normFactTerm;
763
788
  try { ({ normFactTerm } = await import("../adapters/memory/core.mjs")); } catch { return null; }
764
789
  const objVariants = factTermVariants(normFactTerm, asked);
@@ -768,7 +793,7 @@ async function countFromFacts(graph, memoryDir, query, biasByBundle = {}, cache
768
793
  // countable graph class (rankByBiasThenTrust: bias-tied/unconfigured degrades
769
794
  // to the same trust-desc scan this always ran).
770
795
  for (const f of rankByBiasThenTrust(isa, biasByBundle)) {
771
- const cls = COUNT_NOUNS[String(f.subject).toLowerCase()];
796
+ const cls = countNouns[String(f.subject).toLowerCase()];
772
797
  if (cls) { const n = countClass(graph, cls); return `${n} ${asked}.`; }
773
798
  }
774
799
  return null;
@@ -778,7 +803,7 @@ async function countFromFacts(graph, memoryDir, query, biasByBundle = {}, cache
778
803
  // few"/"every"), NEVER real cardinality counting. Dispatched ahead of
779
804
  // answerCount in runTurn (else its noun-scan regex would short-circuit to an
780
805
  // "I can't count 'Xs'" miss first). Claims authority only when the subject
781
- // isn't a real graph-countable class (COUNT_NOUNS) AND tmct has some
806
+ // isn't a real graph-countable class (codeCountNouns) AND tmct has some
782
807
  // isa-family fact about it — otherwise falls through to answerCount untouched.
783
808
  const HOW_MANY_ARE_RE = /^how\s+many\s+([\w-]+)\s+(?:are|is)\s+(.+?)[?.!\s]*$/i;
784
809
  async function answerQuantifierRecall(memoryDir, query, biasByBundle = {}, cache = null) {
@@ -786,7 +811,7 @@ async function answerQuantifierRecall(memoryDir, query, biasByBundle = {}, cache
786
811
  const m = String(query).trim().match(HOW_MANY_ARE_RE);
787
812
  if (!m) return null;
788
813
  const asked = m[1].toLowerCase();
789
- if (COUNT_NOUNS[asked]) return null; // a real graph-countable class — answerCount owns it
814
+ if ((await codeCountNouns())[asked]) return null; // a real graph-countable class — answerCount owns it
790
815
  let normFactTerm;
791
816
  try { ({ normFactTerm } = await import("../adapters/memory/core.mjs")); } catch { return null; }
792
817
  const subjVariants = factTermVariants(normFactTerm, asked);
@@ -1011,7 +1036,7 @@ function taughtMembersUnder(isa, children, variants, biasByBundle) {
1011
1036
  async function longestTaughtClassInRun(memoryDir, nounRun, trailing, biasByBundle, cache) {
1012
1037
  const words = String(nounRun || "").trim().split(/\s+/).filter(Boolean);
1013
1038
  if (!words.length) return null;
1014
- if (COUNT_NOUNS[words[0].toLowerCase()]) return null; // a real graph-countable class — the code lanes own it
1039
+ if ((await codeCountNouns())[words[0].toLowerCase()]) return null; // a real graph-countable class — the code lanes own it
1015
1040
  let normFactTerm;
1016
1041
  try { ({ normFactTerm } = await import("../adapters/memory/core.mjs")); } catch { return null; }
1017
1042
  const rows = await factRows(memoryDir, cache);
@@ -1065,7 +1090,8 @@ async function answerTaughtClassCount(memoryDir, query, biasByBundle = {}, cache
1065
1090
  // one class-level fact. Only a DIRECT member triggers the deferral: an
1066
1091
  // inherited member reached through a taught subclass is still a genuine
1067
1092
  // count of this class's membership.
1068
- if (hit.directMembers.some((f) => COUNT_NOUNS[String(f.subject).toLowerCase()])) return null;
1093
+ const countNouns = await codeCountNouns();
1094
+ if (hit.directMembers.some((f) => countNouns[String(f.subject).toLowerCase()])) return null;
1069
1095
  const n = new Set(hit.members.map((f) => String(f.subject).toLowerCase())).size;
1070
1096
  const noun = n === 1 ? hit.asked.replace(/s$/, "") : hit.asked;
1071
1097
  // Sense reporting: cluster the classes the members were found under,
@@ -1880,12 +1906,21 @@ const T_GREETING_EMPTY = "conversational-greeting-empty";
1880
1906
  const T_GREETING_EMPTY_BROWSER = "conversational-greeting-empty-browser";
1881
1907
  const T_ORIENTATION_EMPTY = "orientation-empty";
1882
1908
  const T_ORIENTATION_EMPTY_BROWSER = "orientation-empty-browser";
1883
- /** IDENTITY answers — self-description and the "no LLM" clarification. Neither
1884
- * varies with graph state (empty vs. populated); identity-self DOES vary with
1885
- * uiContext (its `--repo <path>` clause is CLI-only), so it alone carries a
1886
- * `_BROWSER` twin. */
1909
+ /** No-code-domain siblings of the two CLI ids just above, read only when
1910
+ * codeDomainActive is false: the browser twins already name no code
1911
+ * vocabulary (a page never had a `--repo`/`tmct index` remedy to offer), so
1912
+ * they serve both domain states unchanged — only the CLI wording needed a
1913
+ * second, domain-gated version. */
1914
+ const T_GREETING_EMPTY_NEUTRAL = "conversational-greeting-empty-neutral";
1915
+ const T_ORIENTATION_EMPTY_NEUTRAL = "orientation-empty-neutral";
1916
+ /** IDENTITY answers — self-description and the "no LLM" clarification.
1917
+ * identity-self DOES vary with uiContext (its `--repo <path>` clause is
1918
+ * CLI-only) and now with codeDomainActive too: identity-self-neutral drops
1919
+ * the code-graph clause outright and serves both ui contexts, since neither
1920
+ * had anything left to differ on once that clause is gone. */
1887
1921
  const T_IDENTITY_SELF = "identity-self";
1888
1922
  const T_IDENTITY_SELF_BROWSER = "identity-self-browser";
1923
+ const T_IDENTITY_SELF_NEUTRAL = "identity-self-neutral";
1889
1924
  const T_IDENTITY_NOT_LLM = "identity-not-an-llm";
1890
1925
  const T_IDENTITY_NO_FEELINGS = "identity-no-feelings";
1891
1926
  /** Confirms the honest-miss promise itself when a user asks about it directly
@@ -2280,6 +2315,20 @@ export function renderVerbose(last) {
2280
2315
  * apply to hand-written prose, applied here to which DATA row gets rendered. */
2281
2316
  const uiTemplateId = (uiContext, id, browserId) => (uiContext === "browser" ? browserId : id);
2282
2317
 
2318
+ /** Picks among an empty-graph surface's three template ids: the browser id
2319
+ * (already free of code vocabulary, so it serves both domain states), or —
2320
+ * on the CLI — the domain-active id (today's wording, verbatim) versus the
2321
+ * neutral one when codeDomainActive is false. */
2322
+ const emptyGraphTemplateId = (uiContext, codeDomainActive, activeId, neutralId, browserId) =>
2323
+ (uiContext === "browser" ? browserId : (codeDomainActive ? activeId : neutralId));
2324
+
2325
+ /** identity-self doesn't vary with graph state, only with uiContext (CLI vs
2326
+ * browser) and codeDomainActive (whether its code-graph clause applies at
2327
+ * all) — the neutral id serves both ui contexts, since dropping that clause
2328
+ * leaves nothing left for them to differ on. */
2329
+ const identitySelfTemplateId = (uiContext, codeDomainActive) =>
2330
+ (codeDomainActive ? uiTemplateId(uiContext, T_IDENTITY_SELF, T_IDENTITY_SELF_BROWSER) : T_IDENTITY_SELF_NEUTRAL);
2331
+
2283
2332
  /** The "here's what you CAN ask" tail on a decline that names no term of its own
2284
2333
  * (the SQL-statement and arithmetic shapes below). `ctx.vocabHint` already
2285
2334
  * carries the session-gated vocabulary/teach pointer, so only the CODE-graph
@@ -2375,7 +2424,7 @@ function conversationalTurn(line, ctx) {
2375
2424
  // over-promising "ask me about this codebase". Phrase-specific variants (good
2376
2425
  // morning, hello there) keep their wording; only the default greeting swaps.
2377
2426
  const id = (!T_GREETING_BY_PHRASE[greetHit] && noCodeGraph(ctx.graph))
2378
- ? uiTemplateId(ctx.uiContext, T_GREETING_EMPTY, T_GREETING_EMPTY_BROWSER)
2427
+ ? emptyGraphTemplateId(ctx.uiContext, ctx.codeDomainActive, T_GREETING_EMPTY, T_GREETING_EMPTY_NEUTRAL, T_GREETING_EMPTY_BROWSER)
2379
2428
  : (T_GREETING_BY_PHRASE[greetHit] || T_GREETING);
2380
2429
  note(ctx.trace, `pattern: template "${id}" (data/templates/responses.jsonl)`);
2381
2430
  return mk(t(id, { vocabHint: ctx.vocabHint }), { lane: "greeting" });
@@ -2435,7 +2484,7 @@ function conversationalTurn(line, ctx) {
2435
2484
  if (identityPhraseMatch(raw)) {
2436
2485
  note(ctx.trace, "goal: identity — who/what tmct is, not a capability listing");
2437
2486
  note(ctx.trace, "lane: conversational — identity (IDENTITY_PHRASES closed set)");
2438
- return mk(t(uiTemplateId(ctx.uiContext, T_IDENTITY_SELF, T_IDENTITY_SELF_BROWSER), { vocabHint: ctx.vocabHint }), { lane: "help" });
2487
+ return mk(t(identitySelfTemplateId(ctx.uiContext, ctx.codeDomainActive), { vocabHint: ctx.vocabHint }), { lane: "help" });
2439
2488
  }
2440
2489
  {
2441
2490
  const metaHit = META_COMMAND_ANSWERS.find(([re]) => re.test(raw));
@@ -2455,7 +2504,7 @@ function conversationalTurn(line, ctx) {
2455
2504
  || CAPABILITY_PHRASES.some((re) => re.test(applyPreambleFrames(raw))) || ORIENT_OPENERS.has(q)) {
2456
2505
  note(ctx.trace, "goal: get oriented — what can tmct answer, how do I start");
2457
2506
  note(ctx.trace, "lane: conversational — help/orientation (CAPABILITY_PHRASES/ORIENT_OPENERS / bare help / ?)");
2458
- return mk(orientationAnswer(ctx.templates, ctx.graph, ctx.vocabHint, ctx.uiContext), { lane: "help" });
2507
+ return mk(orientationAnswer(ctx.templates, ctx.graph, ctx.vocabHint, ctx.uiContext, ctx.codeDomainActive), { lane: "help" });
2459
2508
  }
2460
2509
  // Fuzzy-typo fallback (A4): every exact/collapsed closed-set lookup above missed —
2461
2510
  // try a bounded edit-distance match against the flattened conversational phrase
@@ -2472,9 +2521,9 @@ function conversationalTurn(line, ctx) {
2472
2521
  if (bucket === "bye") return mk(t(T_FAREWELL), { end: true });
2473
2522
  if (bucket === "thanks") return mk(t(T_THANKS), { lane: "thanks" });
2474
2523
  if (bucket === "identity") {
2475
- return mk(t(uiTemplateId(ctx.uiContext, T_IDENTITY_SELF, T_IDENTITY_SELF_BROWSER), { vocabHint: ctx.vocabHint }), { lane: "help" });
2524
+ return mk(t(identitySelfTemplateId(ctx.uiContext, ctx.codeDomainActive), { vocabHint: ctx.vocabHint }), { lane: "help" });
2476
2525
  }
2477
- if (bucket === "capability") return mk(orientationAnswer(ctx.templates, ctx.graph, ctx.vocabHint, ctx.uiContext), { lane: "help" });
2526
+ if (bucket === "capability") return mk(orientationAnswer(ctx.templates, ctx.graph, ctx.vocabHint, ctx.uiContext, ctx.codeDomainActive), { lane: "help" });
2478
2527
  const id = (!T_GREETING_BY_PHRASE[fuzzyHit] && noCodeGraph(ctx.graph))
2479
2528
  ? uiTemplateId(ctx.uiContext, T_GREETING_EMPTY, T_GREETING_EMPTY_BROWSER)
2480
2529
  : (T_GREETING_BY_PHRASE[fuzzyHit] || T_GREETING);
@@ -2496,6 +2545,18 @@ export { moduleCountOf };
2496
2545
  * orientation/greeting only fires when we actually hold an empty graph. */
2497
2546
  export const noCodeGraph = (graph) => !!graph && moduleCountOf(graph) === 0;
2498
2547
 
2548
+ /** Whether THIS session's loaded graph or active bundles carry any code-domain
2549
+ * content: a graph with at least one Module individual, or the seon
2550
+ * code-domain corpus active in this session's extensions. Computed once per
2551
+ * session (chat-session.mjs) and threaded through runTurn's ctx so a lane
2552
+ * that would otherwise speak code vocabulary with nothing here to ground it
2553
+ * — a count, a banner clause, a code-shaped miss, a help row — reads this
2554
+ * instead of asking the graph directly. A null/absent graph and no active
2555
+ * seon bundle reads as inactive (the safe default: no evidence, no domain). */
2556
+ export function codeDomainActive({ graph, seonActive = false } = {}) {
2557
+ return (!!graph && moduleCountOf(graph) > 0) || !!seonActive;
2558
+ }
2559
+
2499
2560
  /** LIVE orientation examples: the example queries on the orientation card name
2500
2561
  * entities from the LOADED graph — the sorted-first Module label and the
2501
2562
  * sorted-first Function/Method label, deterministically — so a stranger who
@@ -2534,10 +2595,11 @@ function orientationExamples(graph) {
2534
2595
  /** The orientation surface, module-aware: the empty variant (→ the provably-correct
2535
2596
  * vocabulary hint + --repo/tmct init, or its browser twin) when there's no code
2536
2597
  * graph, the standard one (with live {example1}/{example2} query examples from
2537
- * the loaded graph) otherwise. */
2538
- function orientationAnswer(templates, graph, vocabHint, uiContext = "cli") {
2598
+ * the loaded graph) otherwise. `codeDomainActive` picks the empty variant's own
2599
+ * wording: today's code-structure clause when true, a neutral one when false. */
2600
+ function orientationAnswer(templates, graph, vocabHint, uiContext = "cli", codeDomainActive = false) {
2539
2601
  if (noCodeGraph(graph)) {
2540
- const id = uiTemplateId(uiContext, T_ORIENTATION_EMPTY, T_ORIENTATION_EMPTY_BROWSER);
2602
+ const id = emptyGraphTemplateId(uiContext, codeDomainActive, T_ORIENTATION_EMPTY, T_ORIENTATION_EMPTY_NEUTRAL, T_ORIENTATION_EMPTY_BROWSER);
2541
2603
  return tRender(templates, id, { vocabHint }) ?? TEMPLATES_UNAVAILABLE;
2542
2604
  }
2543
2605
  return tRender(templates, T_ORIENTATION, orientationExamples(graph)) ?? TEMPLATES_UNAVAILABLE;
@@ -2558,15 +2620,18 @@ const ORIENTATION_EMPTY_FALLBACK_BROWSER = "I'm tmct — a deterministic, offlin
2558
2620
  * through the SAME template (T_ORIENTATION_EMPTY/T_ORIENTATION_EMPTY_BROWSER)
2559
2621
  * conversationalTurn's orientation branch uses, so there is exactly one copy of
2560
2622
  * that wording to keep in sync, not two hand-duplicated strings. */
2561
- function orientationText(graph, templates, vocabHint, uiContext = "cli") {
2623
+ function orientationText(graph, templates, vocabHint, uiContext = "cli", codeDomainActive = false) {
2562
2624
  // A null (never-loaded) graph reads as "unknown, not empty" to noCodeGraph,
2563
2625
  // which is the right call for the greeting/orientation CARD — but there is no
2564
2626
  // entity count to render from one either, so the empty wording is the only
2565
2627
  // truthful thing left to say. Without this the entity tally below threw on a
2566
2628
  // graph-less runTurn.
2567
2629
  if (!graph || noCodeGraph(graph)) {
2568
- const id = uiTemplateId(uiContext, T_ORIENTATION_EMPTY, T_ORIENTATION_EMPTY_BROWSER);
2569
- const fallback = uiContext === "browser" ? ORIENTATION_EMPTY_FALLBACK_BROWSER : ORIENTATION_EMPTY_FALLBACK;
2630
+ const id = emptyGraphTemplateId(uiContext, codeDomainActive, T_ORIENTATION_EMPTY, T_ORIENTATION_EMPTY_NEUTRAL, T_ORIENTATION_EMPTY_BROWSER);
2631
+ // ORIENTATION_EMPTY_FALLBACK_BROWSER already carries no code vocabulary,
2632
+ // so it doubles as the neutral CLI fallback too — only the domain-active
2633
+ // CLI branch needs its own (code-pointer-carrying) fallback text.
2634
+ const fallback = (uiContext === "browser" || !codeDomainActive) ? ORIENTATION_EMPTY_FALLBACK_BROWSER : ORIENTATION_EMPTY_FALLBACK;
2570
2635
  return tRender(templates, id, { vocabHint }) ?? fallback;
2571
2636
  }
2572
2637
  const by = (cls) => (graph.individuals || []).filter((i) => (i.class || "") === cls).length;
@@ -4448,16 +4513,71 @@ async function generalVerbTeach(payload) {
4448
4513
  // polarity prefix swap. Negating first would hand the fold an mgxneg: CURIE
4449
4514
  // its /^mgx:[a-z]+$/ guard rejects, stranding "on water" inside the object of
4450
4515
  // "a penguin cannot rest on water" — the very bug the fold exists to prevent.
4451
- const folded = foldPrepositionIntoPredicate(await generalVerbPredicate(verb), objectRaw);
4516
+ const mintedPredicate = await generalVerbPredicate(verb);
4517
+ const folded = foldPrepositionIntoPredicate(mintedPredicate, objectRaw);
4452
4518
  // "the" strips alongside "a"/"an": the read-back side already strips a
4453
4519
  // leading determiner off the queried term, so leaving it on here stores an
4454
4520
  // object no question can match.
4455
4521
  const object = folded.object.replace(/^(?:an?|the)\s+/i, "").trim();
4456
4522
  if (!subject || !object) return null; // no well-formed triple — honest decline (point 6)
4457
4523
  if (PLACE_ADVERB_OBJECT_RE.test(object)) return null; // a place adverb is never a real object
4524
+ if (await readsAsNarratedEvent(verb, folded.predicate !== mintedPredicate)) return null;
4525
+ if (await readsAsUnknownEverywhere(subject, verb, object)) return null;
4458
4526
  return { subject, predicate: negated ? negatedPredicate(folded.predicate) : folded.predicate, object };
4459
4527
  }
4460
4528
 
4529
+ /** Does this word read as a WORD at all — the committed lexicon knows it as a
4530
+ * noun/verb/adjective/proper name, or wink's lemmatizer folds it onto a
4531
+ * different base form, which it only does for a word in its own dictionary.
4532
+ * Gibberish satisfies neither: "qpwoe" is in no lexicon and lemmatizes to
4533
+ * itself. A base-form real word ("rest") lemmatizes to itself too, which is
4534
+ * why this is only ever asked of a whole sentence at once, never one slot. */
4535
+ function readsAsKnownWord(word, lemma) {
4536
+ const w = String(word || "").toLowerCase();
4537
+ if (!w) return false;
4538
+ const lex = loadLexicon();
4539
+ if (lookupNoun(lex, w) || lookupVerb(lex, w) || lookupAdjective(lex, w) || lookupProperName(lex, w)) return true;
4540
+ return Boolean(lemma && lemma(w) !== w);
4541
+ }
4542
+
4543
+ /** A past-tense verb whose object opens with a preposition is narration of
4544
+ * something that happened, not a relation anyone can ask back: "the old
4545
+ * bridge creaked under the weight of the truck" would mint mgx:creak-under
4546
+ * over "weight of the truck", a fact no question this build can ask will
4547
+ * ever match. Decline instead of storing the garble.
4548
+ *
4549
+ * The tense test is the closed "-ed" strip confirmed by wink's lemma, the
4550
+ * same pair matchRelationalVerbTeach uses — so the present-tense teaches this
4551
+ * frame exists for ("disk-1 rests on peg-a", "wolf-1 stands on bank-east")
4552
+ * never reach it, and neither does a past tense with no prepositional tail,
4553
+ * which the frames above already own. */
4554
+ async function readsAsNarratedEvent(verb, prepositionFolded) {
4555
+ if (!prepositionFolded) return false;
4556
+ const v = String(verb || "").toLowerCase();
4557
+ if (!pastVerbBase(v)) return false;
4558
+ try {
4559
+ const { proseLemma } = await import("../adapters/prose-nlp.mjs");
4560
+ const lemma = proseLemma();
4561
+ if (lemma && lemma(v) === v) return false; // wink says this is a base form, not a past
4562
+ } catch { /* no lemmatizer — the closed strip stands on its own */ }
4563
+ return true;
4564
+ }
4565
+
4566
+ /** A sentence in which NOTHING is a word — no slot is in the lexicon and none
4567
+ * lemmatizes, so "asdkjhaskjdh qpwoe zzxx" would mint mgx:qpwoe over two
4568
+ * more non-words. One recognized word anywhere is enough for the frame to
4569
+ * stand, which is what keeps a teach about names nothing has heard of
4570
+ * ("grace mentors alan") storing normally. */
4571
+ async function readsAsUnknownEverywhere(subject, verb, object) {
4572
+ let lemma = null;
4573
+ try {
4574
+ const { proseLemma } = await import("../adapters/prose-nlp.mjs");
4575
+ lemma = proseLemma();
4576
+ } catch { /* no lemmatizer — the lexicon answers alone */ }
4577
+ const words = `${subject} ${verb} ${object}`.split(/[\s-]+/).filter(Boolean);
4578
+ return !words.some((w) => readsAsKnownWord(w, lemma));
4579
+ }
4580
+
4461
4581
  /** Is `word` a genuine NOUN/PROPN, per wink-nlp's optional POS tagger
4462
4582
  * (ask-nlp.mjs's nlpAdapter, the SAME adapter the closed structural grammar
4463
4583
  * already leans on)? Used to let ONE narrow bare (unwrapped) general-verb
@@ -6647,9 +6767,16 @@ const MODULE_ORIENT_POLITENESS_RE = /^(?:(?:please|kindly)\s+)*(?:explain\s+(?:t
6647
6767
  * resolution via resolveEntity, else null — never a guess. Pronoun/self
6648
6768
  * subjects ("what does it/this do", "what's it for") are META_ORIENT_RE's/
6649
6769
  * isConversational's territory, not this lane's — declined here so they
6650
- * fall through unchanged. */
6651
- async function moduleOrientLane(query, { graph }) {
6770
+ * fall through unchanged.
6771
+ *
6772
+ * Declines outright with no code domain active: every resolution below
6773
+ * requires a real graph entity, so an inactive domain (no modules, no seon
6774
+ * bundle) can never actually reach a hit here — this just makes that decline
6775
+ * explicit rather than incidental. */
6776
+ async function moduleOrientLane(query, { graph, codeDomainActive = null }) {
6652
6777
  if (!graph) return null;
6778
+ const domainActive = codeDomainActive ?? (moduleCountOf(graph) > 0);
6779
+ if (!domainActive) return null;
6653
6780
  let q = String(query).trim().replace(/[?.!]+$/, "").replace(/\s+/g, " ");
6654
6781
  // This lane reads the ORIGINAL (case-preserving) query text, so it needs its
6655
6782
  // own normalization: correctMisspellings for a typo'd anchor word ("waht
@@ -6741,7 +6868,7 @@ async function moduleOrientLane(query, { graph }) {
6741
6868
  return null;
6742
6869
  }
6743
6870
 
6744
- async function metaLane(query, { graph, memoryDir, last = null, templates = null, vocabHint = null, focus = null, uiContext = "cli" }) {
6871
+ async function metaLane(query, { graph, memoryDir, last = null, templates = null, vocabHint = null, focus = null, uiContext = "cli", codeDomainActive = false }) {
6745
6872
  // Preamble-peeled twin of `q`: a self-intro/greeting lead ("I'm new here,
6746
6873
  // what should I read first") wraps exactly the orientation questions this
6747
6874
  // lane owns, and the anchored META_ORIENT_RE can't see past it. Peeling
@@ -6752,7 +6879,7 @@ async function metaLane(query, { graph, memoryDir, last = null, templates = null
6752
6879
  return { text: await memorySummary(memoryDir, graph, uiContext), via: "meta" };
6753
6880
  }
6754
6881
  if (peeled !== q && META_ORIENT_RE.test(peeled)) {
6755
- const text = orientationText(graph, templates, vocabHint, uiContext);
6882
+ const text = orientationText(graph, templates, vocabHint, uiContext, codeDomainActive);
6756
6883
  return { text: last?.answer === text ? META_ORIENT_REPEAT_ONELINER : text, via: "meta" };
6757
6884
  }
6758
6885
  if (META_ORIENT_RE.test(q)) {
@@ -6762,7 +6889,7 @@ async function metaLane(query, { graph, memoryDir, last = null, templates = null
6762
6889
  // reprints orientationText(graph) verbatim on every repeat, never
6763
6890
  // collapsing. Mirrors ORIENTATION_REPEAT_ONELINER's identity-check
6764
6891
  // pattern exactly, with its own distinct oneliner text.
6765
- const text = orientationText(graph, templates, vocabHint, uiContext);
6892
+ const text = orientationText(graph, templates, vocabHint, uiContext, codeDomainActive);
6766
6893
  return { text: last?.answer === text ? META_ORIENT_REPEAT_ONELINER : text, via: "meta" };
6767
6894
  }
6768
6895
  // A bare "what is in here" with NO standing focus — see
@@ -6777,7 +6904,7 @@ async function metaLane(query, { graph, memoryDir, last = null, templates = null
6777
6904
  if (!focus?.label) {
6778
6905
  const stripped = normalizeQuery(String(query)).trim().replace(/[?.!]+$/, "").trim();
6779
6906
  if (NO_FOCUS_WHATS_IN_HERE_RE.test(stripped)) {
6780
- const text = orientationText(graph, templates, vocabHint, uiContext);
6907
+ const text = orientationText(graph, templates, vocabHint, uiContext, codeDomainActive);
6781
6908
  return { text: last?.answer === text ? META_ORIENT_REPEAT_ONELINER : text, via: "meta" };
6782
6909
  }
6783
6910
  }
@@ -6785,7 +6912,7 @@ async function metaLane(query, { graph, memoryDir, last = null, templates = null
6785
6912
  // list didn't claim — try the module-grain overview before falling through to
6786
6913
  // the author-sha check below (disjoint triggers; order doesn't matter, but
6787
6914
  // this reads MORE of the query shape space, so it goes first).
6788
- const moduleOrient = await moduleOrientLane(query, { graph });
6915
+ const moduleOrient = await moduleOrientLane(query, { graph, codeDomainActive });
6789
6916
  if (moduleOrient) return moduleOrient;
6790
6917
  // The sha-authorship form ("who authored a1b2c3d") can be as short as
6791
6918
  // THREE words, which the conversational-orientation branch (step 2) would grab
@@ -7118,8 +7245,13 @@ function gameOwnWord(query, planHolder) {
7118
7245
  const WALL_REPEAT_ONELINER = "still couldn't parse that — /help lists every query shape.";
7119
7246
  /** The graph-less bootstrap wall's opening line — shared with the teach-offer
7120
7247
  * collapse below, which treats this wall (like the shortened generic wall)
7121
- * as text a term-specific offer REPLACES rather than stacks under. */
7248
+ * as text a term-specific offer REPLACES rather than stacks under. Rendered
7249
+ * only when the code domain is active; NEUTRAL_BOOTSTRAP_WALL_LEAD stands in
7250
+ * for it otherwise. */
7122
7251
  const NO_GRAPH_BOOTSTRAP_WALL_LEAD = "I can't answer that as a code question — no code graph is loaded in this session.";
7252
+ /** The no-code-domain sibling of the lead above: same role (the bootstrap
7253
+ * wall's opening line), no code vocabulary. */
7254
+ const NEUTRAL_BOOTSTRAP_WALL_LEAD = "I couldn't ground that in anything I know.";
7123
7255
 
7124
7256
  /** The orientation-repeat one-liner. The conversational
7125
7257
  * orientation branch sits OUTSIDE the composed-only wall-shortening gate (it
@@ -7156,13 +7288,28 @@ async function resolveEntity(graph, term) {
7156
7288
  return null;
7157
7289
  }
7158
7290
 
7159
- /** The `/help` body: the bare-question default + every command (from COMMANDS, so
7160
- * it can't drift) + the tmct_ask question shapes, pulled from the engine's own
7161
- * rephraseHint() so the shapes are exactly the ones the grammar supports. */
7162
- export async function helpText() {
7291
+ /** The `/help` body: the bare-question default + the code-domain command rows
7292
+ * + the tmct_ask question shapes, pulled from the engine's own rephraseHint()
7293
+ * so the shapes are exactly the ones the grammar supports.
7294
+ * `codeDomainActive` gates the trailing counts row: it names the code-graph
7295
+ * count vocabulary (classes/functions/modules/…), so it renders only when a
7296
+ * code domain is actually active this session.
7297
+ *
7298
+ * `helpRows` is the code-domain command rows to render — the session's own
7299
+ * merged lane vocabulary (ctx.laneVocab.helpRows, empty when the domain is
7300
+ * inactive: see resolveLaneVocab). COMMANDS itself stays the dispatch source
7301
+ * of truth (every /command's tool/arg wiring, unconditionally); this is only
7302
+ * what /help DISPLAYS. Omitted (undefined, not an explicit `[]`) — the shape
7303
+ * a bare/library `helpText(true)` call takes — falls back to COMMANDS'
7304
+ * own rows, gated the same way, so a caller outside the session seam still
7305
+ * sees every command with none of chat-session.mjs's plumbing. */
7306
+ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7307
+ const codeRows = helpRows !== undefined
7308
+ ? helpRows
7309
+ : (codeDomainActive ? Object.entries(COMMANDS).map(([name, s]) => [`/${name}${s.arg ? (s.optional ? ` [${s.arg}]` : ` <${s.arg}>`) : ""}`, s.help]) : []);
7163
7310
  const rows = [
7164
7311
  ["<question>", "ask the graph in plain English (the default for any non-slash line)"],
7165
- ...Object.entries(COMMANDS).map(([name, s]) => [`/${name}${s.arg ? (s.optional ? ` [${s.arg}]` : ` <${s.arg}>`) : ""}`, s.help]),
7312
+ ...codeRows,
7166
7313
  ["/stats", "a one-screen overview: entity counts, relationship counts, packages"],
7167
7314
  ["/memory [verbose]", "what tmct remembers: facts, utterances, sessions, folded blocks"],
7168
7315
  ["/focus <symbol>", "set the current focus (reused by 'it'/'this' and no-arg entity commands)"],
@@ -7176,7 +7323,8 @@ export async function helpText() {
7176
7323
  ["forget that <X> is a <Y>", "withdraw a fact you taught, and anything derived from it — the phrasing the retract lane reads"],
7177
7324
  ["/narrate on|off", "verbose developer/debug mode: decision points, matched pattern, results+sources, goal per turn"],
7178
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"],
7179
- ["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"],
7180
7328
  ["/help", "this list"],
7181
7329
  ["/exit", "leave the session (also Ctrl+C / Ctrl+D)"],
7182
7330
  ];
@@ -7194,7 +7342,7 @@ export async function helpText() {
7194
7342
  return [
7195
7343
  "commands:", ...lines, "",
7196
7344
  "question shapes for a bare line (tmct_ask):", ` ${shapes}`,
7197
- 'plus counts: "how many <classes|functions|modules|methods|commits> are there".',
7345
+ ...(codeDomainActive ? ['plus counts: "how many <classes|functions|modules|methods|commits> are there".'] : []),
7198
7346
  ].join("\n");
7199
7347
  }
7200
7348
 
@@ -9878,12 +10026,19 @@ const WHOLE_RECALL_RE = /^(?:what\s+(?:did|have)\s+(?:i|we)\s+(?:told?|tell|said
9878
10026
  /** The singular class-noun of the graph entity a term names ("app/lib/a.mjs" →
9879
10027
  * "module", "Widget" → "class"), via the ask engine's own resolver + the loaded
9880
10028
  * graph's class map — or null on a miss/ambiguity/no-graph. Lets forward
9881
- * membership answer over a graph INSTANCE, not just a bare class word. */
10029
+ * membership answer over a graph INSTANCE, not just a bare class word. A
10030
+ * resolved `cls` only ever happens over a real code graph, so reading the
10031
+ * shipped code pack's own class labels here (codeCountNouns' sibling, same
10032
+ * "runs only when the domain is already active" reasoning) is safe
10033
+ * regardless of whether the pack extension itself is formally active. */
9882
10034
  async function entityClassNoun(graph, term) {
9883
10035
  const ent = await resolveEntity(graph, term);
9884
10036
  if (!ent) return null;
9885
10037
  const cls = (graph?.byId?.get?.(ent.id) || (graph?.individuals || []).find((i) => i?.id === ent.id))?.class;
9886
- return cls && CLASS_LABELS[cls] ? CLASS_LABELS[cls][0] : null;
10038
+ if (!cls) return null;
10039
+ const { defaultCodeLaneVocab } = await import("./extensions.mjs");
10040
+ const { classLabels } = await defaultCodeLaneVocab();
10041
+ return classLabels[cls] ? classLabels[cls][0] : null;
9887
10042
  }
9888
10043
 
9889
10044
  /** A relation group that carries class-inheritance edges — the same token family
@@ -11734,13 +11889,13 @@ function reverseCleftRewrite(query) {
11734
11889
  return m ? `${m[1].toLowerCase()} ${m[2].trim()}` : null;
11735
11890
  }
11736
11891
 
11737
- // ---- curated SEON definitions (corpus/seon/definitions.jsonl) ----
11892
+ // ---- curated SEON definitions (corpus/domains/code/definitions.jsonl) ----
11738
11893
  // A "what is a <term>" for a LEXICON term prefers the curated one-sentence
11739
11894
  // definition, cited via:"corpus/seon" — but only when this repo carries the
11740
11895
  // SEON concept seed, and a fact the USER personally asserted still wins.
11741
11896
 
11742
11897
  let seonDefsPromise = null;
11743
- /** Load corpus/seon/definitions.jsonl once → Map(normFactTerm(term) → definition).
11898
+ /** Load corpus/domains/code/definitions.jsonl once → Map(normFactTerm(term) → definition).
11744
11899
  * Lazy + failure-tolerated (chat.mjs ethos): any failure degrades to an empty map. */
11745
11900
  function seonDefinitions() {
11746
11901
  if (!seonDefsPromise) {
@@ -11765,8 +11920,8 @@ function seonDefinitions() {
11765
11920
  }
11766
11921
 
11767
11922
  let seonRelsPromise = null;
11768
- /** Load corpus/seon/relations.jsonl once → Map(relationTerm → definition), keyed on
11769
- * the concept key ("imports","calls",…). Sits beside definitions.jsonl (same seon
11923
+ /** Load corpus/domains/code/relations.jsonl once → Map(relationTerm → definition), keyed on
11924
+ * the concept key ("imports","calls",…). Sits beside definitions.jsonl (same
11770
11925
  * dir), loaded the same lazy + failure-tolerated way — any failure degrades to an
11771
11926
  * empty map, so the relation force simply declines rather than throwing. */
11772
11927
  function relationDefinitions() {
@@ -12036,6 +12191,9 @@ async function ingestReferenceArticle(memoryDir, key, article, cache, tagFor = r
12036
12191
  if (subject && object && subject !== object && !seen.has(id)) { seen.add(id); facts.push({ subject, predicate, object, provenance }); }
12037
12192
  };
12038
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
+ }
12039
12197
  try {
12040
12198
  const { optimisticTriples } = await import("./extract-facts.mjs");
12041
12199
  for (const sentence of splitSentences(article.summary || article.text || "")) {
@@ -12563,7 +12721,7 @@ async function completionsRescueAnswer(query, { memoryDir, graph }) {
12563
12721
  * definition + real example EDGES + pre-validated follow-ups) for a vague touch on a
12564
12722
  * relation/edge kind ("what about imports", "tell me about contains"), or null
12565
12723
  * when it isn't one. Loads the definition from the shipped
12566
- * corpus/seon/relations.jsonl, so it works without per-repo memory seeding.
12724
+ * corpus/domains/code/relations.jsonl, so it works without per-repo memory seeding.
12567
12725
  * Returns { text, pending, kind } — `kind` is the resolved RELATION_TERM
12568
12726
  * canonical kind, the SAME vocabulary GOAL_BY_KIND keys on. */
12569
12727
  async function relationForceAnswer(query, envelope, { graph, config, source, templates }) {
@@ -13412,7 +13570,7 @@ const ARCH_OVERVIEW_PHRASES = [
13412
13570
  new RegExp(`^${ARCH_OVERVIEW_LEAD}(?:(?:an?|the)\\s+)?(?:overview|map|diagram)\\s+${ARCH_OVERVIEW_OF_REPO}(?:\\s+here)?\\??$`, "i"),
13413
13571
  ];
13414
13572
 
13415
- async function runAsk(query, { config, source, graph, focus, last, templates, memoryDir, sessionId = "", lexicon = null, env, trace, vocabHint = null, tel = null, biasByBundle = {}, cache = null, vocabAntecedent = null, planHolder = null, discourseHolder = null, gameConfig = DEFAULT_GAME_CONFIG, liveReference = false, onLiveLookup = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
13573
+ async function runAsk(query, { config, source, graph, focus, last, templates, memoryDir, sessionId = "", lexicon = null, env, trace, vocabHint = null, tel = null, biasByBundle = {}, cache = null, vocabAntecedent = null, planHolder = null, discourseHolder = null, gameConfig = DEFAULT_GAME_CONFIG, liveReference = false, onLiveLookup = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, codeDomainActive = false }) {
13416
13574
  const ts = new Date().toISOString();
13417
13575
  // The surface this turn runs on ("cli" default; "browser" from a web entry) —
13418
13576
  // the honest-miss tail below points a browser/adventure miss at the teach
@@ -13803,8 +13961,11 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
13803
13961
  answer = (!graph || noCodeGraph(graph)) && (!config || e?.emptyGraph || /^cannot read graph artifact\b/.test(thrown))
13804
13962
  // A browser session has no `tmct init in a repo` to reach for, so its
13805
13963
  // fallback drops that CLI-only remedy and keeps just the teach pointer.
13806
- ? `${NO_GRAPH_BOOTSTRAP_WALL_LEAD} ${vocabHint
13807
- || (browser
13964
+ // No code domain active: the lead drops the code-question framing, and
13965
+ // the CLI-only "index one" remedy drops too — there is nothing to index
13966
+ // toward without a code domain.
13967
+ ? `${codeDomainActive ? NO_GRAPH_BOOTSTRAP_WALL_LEAD : NEUTRAL_BOOTSTRAP_WALL_LEAD} ${vocabHint
13968
+ || (browser || !codeDomainActive
13808
13969
  ? "I can still remember and answer taught facts (try \"every bug is an issue\")."
13809
13970
  : "I can still remember and answer taught facts (try \"every bug is an issue\"), or run `tmct init` in a repo to index one.")}`
13810
13971
  : thrown;
@@ -13875,7 +14036,17 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
13875
14036
  }
13876
14037
  }
13877
14038
  const answeredIds = (envelope?.matches || []).map((m) => m?.id).filter(Boolean);
13878
- const askMiss = envelope ? !!envelope.miss : true;
14039
+ // The ask engine carries its OWN aggregate/count grammar (parseAggregate,
14040
+ // ask.mjs), independent of answerCount's own gate earlier in dispatchTurn —
14041
+ // it answers a code-graph class count (parsed.node "count") straight off
14042
+ // the graph regardless of what's actually loaded. With no code domain
14043
+ // active this session has no code-graph vocabulary to answer such a count
14044
+ // from, so treat it as a miss here too: the honest-empty-polish pass below
14045
+ // reads this exact shape (a code-shaped, structurally-worded answer) and
14046
+ // declines it to the ordinary wall, the same outcome answerCount's own gate
14047
+ // produces for the phrasing it owns.
14048
+ const codeCountWithNoDomain = envelope?.parsed?.node === "count" && !codeDomainActive;
14049
+ const askMiss = codeCountWithNoDomain || (envelope ? !!envelope.miss : true);
13879
14050
  // GRAPH-FACT-VS-TAUGHT-FACT PRECEDENCE: a plain declarative "X is a kind of
13880
14051
  // Y" sentence whose SUBJECT already names a real graph entity could get
13881
14052
  // silently "answered" by the ask engine's own relaxation cascade instead of
@@ -13992,7 +14163,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
13992
14163
  // codebase", "how do i start") → a summary / orientation, answered before the
13993
14164
  // fact-dump readers so "what do you know" gets a summary, not raw facts.
13994
14165
  if (!handled && miss) {
13995
- const meta = await metaLane(query, { graph, memoryDir, last, templates, vocabHint, focus, uiContext });
14166
+ const meta = await metaLane(query, { graph, memoryDir, last, templates, vocabHint, focus, uiContext, codeDomainActive });
13996
14167
  if (meta) {
13997
14168
  // A lane may answer with a better-worded decline (the module-orient
13998
14169
  // residue guard) — still a miss in the turn record, like the isa
@@ -14410,7 +14581,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
14410
14581
  // 3 words with no STRUCT_WORDS token, so without this guard
14411
14582
  // isConversational would discard a correct, already-composed answer for
14412
14583
  // the generic orientation wall.
14413
- const orientation = orientationAnswer(templates, graph, vocabHint, uiContext);
14584
+ const orientation = orientationAnswer(templates, graph, vocabHint, uiContext, codeDomainActive);
14414
14585
  const repeat = last?.answer === orientation;
14415
14586
  answer = repeat ? ORIENTATION_REPEAT_ONELINER : orientation;
14416
14587
  via = "template"; handled = true;
@@ -14424,20 +14595,31 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
14424
14595
  // first (factAnswer), then the reverse-membership read-back (factReadBack) so an
14425
14596
  // asserted "every X is a Y" answers "what is a Y" too.
14426
14597
  // Raw query first (the long-standing contract), then ONE retry with the
14427
- // normalized form — gated to the no-envelope bootstrap ONLY: on the FIRST
14428
- // turn of a graph-less session the ask engine throws before its own
14429
- // normalize pass runs, so a politeness-wrapped vocabulary question
14430
- // ("could you tell me what a dog is") reaches this lane still wearing the
14431
- // wrapper no reader matches. From turn 2 on (envelope present) the
14432
- // pipeline unwraps it upstream, and an unrestricted retry would let
14433
- // normalization-mangled text reach readers whose guards were written for
14434
- // the raw surface (the pronoun-subject identity family).
14435
- const normalizedForFacts = envelope ? null : normalizeQuery(String(query));
14598
+ // courtesy wrapper peeled off. A politeness-wrapped vocabulary question
14599
+ // ("could you tell me what a dog is", "please tell me what you know about
14600
+ // dog") reaches this lane still wearing a wrapper no reader matches, so
14601
+ // without the retry it walls while its bare form answers.
14602
+ //
14603
+ // The peel is applyPreambleFrames, not the full normalizeQuery. Only the
14604
+ // closed wrapper frames are wanted here; normalizeQuery goes on to strip
14605
+ // filler words, and one of those is the pronoun in "what do you know
14606
+ // about X" — the very word that shape's reader anchors on. Peeling
14607
+ // rebuilt the question and the filler strip took it straight back apart,
14608
+ // which is why a courtesy-wrapped memory question about a term this
14609
+ // session KNOWS used to wall. It is also why the retry no longer has to
14610
+ // be held to the no-envelope bootstrap turn: what made an unrestricted
14611
+ // retry unsafe was normalization-mangled text reaching readers whose
14612
+ // guards were written for the raw surface, and the closed frames do not
14613
+ // mangle — they either match a whole wrapper or leave the string alone.
14614
+ //
14615
+ // The retry can only run when the raw read already returned nothing, so
14616
+ // it turns a wall into an answer and never overrides one.
14617
+ const peeledForFacts = applyPreambleFrames(String(query));
14436
14618
  const fact = (await factAnswer(memoryDir, query, envelope, miss, biasByBundle, cache, newFocus?.label))
14437
14619
  ?? (await factReadBack(memoryDir, query, envelope, miss, graph, newFocus?.label, biasByBundle, cache))
14438
- ?? (normalizedForFacts && normalizedForFacts !== String(query).trim()
14439
- ? (await factAnswer(memoryDir, normalizedForFacts, envelope, miss, biasByBundle, cache, newFocus?.label))
14440
- ?? (await factReadBack(memoryDir, normalizedForFacts, envelope, miss, graph, newFocus?.label, biasByBundle, cache))
14620
+ ?? (peeledForFacts && peeledForFacts !== String(query).trim()
14621
+ ? (await factAnswer(memoryDir, peeledForFacts, envelope, miss, biasByBundle, cache, newFocus?.label))
14622
+ ?? (await factReadBack(memoryDir, peeledForFacts, envelope, miss, graph, newFocus?.label, biasByBundle, cache))
14441
14623
  : null);
14442
14624
  if (fact) {
14443
14625
  answer = fact.replace ? fact.text : `${answer}\n${fact.text}`;
@@ -14929,8 +15111,22 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
14929
15111
  answer = `${answer}\n(I don't know that yet — you can teach me: say "remember: <thing> is a <kind>".)`;
14930
15112
  note(trace, "intermediate: HONEST-EMPTY POLISH — a browser miss points at the teach lane, not the CLI-only --repo remedy");
14931
15113
  } else if (looksCodeish(String(query), String(query).toLowerCase())) {
14932
- answer = `${answer}\n(this repo has no code graph — index it with \`tmct index\`, point me at a \`.tmct/graph.json\` with \`--repo <path>\`, or run \`npm run example:mini\`.)`;
14933
- note(trace, "intermediate: HONEST-EMPTY POLISH — the loaded graph has 0 modules, so the dead-end got a tmct index/--repo pointer appended");
15114
+ if (codeDomainActive) {
15115
+ answer = `${answer}\n(this repo has no code graph — index it with \`tmct index\`, point me at a \`.tmct/graph.json\` with \`--repo <path>\`, or run \`npm run example:mini\`.)`;
15116
+ note(trace, "intermediate: HONEST-EMPTY POLISH — the loaded graph has 0 modules, so the dead-end got a tmct index/--repo pointer appended");
15117
+ } else {
15118
+ // No code domain active this session: a code-shaped miss here would
15119
+ // otherwise repeat the engine's own code-graph vocabulary. Decline to
15120
+ // the same neutral wall a genuinely unparsed line gets — as if this
15121
+ // lane's grammar had never matched — rather than pointing at a
15122
+ // command that has nothing here to index.
15123
+ answer = vocabHint
15124
+ ? `I couldn't read that as a question I can answer. ${vocabHint} Type /help for all query shapes.`
15125
+ : shortMissHint(query);
15126
+ via = "miss";
15127
+ genericWallMiss = true;
15128
+ note(trace, "intermediate: HONEST-EMPTY POLISH — no code domain active, so the code-shaped miss declined to the ordinary wall instead of a code-graph pointer");
15129
+ }
14934
15130
  } else {
14935
15131
  // Nothing in the question is code-shaped, so indexing a repo would not
14936
15132
  // help. "who won the 2031 world cup" used to carry the pointer anyway,
@@ -14944,7 +15140,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
14944
15140
  // names no term, so keeping it above the offer stacks two messages
14945
15141
  // where one carries everything. A receipt-bearing specific miss keeps
14946
15142
  // the offer appended beneath it, unchanged.
14947
- const genericWall = genericWallMiss || answer.startsWith(NO_GRAPH_BOOTSTRAP_WALL_LEAD);
15143
+ const genericWall = genericWallMiss || answer.startsWith(NO_GRAPH_BOOTSTRAP_WALL_LEAD) || answer.startsWith(NEUTRAL_BOOTSTRAP_WALL_LEAD);
14948
15144
  answer = genericWall ? teachOffer : `${answer}\n${teachOffer}`;
14949
15145
  note(trace, `intermediate: TEACH-OFFER — the term is unknown to both the graph and memory, so the miss ${genericWall ? "collapsed to the offer to learn" : "got an offer to learn appended"}`);
14950
15146
  }
@@ -15100,6 +15296,8 @@ const GOAL_BY_COMMAND = {
15100
15296
  capabilities: "see what /plan can plan over — built-in query tools and taught actions",
15101
15297
  syllogise: "materialize the entailed facts that follow from what's remembered about one term",
15102
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",
15103
15301
  export: "write the memory store to a file, in the standard JSONL shape",
15104
15302
  ingest: "read a local text file and store every fact the recognizer grounds from it",
15105
15303
  };
@@ -15108,12 +15306,28 @@ const GOAL_BY_COMMAND = {
15108
15306
  * cases). Returns the same { answer, logLines, record, focus } shape as
15109
15307
  * runAsk. Also carries a `goal` field mirroring runAsk's own, so
15110
15308
  * withGoalLine's "Goal (inferred): …" line fires for command dispatches too. */
15111
- async function runCommand(line, { config, source, graph, focus, memoryDir, trace, narrate = false, liveReference = false, tel = null, biasByBundle = {}, cache = null }) {
15309
+ /** One loaded domain as /capabilities renders it: the pack's name, the
15310
+ * grounding channel it declares, and what its lane vocabulary adds. A pack
15311
+ * that declares no grounding channel gets no grounding clause — the listing
15312
+ * never fills that gap in for it. */
15313
+ function domainPackLine({ name, groundingKind, groundingAdapter, commandCount, countNounCount }) {
15314
+ const parts = [];
15315
+ if (groundingKind === "extraction" && groundingAdapter) parts.push(`grounded by extraction through ${groundingAdapter}`);
15316
+ else if (groundingKind === "extraction") parts.push("grounded by extraction");
15317
+ else if (groundingKind === "taught-only") parts.push("grounded by the teach lane only");
15318
+ const adds = [];
15319
+ if (commandCount) adds.push(`${commandCount} command${commandCount === 1 ? "" : "s"}`);
15320
+ if (countNounCount) adds.push(`${countNounCount} count noun${countNounCount === 1 ? "" : "s"}`);
15321
+ if (adds.length) parts.push(`adds ${adds.join(" and ")}`);
15322
+ return parts.length ? `${name} — ${parts.join("; ")}` : String(name);
15323
+ }
15324
+
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 }) {
15112
15326
  const ts = new Date().toISOString();
15113
15327
  const sp = line.indexOf(" ");
15114
15328
  const name = (sp === -1 ? line.slice(1) : line.slice(1, sp)).toLowerCase();
15115
15329
  const argText = (sp === -1 ? "" : line.slice(sp + 1)).trim();
15116
- const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext } = {}) => ({
15330
+ const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext, researchSourceNext } = {}) => ({
15117
15331
  answer,
15118
15332
  logLines: [ts, `> ${line}`, answer, ""],
15119
15333
  record: { type: "turn", ts, query: line, command: name, via: "command", resolvedIds, answeredIds: [], miss },
@@ -15121,11 +15335,19 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15121
15335
  goal: GOAL_BY_COMMAND[name] || "use a specific tool/command directly",
15122
15336
  ...(narrateNext !== undefined ? { narrate: narrateNext } : {}),
15123
15337
  ...(liveReferenceNext !== undefined ? { liveReference: liveReferenceNext } : {}),
15338
+ ...(researchSourceNext !== undefined ? { researchSource: researchSourceNext } : {}),
15124
15339
  });
15125
15340
 
15126
- if (name === "help") { note(trace, "goal: get oriented / learn available commands"); return mk(await helpText()); }
15341
+ if (name === "help") { note(trace, "goal: get oriented / learn available commands"); return mk(await helpText(codeDomainActive, codeDomainActive ? laneVocab?.helpRows : [])); }
15127
15342
  if (name === "stats") {
15128
15343
  note(trace, "goal: get a one-screen overview of the loaded graph");
15344
+ if (!codeDomainActive) {
15345
+ // No code domain active: renderStats' own module/package counts would
15346
+ // be code vocabulary with nothing here to ground it. Report the
15347
+ // session's actual, neutral shape instead.
15348
+ const factCount = memoryDir ? (await factRows(memoryDir, cache)).length : 0;
15349
+ return mk(`no graph loaded — this session holds ${factCount} fact${factCount === 1 ? "" : "s"}. Teach me directly, or /memory to inspect what's stored.`, { miss: true });
15350
+ }
15129
15351
  return graph ? mk(renderStats(graph)) : mk("no graph loaded — /stats needs an index.", { miss: true });
15130
15352
  }
15131
15353
 
@@ -15152,15 +15374,34 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15152
15374
  const arg = argText.toLowerCase();
15153
15375
  const stateWord = (v) => (v === "always" ? "always" : v === "supplement" ? "supplement" : v ? "on" : "off");
15154
15376
  if (arg !== "on" && arg !== "off" && arg !== "supplement" && arg !== "always") {
15377
+ const activeResearchSource = researchSourceLabel(researchSource);
15155
15378
  return mk(`live Wikipedia supplement is ${stateWord(liveReference)} — /wiki on, /wiki off, /wiki supplement, or /wiki always. `
15156
15379
  + "When on, a question I can't answer also tries en.wikipedia.org (network); "
15157
15380
  + "supplement adds a cited Wikipedia read-out under every grounded vocabulary answer too; "
15158
- + "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.`);
15159
15383
  }
15160
15384
  const next = arg === "always" ? "always" : arg === "supplement" ? "supplement" : arg === "on";
15161
15385
  return mk(`live Wikipedia supplement ${stateWord(next)}.`, { liveReferenceNext: next });
15162
15386
  }
15163
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
+
15164
15405
  // /memory [verbose] — what tmct remembers, as text (the same renderer
15165
15406
  // serves the `tmct memory` CLI).
15166
15407
  if (name === "memory") {
@@ -15184,9 +15425,14 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15184
15425
  }
15185
15426
 
15186
15427
  // /capabilities — everything a /plan request can plan over: the built-in
15187
- // read-only graph-query tools, plus the taught action families read straight
15428
+ // read-only graph-query tools, the taught action families read straight
15188
15429
  // from this store (they only live in the registry inside a /plan request,
15189
- // so listing them means reading the rules, not the registry).
15430
+ // so listing them means reading the rules, not the registry), and this
15431
+ // session's loaded domain packs. Each domain line restates that pack's own
15432
+ // declaration — its grounding channel and what its vocabulary adds — so the
15433
+ // surface reports what the pack says about itself rather than a second,
15434
+ // drifting description of it. A session with no pack active lists no
15435
+ // domains and says nothing about them.
15190
15436
  if (name === "capabilities") {
15191
15437
  note(trace, "goal: see what /plan can plan over — built-in query tools and taught actions");
15192
15438
  const { declaredCapabilityNames } = await import("../domain/router/drive.mjs");
@@ -15211,6 +15457,11 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15211
15457
  lines.push(` taught:${familyName} — ${sig}`);
15212
15458
  }
15213
15459
  }
15460
+ const packs = Array.isArray(domainPacks) ? domainPacks : [];
15461
+ if (packs.length) {
15462
+ lines.push("loaded domains:");
15463
+ for (const pack of packs) lines.push(` ${domainPackLine(pack)}`);
15464
+ }
15214
15465
  return mk(lines.join("\n"));
15215
15466
  }
15216
15467
 
@@ -15431,7 +15682,7 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15431
15682
 
15432
15683
  let answer;
15433
15684
  try {
15434
- answer = await dispatchTool(spec.tool, spec.arg ? { [spec.arg]: value } : {}, { config, source, tel });
15685
+ answer = await dispatchTool(spec.tool, spec.arg ? { [spec.arg]: value } : {}, { config, source, tel, codeDomainActive });
15435
15686
  } catch (e) {
15436
15687
  note(trace, `intermediate: dispatchTool("${spec.tool}") threw — ${String(e?.message || e)}`);
15437
15688
  return mk(String(e?.message || e), { miss: true }); // the tool's own clean error, never a stack
@@ -16355,13 +16606,35 @@ export async function runTurn(input, options = {}) {
16355
16606
  return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
16356
16607
  }
16357
16608
 
16358
- 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" } = {}) {
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 } = {}) {
16359
16610
  // Every game's tuning knobs (spider-fly's mass economy, guess-the-number's
16360
16611
  // bounds, the shared plan lane's search-depth cap) — a caller's own
16361
16612
  // gameConfig (chat-session.mjs resolves one per session from tmct.toml)
16362
16613
  // wins outright; direct/library callers that omit it get the shipped
16363
16614
  // defaults, byte-identical to before this seam existed.
16364
16615
  const resolvedGameConfig = gameConfig ?? DEFAULT_GAME_CONFIG;
16616
+ // chat-session.mjs computes this ONCE per session (a loaded graph with
16617
+ // modules, or the seon bundle active) and passes it through; a direct/
16618
+ // library caller that omits it gets the graph-only signal — correct for
16619
+ // every existing caller that hands runTurn a real code graph, and
16620
+ // correctly inactive for a graph-less or empty one.
16621
+ const domainActive = codeDomainActive ?? (!!graph && moduleCountOf(graph) > 0);
16622
+ // This turn's lane vocabulary (count nouns/class labels/help rows/the
16623
+ // miss-recovery pointer): the caller's own — chat-session.mjs threads the
16624
+ // real per-session merge (extensions.mjs's mergedLaneVocab) — or, for a
16625
+ // direct/library caller that hands this a real code graph but no merge,
16626
+ // the shipped code pack's own vocabulary (the same "a real graph is
16627
+ // enough" fallback domainActive itself applies, above). An inactive
16628
+ // domain never sees an import, and never sees code-domain vocabulary.
16629
+ const laneVocabValue = laneVocab ?? (domainActive
16630
+ ? await (await import("./extensions.mjs")).defaultCodeLaneVocab()
16631
+ : { countNouns: {}, classLabels: {}, helpRows: [], missRecoveryPointer: "" });
16632
+ // The packs behind that vocabulary, each read from its own declaration —
16633
+ // the same caller-first-then-"a real graph is enough" rule as the
16634
+ // vocabulary. An inactive domain lists no packs at all.
16635
+ const domainPacksValue = domainPacks ?? (domainActive
16636
+ ? await (await import("./extensions.mjs")).defaultCodeDomainPacks()
16637
+ : []);
16365
16638
  const line = String(input ?? "").trim();
16366
16639
  // ONE fresh, empty cache for this turn only — every factRows() reader
16367
16640
  // reached from this call shares it, so the first reader computes
@@ -16425,7 +16698,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
16425
16698
  // an answer's typed content is in hand (runAsk, off the ask envelope's
16426
16699
  // `discourse` referents); the caller re-threads whatever comes back.
16427
16700
  const discourseHolder = { record: discourse ?? emptyDiscourseRecord() };
16428
- 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 };
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 };
16429
16702
  // A DISPATCHED turn (count / slash-command / ask) becomes the new "last
16430
16703
  // answer" that why/say-more re-renders; a conversational turn does not.
16431
16704
  // Every dispatched turn's result passes through finish() here — the LAST
@@ -16623,12 +16896,13 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
16623
16896
  }
16624
16897
  const researchHolder = { state: priorResearchState };
16625
16898
  const resolvedResearchConfig = researchConfig ?? RESEARCH_DEFAULTS;
16899
+ const effectiveResearchSource = researchSource ?? resolvedResearchConfig.source;
16626
16900
  const rTurn = await researchTurn(workingLine, {
16627
16901
  holder: researchHolder,
16628
16902
  memoryDir,
16629
16903
  lexicon,
16630
- provider: getResearchProvider({ minIntervalMs: resolvedResearchConfig.minIntervalMs }),
16631
- config: resolvedResearchConfig,
16904
+ provider: getResearchProvider({ minIntervalMs: resolvedResearchConfig.minIntervalMs, source: effectiveResearchSource }),
16905
+ config: { ...resolvedResearchConfig, source: effectiveResearchSource },
16632
16906
  planActive: Boolean(planHolder.state && !planHolder.state.done),
16633
16907
  pagerActive: Boolean(Array.isArray(last?.detail?.pending?.items) && last.detail.pending.items.length),
16634
16908
  notify: onLiveLookup,
@@ -16969,7 +17243,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
16969
17243
  // short-circuit straight to "I can't count 'tests'" before this lane ever
16970
17244
  // got a turn. Declines (null) for anything answerCount should own, or a bare
16971
17245
  // global count with no named entity — see answerEdgeCount's own docblock.
16972
- const edgeCount = await answerEdgeCount(graph, workingLine);
17246
+ const edgeCount = await answerEdgeCount(graph, workingLine, { codeDomainActive: domainActive, countNouns: laneVocabValue.countNouns });
16973
17247
  if (edgeCount != null) {
16974
17248
  note(trace, 'goal: get a per-entity count of an edge-nominalized kind ("how many tests cover X", "how many callers does X have")');
16975
17249
  note(trace, "lane: answerEdgeCount — matched an EDGE_NOUN_TO_METRIC noun with a resolvable named entity, answered via the same degreeMetric the superlative lane uses");
@@ -16977,7 +17251,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
16977
17251
  }
16978
17252
  // Aggregate/count questions are answered mechanically off the loaded graph header,
16979
17253
  // BEFORE falling through to the ask engine (focus unchanged — a count names no entity).
16980
- const count = answerCount(graph, workingLine, { uiContext });
17254
+ const count = answerCount(graph, workingLine, { uiContext, codeDomainActive: domainActive, countNouns: laneVocabValue.countNouns, classLabels: laneVocabValue.classLabels });
16981
17255
  if (count != null) {
16982
17256
  // An "I can't count <noun>" from a bare kind may still be answerable from an
16983
17257
  // ASSERTED vocabulary fact ("every class is a type" → "how many types" = the