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

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 -2
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-belief.mjs +33 -11
  14. package/src/domain/agent-traits.mjs +282 -0
  15. package/src/domain/choice-question.mjs +259 -6
  16. package/src/domain/el-classify.mjs +55 -7
  17. package/src/domain/fact-phrase.mjs +7 -4
  18. package/src/domain/grammar/ace.mjs +66 -3
  19. package/src/domain/interpret/normalize.mjs +58 -2
  20. package/src/domain/tableau.mjs +101 -14
  21. package/src/domain/town-square-world.mjs +44 -19
  22. package/src/services/adventure.mjs +5 -16
  23. package/src/services/agent-editor.mjs +216 -0
  24. package/src/services/chat-session.mjs +26 -5
  25. package/src/services/chat.mjs +118 -58
  26. package/src/services/mudiii-scene.mjs +32 -5
  27. package/src/services/mudiii-turn.mjs +120 -5
  28. package/src/services/mudiii-viz.mjs +299 -1
  29. package/src/services/predator-prey.mjs +234 -57
  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 +48 -2
  33. package/src/surfaces/web/planner-instances.mjs +64 -3
  34. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -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;
@@ -18,15 +18,21 @@ import {
18
18
  agentKindOf, liveIdsOfKind, layoutNamed, isFoodId,
19
19
  } from "../domain/town-square-world.mjs";
20
20
  import {
21
- MUDIII_ROLES, foldTownSquareState, startTownSquareGame, runTownSquareTick,
21
+ MUDIII_ROLES, foldTownSquareState, startTownSquareGame, runTownSquareTick, planTownSquareTurn,
22
22
  placeFood, roleOfId, beliefSnapshotFor,
23
23
  } from "./predator-prey.mjs";
24
24
  import { snapshotSubject, parseSnapshotSubject } from "./adventure.mjs";
25
25
  import { correctMisspellings, QUESTION_LEAD_RE } from "../domain/interpret/normalize.mjs";
26
26
  import { worldProvenanceTag } from "../domain/worlds-pack.mjs";
27
27
  import { getWorldsPackProvider } from "../adapters/corpus/worlds-pack.mjs";
28
- import { appendFacts, appendRule, loadMemory, readFactRows } from "../adapters/memory/core.mjs";
28
+ import { appendFacts, appendRule, loadMemory, readFactRows, readRuleRows } from "../adapters/memory/core.mjs";
29
29
  import { DEFAULT_GAME_CONFIG } from "../domain/game-config.mjs";
30
+ import { agentTraitsOf, constraintsFromDrives } from "../domain/agent-traits.mjs";
31
+ import { beliefOriginOf } from "../domain/agent-belief.mjs";
32
+ import {
33
+ compileDomain, stateFromFacts, stateKeyFor, movesFromRules, compileGoal, PlanBudgetError,
34
+ } from "../domain/domain.mjs";
35
+ import { findActionPath } from "../domain/planning.mjs";
30
36
 
31
37
  const PREDATOR_KIND = MUDIII_ROLES.predator.kind; // "fox"
32
38
  const PREY_KIND = MUDIII_ROLES.prey.kind; // "goblin"
