@polycode-projects/the-mechanical-code-talker 5.0.26 → 5.0.28

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 (34) hide show
  1. package/corpus/worlds/index.json.gz +0 -0
  2. package/corpus/worlds/manifest.json +27 -17
  3. package/corpus/worlds/shards/river-crossing.jsonl.gz +0 -0
  4. package/corpus/worlds/shards/town-square-chapel.jsonl.gz +0 -0
  5. package/corpus/worlds/shards/town-square-market.jsonl.gz +0 -0
  6. package/corpus/worlds/shards/town-square.jsonl.gz +0 -0
  7. package/corpus/worlds/src/river-crossing.jsonl +29 -0
  8. package/corpus/worlds/src/town-square-chapel.jsonl +12 -8
  9. package/corpus/worlds/src/town-square-market.jsonl +12 -8
  10. package/corpus/worlds/src/town-square.jsonl +12 -8
  11. package/package.json +2 -1
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-traits.mjs +282 -0
  14. package/src/domain/ask.mjs +19 -6
  15. package/src/domain/choice-question.mjs +135 -6
  16. package/src/domain/codegraph.mjs +8 -1
  17. package/src/domain/el-classify.mjs +39 -7
  18. package/src/domain/fact-phrase.mjs +7 -4
  19. package/src/domain/interpret/normalize.mjs +58 -2
  20. package/src/domain/town-square-world.mjs +44 -19
  21. package/src/services/adventure.mjs +5 -16
  22. package/src/services/agent-editor.mjs +216 -0
  23. package/src/services/chat-session.mjs +26 -5
  24. package/src/services/chat.mjs +221 -58
  25. package/src/services/mudiii-scene.mjs +32 -5
  26. package/src/services/mudiii-turn.mjs +7 -3
  27. package/src/services/mudiii-viz.mjs +215 -1
  28. package/src/services/news-viz.mjs +489 -0
  29. package/src/services/predator-prey.mjs +157 -24
  30. package/src/surfaces/web/chat-browser-entry.mjs +69 -3
  31. package/src/surfaces/web/memory-ask-browser.bundle.js +155 -155
  32. package/src/surfaces/web/mudiii-browser-entry.mjs +35 -0
  33. package/src/surfaces/web/news-browser-entry.mjs +384 -0
  34. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -22,6 +22,13 @@ import { dispatchTool, dispatchToolStructured, loadGraph, TOOLS } from "../tools
22
22
  import { ToolError } from "../adapters/config.mjs";
23
23
  import { parseEntities, edgesOfKind, moduleCountOf, packageCounts, modulesOf, renderAuthorCard, renderAuthorTouches, renderCommitAuthor, resolveSymbol, renderCompare } from "../domain/codegraph.mjs";
24
24
  import { classDisplayName, DYNAMIC_TAIL_OK_RE } from "../domain/ask.mjs";
25
+ // How a stored fact predicate reads in English — one phrase per predicate the
26
+ // two writers (the ACE grammar, the ConceptNet map) actually emit, shared
27
+ // with the news feed's own paraphrase renderer (src/domain/news-feed.mjs)
28
+ // instead of growing a twin. An unknown predicate renders verbatim rather
29
+ // than being guessed around (see this file's own predicatePhrase, below,
30
+ // which layers polarity/comparative/mechanical-fallback handling on top).
31
+ import { FACT_PREDICATE_PHRASES } from "../domain/fact-phrase.mjs";
25
32
  import { emptyRecord as emptyDiscourseRecord, advanceTurn as advanceDiscourseTurn, register as registerReferent, bind as bindDiscourseForm } from "../domain/discourse.mjs";
26
33
  import { uuidv7 } from "../adapters/uuid.mjs";
27
34
  import * as defaultSource from "../adapters/source.mjs";
@@ -59,6 +66,7 @@ import { getLiveReferenceProvider, getResearchProvider } from "../adapters/corpu
59
66
  import "../adapters/corpus/wikidata-live.mjs";
60
67
  import { researchTurn, researchSnapshot, resolveResearchConfig, RESEARCH_DEFAULTS, parseResearchRequest, researchSourceLabel } from "./research.mjs";
61
68
  import { loadResearchQueue, saveResearchQueue } from "../adapters/research-queue-store.mjs";
69
+ import { newsTurn, resolveNewsConfig, NEWS_DEFAULTS, createNewsState } from "./news.mjs";
62
70
  import { CHILD_PACK_NAME, childProvenanceTag } from "../domain/child-pack.mjs";
63
71
  import { getChildPackProvider } from "../adapters/corpus/child-pack.mjs";
64
72
  import { dialogueActForLane } from "../domain/dialogue-acts.mjs";
