@polycode-projects/the-mechanical-code-talker 5.0.27 → 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 (30) 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 +1 -1
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-traits.mjs +282 -0
  14. package/src/domain/choice-question.mjs +135 -6
  15. package/src/domain/el-classify.mjs +39 -7
  16. package/src/domain/fact-phrase.mjs +7 -4
  17. package/src/domain/interpret/normalize.mjs +58 -2
  18. package/src/domain/town-square-world.mjs +44 -19
  19. package/src/services/adventure.mjs +5 -16
  20. package/src/services/agent-editor.mjs +216 -0
  21. package/src/services/chat-session.mjs +26 -5
  22. package/src/services/chat.mjs +118 -58
  23. package/src/services/mudiii-scene.mjs +32 -5
  24. package/src/services/mudiii-turn.mjs +7 -3
  25. package/src/services/mudiii-viz.mjs +215 -1
  26. package/src/services/predator-prey.mjs +157 -24
  27. package/src/surfaces/web/chat-browser-entry.mjs +69 -3
  28. package/src/surfaces/web/memory-ask-browser.bundle.js +155 -155
  29. package/src/surfaces/web/mudiii-browser-entry.mjs +35 -0
  30. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -31,6 +31,7 @@ import { resolveGameConfig } from "../domain/game-config.mjs";
31
31
  import { emptyRecord, resolveDiscourseConfig } from "../domain/discourse.mjs";
32
32
  import { resolveRecognitionConfig } from "../domain/router/recognize.mjs";
33
33
  import { resolveResearchConfig } from "./research.mjs";
34
+ import { resolveNewsConfig } from "./news.mjs";
34
35
  import { normalizeResearchChoice } from "../adapters/corpus/research-source.mjs";
35
36
  import { sessionLogHeaderMarkdown, sessionLogTurnMarkdown, sessionLogEndMarkdown } from "./session-log-format.mjs";
36
37
 
