@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
@@ -717,6 +717,16 @@ ${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>
720
730
  <section class="mudiii-chat" aria-label="talk to the square">
721
731
  <div class="chatlog" id="chatLog" aria-live="polite"></div>
722
732
  <div class="log-popup" id="chatLogPopup" role="dialog" aria-label="the whole reply" hidden>
@@ -964,6 +974,23 @@ const MUDIII_STYLE = `
964
974
  .edit-placement-row { display: flex; gap: .4rem; }
965
975
  .edit-empty { font-size: .74rem; font-style: italic; color: var(--square-stone-dark); }
966
976
 
977
+ .actor-card {
978
+ display: none; flex-direction: column; gap: .45rem; margin-bottom: 1rem;
979
+ background: var(--parchment); border: 1px solid var(--square-stone-dark); border-radius: 4px;
980
+ box-shadow: 0 2px 0 rgba(0,0,0,.18); padding: .7rem .8rem; min-width: 0;
981
+ }
982
+ body.editing .actor-card { display: flex; }
983
+ .actor-tabs { display: flex; gap: .35rem; }
984
+ .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); }
985
+ .actor-tab[aria-selected="true"] { background: var(--square-accent); border-color: var(--square-accent); }
986
+ #actorEditorText {
987
+ width: 100%; box-sizing: border-box; min-height: 12rem; resize: vertical;
988
+ font-family: ${MONO_STACK}; font-size: .74rem; line-height: 1.6;
989
+ color: var(--square-ink); background: rgba(255,255,255,.6);
990
+ border: 1px solid var(--square-stone-dark); border-radius: 3px; padding: .55rem .6rem;
991
+ }
992
+ #actorEditorText:disabled { opacity: .55; }
993
+
967
994
  .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
995
  .chatlog { min-height: 8rem; max-height: 16rem; overflow-y: auto; }
969
996
  .chatlog > * { margin: 0 0 .32rem; }
@@ -1575,6 +1602,7 @@ function pageScript() {
1575
1602
  camera = { mode: mode, selectedId: id, status: null };
1576
1603
  renderCameraButtons();
1577
1604
  renderDriveRing();
1605
+ if (editing) renderActorEditor();
1578
1606
  sendCameraToScene(camera);
1579
1607
  });
1580
1608
 
@@ -1669,6 +1697,42 @@ function pageScript() {
1669
1697
  // mud.html's burrow-survey SVG, since a town square is a grid, not a room
1670
1698
  // graph.
1671
1699
  function worldOnlyRows(rows) { return rowsForWorld(rows, scenario().worldPayload.name); }
1700
+
1701
+ // What the rows say each agent is called (mgx:display-name) and drawn as
1702
+ // (mgx:model), resolved through the class chain so a class row covers every
1703
+ // instance, a mid-play arrival included. Null when the rows state neither
1704
+ // for anything — the scene then keeps ids and prefix meshes, the honest
1705
+ // fallback for a world that names nobody.
1706
+ function agentPresentationFrom(rows) {
1707
+ var traitsOf = window.tmct && window.tmct.page && window.tmct.page.agentTraitsOf;
1708
+ if (!traitsOf) return null;
1709
+ var kinds = {};
1710
+ var instanceIds = {};
1711
+ var presentedPredicates = { "mgx:display-name": true, "mgx:model": true };
1712
+ (rows || []).forEach(function (row) {
1713
+ if (!row || !row.subject || row.subject.indexOf("@") !== -1) return;
1714
+ if (row.predicate === "rdf:type" && /-\d+$/.test(row.subject)) {
1715
+ kinds[row.object] = true;
1716
+ instanceIds[row.subject] = true;
1717
+ return;
1718
+ }
1719
+ if (!presentedPredicates[row.predicate]) return;
1720
+ if (/-\d+$/.test(row.subject)) instanceIds[row.subject] = true;
1721
+ else kinds[row.subject] = true;
1722
+ });
1723
+ var byKind = {};
1724
+ var byId = {};
1725
+ var any = false;
1726
+ var take = function (bag, key) {
1727
+ var traits = traitsOf(rows, key);
1728
+ if (!traits.displayName && !traits.model) return;
1729
+ bag[key] = { label: traits.displayName, model: traits.model };
1730
+ any = true;
1731
+ };
1732
+ Object.keys(kinds).forEach(function (kind) { take(byKind, kind); });
1733
+ Object.keys(instanceIds).forEach(function (id) { take(byId, id); });
1734
+ return any ? { byId: byId, byKind: byKind } : null;
1735
+ }
1672
1736
  let editRows = [];
1673
1737
  // The FULL store, not the world's own rows: a term's synonyms and its is-a
1674
1738
  // chain mostly live in the background corpus, not in the square's vocabulary.
@@ -1699,6 +1763,7 @@ function pageScript() {
1699
1763
  el("editorStatus").textContent = "";
1700
1764
  renderSuggestionPills();
1701
1765
  renderEditPlacements();
1766
+ renderActorEditor();
1702
1767
  }
1703
1768
 
1704
1769
  function exitEditMode() {
@@ -1772,6 +1837,7 @@ function pageScript() {
1772
1837
  }
1773
1838
  await callScene("boot", {
1774
1839
  propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1,
1840
+ agentPresentation: agentPresentationFrom(allStoreRows.length ? allStoreRows : editRows),
1775
1841
  });
1776
1842
  sendCameraToScene(camera);
1777
1843
  callScene("applyTick", { agents: agentsById, items: itemsById, ecology: [] });
@@ -1800,6 +1866,151 @@ function pageScript() {
1800
1866
  renderEditPlacements();
1801
1867
  }
1802
1868
 
1869
+ // ---- actor card (per-instance edit) -------------------------------------
1870
+ // A second, disjoint sentence table beside the world editor's own: this
1871
+ // card edits whichever agent #agentSelect currently follows, alone,
1872
+ // through agent-editor.mjs's AGENT_TRAIT_PREDICATES rather than
1873
+ // mud-editor.mjs's placement/class/exit/dig vocabulary. "this <kind>"
1874
+ // writes to the instance id; "every <kind>" writes to the class name,
1875
+ // which changes the NEXT spawn (R2's copy-on-spawn), never an instance
1876
+ // already standing — the lede says so, naming which instances already
1877
+ // carry their own copies.
1878
+ let actorTab = "instance";
1879
+
1880
+ function actorPluralOf(word) {
1881
+ return /(?:[sxz]|ch|sh)$/i.test(word) ? word + "es" : word + "s";
1882
+ }
1883
+
1884
+ function actorEditSubject() {
1885
+ const id = el("agentSelect").value;
1886
+ if (!id) return null;
1887
+ return actorTab === "class" ? roleOfAgentId(id) : id;
1888
+ }
1889
+
1890
+ function renderActorEditor() {
1891
+ const id = el("agentSelect").value;
1892
+ const area = el("actorEditorText");
1893
+ const status = el("actorEditorStatus");
1894
+ status.className = "edit-status";
1895
+ status.textContent = "";
1896
+ if (!id || !window.tmct || !window.tmct.page.renderAgentEditorText) {
1897
+ area.value = "";
1898
+ area.disabled = true;
1899
+ el("actorTabInstance").textContent = "this actor";
1900
+ el("actorTabClass").textContent = "its whole class";
1901
+ el("actorCardLede").textContent = "Follow an agent above to edit what it wants.";
1902
+ return;
1903
+ }
1904
+ const kind = roleOfAgentId(id);
1905
+ area.disabled = false;
1906
+ el("actorTabInstance").textContent = "this " + kind;
1907
+ el("actorTabInstance").setAttribute("aria-selected", actorTab === "instance" ? "true" : "false");
1908
+ el("actorTabClass").textContent = "every " + actorPluralOf(kind);
1909
+ el("actorTabClass").setAttribute("aria-selected", actorTab === "class" ? "true" : "false");
1910
+ if (actorTab === "class") {
1911
+ const siblings = Object.keys(agentsById).filter(function (aid) { return roleOfAgentId(aid) === kind; }).sort();
1912
+ area.value = window.tmct.page.renderAgentClassText(allStoreRows, kind);
1913
+ el("actorCardLede").textContent = (siblings.length ? siblings.join(", ") + " already carry their own copies. " : "")
1914
+ + "This changes the next " + kind + " to arrive.";
1915
+ } else {
1916
+ area.value = window.tmct.page.renderAgentEditorText(allStoreRows, id);
1917
+ el("actorCardLede").textContent = "This changes " + id + " alone.";
1918
+ }
1919
+ }
1920
+
1921
+ el("actorTabInstance").addEventListener("click", function () {
1922
+ if (actorTab === "instance") return;
1923
+ actorTab = "instance";
1924
+ renderActorEditor();
1925
+ });
1926
+ el("actorTabClass").addEventListener("click", function () {
1927
+ if (actorTab === "class") return;
1928
+ actorTab = "class";
1929
+ renderActorEditor();
1930
+ });
1931
+
1932
+ function renderActorSuggestionPills() {
1933
+ const box = el("actorEditorPills");
1934
+ const area = el("actorEditorText");
1935
+ const term = wordBeforeCursor(area.value, area.selectionStart);
1936
+ if (!term || !window.tmct) { box.innerHTML = ""; return; }
1937
+ const related = window.tmct.page.relatedForTerm ? window.tmct.page.relatedForTerm(allStoreRows, term) : null;
1938
+ const chain = window.tmct.page.classAncestorChain ? window.tmct.page.classAncestorChain(term, allStoreRows) : [];
1939
+ const seen = {};
1940
+ seen[term] = true;
1941
+ const out = [];
1942
+ const push = function (label) { if (label && !seen[label]) { seen[label] = true; out.push(label); } };
1943
+ if (related) {
1944
+ related.synonyms.forEach(push);
1945
+ related.related.forEach(function (r) { push(r.prefLabel); });
1946
+ }
1947
+ chain.slice(1).forEach(push);
1948
+ box.innerHTML = out.slice(0, 8).map(function (s) {
1949
+ return '<button type="button" class="pill" data-insert="' + esc(s) + '">' + esc(s) + "</button>";
1950
+ }).join("");
1951
+ }
1952
+
1953
+ el("actorEditorPills").addEventListener("click", function (e) {
1954
+ const btn = e.target.closest(".pill");
1955
+ if (!btn) return;
1956
+ const area = el("actorEditorText");
1957
+ const pos = area.selectionStart;
1958
+ const word = wordBeforeCursor(area.value, pos);
1959
+ const insert = btn.getAttribute("data-insert");
1960
+ area.value = area.value.slice(0, pos - word.length) + insert + area.value.slice(pos);
1961
+ const next = pos - word.length + insert.length;
1962
+ area.setSelectionRange(next, next);
1963
+ area.focus();
1964
+ onActorEditorChanged();
1965
+ });
1966
+
1967
+ let actorSuggestTimer = null;
1968
+ let actorSyncTimer = null;
1969
+ function scheduleActorSuggestions() { clearTimeout(actorSuggestTimer); actorSuggestTimer = setTimeout(renderActorSuggestionPills, 180); }
1970
+ function scheduleActorSync() { clearTimeout(actorSyncTimer); actorSyncTimer = setTimeout(applyActorEditorText, 450); }
1971
+ function onActorEditorChanged() { scheduleActorSuggestions(); scheduleActorSync(); }
1972
+ el("actorEditorText").addEventListener("input", onActorEditorChanged);
1973
+ el("actorEditorText").addEventListener("click", scheduleActorSuggestions);
1974
+ el("actorEditorText").addEventListener("keyup", function (e) {
1975
+ if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].indexOf(e.key) !== -1) scheduleActorSuggestions();
1976
+ });
1977
+
1978
+ // Redraws the label/mesh presentation and replays the CURRENT tick
1979
+ // payload — never calls session.recast, unlike rebuildSceneFromEdit's own
1980
+ // add/remove branch. A trait is not where anything stands, so a trait
1981
+ // edit must never move a single placement on the board.
1982
+ async function redrawAgentPresentation() {
1983
+ await callScene("boot", {
1984
+ propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1,
1985
+ agentPresentation: agentPresentationFrom(allStoreRows),
1986
+ });
1987
+ sendCameraToScene(camera);
1988
+ callScene("applyTick", { agents: agentsById, items: itemsById, ecology: [] });
1989
+ }
1990
+
1991
+ async function applyActorEditorText() {
1992
+ if (!session) return;
1993
+ const subject = actorEditSubject();
1994
+ if (!subject) return;
1995
+ const status = el("actorEditorStatus");
1996
+ status.className = "edit-status pending";
1997
+ status.textContent = "reading the square\\u2026";
1998
+ const result = await serializeTick(function () { return session.applyAgentEdit(subject, el("actorEditorText").value); });
1999
+ const snap = await session.snapshot();
2000
+ allStoreRows = snap.rows;
2001
+ await redrawAgentPresentation();
2002
+ if (result && result.unrecognized && result.unrecognized.length) {
2003
+ status.className = "edit-status pending";
2004
+ status.textContent = result.unrecognized.length + " line" + (result.unrecognized.length === 1 ? "" : "s")
2005
+ + " not understood yet \\u2014 nothing is retracted until they are.";
2006
+ } else {
2007
+ status.className = "edit-status ok";
2008
+ status.textContent = (result && (result.added || result.removed))
2009
+ ? "synced \\u2014 " + result.added + " fact(s) written, " + result.removed + " retracted."
2010
+ : "synced \\u2014 no change.";
2011
+ }
2012
+ }
2013
+
1803
2014
  // ---- booting ---------------------------------------------------------
1804
2015
  // The board opens playing: a square standing still reads as broken, and the
1805
2016
  // first thing anyone does is press play anyway. A visitor who asked for
@@ -1860,7 +2071,10 @@ function pageScript() {
1860
2071
  agentsById = {};
1861
2072
  itemsById = {};
1862
2073
  el("chatInput").disabled = false;
1863
- await callScene("boot", { propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1 });
2074
+ await callScene("boot", {
2075
+ propPlacements: props, assetManifest: DATA.assetManifest, gridSize: gridSizeOf(), cellSize: 1,
2076
+ agentPresentation: agentPresentationFrom((s.worldPayload && s.worldPayload.facts) || []),
2077
+ });
1864
2078
 
1865
2079
  // The opening board, drawn through the very path a tick takes. Without
1866
2080
  // this the page's first sight of where anything stands is the first tick,
@@ -47,6 +47,9 @@ import { worldProvenanceTag } from "../domain/worlds-pack.mjs";
47
47
  import { mulberry32 } from "../domain/seeded-random.mjs";
48
48
  import { fnv1a32 } from "../domain/hash.mjs";
49
49
  import { DEFAULT_GAME_CONFIG } from "../domain/game-config.mjs";
50
+ import {
51
+ agentTraitsOf, classChainOf, fearedClassesOf, instanceFactsFrom, rowsDeclareDrives, traitValuesOf,
52
+ } from "../domain/agent-traits.mjs";
50
53
  import { objectClassChain, parseSnapshotSubject, snapshotSubject, worldEpochFact, WORLD_EPOCH_PREDICATE } from "./adventure.mjs";
51
54
 
52
55
  export { DEFAULT_VISION_RADIUS, believedCellOf, nearestBelievedTarget, beliefSnapshotFor };
@@ -82,6 +85,38 @@ export function rolesHunting(role, roles = MUDIII_ROLES) {
82
85
  return CAST_ROLES.filter((other) => rolesHuntedBy(other, roles).includes(role));
83
86
  }
84
87
 
88
+ /** The rows-aware sibling of rolesHuntedBy: the class names THIS subject
89
+ * moves toward, read off its own chain's mgx:pursues rows. Empty for a
90
+ * subject whose world states none — on a board whose rows state no drives
91
+ * at all, the decision chain falls back to the cast's role links. Pure. */
92
+ export function pursuedBy(rows, subject) {
93
+ return traitValuesOf(rows, subject, "mgx:pursues");
94
+ }
95
+
96
+ /** The rows-aware sibling of rolesHunting: the class names THIS subject
97
+ * moves away from — its declared mgx:evades set when its chain states one,
98
+ * otherwise every class whose members declare mgx:consumes for a class on
99
+ * this subject's own chain. One appetite row carries both the hunt and the
100
+ * flight, so a world never states the fear twice. Pure. */
101
+ export function fearedBy(rows, subject) {
102
+ return fearedClassesOf(rows, subject);
103
+ }
104
+
105
+ /** Provenance for the trait rows a spawn copies from a class onto an
106
+ * instance — its own tag family, apart from the world tag, so the ledger,
107
+ * the editors and a later respawn can tell a copied row from an authored
108
+ * one. */
109
+ const spawnProvenanceTag = (kind, id, epoch) => `spawn:${kind}:${id}@epoch${epoch}`;
110
+
111
+ /** The trait rows a fresh mint of `id` (an instance of `kind`) carries as its
112
+ * own, ready to append: instanceFactsFrom minus the rdf:type row the mint
113
+ * itself already writes, each stamped with the spawn provenance. */
114
+ function spawnTraitCopies(rows, kind, id, epoch) {
115
+ return instanceFactsFrom(rows, kind, id)
116
+ .filter((copied) => copied.predicate !== "rdf:type")
117
+ .map((copied) => ({ ...copied, provenance: spawnProvenanceTag(kind, id, epoch) }));
118
+ }
119
+
85
120
  const PLACEMENT_PREDICATE = "mgx:currently-in";
86
121
  const MASS_PREDICATE = "mgx:hasMass";
87
122
  const MOOD_PREDICATE = "mgx:feels";
@@ -587,7 +622,7 @@ function goalLine(kind, { subject, cell, arrived, boardNoun = "square", catches
587
622
  // arrival, and a cast that sets no interval never spawns that kind at all.
588
623
 
589
624
  function runEcologyPass({
590
- state, layout, roles, config, turn, epoch,
625
+ state, rows, layout, roles, config, turn, epoch,
591
626
  postMovePlacements, postMoveMass, liveItemIds, itemCellOf, itemMassOf, foodIds,
592
627
  }) {
593
628
  const k = turn;
@@ -597,6 +632,17 @@ function runEcologyPass({
597
632
  const carriesPrey = config.carryPreyToWeb === true;
598
633
  const laysEggs = config.layEggs === true;
599
634
  const webbedAt = (c) => hasActiveWebAt(layout, state, k, c.x, c.y, config.webDurationTurns);
635
+ // On a board whose rows state drives, contact only removes what the eater's
636
+ // own mgx:consumes chain names — an appetite nobody declared eats nothing.
637
+ // On a board with no drive rows, the role pairing decides alone, exactly as
638
+ // it always has.
639
+ const factDriven = rowsDeclareDrives(rows);
640
+ const eats = (eaterId, targetId) => {
641
+ if (!factDriven) return true;
642
+ const appetite = traitValuesOf(rows, eaterId, "mgx:consumes");
643
+ const chain = classChainOf(rows, targetId);
644
+ return appetite.some((eaten) => chain.includes(eaten));
645
+ };
600
646
 
601
647
  const predators = [...postMovePlacements.keys()].filter((id) => roleOfId(id, roles) === "predator").sort();
602
648
  const prey = [...postMovePlacements.keys()].filter((id) => roleOfId(id, roles) === "prey").sort();
@@ -613,6 +659,7 @@ function runEcologyPass({
613
659
  if (takenAgents.has(preyId)) continue;
614
660
  const qc = postMovePlacements.get(preyId);
615
661
  if (pc.x !== qc.x || pc.y !== qc.y) continue;
662
+ if (!eats(predatorId, preyId)) continue;
616
663
  takenAgents.add(preyId);
617
664
  const gained = finalMass.get(preyId) ?? 0;
618
665
  finalMass.set(predatorId, (finalMass.get(predatorId) ?? 0) + gained);
@@ -634,6 +681,7 @@ function runEcologyPass({
634
681
  if (claimed.has(preyId)) continue;
635
682
  const qc = postMovePlacements.get(preyId);
636
683
  if (pc.x !== qc.x || pc.y !== qc.y) continue;
684
+ if (!eats(predatorId, preyId)) continue;
637
685
  carriedBy.set(predatorId, preyId);
638
686
  claimed.add(preyId);
639
687
  events.push({ type: "catch-prey", predator: predatorId, prey: preyId, cell: cellId(pc.x, pc.y) });
@@ -669,6 +717,7 @@ function runEcologyPass({
669
717
  if (takenItems.has(itemId)) continue;
670
718
  if (!foodIds.has(itemId)) continue;
671
719
  if (itemCellOf.get(itemId) !== here) continue;
720
+ if (!eats(preyId, itemId)) continue;
672
721
  takenItems.add(itemId);
673
722
  const gained = itemMassOf.get(itemId) ?? 0;
674
723
  finalMass.set(preyId, (finalMass.get(preyId) ?? 0) + gained);
@@ -743,6 +792,7 @@ function runEcologyPass({
743
792
  const hatchlingId = `${roles.predator.idPrefix}-${nextHatchlingNum}`;
744
793
  nextHatchlingNum += 1;
745
794
  const hatchlingMass = share + (i === 0 ? remainder : 0);
795
+ writes.push(...spawnTraitCopies(rows, roles.predator.kind, hatchlingId, epoch));
746
796
  writes.push({ subject: hatchlingId, predicate: "rdf:type", object: roles.predator.kind });
747
797
  writes.push({ subject: stamp(hatchlingId), predicate: PLACEMENT_PREDICATE, object: eggCell });
748
798
  writes.push({ subject: stamp(hatchlingId), predicate: MASS_PREDICATE, object: String(hatchlingMass) });
@@ -781,12 +831,14 @@ function runEcologyPass({
781
831
  const preyId = `${roles.prey.idPrefix}-${1 + maxIdSuffix(state.placements.keys(), roles.prey.kind)}`;
782
832
  const cell = seededPick(free, seedKey(layout.name, epoch, k, preyId, "spawn"));
783
833
  occupied.add(cell);
834
+ const preySpawnMass = agentTraitsOf(rows, roles.prey.kind).mass ?? config.preyInitialMass;
835
+ writes.push(...spawnTraitCopies(rows, roles.prey.kind, preyId, epoch));
784
836
  writes.push({ subject: preyId, predicate: "rdf:type", object: roles.prey.kind });
785
837
  writes.push({ subject: stamp(preyId), predicate: PLACEMENT_PREDICATE, object: cell });
786
- writes.push({ subject: stamp(preyId), predicate: MASS_PREDICATE, object: String(config.preyInitialMass) });
838
+ writes.push({ subject: stamp(preyId), predicate: MASS_PREDICATE, object: String(preySpawnMass) });
787
839
  writes.push({ subject: stamp(preyId), predicate: FACING_PREDICATE, object: DEFAULT_FACING });
788
- events.push({ type: "spawn-prey", agent: preyId, cell, mass: round2(config.preyInitialMass) });
789
- spawned.push({ id: preyId, role: "prey", cell, mass: config.preyInitialMass });
840
+ events.push({ type: "spawn-prey", agent: preyId, cell, mass: round2(preySpawnMass) });
841
+ spawned.push({ id: preyId, role: "prey", cell, mass: preySpawnMass });
790
842
  }
791
843
  }
792
844
 
@@ -858,7 +910,8 @@ export async function startTownSquareGame(memoryDir, {
858
910
  layout, agents = null, predatorCount = null, preyCount = null,
859
911
  config = DEFAULT_GAME_CONFIG.mudiii, roles = MUDIII_ROLES, epoch = 0,
860
912
  } = {}) {
861
- const state = foldTownSquareState(readFactRows(await loadMemory(memoryDir)));
913
+ const rows = readFactRows(await loadMemory(memoryDir));
914
+ const state = foldTownSquareState(rows);
862
915
  const firstPredator = `${roles.predator.idPrefix}-1`;
863
916
  if (state.placements.get(firstPredator)?.epoch === epoch) return { started: false, facts: [] };
864
917
 
@@ -874,14 +927,21 @@ export async function startTownSquareGame(memoryDir, {
874
927
  const spec = roster[id];
875
928
  const role = spec.role ?? roleOfId(id, roles);
876
929
  const kind = role === "predator" ? roles.predator.kind : roles.prey.kind;
877
- const mass = spec.mass ?? (role === "predator" ? config.predatorInitialMass : config.preyInitialMass);
930
+ const mass = spec.mass
931
+ ?? agentTraitsOf(rows, kind).mass
932
+ ?? (role === "predator" ? config.predatorInitialMass : config.preyInitialMass);
933
+ // The class's traits copy onto the instance BEFORE its own stamped rows:
934
+ // both rank as turn 0 of this epoch in the fold, and the fold takes the
935
+ // later row on a tied rank, so an explicit roster mass (a fixture's
936
+ // seeded starvation) must land after the copied class default.
937
+ facts.push(...spawnTraitCopies(rows, kind, id, epoch));
878
938
  facts.push({ subject: id, predicate: "rdf:type", object: kind });
879
939
  facts.push({ subject: stamp(id), predicate: PLACEMENT_PREDICATE, object: spec.cell });
880
940
  facts.push({ subject: stamp(id), predicate: MASS_PREDICATE, object: String(mass) });
881
941
  facts.push({ subject: stamp(id), predicate: MOOD_PREDICATE, object: "calm" });
882
942
  facts.push({ subject: stamp(id), predicate: FACING_PREDICATE, object: spec.facing ?? DEFAULT_FACING });
883
943
  }
884
- await appendFacts(memoryDir, facts.map((f) => ({ ...f, provenance: worldProvenanceTag(layout.name) })));
944
+ await appendFacts(memoryDir, facts.map((f) => ({ ...f, provenance: f.provenance ?? worldProvenanceTag(layout.name) })));
885
945
  return { started: true, facts };
886
946
  }
887
947
 
@@ -1056,6 +1116,32 @@ function readLiveBoard(rows, state, { config, roles }) {
1056
1116
  };
1057
1117
  }
1058
1118
 
1119
+ /** `rows` widened with a bare `rdf:type` row for every rostered id that has
1120
+ * none — the rows every trait read below resolves against. A hand-taught
1121
+ * board can place `fox-1` by id without ever typing it (the pre-placement
1122
+ * then makes the mint's idempotency guard skip the roster write), and the
1123
+ * class chain would dead-end on the bare id while the roster itself already
1124
+ * knows the kind. The synthetic row states only what `liveOfKind` has
1125
+ * already concluded from the id, so this stays a pure function of the row
1126
+ * set. */
1127
+ function withRosterTypeRows(rows, { predators, prey, liveItemIds, roles }) {
1128
+ const typed = new Set();
1129
+ for (const row of rows || []) {
1130
+ if (row.predicate === "rdf:type") typed.add(row.subject);
1131
+ }
1132
+ const synthetic = [];
1133
+ for (const id of predators) {
1134
+ if (!typed.has(id)) synthetic.push({ subject: id, predicate: "rdf:type", object: roles.predator.kind });
1135
+ }
1136
+ for (const id of prey) {
1137
+ if (!typed.has(id)) synthetic.push({ subject: id, predicate: "rdf:type", object: roles.prey.kind });
1138
+ }
1139
+ for (const id of liveItemIds) {
1140
+ if (!typed.has(id)) synthetic.push({ subject: id, predicate: "rdf:type", object: kindOfItem(id, roles) });
1141
+ }
1142
+ return synthetic.length ? [...rows, ...synthetic] : rows;
1143
+ }
1144
+
1059
1145
  /** The render payload's `items` half — `{ id: { kind, cell } }` — over
1060
1146
  * `liveItemIds`, skipping anything in `taken` (a tick's eaten set; a resting
1061
1147
  * board passes none). Pure. */
@@ -1146,6 +1232,33 @@ export async function runTownSquareTick(memoryDir, {
1146
1232
  const agentsOfRoles = (roleList, exceptId) =>
1147
1233
  roleList.flatMap((r) => liveIdsOfRole[r] ?? []).filter((id) => id !== exceptId).sort();
1148
1234
 
1235
+ // The one gate between the two ways a cast can be driven. Rows that state
1236
+ // any drive at all drive EVERY threat/quarry/forage read below through the
1237
+ // trait resolver; rows that state none leave the injected roles object and
1238
+ // config numbers deciding alone, so a cast written before the trait
1239
+ // vocabulary existed behaves exactly as it always did.
1240
+ const traitRows = withRosterTypeRows(rows, { predators, prey, liveItemIds, roles });
1241
+ const factDriven = rowsDeclareDrives(traitRows);
1242
+ const traitsCache = new Map();
1243
+ const traitsOf = (subject) => {
1244
+ if (!traitsCache.has(subject)) traitsCache.set(subject, agentTraitsOf(traitRows, subject));
1245
+ return traitsCache.get(subject);
1246
+ };
1247
+ const chainCache = new Map();
1248
+ const chainSetOf = (subject) => {
1249
+ if (!chainCache.has(subject)) chainCache.set(subject, new Set(classChainOf(traitRows, subject)));
1250
+ return chainCache.get(subject);
1251
+ };
1252
+ const liveAgents = [...predators, ...prey].sort();
1253
+ const agentsOfClasses = (classNames, exceptId) => (classNames.length
1254
+ ? liveAgents.filter((id) => id !== exceptId && classNames.some((c) => chainSetOf(id).has(c)))
1255
+ : []);
1256
+ const forageTargetsOf = (agentId) => {
1257
+ const appetite = traitsOf(agentId).consumes;
1258
+ if (!appetite.length) return [];
1259
+ return liveItemIds.filter((id) => foodIds.has(id) && appetite.some((c) => chainSetOf(id).has(c)));
1260
+ };
1261
+
1149
1262
  const decide = (agentId, role) => {
1150
1263
  const fromCell = parseCellId(state.placements.get(agentId).cell);
1151
1264
  // The visitor's hand, checked before any of the belief chain below. A
@@ -1153,7 +1266,8 @@ export async function runTownSquareTick(memoryDir, {
1153
1266
  // it would have on a turn nobody touched.
1154
1267
  const driven = acceptedManualMove(manualMoves?.[agentId], fromCell, applyActions);
1155
1268
  const restingFacing = state.facing.get(agentId)?.value ?? DEFAULT_FACING;
1156
- const visionRadius = role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius;
1269
+ const visionRadius = traitsOf(agentId).visionRadius
1270
+ ?? (role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius);
1157
1271
  const beliefOpts = { visionRadius, toldFacts };
1158
1272
  // True unless a caller explicitly turns it off. A config object built by
1159
1273
  // hand (a fixture, a test, an older tmct.toml read before this key
@@ -1166,13 +1280,23 @@ export async function runTownSquareTick(memoryDir, {
1166
1280
  // visionRadius: Infinity call, not new belief machinery. The rival-threat
1167
1281
  // lookup below stays on beliefOpts either way: this switch is about food.
1168
1282
  const foodBeliefOpts = foodVisionGated ? beliefOpts : { ...beliefOpts, visionRadius: Infinity };
1169
- // Who counts as a threat and who counts as quarry both come off the cast's
1170
- // own hunts links. Nothing hunts a predator on either shipped board, so a
1171
- // predator's threat list is empty and a second predator in view is just
1172
- // another animal on the square.
1173
- const huntedRoles = rolesHuntedBy(role, roles);
1174
- const huntsAgents = huntedRoles.length > 0;
1175
- const hunters = agentsOfRoles(rolesHunting(role, roles), agentId);
1283
+ // Who counts as a threat, who counts as quarry and what counts as food
1284
+ // all come off the agent's OWN trait rows when the world states drives,
1285
+ // and off the cast's role links when it states none. Nothing hunts a
1286
+ // predator on either shipped board, so a predator's threat list is empty
1287
+ // and a second predator in view is just another animal on the square.
1288
+ const huntsAgents = factDriven
1289
+ ? pursuedBy(traitRows, agentId).length > 0
1290
+ : rolesHuntedBy(role, roles).length > 0;
1291
+ const hunters = factDriven
1292
+ ? agentsOfClasses(fearedBy(traitRows, agentId), agentId)
1293
+ : agentsOfRoles(rolesHunting(role, roles), agentId);
1294
+ const quarryCandidates = !huntsAgents ? [] : (factDriven
1295
+ ? agentsOfClasses(pursuedBy(traitRows, agentId), agentId)
1296
+ : agentsOfRoles(rolesHuntedBy(role, roles), agentId));
1297
+ const forageCandidates = huntsAgents ? [] : (factDriven
1298
+ ? forageTargetsOf(agentId)
1299
+ : [...foodIds].sort());
1176
1300
  const threat = driven ? null : nearestBelievedTarget(agentId, fromCell, hunters, state, beliefOpts);
1177
1301
 
1178
1302
  let rung;
@@ -1235,7 +1359,7 @@ export async function runTownSquareTick(memoryDir, {
1235
1359
  } else if (threat) {
1236
1360
  const towardFood = huntsAgents
1237
1361
  ? null
1238
- : nearestBelievedTarget(agentId, fromCell, [...foodIds].sort(), state, foodBeliefOpts);
1362
+ : nearestBelievedTarget(agentId, fromCell, forageCandidates, state, foodBeliefOpts);
1239
1363
  if (blendsPreyDecision && !huntsAgents && towardFood) {
1240
1364
  // The one case the two rungs disagree about: this prey believes a
1241
1365
  // predator AND food, so a strict order has to pick between them and a
@@ -1270,8 +1394,8 @@ export async function runTownSquareTick(memoryDir, {
1270
1394
  }
1271
1395
  } else {
1272
1396
  const quarry = huntsAgents
1273
- ? nearestBelievedTarget(agentId, fromCell, agentsOfRoles(huntedRoles, agentId), state, beliefOpts)
1274
- : nearestBelievedTarget(agentId, fromCell, [...foodIds].sort(), state, foodBeliefOpts);
1397
+ ? nearestBelievedTarget(agentId, fromCell, quarryCandidates, state, beliefOpts)
1398
+ : nearestBelievedTarget(agentId, fromCell, forageCandidates, state, foodBeliefOpts);
1275
1399
  if (quarry) {
1276
1400
  rung = huntsAgents ? "chase" : "forage";
1277
1401
  const path = findActionPath(fromCell, (s) => s.x === quarry.cell.x && s.y === quarry.cell.y, applyActions, { stateKey: pathStateKey });
@@ -1343,8 +1467,11 @@ export async function runTownSquareTick(memoryDir, {
1343
1467
  const postMoveMass = new Map();
1344
1468
  for (const id of [...predators, ...prey]) {
1345
1469
  const role = agents[id].role;
1346
- const drain = role === "predator" ? config.predatorMassDecrementPerTurn : config.preyMassDecrementPerTurn;
1347
- const start = role === "predator" ? config.predatorInitialMass : config.preyInitialMass;
1470
+ const traits = traitsOf(id);
1471
+ const drain = traits.massDrainPerTurn
1472
+ ?? (role === "predator" ? config.predatorMassDecrementPerTurn : config.preyMassDecrementPerTurn);
1473
+ const start = traits.mass
1474
+ ?? (role === "predator" ? config.predatorInitialMass : config.preyInitialMass);
1348
1475
  const prior = state.mass.get(id)?.value ?? start;
1349
1476
  postMoveMass.set(id, Math.max(0, prior - drain));
1350
1477
  }
@@ -1356,7 +1483,7 @@ export async function runTownSquareTick(memoryDir, {
1356
1483
  }
1357
1484
 
1358
1485
  const pass = runEcologyPass({
1359
- state, layout: lay, roles, config, turn: k, epoch,
1486
+ state, rows: traitRows, layout: lay, roles, config, turn: k, epoch,
1360
1487
  postMovePlacements, postMoveMass, liveItemIds, itemCellOf, itemMassOf, foodIds,
1361
1488
  });
1362
1489
 
@@ -1445,7 +1572,7 @@ export async function runTownSquareTick(memoryDir, {
1445
1572
 
1446
1573
  const turnMarker = { subject: stamp(BOARD_SUBJECT), predicate: TURN_PLAYED_PREDICATE, object: String(k) };
1447
1574
  const writes = [...movementWrites, ...pass.writes, ...moodWrites, turnMarker];
1448
- await appendFacts(memoryDir, writes.map((f) => ({ ...f, provenance: `${worldProvenanceTag(lay.name)}:turn${k}` })));
1575
+ await appendFacts(memoryDir, writes.map((f) => ({ ...f, provenance: f.provenance ?? `${worldProvenanceTag(lay.name)}:turn${k}` })));
1449
1576
 
1450
1577
  return {
1451
1578
  turn: k,
@@ -1488,6 +1615,9 @@ export async function townSquareBoard(memoryDir, {
1488
1615
  const rows = readFactRows(await loadMemory(memoryDir));
1489
1616
  const state = foldTownSquareState(rows);
1490
1617
  const board = readLiveBoard(rows, state, { config, roles });
1618
+ const traitRows = withRosterTypeRows(rows, {
1619
+ predators: board.predators, prey: board.prey, liveItemIds: board.liveItemIds, roles,
1620
+ });
1491
1621
 
1492
1622
  const agents = {};
1493
1623
  const rostered = [
@@ -1496,8 +1626,11 @@ export async function townSquareBoard(memoryDir, {
1496
1626
  ];
1497
1627
  for (const [id, role] of rostered) {
1498
1628
  const cell = state.placements.get(id).cell;
1499
- const visionRadius = role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius;
1500
- const initialMass = role === "predator" ? config.predatorInitialMass : config.preyInitialMass;
1629
+ const traits = agentTraitsOf(traitRows, id);
1630
+ const visionRadius = traits.visionRadius
1631
+ ?? (role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius);
1632
+ const initialMass = traits.mass
1633
+ ?? (role === "predator" ? config.predatorInitialMass : config.preyInitialMass);
1501
1634
  agents[id] = {
1502
1635
  role,
1503
1636
  cell,