@@ -7483,6 +7491,7 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7483
7491
  ["/goals", "the goals a trace can be recognized against: the maintenance invariants, the tool goals, this world's objective, and your taught actions"],
7484
7492
  ["/syllogise <term>", "work out and remember what follows from the facts about a term (needed for chains longer than 2 hops)"],
7485
7493
  ["/classify <term>", "run the EL classifier and remember what follows from a term (reaches restriction-shaped conclusions /syllogise's chains can't)"],
7494
+ ["/prove <question>", "check a yes/no entailment by DL tableau refutation (\"is rex a dog\") — reaches disjunction and complement-class shapes /classify's EL rules can't, citing what it rests on"],
7486
7495
  ["/export <path>", "write the memory store to a file, as JSONL (the same shape `tmct memory --export` writes)"],
7487
7496
  ["/ingest <path>", "read a local text file and store every fact the recognizer grounds from it (same recognizer as `tmct extract`)"],
7488
7497
  ["remember <X> is a <Y>", "teach a fact in plain English (\"every X is a Y\" and a bare \"X is a Y\" work too)"],
@@ -7492,6 +7501,7 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7492
7501
  ["/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"],
7493
7502
  ["/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"],
7494
7503
  ["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"],
7504
+ ["/news [poll|rank|enrich|sources|add <url>]", "the news feed over this graph"],
7495
7505
  ["/help", "this list"],
7496
7506
  ["/exit", "leave the session (also Ctrl+C / Ctrl+D)"],
7497
7507
  ];