@@ -134,6 +135,15 @@ export async function createSession({
134
135
  // --research-source`) > tmct.toml's [research] source > "wikipedia".
135
136
  // Omitted (null) defers entirely to the toml/default tier.
136
137
  researchSource = null,
138
+ // The /news command's fetcher/research-provider set for this session —
139
+ // `{ newsFetchers, getResearchProvider, preflightNewsUrl }` (news.mjs's own
140
+ // ctx.providers shape). Omitted (the default) leaves it to runCommand's own
141
+ // fallback (KB enrichment through the shared research provider, contemporary
142
+ // polling reporting an honest "no-fetcher" per source). The seam a caller —
143
+ // a test, or a host embedding tmct with its own source set — hands in a
144
+ // fixed provider set without touching the network, the same way
145
+ // registerResearchProvider does for the research lane.
146
+ newsProviders = null,
137
147
  // The storage-backend seam: the default (empty or "default") resolves to
138
148
  // Backend C — the sqlite store at .tmct/memory/graph.sqlite, a live
139
149
  // node:sqlite connection lazily imported on open. The flat-file Backend A is
@@ -255,6 +265,12 @@ export async function createSession({
255
265
  // resolved once per session from the same tmct.toml, defaults filling
256
266
  // every unset key exactly as resolveGameConfig does above.
257
267
  const researchConfig = resolveResearchConfig(toml);
268
+ // The news lane's knobs (enabled sources, poll/enrich cadence, the
269
+ // enrichment/negative-cache budgets) — resolved once per session, the same
270
+ // way researchConfig is above. Threaded into every runTurn call as a
271
+ // stable, mutable object, so a `/news add`/`/news interval` mutation
272
+ // persists turn to turn by reference (see runCommand's own /news branch).
273
+ const newsConfig = resolveNewsConfig(toml);
258
274
  // This session's starting research source: the flag tier (`researchSource`,
259
275
  // e.g. `tmct chat --research-source`) over the toml tier over the shipped
260
276
  // default — /wikipedia|/wikidata in chat mutate this turn-to-turn below,
@@ -484,6 +500,7 @@ export async function createSession({
484
500
  // starting null and waiting for a "play <world>" opener line.
485
501
  let planState = adventureWorld ? { adventure: { world: adventureWorld } } : null;
486
502
  let researchState = null; // the in-progress research queue — advanced by "research next", cleared by completion or "research stop"
503
+ let newsState = null; // the news feed's session state (items/ledger/health/requestLog/metrics) — threaded the same way researchState is
487
504
  // The typed discourse record ([discourse] max_referents caps it) — session-scoped
488
505
  // like the focus, threaded turn to turn, never persisted.
489
506
  let discourseRecord = emptyRecord(resolveDiscourseConfig(toml));
@@ -506,6 +523,7 @@ export async function createSession({
506
523
  get lastAnswer() { return last; },
507
524
  get planState() { return planState; },
508
525
  get researchState() { return researchState; },
526
+ get newsState() { return newsState; },
509
527
  get turns() { return turns; },
510
528
  get narrate() { return narrateOn; },
511
529
  get liveReference() { return liveReferenceOn; },
@@ -514,13 +532,15 @@ export async function createSession({
514
532
 
515
533
  /** One dispatched turn through the FULL sink sequencing (writeLog → writeSidecar
516
534
  * → telemetry → upsertGraph, in that exact order). Returns { answer, end, prompt,
517
- * plan, record } — record is the same sidecar turn record the session persists.
518
- * A throwing runTurn must never abort the session: a piped/non-interactive
519
- * driver has no other chance to see this turn's answer. */
535
+ * plan, record, factsTouched } — record is the same sidecar turn record the
536
+ * session persists, and factsTouched is runTurn's own diffed Fact-row list
537
+ * (empty when the turn wrote nothing). A throwing runTurn must never abort
538
+ * the session: a piped/non-interactive driver has no other chance to see
539
+ * this turn's answer. */
520
540
  async turn(line) {
521
541
  let result;
522
542
  try {
523
- result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
543
+ result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
524
544
  } catch (e) {
525
545
  const ts = new Date().toISOString();
526
546
  const message = e instanceof Error ? e.message : String(e);
@@ -542,6 +562,7 @@ export async function createSession({
542
562
  last = nextLast;
543
563
  if ("planState" in result) planState = result.planState;
544
564
  if ("researchState" in result) researchState = result.researchState;
565
+ if ("newsState" in result) newsState = result.newsState;
545
566
  if ("discourse" in result) discourseRecord = result.discourse;
546
567
  // /narrate on|off and /wiki on|off (runCommand) ride the turn RESULT the
547
568
  // same way a focus update does — apply them to this handle's
@@ -564,7 +585,7 @@ export async function createSession({
564
585
  });
565
586
  await upsertGraph(record.ts);
566
587
  turns += 1;
567
- return { answer, end: Boolean(end), prompt: promptFor(focus), plan: result.plan ?? null, research: result.research, record };
588
+ return { answer, end: Boolean(end), prompt: promptFor(focus), plan: result.plan ?? null, research: result.research, record, factsTouched: result.factsTouched };
568
589
  },
569
590
 
570
591
  /** End-of-session close: end lines in both artifacts, the final graph upsert
@@ -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";
@@ -7493,6 +7501,7 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7493
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"],
7494
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"],
7495
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"],
7496
7505
  ["/help", "this list"],
7497
7506
  ["/exit", "leave the session (also Ctrl+C / Ctrl+D)"],
7498
7507
  ];
@@ -7644,60 +7653,6 @@ async function recallFromBlocks(memoryDir, query, graph) {
7644
7653
 
7645
7654
  // ---- W4: asserted Facts → answers (the memory graph's reified triples) ----
7646
7655
 
7647
- /** How a stored fact predicate reads in English — one phrase per predicate the
7648
- * two writers (the ACE grammar, the ConceptNet map) actually emit. An unknown
7649
- * predicate renders verbatim rather than being guessed around. */
7650
- const FACT_PREDICATE_PHRASES = {
7651
- "rdfs:subClassOf": "is a kind of",
7652
- "mgxneg:subClassOf": "is not a kind of",
7653
- "rdf:type": "is a",
7654
- "owl:disjointWith": "is not a",
7655
- "owl:unionOf": "is either",
7656
- "owl:complementOf": "is anything that is not",
7657
- "owl:oneOf": "includes exactly",
7658
- "owl:differentFrom": "is not the same as",
7659
- "mgx:partOf": "is part of",
7660
- "mgx:memberOf": "is a member of",
7661
- "mgx:collectionOf": "is a collection of",
7662
- "mgx:hasA": "has",
7663
- "mgx:usedFor": "is used for",
7664
- "mgx:capableOf": "can",
7665
- "mgx:atLocation": "is found in",
7666
- "mgx:causes": "causes",
7667
- "mgx:hasProperty": "is",
7668
- "mgx:madeOf": "is made of",
7669
- "mgx:receivesAction": "can be",
7670
- "mgx:createdBy": "is created by",
7671
- "mgx:mannerOf": "is a way to",
7672
- "mgx:desires": "wants",
7673
- "mgx:locatedNear": "is typically near",
7674
- "mgx:motivatedByGoal": "is motivated by",
7675
- "mgx:obstructedBy": "can be prevented by",
7676
- "mgx:causesDesire": "makes you want to",
7677
- "mgx:hasSubevent": "involves",
7678
- "mgx:hasFirstSubevent": "begins with",
7679
- "mgx:hasLastSubevent": "ends with",
7680
- "mgx:hasPrerequisite": "requires",
7681
- "mgx:ownedBy": "is owned by", // the teach lane's ownership frame ("Priya owns tasks.mjs")
7682
- "mgx:rendersAs": "renders as", // the render-template binding ("a disk renders as a block")
7683
- "mgx:synonym": "means the same as",
7684
- "mgx:antonym": "is the opposite of",
7685
- "mgx:similarTo": "is similar to",
7686
- "mgx:relatedTo": "is related to",
7687
- "mgx:symbolOf": "is a symbol of",
7688
- // A loaded adventure world's placement predicates, so a describe read-back of
7689
- // a visible prop reads as English ("lamp is in the study") instead of the
7690
- // mechanical -s fold garbling them ("lamp locateds in study"). The world's
7691
- // SECRET/mechanics predicates (a hidden object's location, the objective
7692
- // marker, the lock/open/NPC internals) are kept out of the describe lane
7693
- // entirely by WORLD_INTERNAL_PREDICATES below, so they never render at all.
7694
- "mgx:currently-in": "is in",
7695
- "mgx:located-in": "is in",
7696
- "mgx:fixed-in": "is fixed in",
7697
- "mgx:stands-locked-in": "stands locked in",
7698
- "mgx:works-in": "works in",
7699
- };
7700
-
7701
7656
  /** The world-mechanics predicates the generic describe read-back must never
7702
7657
  * surface: a hidden object's location and the objective marker spoil the
7703
7658
  * puzzle, and the lock/container/open/NPC-schedule flags are datatype internals
@@ -9005,6 +8960,53 @@ async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fill
9005
8960
  return null;
9006
8961
  }
9007
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
+
9008
9010
  async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle = {}, cache = null, focusLabel = null) {
9009
9011
  let normFactTerm; let normFactPredicate;
9010
9012
  try { ({ normFactTerm, normFactPredicate } = await import("../adapters/memory/core.mjs")); } catch { return null; }
@@ -9480,6 +9482,18 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9480
9482
  const obj = factTermVariants(normFactTerm, m[2]);
9481
9483
  const hit = facts.find((f) => f.predicate === predicate && subj.has(f.subject) && obj.has(f.object));
9482
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
+ }
9483
9497
  const teachHint = FORWARD_YESNO_TEACHABLE.has(predicate) ? ` If it's true, teach me: "${m[1]} ${phrase} ${m[2]}".` : "";
9484
9498
  const sameRelation = facts.filter((f) => f.predicate === predicate && subj.has(f.subject));
9485
9499
  if (sameRelation.length) {
@@ -10012,6 +10026,17 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10012
10026
  };
10013
10027
  }
10014
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 };
10015
10040
  // echo the STORED spelling ("caches" asked → "cache" known), never a guess
10016
10041
  const literalHit = hits.find((f) => variants.has(f.subject) || variants.has(f.object));
10017
10042
  const term = literalHit
@@ -15971,6 +15996,7 @@ const GOAL_BY_COMMAND = {
15971
15996
  wikidata: "choose which source the research lane fetches from",
15972
15997
  export: "write the memory store to a file, in the standard JSONL shape",
15973
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",
15974
16000
  };
15975
16001
 
15976
16002
  /** A slash-command → the mapped tool (or the /help, /focus, /narrate, unknown
@@ -16045,12 +16071,12 @@ export function renderDeclaredGoals(goals) {
16045
16071
  return lines.join("\n").replace(/\n+$/, "");
16046
16072
  }
16047
16073
 
16048
- 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 }) {
16049
16075
  const ts = new Date().toISOString();
16050
16076
  const sp = line.indexOf(" ");
16051
16077
  const name = (sp === -1 ? line.slice(1) : line.slice(1, sp)).toLowerCase();
16052
16078
  const argText = (sp === -1 ? "" : line.slice(sp + 1)).trim();
16053
- const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext, researchSourceNext } = {}) => ({
16079
+ const mk = (answer, { resolvedIds = [], miss = false, newFocus = focus, narrateNext, liveReferenceNext, researchSourceNext, newsStateNext } = {}) => ({
16054
16080
  answer,
16055
16081
  logLines: [ts, `> ${line}`, answer, ""],
16056
16082
  record: { type: "turn", ts, query: line, command: name, via: "command", resolvedIds, answeredIds: [], miss },
@@ -16059,6 +16085,7 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
16059
16085
  ...(narrateNext !== undefined ? { narrate: narrateNext } : {}),
16060
16086
  ...(liveReferenceNext !== undefined ? { liveReference: liveReferenceNext } : {}),
16061
16087
  ...(researchSourceNext !== undefined ? { researchSource: researchSourceNext } : {}),
16088
+ ...(newsStateNext !== undefined ? { newsState: newsStateNext } : {}),
16062
16089
  });
16063
16090
 
16064
16091
  if (name === "help") { note(trace, "goal: get oriented / learn available commands"); return mk(await helpText(codeDomainActive, codeDomainActive ? laneVocab?.helpRows : [])); }
@@ -16125,6 +16152,39 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
16125
16152
  );
16126
16153
  }
16127
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
+
16128
16188
  // /memory [verbose] — what tmct remembers, as text (the same renderer
16129
16189
  // serves the `tmct memory` CLI).
16130
16190
  if (name === "memory") {
@@ -17506,7 +17566,7 @@ export async function runTurn(input, options = {}) {
17506
17566
  return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
17507
17567
  }
17508
17568
 
17509
- 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 } = {}) {
17510
17570
  // Every game's tuning knobs (spider-fly's mass economy, guess-the-number's
17511
17571
  // bounds, the shared plan lane's search-depth cap) — a caller's own
17512
17572
  // gameConfig (chat-session.mjs resolves one per session from tmct.toml)
@@ -17598,7 +17658,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
17598
17658
  // an answer's typed content is in hand (runAsk, off the ask envelope's
17599
17659
  // `discourse` referents); the caller re-threads whatever comes back.
17600
17660
  const discourseHolder = { record: discourse ?? emptyDiscourseRecord() };
17601
- 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 };
17602
17662
  // A DISPATCHED turn (count / slash-command / ask) becomes the new "last
17603
17663
  // answer" that why/say-more re-renders; a conversational turn does not.
17604
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 {