@@ -506,9 +512,12 @@ async function mudiiiBeliefAnswer(match, { memoryDir, gameConfig = DEFAULT_GAME_
506
512
  ...liveIdsOfKind(state.placements, SPAWNED_FOOD_KIND, state.removed),
507
513
  ...liveIdsOfKind(state.placements, PLACED_FOOD_KIND, state.removed),
508
514
  ];
509
- const visionRadius = role === "predator"
510
- ? gameConfig?.mudiii?.predatorVisionRadius
511
- : gameConfig?.mudiii?.preyVisionRadius;
515
+ // The same trait-first read the tick engine performs: the observer's own
516
+ // mgx:vision-radius (or its class's) decides what it can see, and the
517
+ // config number covers a board whose rows state none — two readers of one
518
+ // question must not drift.
519
+ const visionRadius = agentTraitsOf(rows, observerId).visionRadius
520
+ ?? (role === "predator" ? gameConfig?.mudiii?.predatorVisionRadius : gameConfig?.mudiii?.preyVisionRadius);
512
521
  const belief = beliefSnapshotFor(observerId, observerCell, candidateIds, state, { visionRadius });
513
522
  const text = beliefLineFor(observerId, Object.entries(belief), taughtPlacementSubjects(rows, state.epoch));
514
523
  return {
@@ -518,6 +527,112 @@ async function mudiiiBeliefAnswer(match, { memoryDir, gameConfig = DEFAULT_GAME_
518
527
  };
519
528
  }
520
529
 
530
+ // ---- beliefs and plans, recomputed live, no turn spent ----------------------
531
+
532
+ // The one puzzle this plan ships (PLAN_RIVER_CROSSING.md's R3): a world that
533
+ // carries no "ferry onto" action-signature has no puzzle plan to compute, so
534
+ // riverPuzzleOutlook stays null on the town square and any other board with
535
+ // no ferry action rule.
536
+ const RIVER_CROSSING_ACTION = "ferry onto";
537
+ const RIVER_CROSSING_GOAL = [{ universal: true, term: "passenger", predicate: "currently-in", object: "bank-west" }];
538
+
539
+ /** The river-crossing puzzle's own plan, recomputed from `rows`/`ruleRows` as
540
+ * they stand right now: the world's own action rules plus whatever
541
+ * action-constraint rows the drive facts themselves imply
542
+ * (constraintsFromDrives), searched the same way the chat lane solves
543
+ * data/games/river.txt. Null on a world whose rule rows carry no "ferry
544
+ * onto" action-signature, or whose action domain does not carry a
545
+ * "passenger" class the goal can quantify over. Returns `{ moves, plan,
546
+ * miss }`: `moves` is every legal move from the CURRENT position (the empty
547
+ * list when nothing may move), `plan` is the found action sequence or null,
548
+ * `miss` is null when a plan was found and the stated reason otherwise — a
549
+ * budget decline as well as an exhausted search, never a shortened plan
550
+ * either way. Pure. */
551
+ function riverPuzzleOutlook(rows, ruleRows) {
552
+ const hasFerryAction = (ruleRows || []).some((r) => r.kind === "action-signature" && r.name === RIVER_CROSSING_ACTION);
553
+ if (!hasFerryAction) return null;
554
+ const derived = constraintsFromDrives(rows).map((slots) => ({ name: RIVER_CROSSING_ACTION, kind: "action-constraint", slots }));
555
+ const domain = compileDomain(rows, [...(ruleRows || []), ...derived]);
556
+ let isGoal;
557
+ try {
558
+ isGoal = compileGoal(RIVER_CROSSING_GOAL, domain);
559
+ } catch {
560
+ return null; // this board's action domain is not the river puzzle's own shape
561
+ }
562
+ const start = stateFromFacts(rows, domain);
563
+ const moves = movesFromRules(start, domain).map((m) => m.action.label);
564
+ const maxDepth = DEFAULT_GAME_CONFIG.planning.maxDepth;
565
+ try {
566
+ const found = findActionPath(start, isGoal, (s) => movesFromRules(s, domain), { maxDepth, stateKey: stateKeyFor });
567
+ return { moves, plan: found ? found.actions : null, miss: found ? null : `no plan found within ${maxDepth} moves` };
568
+ } catch (err) {
569
+ if (!(err instanceof PlanBudgetError)) throw err;
570
+ return { moves, plan: null, miss: `action grounding count ${err.groundings} exceeds the budget of ${err.budget}` };
571
+ }
572
+ }
573
+
574
+ /** Every live agent's belief map and plan, computed from the store as it
575
+ * stands right now, without writing a fact or advancing a turn. Runs the
576
+ * SAME derivation runTownSquareTick's own decision phase performs
577
+ * (predator-prey.mjs's planTownSquareTurn) and reads only the answers — the
578
+ * rung, the goal line, the belief snapshot and the plan each live agent
579
+ * would carry into its NEXT tick — never a tick's effects (no eating, no
580
+ * spawn, no mass debit, no write).
581
+ *
582
+ * `layout` is optional here (unlike runTownSquareTick, which requires one):
583
+ * a board with no town-square roster to decide over — the puzzle world
584
+ * before R6 wires it to a layout, or a caller asking only about `puzzle` —
585
+ * still gets its `puzzle` field computed, with `agents` empty rather than a
586
+ * thrown "no such layout".
587
+ *
588
+ * Returns `{ turn, agents: { id: { rung, goal, belief, beliefOrigin, plan,
589
+ * traits } }, puzzle: { moves, plan, miss } | null }`. `beliefOrigin` mirrors
590
+ * `belief`'s own key set, each value `"seen"`, `{ told: turn }` or null —
591
+ * `beliefOriginOf` walking the exact cell/candidates/opts the tick's own
592
+ * belief snapshot was taken with (planTownSquareTurn's `beliefContext`), so
593
+ * a panel's cell and its "how it knows" label can never disagree.
594
+ *
595
+ * Deterministic: a pure function of the store's current rows (and
596
+ * `toldFacts`), whatever order either arrived in. Two calls with no edit
597
+ * between them, or the same rows fed in twice in a different order, return
598
+ * deep-equal results. */
599
+ export async function agentOutlook(memoryDir, {
600
+ layout = null, toldFacts = [], config = DEFAULT_GAME_CONFIG.mudiii, roles = MUDIII_ROLES,
601
+ } = {}) {
602
+ const memory = await loadMemory(memoryDir);
603
+ const rows = readFactRows(memory);
604
+ const ruleRows = readRuleRows(memory);
605
+ const state = foldTownSquareState(rows);
606
+
607
+ const outlookAgents = {};
608
+ if (layout) {
609
+ const { agents, rungs, beliefContext, traitRows } =
610
+ planTownSquareTurn(rows, state, { layout, config, roles, toldFacts, manualMoves: {} });
611
+ for (const id of Object.keys(agents).sort()) {
612
+ const ctx = beliefContext[id];
613
+ const beliefOrigin = {};
614
+ for (const candidateId of ctx.candidates) {
615
+ if (candidateId === id) continue;
616
+ beliefOrigin[candidateId] = beliefOriginOf(candidateId, id, ctx.cell, state, ctx.opts);
617
+ }
618
+ for (const candidateId of ctx.foodCandidates) {
619
+ if (candidateId === id) continue;
620
+ beliefOrigin[candidateId] = beliefOriginOf(candidateId, id, ctx.cell, state, ctx.foodOpts);
621
+ }
622
+ outlookAgents[id] = {
623
+ rung: rungs[id],
624
+ goal: agents[id].goal,
625
+ belief: agents[id].belief,
626
+ beliefOrigin,
627
+ plan: agents[id].plan,
628
+ traits: agentTraitsOf(traitRows, id),
629
+ };
630
+ }
631
+ }
632
+
633
+ return { turn: state.tickCount, agents: outlookAgents, puzzle: riverPuzzleOutlook(rows, ruleRows) };
634
+ }
635
+
521
636
  function noLivePlacedSubjectAnswer(kind) {
522
637
  return {
523
638
  text: `there's no live ${kind} on the board for that to be about.`,
@@ -717,6 +717,25 @@ ${RING_POINTS.map((point) => ` <span class="dir-slot dir-${point}"><button
717
717
  </section>
718
718
  </aside>
719
719
  </div>
720
+ <section class="actor-card" id="mudiiiActorCard" aria-label="the followed actor's own facts">
721
+ <div class="actor-tabs" role="tablist" aria-label="edit this actor alone, or its whole class">
722
+ <button type="button" id="actorTabInstance" class="actor-tab" role="tab" aria-selected="true">this actor</button>
723
+ <button type="button" id="actorTabClass" class="actor-tab" role="tab" aria-selected="false">its whole class</button>
724
+ </div>
725
+ <p class="edit-lede" id="actorCardLede">Follow an agent to edit what it wants — the class tab changes every one that has not been edited on its own, and the next one spawned; this tab changes only the one selected above.</p>
726
+ <textarea id="actorEditorText" spellcheck="false" aria-label="the followed actor's own facts as plain sentences, one per line"></textarea>
727
+ <div class="chatpills" id="actorEditorPills" aria-label="related words for the term before the cursor"></div>
728
+ <p class="edit-status" id="actorEditorStatus" role="status"></p>
729
+ </section>
730
+ <section class="outlook-panel" id="mudiiiOutlookPanel" aria-label="the followed actor's own beliefs and plan">
731
+ <h2>what it believes, and its plan</h2>
732
+ <table class="outlook-belief-table" id="outlookBeliefTable" aria-label="what the followed actor currently believes">
733
+ <caption>beliefs</caption>
734
+ <tbody id="outlookBeliefBody"></tbody>
735
+ </table>
736
+ <p class="outlook-plan" id="outlookPlanText" role="status"></p>
737
+ <p class="outlook-plan outlook-puzzle-plan" id="outlookPuzzlePlanText" role="status" hidden></p>
738
+ </section>
720
739
  <section class="mudiii-chat" aria-label="talk to the square">
721
740
  <div class="chatlog" id="chatLog" aria-live="polite"></div>
722
741
  <div class="log-popup" id="chatLogPopup" role="dialog" aria-label="the whole reply" hidden>
@@ -964,6 +983,35 @@ const MUDIII_STYLE = `
964
983
  .edit-placement-row { display: flex; gap: .4rem; }
965
984
  .edit-empty { font-size: .74rem; font-style: italic; color: var(--square-stone-dark); }
966
985
 
986
+ .actor-card {
987
+ display: none; flex-direction: column; gap: .45rem; margin-bottom: 1rem;
988
+ background: var(--parchment); border: 1px solid var(--square-stone-dark); border-radius: 4px;
989
+ box-shadow: 0 2px 0 rgba(0,0,0,.18); padding: .7rem .8rem; min-width: 0;
990
+ }
991
+ body.editing .actor-card { display: flex; }
992
+ .actor-tabs { display: flex; gap: .35rem; }
993
+ .actor-tab { font-family: ${MONO_STACK}; font-size: .68rem; padding: .22rem .6rem; border: 1px solid var(--square-stone-dark); border-radius: 3px; background: rgba(255,255,255,.5); }
994
+ .actor-tab[aria-selected="true"] { background: var(--square-accent); border-color: var(--square-accent); }
995
+ #actorEditorText {
996
+ width: 100%; box-sizing: border-box; min-height: 12rem; resize: vertical;
997
+ font-family: ${MONO_STACK}; font-size: .74rem; line-height: 1.6;
998
+ color: var(--square-ink); background: rgba(255,255,255,.6);
999
+ border: 1px solid var(--square-stone-dark); border-radius: 3px; padding: .55rem .6rem;
1000
+ }
1001
+ #actorEditorText:disabled { opacity: .55; }
1002
+
1003
+ .outlook-panel {
1004
+ display: none; flex-direction: column; gap: .45rem; margin-bottom: 1rem;
1005
+ background: var(--parchment); border: 1px solid var(--square-stone-dark); border-radius: 4px;
1006
+ box-shadow: 0 2px 0 rgba(0,0,0,.18); padding: .7rem .8rem; min-width: 0;
1007
+ }
1008
+ body.editing .outlook-panel { display: flex; }
1009
+ .outlook-panel h2 { margin: 0; font-size: .8rem; }
1010
+ .outlook-belief-table { width: 100%; border-collapse: collapse; font-family: ${MONO_STACK}; font-size: .68rem; }
1011
+ .outlook-belief-table caption { caption-side: top; text-align: left; font-size: .62rem; color: var(--square-stone-dark); padding-bottom: .2rem; }
1012
+ .outlook-belief-table td { padding: .12rem .4rem .12rem 0; vertical-align: top; }
1013
+ .outlook-plan { margin: 0; font-family: ${MONO_STACK}; font-size: .68rem; white-space: pre-wrap; color: var(--square-ink); }
1014
+
967
1015
  .mudiii-chat { background: var(--parchment); border: 1px solid var(--square-stone-dark); border-radius: 4px; box-shadow: 0 2px 0 rgba(0,0,0,.18); padding: .7rem .8rem; display: flex; flex-direction: column; gap: .5rem; }
968
1016
  .chatlog { min-height: 8rem; max-height: 16rem; overflow-y: auto; }
969
1017
  .chatlog > * { margin: 0 0 .32rem; }
@@ -1575,6 +1623,7 @@ function pageScript() {
1575
1623
  camera = { mode: mode, selectedId: id, status: null };
1576
1624
  renderCameraButtons();
1577
1625
  renderDriveRing();
1626
+ if (editing) { renderActorEditor(); renderOutlookPanel(); }
1578
1627
  sendCameraToScene(camera);
1579
1628
  });
1580
1629
 
@@ -1669,6 +1718,42 @@ function pageScript() {
1669
1718
  // mud.html's burrow-survey SVG, since a town square is a grid, not a room
1670
1719
  // graph.
1671
1720
  function worldOnlyRows(rows) { return rowsForWorld(rows, scenario().worldPayload.name); }
1721
+
1722
+ // What the rows say each agent is called (mgx:display-name) and drawn as
1723
+ // (mgx:model), resolved through the class chain so a class row covers every
1724
+ // instance, a mid-play arrival included. Null when the rows state neither
1725
+ // for anything — the scene then keeps ids and prefix meshes, the honest
1726
+ // fallback for a world that names nobody.
1727
+ function agentPresentationFrom(rows) {
1728
+ var traitsOf = window.tmct && window.tmct.page && window.tmct.page.agentTraitsOf;
1729
+ if (!traitsOf) return null;
1730
+ var kinds = {};
1731
+ var instanceIds = {};
1732
+ var presentedPredicates = { "mgx:display-name": true, "mgx:model": true };
1733
+ (rows || []).forEach(function (row) {
1734
+ if (!row || !row.subject || row.subject.indexOf("@") !== -1) return;
1735
+ if (row.predicate === "rdf:type" && /-\d+$/.test(row.subject)) {
1736
+ kinds[row.object] = true;
1737
+ instanceIds[row.subject] = true;
1738
+ return;
1739
+ }
1740
+ if (!presentedPredicates[row.predicate]) return;
1741
+ if (/-\d+$/.test(row.subject)) instanceIds[row.subject] = true;
1742
+ else kinds[row.subject] = true;
1743
+ });
1744
+ var byKind = {};
1745
+ var byId = {};
1746
+ var any = false;
1747
+ var take = function (bag, key) {
1748
+ var traits = traitsOf(rows, key);
1749
+ if (!traits.displayName && !traits.model) return;
1750
+ bag[key] = { label: traits.displayName, model: traits.model };
1751
+ any = true;
1752
+ };
1753
+ Object.keys(kinds).forEach(function (kind) { take(byKind, kind); });
1754
+ Object.keys(instanceIds).forEach(function (id) { take(byId, id); });
1755
+ return any ? { byId: byId, byKind: byKind } : null;
1756
+ }
1672
1757
  let editRows = [];
1673
1758
  // The FULL store, not the world's own rows: a term's synonyms and its is-a
1674
1759
  // chain mostly live in the background corpus, not in the square's vocabulary.
@@ -1699,6 +1784,8 @@ function pageScript() {
1699
1784
  el("editorStatus").textContent = "";
1700
1785
  renderSuggestionPills();
1701
1786
  renderEditPlacements();
1787
+ renderActorEditor();
1788
+ await refreshOutlook();
1702
1789
  }
1703
1790
 
1704
1791
  function exitEditMode() {
@@ -1772,6 +1859,7 @@ function pageScript() {
1772
1859
  }
1773
1860
  await callScene("boot", {
1774
1861
  propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1,
1862
+ agentPresentation: agentPresentationFrom(allStoreRows.length ? allStoreRows : editRows),
1775
1863
  });
1776
1864
  sendCameraToScene(camera);
1777
1865
  callScene("applyTick", { agents: agentsById, items: itemsById, ecology: [] });
@@ -1798,6 +1886,212 @@ function pageScript() {
1798
1886
  : "synced \\u2014 no change.";
1799
1887
  }
1800
1888
  renderEditPlacements();
1889
+ await refreshOutlook();
1890
+ }
1891
+
1892
+ // ---- actor card (per-instance edit) -------------------------------------
1893
+ // A second, disjoint sentence table beside the world editor's own: this
1894
+ // card edits whichever agent #agentSelect currently follows, alone,
1895
+ // through agent-editor.mjs's AGENT_TRAIT_PREDICATES rather than
1896
+ // mud-editor.mjs's placement/class/exit/dig vocabulary. "this <kind>"
1897
+ // writes to the instance id; "every <kind>" writes to the class name,
1898
+ // which changes the NEXT spawn (R2's copy-on-spawn), never an instance
1899
+ // already standing — the lede says so, naming which instances already
1900
+ // carry their own copies.
1901
+ let actorTab = "instance";
1902
+
1903
+ function actorPluralOf(word) {
1904
+ return /(?:[sxz]|ch|sh)$/i.test(word) ? word + "es" : word + "s";
1905
+ }
1906
+
1907
+ function actorEditSubject() {
1908
+ const id = el("agentSelect").value;
1909
+ if (!id) return null;
1910
+ return actorTab === "class" ? roleOfAgentId(id) : id;
1911
+ }
1912
+
1913
+ function renderActorEditor() {
1914
+ const id = el("agentSelect").value;
1915
+ const area = el("actorEditorText");
1916
+ const status = el("actorEditorStatus");
1917
+ status.className = "edit-status";
1918
+ status.textContent = "";
1919
+ if (!id || !window.tmct || !window.tmct.page.renderAgentEditorText) {
1920
+ area.value = "";
1921
+ area.disabled = true;
1922
+ el("actorTabInstance").textContent = "this actor";
1923
+ el("actorTabClass").textContent = "its whole class";
1924
+ el("actorCardLede").textContent = "Follow an agent above to edit what it wants.";
1925
+ return;
1926
+ }
1927
+ const kind = roleOfAgentId(id);
1928
+ area.disabled = false;
1929
+ el("actorTabInstance").textContent = "this " + kind;
1930
+ el("actorTabInstance").setAttribute("aria-selected", actorTab === "instance" ? "true" : "false");
1931
+ el("actorTabClass").textContent = "every " + actorPluralOf(kind);
1932
+ el("actorTabClass").setAttribute("aria-selected", actorTab === "class" ? "true" : "false");
1933
+ if (actorTab === "class") {
1934
+ const siblings = Object.keys(agentsById).filter(function (aid) { return roleOfAgentId(aid) === kind; }).sort();
1935
+ area.value = window.tmct.page.renderAgentClassText(allStoreRows, kind);
1936
+ el("actorCardLede").textContent = (siblings.length ? siblings.join(", ") + " already carry their own copies. " : "")
1937
+ + "This changes the next " + kind + " to arrive.";
1938
+ } else {
1939
+ area.value = window.tmct.page.renderAgentEditorText(allStoreRows, id);
1940
+ el("actorCardLede").textContent = "This changes " + id + " alone.";
1941
+ }
1942
+ }
1943
+
1944
+ el("actorTabInstance").addEventListener("click", function () {
1945
+ if (actorTab === "instance") return;
1946
+ actorTab = "instance";
1947
+ renderActorEditor();
1948
+ });
1949
+ el("actorTabClass").addEventListener("click", function () {
1950
+ if (actorTab === "class") return;
1951
+ actorTab = "class";
1952
+ renderActorEditor();
1953
+ });
1954
+
1955
+ function renderActorSuggestionPills() {
1956
+ const box = el("actorEditorPills");
1957
+ const area = el("actorEditorText");
1958
+ const term = wordBeforeCursor(area.value, area.selectionStart);
1959
+ if (!term || !window.tmct) { box.innerHTML = ""; return; }
1960
+ const related = window.tmct.page.relatedForTerm ? window.tmct.page.relatedForTerm(allStoreRows, term) : null;
1961
+ const chain = window.tmct.page.classAncestorChain ? window.tmct.page.classAncestorChain(term, allStoreRows) : [];
1962
+ const seen = {};
1963
+ seen[term] = true;
1964
+ const out = [];
1965
+ const push = function (label) { if (label && !seen[label]) { seen[label] = true; out.push(label); } };
1966
+ if (related) {
1967
+ related.synonyms.forEach(push);
1968
+ related.related.forEach(function (r) { push(r.prefLabel); });
1969
+ }
1970
+ chain.slice(1).forEach(push);
1971
+ box.innerHTML = out.slice(0, 8).map(function (s) {
1972
+ return '<button type="button" class="pill" data-insert="' + esc(s) + '">' + esc(s) + "</button>";
1973
+ }).join("");
1974
+ }
1975
+
1976
+ el("actorEditorPills").addEventListener("click", function (e) {
1977
+ const btn = e.target.closest(".pill");
1978
+ if (!btn) return;
1979
+ const area = el("actorEditorText");
1980
+ const pos = area.selectionStart;
1981
+ const word = wordBeforeCursor(area.value, pos);
1982
+ const insert = btn.getAttribute("data-insert");
1983
+ area.value = area.value.slice(0, pos - word.length) + insert + area.value.slice(pos);
1984
+ const next = pos - word.length + insert.length;
1985
+ area.setSelectionRange(next, next);
1986
+ area.focus();
1987
+ onActorEditorChanged();
1988
+ });
1989
+
1990
+ let actorSuggestTimer = null;
1991
+ let actorSyncTimer = null;
1992
+ function scheduleActorSuggestions() { clearTimeout(actorSuggestTimer); actorSuggestTimer = setTimeout(renderActorSuggestionPills, 180); }
1993
+ function scheduleActorSync() { clearTimeout(actorSyncTimer); actorSyncTimer = setTimeout(applyActorEditorText, 450); }
1994
+ function onActorEditorChanged() { scheduleActorSuggestions(); scheduleActorSync(); }
1995
+ el("actorEditorText").addEventListener("input", onActorEditorChanged);
1996
+ el("actorEditorText").addEventListener("click", scheduleActorSuggestions);
1997
+ el("actorEditorText").addEventListener("keyup", function (e) {
1998
+ if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].indexOf(e.key) !== -1) scheduleActorSuggestions();
1999
+ });
2000
+
2001
+ // Redraws the label/mesh presentation and replays the CURRENT tick
2002
+ // payload — never calls session.recast, unlike rebuildSceneFromEdit's own
2003
+ // add/remove branch. A trait is not where anything stands, so a trait
2004
+ // edit must never move a single placement on the board.
2005
+ async function redrawAgentPresentation() {
2006
+ await callScene("boot", {
2007
+ propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1,
2008
+ agentPresentation: agentPresentationFrom(allStoreRows),
2009
+ });
2010
+ sendCameraToScene(camera);
2011
+ callScene("applyTick", { agents: agentsById, items: itemsById, ecology: [] });
2012
+ }
2013
+
2014
+ async function applyActorEditorText() {
2015
+ if (!session) return;
2016
+ const subject = actorEditSubject();
2017
+ if (!subject) return;
2018
+ const status = el("actorEditorStatus");
2019
+ status.className = "edit-status pending";
2020
+ status.textContent = "reading the square\\u2026";
2021
+ const result = await serializeTick(function () { return session.applyAgentEdit(subject, el("actorEditorText").value); });
2022
+ const snap = await session.snapshot();
2023
+ allStoreRows = snap.rows;
2024
+ await redrawAgentPresentation();
2025
+ if (result && result.unrecognized && result.unrecognized.length) {
2026
+ status.className = "edit-status pending";
2027
+ status.textContent = result.unrecognized.length + " line" + (result.unrecognized.length === 1 ? "" : "s")
2028
+ + " not understood yet \\u2014 nothing is retracted until they are.";
2029
+ } else {
2030
+ status.className = "edit-status ok";
2031
+ status.textContent = (result && (result.added || result.removed))
2032
+ ? "synced \\u2014 " + result.added + " fact(s) written, " + result.removed + " retracted."
2033
+ : "synced \\u2014 no change.";
2034
+ }
2035
+ await refreshOutlook();
2036
+ }
2037
+
2038
+ // ---- belief and plan panels: recomputed live, no turn spent ------------
2039
+ // agentOutlook (mudiii-turn.mjs, reached through session.outlook()) is a
2040
+ // pure read over the store as it stands — same rows, same outlook, byte
2041
+ // for byte, whatever order they arrived in. Refreshed on boot and after
2042
+ // every edit (world or actor); the follow select alone just re-renders the
2043
+ // already-fetched outlook for whichever agent it now names, no new fetch.
2044
+ let lastOutlook = null;
2045
+
2046
+ async function refreshOutlook() {
2047
+ if (!session || !session.outlook) return;
2048
+ lastOutlook = await session.outlook();
2049
+ renderOutlookPanel();
2050
+ }
2051
+
2052
+ function beliefOriginText(cell, origin) {
2053
+ if (!cell) return "nothing seen, nothing told";
2054
+ if (origin === "seen") return "seen";
2055
+ if (origin && typeof origin === "object" && "told" in origin) return "told, turn " + origin.told;
2056
+ return "seen";
2057
+ }
2058
+
2059
+ function renderOutlookPanel() {
2060
+ const id = el("agentSelect").value;
2061
+ const body = el("outlookBeliefBody");
2062
+ const planText = el("outlookPlanText");
2063
+ const puzzleText = el("outlookPuzzlePlanText");
2064
+ const entry = (lastOutlook && id) ? lastOutlook.agents[id] : null;
2065
+ if (!entry) {
2066
+ body.innerHTML = '<tr><td class="outlook-empty" colspan="3">Follow an agent above to see what it believes.</td></tr>';
2067
+ planText.textContent = "";
2068
+ puzzleText.hidden = true;
2069
+ return;
2070
+ }
2071
+ const subjects = Object.keys(entry.belief).sort();
2072
+ body.innerHTML = subjects.length
2073
+ ? subjects.map(function (subject) {
2074
+ const cell = entry.belief[subject];
2075
+ const howText = beliefOriginText(cell, entry.beliefOrigin[subject]);
2076
+ return '<tr><td class="mono">' + esc(subject) + '</td><td class="mono">' + esc(cell || "\\u2014") + "</td><td>" + esc(howText) + "</td></tr>";
2077
+ }).join("")
2078
+ : '<tr><td class="outlook-empty" colspan="3">' + esc(id) + " is alone on the board \\u2014 nothing else to believe anything about.</td></tr>";
2079
+ const planLine = entry.plan.length ? entry.plan.join(" \\u2192 ") : "holding";
2080
+ planText.textContent = id + "'s plan (" + entry.rung + "): " + planLine + " \\u2014 " + entry.goal;
2081
+ const puzzle = lastOutlook.puzzle;
2082
+ if (!puzzle) {
2083
+ puzzleText.hidden = true;
2084
+ puzzleText.textContent = "";
2085
+ } else {
2086
+ puzzleText.hidden = false;
2087
+ if (puzzle.plan) {
2088
+ const n = puzzle.plan.length;
2089
+ const moveLines = puzzle.plan.map(function (a, i) { return " " + (i + 1) + ". " + a.label; }).join("\\n");
2090
+ puzzleText.textContent = "puzzle plan \\u2014 found " + n + " move" + (n === 1 ? "" : "s") + " (shortest):\\n" + moveLines;
2091
+ } else {
2092
+ puzzleText.textContent = "puzzle plan \\u2014 " + puzzle.miss;
2093
+ }
2094
+ }
1801
2095
  }
1802
2096
 
1803
2097
  // ---- booting ---------------------------------------------------------
@@ -1860,7 +2154,10 @@ function pageScript() {
1860
2154
  agentsById = {};
1861
2155
  itemsById = {};
1862
2156
  el("chatInput").disabled = false;
1863
- await callScene("boot", { propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1 });
2157
+ await callScene("boot", {
2158
+ propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1,
2159
+ agentPresentation: agentPresentationFrom((s.worldPayload && s.worldPayload.facts) || []),
2160
+ });
1864
2161
 
1865
2162
  // The opening board, drawn through the very path a tick takes. Without
1866
2163
  // this the page's first sight of where anything stands is the first tick,
@@ -1872,6 +2169,7 @@ function pageScript() {
1872
2169
  camera.selectedId = openingFollowId(opening.agents);
1873
2170
  applyTickResult(opening);
1874
2171
  renderAll();
2172
+ await refreshOutlook();
1875
2173
  if (!prefersReducedMotion()) {
1876
2174
  autoOn = true;
1877
2175
  ensureTicker().play();