@@ -7643,60 +7653,6 @@ async function recallFromBlocks(memoryDir, query, graph) {
7643
7653
 
7644
7654
  // ---- W4: asserted Facts → answers (the memory graph's reified triples) ----
7645
7655
 
7646
- /** How a stored fact predicate reads in English — one phrase per predicate the
7647
- * two writers (the ACE grammar, the ConceptNet map) actually emit. An unknown
7648
- * predicate renders verbatim rather than being guessed around. */
7649
- const FACT_PREDICATE_PHRASES = {
7650
- "rdfs:subClassOf": "is a kind of",
7651
- "mgxneg:subClassOf": "is not a kind of",
7652
- "rdf:type": "is a",
7653
- "owl:disjointWith": "is not a",
7654
- "owl:unionOf": "is either",
7655
- "owl:complementOf": "is anything that is not",
7656
- "owl:oneOf": "includes exactly",
7657
- "owl:differentFrom": "is not the same as",
7658
- "mgx:partOf": "is part of",
7659
- "mgx:memberOf": "is a member of",
7660
- "mgx:collectionOf": "is a collection of",
7661
- "mgx:hasA": "has",
7662
- "mgx:usedFor": "is used for",
7663
- "mgx:capableOf": "can",
7664
- "mgx:atLocation": "is found in",
7665
- "mgx:causes": "causes",
7666
- "mgx:hasProperty": "is",
7667
- "mgx:madeOf": "is made of",
7668
- "mgx:receivesAction": "can be",
7669
- "mgx:createdBy": "is created by",
7670
- "mgx:mannerOf": "is a way to",
7671
- "mgx:desires": "wants",
7672
- "mgx:locatedNear": "is typically near",
7673
- "mgx:motivatedByGoal": "is motivated by",
7674
- "mgx:obstructedBy": "can be prevented by",
7675
- "mgx:causesDesire": "makes you want to",
7676
- "mgx:hasSubevent": "involves",
7677
- "mgx:hasFirstSubevent": "begins with",
7678
- "mgx:hasLastSubevent": "ends with",
7679
- "mgx:hasPrerequisite": "requires",
7680
- "mgx:ownedBy": "is owned by", // the teach lane's ownership frame ("Priya owns tasks.mjs")
7681
- "mgx:rendersAs": "renders as", // the render-template binding ("a disk renders as a block")
7682
- "mgx:synonym": "means the same as",
7683
- "mgx:antonym": "is the opposite of",
7684
- "mgx:similarTo": "is similar to",
7685
- "mgx:relatedTo": "is related to",
7686
- "mgx:symbolOf": "is a symbol of",
7687
- // A loaded adventure world's placement predicates, so a describe read-back of
7688
- // a visible prop reads as English ("lamp is in the study") instead of the
7689
- // mechanical -s fold garbling them ("lamp locateds in study"). The world's
7690
- // SECRET/mechanics predicates (a hidden object's location, the objective
7691
- // marker, the lock/open/NPC internals) are kept out of the describe lane
7692
- // entirely by WORLD_INTERNAL_PREDICATES below, so they never render at all.
7693
- "mgx:currently-in": "is in",
7694
- "mgx:located-in": "is in",
7695
- "mgx:fixed-in": "is fixed in",
7696
- "mgx:stands-locked-in": "stands locked in",
7697
- "mgx:works-in": "works in",
7698
- };
7699
-
7700
7656
  /** The world-mechanics predicates the generic describe read-back must never
7701
7657
  * surface: a hidden object's location and the objective marker spoil the
7702
7658
  * puzzle, and the lock/container/open/NPC-schedule flags are datatype internals
@@ -9004,6 +8960,53 @@ async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fill
9004
8960
  return null;
9005
8961
  }
9006
8962
 
8963
+ /** Phase 5 (PLAN_SYLLOGIST_EL_DL.md): the wider consistency check beside
8964
+ * findConsistencyViolations, not folded into it — a DL tableau clash
8965
+ * (tableau.mjs's findTableauViolations) and an EL-saturation-proved
8966
+ * unsatisfiable class (el-classify.mjs's read-only elUnsatisfiableClasses)
8967
+ * both sit outside what that cheaper cax-dw chase reads: neither a
8968
+ * cardinality restriction nor a class-level EL⊥ derivation ever touches an
8969
+ * `rdf:type` edge. Both run READ-ONLY, scoped to `variants`'s own
8970
+ * signature-connected module (tableau.mjs's extractTableauModule) so an
8971
+ * unrelated part of the store never spends this turn's budget, and both
8972
+ * stay silent on a subject their own check couldn't finish rather than
8973
+ * clearing it. Returns the refusal text citing both premises, or null. */
8974
+ async function findWiderConsistencyClash(rows, variants, reasoning) {
8975
+ const { extractTableauModule, buildTableauKb, findTableauViolations } = await import("../domain/tableau.mjs");
8976
+ const { elUnsatisfiableClasses } = await import("../domain/el-classify.mjs");
8977
+ // An individual's own stored TYPES seed the module too, not just its own
8978
+ // name — extractTableauModule's structural walk starts from class/role
8979
+ // vocabulary (rdfs:subClassOf, owl:onProperty, …), so an individual with
8980
+ // only an `rdf:type` edge never pulls in its class's own restrictions
8981
+ // unless that class is seeded directly.
8982
+ const typeSeeds = rows.filter((r) => r.predicate === "rdf:type" && variants.has(r.subject)).map((r) => r.object);
8983
+ const seeds = [...new Set([...variants, ...typeSeeds])];
8984
+ const moduleRows = extractTableauModule(rows, seeds);
8985
+ const byId = new Map(moduleRows.map((r) => [r.id, r]));
8986
+
8987
+ const kb = buildTableauKb(moduleRows);
8988
+ const tableauSubjects = kb.individuals.filter((ind) => variants.has(ind));
8989
+ if (tableauSubjects.length) {
8990
+ const proveOpts = { maxSteps: reasoning.proveSteps, maxBranches: reasoning.proveBranches, maxNodes: reasoning.proveNodes };
8991
+ const violation = findTableauViolations(kb, tableauSubjects, proveOpts)[0];
8992
+ if (violation) {
8993
+ const cited = violation.premises.map((id) => byId.get(id)).filter(Boolean).map(renderFactLine).join("; ");
8994
+ return `I can't answer that — what I've been told about ${violation.subject} is inconsistent: `
8995
+ + `${cited || "the facts I hold about it clash"}. I'd need one of those retracted before I can answer honestly.`;
8996
+ }
8997
+ }
8998
+
8999
+ const elCheck = elUnsatisfiableClasses(moduleRows, { budget: reasoning.classifyBudget, rounds: reasoning.classifyRounds, focus: new Set(seeds) });
9000
+ const unsatHit = elCheck.unsatisfiable.find((c) => variants.has(c) || typeSeeds.includes(c));
9001
+ if (unsatHit) {
9002
+ const cited = elCheck.premisesOf(unsatHit).map((id) => byId.get(id)).filter(Boolean).map(renderFactLine).join("; ");
9003
+ return `I can't answer that — "${unsatHit}" can never have any members: `
9004
+ + `${cited || "its own subclass chain is unsatisfiable"}. I'd need one of those retracted before I can answer honestly.`;
9005
+ }
9006
+ return null;
9007
+ }
9008
+ export { findWiderConsistencyClash };
9009
+
9007
9010
  async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle = {}, cache = null, focusLabel = null) {
9008
9011
  let normFactTerm; let normFactPredicate;
9009
9012
  try { ({ normFactTerm, normFactPredicate } = await import("../adapters/memory/core.mjs")); } catch { return null; }
@@ -9479,6 +9482,18 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9479
9482
  const obj = factTermVariants(normFactTerm, m[2]);
9480
9483
  const hit = facts.find((f) => f.predicate === predicate && subj.has(f.subject) && obj.has(f.object));
9481
9484
  if (hit) return { text: `yes — ${renderFactLine(hit)}`, replace: true };
9485
+ // A curated phrase can share its English verb with the general-verb
9486
+ // teach mint ("eats" renders mgx:consumes, but teaching "X eats Y"
9487
+ // stores mgx:eat): when the subject holds a fact under the verb's own
9488
+ // general predicate, that reader owns the answer either way, so this
9489
+ // one stands down instead of committing a miss over the wrong
9490
+ // predicate namespace.
9491
+ const [phraseHead] = phrase.split(" ");
9492
+ const generalPredicate = await generalVerbPredicate(baseVerbSurface(phraseHead));
9493
+ if (generalPredicate !== predicate) {
9494
+ const negTwin = generalPredicate.replace(/^mgx:/, "mgxneg:");
9495
+ if (facts.some((f) => (f.predicate === generalPredicate || f.predicate === negTwin) && subj.has(f.subject))) continue;
9496
+ }
9482
9497
  const teachHint = FORWARD_YESNO_TEACHABLE.has(predicate) ? ` If it's true, teach me: "${m[1]} ${phrase} ${m[2]}".` : "";
9483
9498
  const sameRelation = facts.filter((f) => f.predicate === predicate && subj.has(f.subject));
9484
9499
  if (sameRelation.length) {
@@ -10011,6 +10026,17 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10011
10026
  };
10012
10027
  }
10013
10028
  }
10029
+ // WIDER CONSISTENCY CHECK, beside the cax-dw chase above rather than
10030
+ // folded into it (PLAN_SYLLOGIST_EL_DL.md, phase 5): a DL tableau clash
10031
+ // (a cardinality clash — E5's own flagship — or any other clash the
10032
+ // ALC-through-SHOIQ tableau derives) and an EL-saturation-proved
10033
+ // unsatisfiable class both sit outside findConsistencyViolations, which
10034
+ // only reads type, subclass and disjointness edges. Same READ-ONLY
10035
+ // discipline, scoped to this subject's own signature-connected module so
10036
+ // an unrelated part of the store never spends this turn's budget.
10037
+ const reasoning = await resolveReasoningConfigForRepo(memoryDir);
10038
+ const widerClash = await findWiderConsistencyClash(rows, variants, reasoning);
10039
+ if (widerClash) return { text: widerClash, replace: true };
10014
10040
  // echo the STORED spelling ("caches" asked → "cache" known), never a guess
10015
10041
  const literalHit = hits.find((f) => variants.has(f.subject) || variants.has(f.object));
10016
10042
  const term = literalHit
@@ -12589,6 +12615,24 @@ function elClassifyFocus(rows, seedTerms, onPropertyPredicate, someValuesFromPre
12589
12615
  return focus;
12590
12616
  }
12591
12617
 
12618
+ /** /prove's own single-term resolver: the exact stored spelling a surface
12619
+ * word (`isa[1]`/`isa[2]`) names, so `buildTableauKb`'s individual/class
12620
+ * test and `proveEntailment`/`proveSubsumption`'s own concept-name
12621
+ * arguments see the SAME string the fact rows are keyed under, not just a
12622
+ * normalized guess. Tries every plural/singular spelling `factTermVariants`
12623
+ * produces against every row's subject and object, in row order (row order
12624
+ * never varies the answer — normFactTerm is a pure fold, so every variant
12625
+ * present resolves to the one term the store actually uses); falls back to
12626
+ * the bare normalized surface word when the term is stored nowhere yet (an
12627
+ * honest "nothing constrains this" rather than a thrown error). Pure. */
12628
+ function resolveProveTerm(variants, rows, fallback) {
12629
+ for (const r of rows) {
12630
+ if (variants.has(r.subject)) return r.subject;
12631
+ if (variants.has(r.object)) return r.object;
12632
+ }
12633
+ return fallback;
12634
+ }
12635
+
12592
12636
  /** After a learn-on-miss load stored new facts about `term`, run a bounded,
12593
12637
  * focus-scoped forward-chaining pass so the new facts connect to what's
12594
12638
  * already remembered — the auto sibling of the /syllogise command, plus its
@@ -15952,6 +15996,7 @@ const GOAL_BY_COMMAND = {
15952
15996
  wikidata: "choose which source the research lane fetches from",
15953
15997
  export: "write the memory store to a file, in the standard JSONL shape",
15954
15998
  ingest: "read a local text file and store every fact the recognizer grounds from it",
15999
+ news: "surface or work the news feed built over this graph",
15955
16000
  };
15956
16001
 
15957
16002
  /** A slash-command → the mapped tool (or the /help, /focus, /narrate, unknown
@@ -16026,12 +16071,12 @@ export function renderDeclaredGoals(goals) {
16026
16071
  return lines.join("\n").replace(/\n+$/, "");
16027
16072
  }
16028
16073
 
16029
- 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 }) {
16074
+ 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, lexicon = null, newsState = null, newsConfig = null, newsProviders = null }) {
16030
16075
  const ts = new Date().toISOString();
16031
16076
  const sp = line.indexOf(" ");
16032
16077
  const name = (sp === -1 ? line.slice(1) : line.slice(1, sp)).toLowerCase();
16033
16078
  const argText = (sp === -1 ? "" : line.slice(sp + 1)).trim();
16034
- const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext, researchSourceNext } = {}) => ({
16079
+ const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext, researchSourceNext, newsStateNext } = {}) => ({
16035
16080
  answer,
16036
16081
  logLines: [ts, `> ${line}`, answer, ""],
16037
16082
  record: { type: "turn", ts, query: line, command: name, via: "command", resolvedIds, answeredIds: [], miss },
@@ -16040,6 +16085,7 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
16040
16085
  ...(narrateNext !== undefined ? { narrate: narrateNext } : {}),
16041
16086
  ...(liveReferenceNext !== undefined ? { liveReference: liveReferenceNext } : {}),
16042
16087
  ...(researchSourceNext !== undefined ? { researchSource: researchSourceNext } : {}),
16088
+ ...(newsStateNext !== undefined ? { newsState: newsStateNext } : {}),
16043
16089
  });
16044
16090
 
16045
16091
  if (name === "help") { note(trace, "goal: get oriented / learn available commands"); return mk(await helpText(codeDomainActive, codeDomainActive ? laneVocab?.helpRows : [])); }
@@ -16106,6 +16152,39 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
16106
16152
  );
16107
16153
  }
16108
16154
 
16155
+ // /news [poll|rank|enrich|sources|add <url>|interval <minutes>] — the news
16156
+ // feed built over this graph. src/services/news.mjs owns the capability;
16157
+ // every surface (this one, news.html, the CLI verb, a JS import) renders
16158
+ // through its own newsTurn, so wording never drifts between them. Session
16159
+ // state threads turn-to-turn as newsState, the same way researchState
16160
+ // does; newsConfig is a live, mutable object a caller threads once per
16161
+ // session, so a `/news add`/`/news interval` mutation persists by
16162
+ // reference across turns without a separate round-trip field.
16163
+ if (name === "news") {
16164
+ note(trace, "goal: surface or work the news feed built over this graph");
16165
+ if (!memoryDir) return mk("no memory store here — /news works inside a repo session.", { miss: true });
16166
+ try {
16167
+ const { loadMemory, readFactRows, appendFacts, removeFacts } = await import("../adapters/memory/core.mjs");
16168
+ const effectiveNewsConfig = newsConfig || resolveNewsConfig(null);
16169
+ const effectiveNewsState = newsState || createNewsState();
16170
+ const newsCtx = {
16171
+ memoryDir,
16172
+ store: { loadMemory, readFactRows, appendFacts, removeFacts },
16173
+ cache,
16174
+ lexicon,
16175
+ config: effectiveNewsConfig,
16176
+ state: effectiveNewsState,
16177
+ providers: newsProviders || { getResearchProvider },
16178
+ now: () => new Date().toISOString(),
16179
+ };
16180
+ const result = await newsTurn(line, newsCtx);
16181
+ note(trace, `result: ${String(result?.text || "").split("\n")[0]}`);
16182
+ return mk(result.text, { miss: Boolean(result.miss), newsStateNext: effectiveNewsState });
16183
+ } catch (e) {
16184
+ return mk(String(e?.message || e), { miss: true }); // a broken store reads as its own clean error
16185
+ }
16186
+ }
16187
+
16109
16188
  // /memory [verbose] — what tmct remembers, as text (the same renderer
16110
16189
  // serves the `tmct memory` CLI).
16111
16190
  if (name === "memory") {
@@ -16290,6 +16369,90 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
16290
16369
  }
16291
16370
  }
16292
16371
 
16372
+ // /prove <question> — check a yes/no entailment by DL tableau refutation
16373
+ // (src/domain/tableau.mjs), for a shape /classify's EL completion rules
16374
+ // can't reach: disjunction elimination, complement classes, and every
16375
+ // other class expression the ALC-through-SHOIQ tableau covers.
16376
+ //
16377
+ // Same posture as /syllogise and /classify: an explicit request, a
16378
+ // required question, never the hot path an ordinary ask runs down. Unlike
16379
+ // those two, this one writes NOTHING — a case-split conclusion's own
16380
+ // provenance is an open design problem (PLAN_SYLLOGIST_EL_DL.md section
16381
+ // 14), so the tableau stays query-time only, and every rendered verdict
16382
+ // cites the taught facts it rests on rather than a stored one.
16383
+ //
16384
+ // The question parses through the same "is X a Y" shape the plain ask
16385
+ // lane's isa family already reads (ISA_ASK_RE) — /prove is the explicit
16386
+ // command for a shape that shape's own live chases can't close, not a
16387
+ // second grammar. Refuses by name on anything else.
16388
+ if (name === "prove") {
16389
+ note(trace, "goal: check a yes/no entailment by DL tableau refutation, citing what it rests on");
16390
+ if (!memoryDir) return mk("no memory store here — /prove works inside a repo session.", { miss: true });
16391
+ if (!argText) {
16392
+ return mk('/prove needs a question, e.g. `/prove is rex a dog` — a yes/no shape it can check by tableau refutation.', { miss: true });
16393
+ }
16394
+ const isaMatch = argText.match(ISA_ASK_RE);
16395
+ if (!isaMatch) {
16396
+ return mk('/prove only reads a yes/no shape today, e.g. "is rex a dog" or "is a stone a mammal".', { miss: true });
16397
+ }
16398
+ const subjectWord = isaMatch[1].trim();
16399
+ const classWord = isaMatch[2].trim();
16400
+ try {
16401
+ const { normFactTerm } = await import("../adapters/memory/core.mjs");
16402
+ const { extractTableauModule, buildTableauKb, proveEntailment, proveSubsumption } = await import("../domain/tableau.mjs");
16403
+ const rows = await factRows(memoryDir, cache);
16404
+ const subjectTerm = resolveProveTerm(factTermVariants(normFactTerm, subjectWord), rows, normFactTerm(subjectWord));
16405
+ const classTerm = resolveProveTerm(factTermVariants(normFactTerm, classWord), rows, normFactTerm(classWord));
16406
+ const reasoning = await resolveReasoningConfigForRepo(memoryDir);
16407
+ const proveOpts = { maxSteps: reasoning.proveSteps, maxBranches: reasoning.proveBranches, maxNodes: reasoning.proveNodes };
16408
+ const moduleRows = extractTableauModule(rows, [subjectTerm, classTerm]);
16409
+ const kb = buildTableauKb(moduleRows);
16410
+ const result = kb.namedIndividuals.has(subjectTerm)
16411
+ ? proveEntailment(kb, subjectTerm, { t: "atom", name: classTerm }, proveOpts)
16412
+ : proveSubsumption(kb, subjectTerm, classTerm, proveOpts);
16413
+ note(trace, `result: ${result.status} (steps ${result.steps}, branches ${result.branches})`);
16414
+ const byId = new Map(moduleRows.map((r) => [r.id, r]));
16415
+
16416
+ if (result.status === "proved") {
16417
+ const premiseRows = result.premises.map((id) => byId.get(id)).filter(Boolean);
16418
+ const cited = premiseRows.map(renderFactLine).join("; ");
16419
+ // A case-split conclusion (the ⊔-rule fired on a genuine owl:unionOf
16420
+ // or owl:oneOf premise, not just the ⊑-rule's own routine
16421
+ // TBox-internalization disjunction, which every proof passes
16422
+ // through) reads as reasoning by cases, not a single deduction.
16423
+ const caseSplit = premiseRows.some((r) => r.predicate === "owl:unionOf" || r.predicate === "owl:oneOf");
16424
+ const conclusion = caseSplit ? `in every case, ${subjectWord} is a ${classWord}.` : `so ${subjectWord} is a ${classWord}.`;
16425
+ return mk(`yes — ${cited}; ${conclusion}`);
16426
+ }
16427
+ if (result.status === "disproved") {
16428
+ // A genuine "no", not a miss: the tableau built a consistent model
16429
+ // where the entailment fails, and names the stored facts that model
16430
+ // had to satisfy along the way (every label on the queried
16431
+ // individual's own node, unioned across the branch it found).
16432
+ const node = (result.model?.nodes || []).find((n) => n.id === subjectTerm);
16433
+ const constrainingIds = [...new Set((node?.labels || []).flatMap((l) => l.from || []))].sort();
16434
+ const constrainingRows = constrainingIds.map((id) => byId.get(id)).filter(Boolean);
16435
+ const suffix = constrainingRows.length ? ` What I remember: ${constrainingRows.map(renderFactLine).join("; ")}.` : "";
16436
+ return mk(`no — I can build a consistent picture where ${subjectWord} is not a ${classWord}.${suffix}`);
16437
+ }
16438
+ // exhausted: the honest budget wall, never a downgraded guess. Names
16439
+ // the specific [reasoning] knob (tmct.toml) that ran out, so the
16440
+ // reply says exactly what to raise for a wider search.
16441
+ const knobByReason = { steps: "prove_steps", branches: "prove_branches", nodes: "prove_nodes" };
16442
+ const budgetByReason = { steps: reasoning.proveSteps, branches: reasoning.proveBranches, nodes: reasoning.proveNodes };
16443
+ const reason = knobByReason[result.reason] ? result.reason : "steps";
16444
+ const res = mk(
16445
+ `I can't prove or disprove that within my budget (${budgetByReason[reason]} ${reason}). Nothing was guessed. `
16446
+ + `Raise \`[reasoning] ${knobByReason[reason]}\` in tmct.toml for a wider search.`,
16447
+ { miss: true },
16448
+ );
16449
+ res.record.budgetExhausted = true;
16450
+ return res;
16451
+ } catch (e) {
16452
+ return mk(String(e?.message || e), { miss: true }); // a broken store reads as its own clean error
16453
+ }
16454
+ }
16455
+
16293
16456
  // /export <path> — write the whole memory store as JSONL, the SAME shape
16294
16457
  // `tmct memory --export` and the tmct_export cold tool already emit
16295
16458
  // (serializeFactsJsonl, export-jsonl.mjs) — so a chat session can take its
@@ -17403,7 +17566,7 @@ export async function runTurn(input, options = {}) {
17403
17566
  return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
17404
17567
  }
17405
17568
 
17406
- 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 } = {}) {
17569
+ 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, newsState = null, newsConfig = null, newsProviders = null, discourse = null, _noSplit = false, actingSubject = "player", codeDomainActive = null, laneVocab = null, domainPacks = null } = {}) {
17407
17570
  // Every game's tuning knobs (spider-fly's mass economy, guess-the-number's
17408
17571
  // bounds, the shared plan lane's search-depth cap) — a caller's own
17409
17572
  // gameConfig (chat-session.mjs resolves one per session from tmct.toml)
@@ -17495,7 +17658,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
17495
17658
  // an answer's typed content is in hand (runAsk, off the ask envelope's
17496
17659
  // `discourse` referents); the caller re-threads whatever comes back.
17497
17660
  const discourseHolder = { record: discourse ?? emptyDiscourseRecord() };
17498
- 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 };
17661
+ 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, newsState, newsConfig, newsProviders };
17499
17662
  // A DISPATCHED turn (count / slash-command / ask) becomes the new "last
17500
17663
  // answer" that why/say-more re-renders; a conversational turn does not.
17501
17664
  // Every dispatched turn's result passes through finish() here — the LAST
@@ -428,6 +428,11 @@ export function mudiiiSceneScript({ canvasId, statusId, gridSize, cellSize } = {
428
428
  var propTemplates = {};
429
429
  var propInstances = [];
430
430
  var manifestByKind = {};
431
+ // What the world's own fact rows say each agent is called and drawn as:
432
+ // { byId: { id: { label, model } }, byKind: { kind: { label, model } } },
433
+ // or null for a page that passed none. An agent the rows say nothing about
434
+ // keeps its id as the label and its id-prefix kind as the mesh.
435
+ var agentPresentation = null;
431
436
  var lastAgentsById = {};
432
437
  var lastItemsById = {};
433
438
  // Every removeAgent/removeItem call, kept small and reset on boot — an
@@ -828,7 +833,10 @@ export function mudiiiSceneScript({ canvasId, statusId, gridSize, cellSize } = {
828
833
  // than no id at all — which is why the scale below is in screen fractions
829
834
  // rather than world units.
830
835
  var LABEL_SCREEN_WIDTH = 0.13;
831
- function makeAgentLabel(id, height) {
836
+ // The label text is what the rows say to call the agent (its
837
+ // mgx:display-name, or its id when nothing is stated) — the caller
838
+ // resolves that; this only draws whatever it is handed.
839
+ function makeAgentLabel(label, height) {
832
840
  var canvas = document.createElement("canvas");
833
841
  canvas.width = 256;
834
842
  canvas.height = 64;
@@ -839,19 +847,25 @@ export function mudiiiSceneScript({ canvasId, statusId, gridSize, cellSize } = {
839
847
  ctx.lineWidth = 8;
840
848
  ctx.lineJoin = "round";
841
849
  ctx.strokeStyle = "rgba(20,16,10,.85)";
842
- ctx.strokeText(id, 128, 34);
850
+ ctx.strokeText(label, 128, 34);
843
851
  ctx.fillStyle = "#F3ECDD";
844
- ctx.fillText(id, 128, 34);
852
+ ctx.fillText(label, 128, 34);
845
853
  var material = new THREE.SpriteMaterial({
846
854
  map: new THREE.CanvasTexture(canvas), transparent: true, sizeAttenuation: false, depthWrite: false,
847
855
  });
848
856
  var sprite = new THREE.Sprite(material);
849
857
  sprite.scale.set(LABEL_SCREEN_WIDTH, LABEL_SCREEN_WIDTH / 4, 1);
850
858
  sprite.position.y = height + 0.3;
851
- sprite.name = "label-" + id;
852
859
  return sprite;
853
860
  }
854
861
 
862
+ function presentationFor(id, kind) {
863
+ if (!agentPresentation) return null;
864
+ var byId = agentPresentation.byId || {};
865
+ var byKind = agentPresentation.byKind || {};
866
+ return byId[id] || byKind[kind] || null;
867
+ }
868
+
855
869
  function ensureAgent(id, agent) {
856
870
  if (agentGroups[id]) return agentGroups[id];
857
871
  var kind = roleOfAgentId(id);
@@ -863,8 +877,20 @@ export function mudiiiSceneScript({ canvasId, statusId, gridSize, cellSize } = {
863
877
  entry.group.visible = false;
864
878
  scene.add(entry.group);
865
879
  agentGroups[id] = entry;
880
+ var pres = presentationFor(id, kind);
866
881
  var asset = manifestByKind[kind];
867
- entry.group.add(makeAgentLabel(id, asset ? asset.targetHeight : 1));
882
+ // A stated mgx:model wins over the id-prefix lookup — and a model name
883
+ // the manifest carries no key for falls back to the prefix and logs the
884
+ // miss, so an edit can never blank the board.
885
+ if (pres && pres.model) {
886
+ var statedAsset = manifestByKind[pres.model];
887
+ if (statedAsset) asset = statedAsset;
888
+ // eslint-disable-next-line no-console
889
+ else console.warn("tmct: no model named '" + pres.model + "' in the asset manifest — " + id + " keeps its " + kind + " mesh");
890
+ }
891
+ var labelSprite = makeAgentLabel(pres && pres.label ? pres.label : id, asset ? asset.targetHeight : 1);
892
+ labelSprite.name = "label-" + id;
893
+ entry.group.add(labelSprite);
868
894
  if (asset) {
869
895
  loadGlbRaw(modelUrlFor(asset.destPath)).then(function (gltf) {
870
896
  normalizeToHeight(gltf.scene, asset.targetHeight);
@@ -1133,6 +1159,7 @@ export function mudiiiSceneScript({ canvasId, statusId, gridSize, cellSize } = {
1133
1159
  clearFlash();
1134
1160
  removalLog = [];
1135
1161
  manifestByKind = buildManifestByKind(input && input.assetManifest);
1162
+ agentPresentation = (input && input.agentPresentation) || null;
1136
1163
  await placeProps((input && input.propPlacements) || []);
1137
1164
  cameraRigged = false;
1138
1165
  lookTarget = null;
@@ -27,6 +27,7 @@ import { worldProvenanceTag } from "../domain/worlds-pack.mjs";
27
27
  import { getWorldsPackProvider } from "../adapters/corpus/worlds-pack.mjs";
28
28
  import { appendFacts, appendRule, loadMemory, readFactRows } from "../adapters/memory/core.mjs";
29
29
  import { DEFAULT_GAME_CONFIG } from "../domain/game-config.mjs";
30
+ import { agentTraitsOf } from "../domain/agent-traits.mjs";
30
31
 
31
32
  const PREDATOR_KIND = MUDIII_ROLES.predator.kind; // "fox"
32
33
  const PREY_KIND = MUDIII_ROLES.prey.kind; // "goblin"
@@ -506,9 +507,12 @@ async function mudiiiBeliefAnswer(match, { memoryDir, gameConfig = DEFAULT_GAME_
506
507
  ...liveIdsOfKind(state.placements, SPAWNED_FOOD_KIND, state.removed),
507
508
  ...liveIdsOfKind(state.placements, PLACED_FOOD_KIND, state.removed),
508
509
  ];
509
- const visionRadius = role === "predator"
510
- ? gameConfig?.mudiii?.predatorVisionRadius
511
- : gameConfig?.mudiii?.preyVisionRadius;
510
+ // The same trait-first read the tick engine performs: the observer's own
511
+ // mgx:vision-radius (or its class's) decides what it can see, and the
512
+ // config number covers a board whose rows state none — two readers of one
513
+ // question must not drift.
514
+ const visionRadius = agentTraitsOf(rows, observerId).visionRadius
515
+ ?? (role === "predator" ? gameConfig?.mudiii?.predatorVisionRadius : gameConfig?.mudiii?.preyVisionRadius);
512
516
  const belief = beliefSnapshotFor(observerId, observerCell, candidateIds, state, { visionRadius });
513
517
  const text = beliefLineFor(observerId, Object.entries(belief), taughtPlacementSubjects(rows, state.epoch));
514
518
  return {