@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
@@ -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. */
@@ -1071,42 +1157,34 @@ function itemsPayload(liveItemIds, { state, itemCellOf, roles, taken = null }) {
1071
1157
  // ---- one tick --------------------------------------------------------------------
1072
1158
 
1073
1159
  /**
1074
- * One full tick over `layout`: fold, believe, decide, move, run the ecology
1075
- * pass, and append everything as this turn's stamped facts in a single write.
1076
- *
1077
- * Predators move before prey, and that ordering is load-bearing for replay: a
1078
- * prey's belief is computed against the PRE-move predator positions (it reacts
1079
- * to where the predator was when it looked), while eating resolves on the
1080
- * post-move ones (it is caught where the predator actually ends up).
1081
- *
1082
- * `manualMoves` is the one place a visitor's own hand reaches the world:
1083
- * `{ agentId: cellId }`, or `{ agentId: { cell, facing } }`, checked before
1084
- * that agent's belief chain runs. A legal request moves the agent under the
1085
- * `driven` rung; an illegal one is refused and that agent decides for itself
1086
- * this turn, so a rejected press never freezes it. A driven turn spends a
1087
- * turn like any other: the ecology pass runs, and every other agent decides
1088
- * and moves in this same call.
1160
+ * The movement DECISION half of one tick, over `rows`/`state` as they stand
1161
+ * right now: fold nothing further, believe, and decide — for every live
1162
+ * predator and prey, exactly the rung, plan, goal, mood and belief a real
1163
+ * tick would assign it, with none of a tick's EFFECTS (no eating, no spawn,
1164
+ * no mass debit, no write). `runTownSquareTick` runs this and then applies
1165
+ * the effects; `agentOutlook` (mudiii-turn.mjs) runs the SAME derivation and
1166
+ * reads only the answers, so the two can never disagree about what an agent
1167
+ * currently believes or plans.
1089
1168
  *
1090
- * Returns `{ turn, epoch, agents, items, ecology, rungs, activeWebs, writes }`.
1091
- * `agents` and `items` and `ecology` are the frozen render payload — see
1092
- * townSquareTickPayload, which projects exactly those three plus the turn.
1093
- * `rungs` is the decision each live agent reached this turn ("driven" for a
1094
- * hand-driven move, then "chase", "evade", "forage", "wander", and —
1095
- * on a cast that carries or spins webs —
1096
- * "carry", "deliver", "carried", "trapped", "hold-web", "build-web"); an agent
1097
- * that decided and then died still has a rung and no longer has an `agents`
1098
- * entry, which is the difference between a decision and a survivor.
1099
- * `activeWebs` is every unexpired predator-built web, empty on a board with
1100
- * none.
1169
+ * Returns everything either caller needs to keep going: `{ lay, k, epoch,
1170
+ * stamp, agents, rungs, movementWrites, postMovePlacements, tickWebs,
1171
+ * traitRows, traitsOf, predators, prey, liveItemIds, foodIds, itemCellOf,
1172
+ * itemMassOf, beliefContext }`. `agents[id]` carries exactly the shape a tick
1173
+ * payload's own entry does before the ecology pass and mass debit finalise
1174
+ * it — `{ role, cell, facing, goal, mood, plan, mass: 0, belief }` — so
1175
+ * appending fields here would drift the tick's own frozen payload shape.
1176
+ * `beliefContext[id]` is `{ cell, candidates, opts, foodCandidates, foodOpts
1177
+ * }`, the exact inputs this agent's own belief snapshot was taken with —
1178
+ * `agentOutlook`'s own "how it knows" column reads it through
1179
+ * `beliefOriginOf`, off the same walk, so a panel's cell and its origin can
1180
+ * never drift apart either.
1101
1181
  */
1102
- export async function runTownSquareTick(memoryDir, {
1103
- layout, toldFacts = [], config = DEFAULT_GAME_CONFIG.mudiii, roles = MUDIII_ROLES,
1104
- manualMoves = {},
1182
+ export function planTownSquareTurn(rows, state, {
1183
+ layout, config = DEFAULT_GAME_CONFIG.mudiii, roles = MUDIII_ROLES,
1184
+ toldFacts = [], manualMoves = {},
1105
1185
  } = {}) {
1106
1186
  const lay = typeof layout === "string" ? TOWN_SQUARE_LAYOUTS[layout] : layout;
1107
- if (!lay) throw new Error(`runTownSquareTick: no such layout "${layout}"`);
1108
- const rows = readFactRows(await loadMemory(memoryDir));
1109
- const state = foldTownSquareState(rows);
1187
+ if (!lay) throw new Error(`planTownSquareTurn: no such layout "${layout}"`);
1110
1188
  const k = state.tickCount + 1;
1111
1189
  const epoch = state.epoch;
1112
1190
  const stamp = (base) => snapshotSubject(base, k, epoch);
@@ -1118,6 +1196,7 @@ export async function runTownSquareTick(memoryDir, {
1118
1196
  const postMovePlacements = new Map();
1119
1197
  const agents = {};
1120
1198
  const rungs = {};
1199
+ const beliefContext = {};
1121
1200
 
1122
1201
  const carriesPrey = config.carryPreyToWeb === true;
1123
1202
  const buildsWebs = config.buildWebs === true;
@@ -1146,6 +1225,33 @@ export async function runTownSquareTick(memoryDir, {
1146
1225
  const agentsOfRoles = (roleList, exceptId) =>
1147
1226
  roleList.flatMap((r) => liveIdsOfRole[r] ?? []).filter((id) => id !== exceptId).sort();
1148
1227
 
1228
+ // The one gate between the two ways a cast can be driven. Rows that state
1229
+ // any drive at all drive EVERY threat/quarry/forage read below through the
1230
+ // trait resolver; rows that state none leave the injected roles object and
1231
+ // config numbers deciding alone, so a cast written before the trait
1232
+ // vocabulary existed behaves exactly as it always did.
1233
+ const traitRows = withRosterTypeRows(rows, { predators, prey, liveItemIds, roles });
1234
+ const factDriven = rowsDeclareDrives(traitRows);
1235
+ const traitsCache = new Map();
1236
+ const traitsOf = (subject) => {
1237
+ if (!traitsCache.has(subject)) traitsCache.set(subject, agentTraitsOf(traitRows, subject));
1238
+ return traitsCache.get(subject);
1239
+ };
1240
+ const chainCache = new Map();
1241
+ const chainSetOf = (subject) => {
1242
+ if (!chainCache.has(subject)) chainCache.set(subject, new Set(classChainOf(traitRows, subject)));
1243
+ return chainCache.get(subject);
1244
+ };
1245
+ const liveAgents = [...predators, ...prey].sort();
1246
+ const agentsOfClasses = (classNames, exceptId) => (classNames.length
1247
+ ? liveAgents.filter((id) => id !== exceptId && classNames.some((c) => chainSetOf(id).has(c)))
1248
+ : []);
1249
+ const forageTargetsOf = (agentId) => {
1250
+ const appetite = traitsOf(agentId).consumes;
1251
+ if (!appetite.length) return [];
1252
+ return liveItemIds.filter((id) => foodIds.has(id) && appetite.some((c) => chainSetOf(id).has(c)));
1253
+ };
1254
+
1149
1255
  const decide = (agentId, role) => {
1150
1256
  const fromCell = parseCellId(state.placements.get(agentId).cell);
1151
1257
  // The visitor's hand, checked before any of the belief chain below. A
@@ -1153,7 +1259,8 @@ export async function runTownSquareTick(memoryDir, {
1153
1259
  // it would have on a turn nobody touched.
1154
1260
  const driven = acceptedManualMove(manualMoves?.[agentId], fromCell, applyActions);
1155
1261
  const restingFacing = state.facing.get(agentId)?.value ?? DEFAULT_FACING;
1156
- const visionRadius = role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius;
1262
+ const visionRadius = traitsOf(agentId).visionRadius
1263
+ ?? (role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius);
1157
1264
  const beliefOpts = { visionRadius, toldFacts };
1158
1265
  // True unless a caller explicitly turns it off. A config object built by
1159
1266
  // hand (a fixture, a test, an older tmct.toml read before this key
@@ -1166,13 +1273,23 @@ export async function runTownSquareTick(memoryDir, {
1166
1273
  // visionRadius: Infinity call, not new belief machinery. The rival-threat
1167
1274
  // lookup below stays on beliefOpts either way: this switch is about food.
1168
1275
  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);
1276
+ // Who counts as a threat, who counts as quarry and what counts as food
1277
+ // all come off the agent's OWN trait rows when the world states drives,
1278
+ // and off the cast's role links when it states none. Nothing hunts a
1279
+ // predator on either shipped board, so a predator's threat list is empty
1280
+ // and a second predator in view is just another animal on the square.
1281
+ const huntsAgents = factDriven
1282
+ ? pursuedBy(traitRows, agentId).length > 0
1283
+ : rolesHuntedBy(role, roles).length > 0;
1284
+ const hunters = factDriven
1285
+ ? agentsOfClasses(fearedBy(traitRows, agentId), agentId)
1286
+ : agentsOfRoles(rolesHunting(role, roles), agentId);
1287
+ const quarryCandidates = !huntsAgents ? [] : (factDriven
1288
+ ? agentsOfClasses(pursuedBy(traitRows, agentId), agentId)
1289
+ : agentsOfRoles(rolesHuntedBy(role, roles), agentId));
1290
+ const forageCandidates = huntsAgents ? [] : (factDriven
1291
+ ? forageTargetsOf(agentId)
1292
+ : [...foodIds].sort());
1176
1293
  const threat = driven ? null : nearestBelievedTarget(agentId, fromCell, hunters, state, beliefOpts);
1177
1294
 
1178
1295
  let rung;
@@ -1235,7 +1352,7 @@ export async function runTownSquareTick(memoryDir, {
1235
1352
  } else if (threat) {
1236
1353
  const towardFood = huntsAgents
1237
1354
  ? null
1238
- : nearestBelievedTarget(agentId, fromCell, [...foodIds].sort(), state, foodBeliefOpts);
1355
+ : nearestBelievedTarget(agentId, fromCell, forageCandidates, state, foodBeliefOpts);
1239
1356
  if (blendsPreyDecision && !huntsAgents && towardFood) {
1240
1357
  // The one case the two rungs disagree about: this prey believes a
1241
1358
  // predator AND food, so a strict order has to pick between them and a
@@ -1270,8 +1387,8 @@ export async function runTownSquareTick(memoryDir, {
1270
1387
  }
1271
1388
  } else {
1272
1389
  const quarry = huntsAgents
1273
- ? nearestBelievedTarget(agentId, fromCell, agentsOfRoles(huntedRoles, agentId), state, beliefOpts)
1274
- : nearestBelievedTarget(agentId, fromCell, [...foodIds].sort(), state, foodBeliefOpts);
1390
+ ? nearestBelievedTarget(agentId, fromCell, quarryCandidates, state, beliefOpts)
1391
+ : nearestBelievedTarget(agentId, fromCell, forageCandidates, state, foodBeliefOpts);
1275
1392
  if (quarry) {
1276
1393
  rung = huntsAgents ? "chase" : "forage";
1277
1394
  const path = findActionPath(fromCell, (s) => s.x === quarry.cell.x && s.y === quarry.cell.y, applyActions, { stateKey: pathStateKey });
@@ -1318,6 +1435,7 @@ export async function runTownSquareTick(memoryDir, {
1318
1435
  }
1319
1436
 
1320
1437
  const belief = beliefSnapshotFor(agentId, beliefCell, beliefCandidates, state, beliefOpts);
1438
+ const foodCandidates = foodVisionGated ? [] : beliefCandidates.filter((id) => foodIds.has(id));
1321
1439
  // beliefSnapshotFor's one call covers every candidate, food included, so
1322
1440
  // an ungated food call needs the food entries re-taken at the widened
1323
1441
  // radius too — otherwise the panel would show a crumb null while the
@@ -1325,9 +1443,12 @@ export async function runTownSquareTick(memoryDir, {
1325
1443
  // only: every key already exists from the call above, so this can never
1326
1444
  // reorder the panel.
1327
1445
  if (!foodVisionGated) {
1328
- const foodCandidates = beliefCandidates.filter((id) => foodIds.has(id));
1329
1446
  Object.assign(belief, beliefSnapshotFor(agentId, beliefCell, foodCandidates, state, foodBeliefOpts));
1330
1447
  }
1448
+ // What a belief panel's own "how it knows" column re-derives per entry —
1449
+ // the exact cell and opts this agent's belief was just taken with, so
1450
+ // `beliefOriginOf` walks the identical rung `belief` did.
1451
+ beliefContext[agentId] = { cell: beliefCell, candidates: beliefCandidates, opts: beliefOpts, foodCandidates, foodOpts: foodBeliefOpts };
1331
1452
  // A hand-picked facing beats the step it came with, which is what lets the
1332
1453
  // page walk an agent backwards without spinning it round.
1333
1454
  const facing = drivenFacing ?? plan[0] ?? restingFacing;
@@ -1340,11 +1461,61 @@ export async function runTownSquareTick(memoryDir, {
1340
1461
  for (const id of predators) decide(id, "predator");
1341
1462
  for (const id of prey) decide(id, "prey");
1342
1463
 
1464
+ return {
1465
+ lay, k, epoch, stamp, agents, rungs, movementWrites, postMovePlacements, tickWebs, traitRows, traitsOf,
1466
+ predators, prey, liveItemIds, foodIds, itemCellOf, itemMassOf, beliefContext,
1467
+ };
1468
+ }
1469
+
1470
+ /**
1471
+ * One full tick over `layout`: fold, believe, decide, move, run the ecology
1472
+ * pass, and append everything as this turn's stamped facts in a single write.
1473
+ *
1474
+ * Predators move before prey, and that ordering is load-bearing for replay: a
1475
+ * prey's belief is computed against the PRE-move predator positions (it reacts
1476
+ * to where the predator was when it looked), while eating resolves on the
1477
+ * post-move ones (it is caught where the predator actually ends up).
1478
+ *
1479
+ * `manualMoves` is the one place a visitor's own hand reaches the world:
1480
+ * `{ agentId: cellId }`, or `{ agentId: { cell, facing } }`, checked before
1481
+ * that agent's belief chain runs. A legal request moves the agent under the
1482
+ * `driven` rung; an illegal one is refused and that agent decides for itself
1483
+ * this turn, so a rejected press never freezes it. A driven turn spends a
1484
+ * turn like any other: the ecology pass runs, and every other agent decides
1485
+ * and moves in this same call.
1486
+ *
1487
+ * Returns `{ turn, epoch, agents, items, ecology, rungs, activeWebs, writes }`.
1488
+ * `agents` and `items` and `ecology` are the frozen render payload — see
1489
+ * townSquareTickPayload, which projects exactly those three plus the turn.
1490
+ * `rungs` is the decision each live agent reached this turn ("driven" for a
1491
+ * hand-driven move, then "chase", "evade", "forage", "wander", and —
1492
+ * on a cast that carries or spins webs —
1493
+ * "carry", "deliver", "carried", "trapped", "hold-web", "build-web"); an agent
1494
+ * that decided and then died still has a rung and no longer has an `agents`
1495
+ * entry, which is the difference between a decision and a survivor.
1496
+ * `activeWebs` is every unexpired predator-built web, empty on a board with
1497
+ * none.
1498
+ */
1499
+ export async function runTownSquareTick(memoryDir, {
1500
+ layout, toldFacts = [], config = DEFAULT_GAME_CONFIG.mudiii, roles = MUDIII_ROLES,
1501
+ manualMoves = {},
1502
+ } = {}) {
1503
+ const rows = readFactRows(await loadMemory(memoryDir));
1504
+ const state = foldTownSquareState(rows);
1505
+ const {
1506
+ lay, k, epoch, stamp, agents, rungs, movementWrites, postMovePlacements, tickWebs, traitRows, traitsOf,
1507
+ predators, prey, liveItemIds, foodIds, itemCellOf, itemMassOf,
1508
+ } = planTownSquareTurn(rows, state, { layout, config, roles, toldFacts, manualMoves });
1509
+ const carriesPrey = config.carryPreyToWeb === true;
1510
+
1343
1511
  const postMoveMass = new Map();
1344
1512
  for (const id of [...predators, ...prey]) {
1345
1513
  const role = agents[id].role;
1346
- const drain = role === "predator" ? config.predatorMassDecrementPerTurn : config.preyMassDecrementPerTurn;
1347
- const start = role === "predator" ? config.predatorInitialMass : config.preyInitialMass;
1514
+ const traits = traitsOf(id);
1515
+ const drain = traits.massDrainPerTurn
1516
+ ?? (role === "predator" ? config.predatorMassDecrementPerTurn : config.preyMassDecrementPerTurn);
1517
+ const start = traits.mass
1518
+ ?? (role === "predator" ? config.predatorInitialMass : config.preyInitialMass);
1348
1519
  const prior = state.mass.get(id)?.value ?? start;
1349
1520
  postMoveMass.set(id, Math.max(0, prior - drain));
1350
1521
  }
@@ -1356,7 +1527,7 @@ export async function runTownSquareTick(memoryDir, {
1356
1527
  }
1357
1528
 
1358
1529
  const pass = runEcologyPass({
1359
- state, layout: lay, roles, config, turn: k, epoch,
1530
+ state, rows: traitRows, layout: lay, roles, config, turn: k, epoch,
1360
1531
  postMovePlacements, postMoveMass, liveItemIds, itemCellOf, itemMassOf, foodIds,
1361
1532
  });
1362
1533
 
@@ -1445,7 +1616,7 @@ export async function runTownSquareTick(memoryDir, {
1445
1616
 
1446
1617
  const turnMarker = { subject: stamp(BOARD_SUBJECT), predicate: TURN_PLAYED_PREDICATE, object: String(k) };
1447
1618
  const writes = [...movementWrites, ...pass.writes, ...moodWrites, turnMarker];
1448
- await appendFacts(memoryDir, writes.map((f) => ({ ...f, provenance: `${worldProvenanceTag(lay.name)}:turn${k}` })));
1619
+ await appendFacts(memoryDir, writes.map((f) => ({ ...f, provenance: f.provenance ?? `${worldProvenanceTag(lay.name)}:turn${k}` })));
1449
1620
 
1450
1621
  return {
1451
1622
  turn: k,
@@ -1488,6 +1659,9 @@ export async function townSquareBoard(memoryDir, {
1488
1659
  const rows = readFactRows(await loadMemory(memoryDir));
1489
1660
  const state = foldTownSquareState(rows);
1490
1661
  const board = readLiveBoard(rows, state, { config, roles });
1662
+ const traitRows = withRosterTypeRows(rows, {
1663
+ predators: board.predators, prey: board.prey, liveItemIds: board.liveItemIds, roles,
1664
+ });
1491
1665
 
1492
1666
  const agents = {};
1493
1667
  const rostered = [
@@ -1496,8 +1670,11 @@ export async function townSquareBoard(memoryDir, {
1496
1670
  ];
1497
1671
  for (const [id, role] of rostered) {
1498
1672
  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;
1673
+ const traits = agentTraitsOf(traitRows, id);
1674
+ const visionRadius = traits.visionRadius
1675
+ ?? (role === "predator" ? config.predatorVisionRadius : config.preyVisionRadius);
1676
+ const initialMass = traits.mass
1677
+ ?? (role === "predator" ? config.predatorInitialMass : config.preyInitialMass);
1501
1678
  agents[id] = {
1502
1679
  role,
1503
1680
  cell,
@@ -4,13 +4,24 @@
4
4
  // Unlike memory-ask-browser-entry.mjs (factAnswer/factReadBack only), this
5
5
  // exposes the FULL turn engine: createChatSession wraps the shared
6
6
  // createTurnSession (turn-session.mjs) around chat.mjs's runTurn — the
7
- // focus/last/planState/researchState threading src/services/chat-session.mjs's
7
+ // focus/last/planState/researchState/newsState threading src/services/chat-session.mjs's
8
8
  // createSession.turn does, minus every filesystem side effect (no transcript
9
9
  // log, no sidecar, no graph upsert). Memory is an in-memory Backend-B handle,
10
10
  // optionally pre-loaded with a built seed payload (scripts/build-chat-seed.mjs),
11
11
  // so teach turns, recall, proof chains and the honest miss all run
12
12
  // client-side with zero I/O.
13
13
  //
14
+ // The news lane's own state (newsState) rides turn-session.mjs's shared
15
+ // threading with no extra wiring here, the same way researchState already
16
+ // does. What IS this file's own job: a persistent newsConfig object (so a
17
+ // `/news add`/`/news interval` mutation survives turn to turn, the same
18
+ // reason liveReferenceOn/synthesisBudgetOn are held here rather than
19
+ // recreated per turn) and registerNewsProvider — the news lane's own
20
+ // provider-set stub seam, the same shape registerResearchProvider gives
21
+ // tests below. Neither building the default fetchers nor registering a stub
22
+ // set fires a fetch; a fetch only happens once the user's own turn actually
23
+ // runs `/news poll` or `/news enrich`.
24
+ //
14
25
  // Two browser traps this file still owns, beyond what createTurnSession
15
26
  // already covers (passing `env: {}` explicitly, since a browser has no
16
27
  // `process` global; the crash-resistant catch fallback):
@@ -47,7 +58,13 @@ import { registerReferencePackProvider } from "../../adapters/corpus/reference-p
47
58
  // provider is stubbed. The adapter is fetch-only, so it bundles as-is.
48
59
  // registerResearchProvider is the research lane's sibling seam
49
60
  // (simple.wikipedia.org) — same stubbing contract for its e2e tests.
50
- import { registerLiveReferenceProvider, registerResearchProvider } from "../../adapters/corpus/wikipedia-live.mjs";
61
+ import { registerLiveReferenceProvider, registerResearchProvider, getResearchProvider } from "../../adapters/corpus/wikipedia-live.mjs";
62
+ // The news lane's own config resolver and contemporary-source registry —
63
+ // this session's default /news providers are built from the same fetcher
64
+ // factory news.html's own session uses (src/surfaces/web/news-browser-entry.mjs),
65
+ // just over the browser's own fetch rather than an injected test one.
66
+ import { resolveNewsConfig } from "../../services/news.mjs";
67
+ import { newsSourceRecords, normalizeNewsSourceIds, createNewsFetcher, preflightNewsUrl } from "../../adapters/corpus/news-sources.mjs";
51
68
  // Best-effort IndexedDB persistence for the page's session store — the page
52
69
  // decides when to save/load/clear; this entry only carries the wrapper
53
70
  // across the bundle boundary.
@@ -82,6 +99,48 @@ import { graphAsk, enginePlan } from "./engine-surface.mjs";
82
99
  * for `ask()` — a question about taught facts has a real graph to traverse
83
100
  * while a code-structure question keeps its honest no-code-graph refusal.
84
101
  */
102
+ let registeredNewsProviders = null;
103
+
104
+ /** Swap chat.html's own `/news` providers set — `{ newsFetchers, getResearchProvider,
105
+ * preflightNewsUrl }`, the same stub seam registerResearchProvider gives tests
106
+ * above — so a test (or a future page control) can answer `/news` against a
107
+ * fixed set of sources instead of the real network. Pass null to restore the
108
+ * default: real fetchers, over the browser's own fetch, for every source the
109
+ * session's own newsConfig currently enables. Registering (or not) never
110
+ * fires a fetch by itself — only the user's own `/news poll`/`/news enrich`
111
+ * turn does. */
112
+ export function registerNewsProvider(providers) {
113
+ registeredNewsProviders = providers && typeof providers === "object" ? providers : null;
114
+ }
115
+
116
+ /** The default `/news` providers for one session's current `newsConfig`:
117
+ * real fetchers for every enabled contemporary source (browser fetch, no
118
+ * request until a fetcher's own fetchItems() runs) and the same research
119
+ * provider `/wiki` and `research <topic>` already use for KB enrichment.
120
+ * Rebuilt only when the enabled source list has actually changed since the
121
+ * last call (`/news add` is the one turn that can change it), so an
122
+ * ordinary turn that never touches `/news` pays nothing repeated here. */
123
+ function newsProvidersFor(config) {
124
+ let cachedProviders = null;
125
+ let cachedKey = null;
126
+ return () => {
127
+ const key = normalizeNewsSourceIds(config.sources).join(",");
128
+ if (cachedProviders && cachedKey === key) return cachedProviders;
129
+ const newsFetchers = new Map();
130
+ for (const id of normalizeNewsSourceIds(config.sources)) {
131
+ const record = newsSourceRecords().find((r) => r.id === id);
132
+ if (record) newsFetchers.set(id, createNewsFetcher(record, { fetchImpl: (...args) => globalThis.fetch(...args) }));
133
+ }
134
+ cachedProviders = {
135
+ newsFetchers,
136
+ getResearchProvider: ({ source } = {}) => getResearchProvider({ source }),
137
+ preflightNewsUrl: (url) => preflightNewsUrl(url, { fetchImpl: (...args) => globalThis.fetch(...args) }),
138
+ };
139
+ cachedKey = key;
140
+ return cachedProviders;
141
+ };
142
+ }
143
+
85
144
  export function createChatSession({ seedPayload = null, vocabSeeded = false, liveReference = false, onLiveLookup = null, synthesisBudget = 12, digestStructures = null } = {}) {
86
145
  setDigestStructures(digestStructures || []);
87
146
  const memoryDir = createInMemoryStore();
@@ -117,12 +176,19 @@ export function createChatSession({ seedPayload = null, vocabSeeded = false, liv
117
176
  // The auto-synthesis budget for this session's learn-on-miss loads — the
118
177
  // page's slider sets it; 0 stores article facts without any entailed rows.
119
178
  let synthesisBudgetOn = Number.isFinite(synthesisBudget) ? synthesisBudget : 12;
179
+ // This session's own `/news` config — one persistent, mutable object (not
180
+ // recreated per turn), so a `/news add`/`/news interval` mutation survives
181
+ // turn to turn the same way it does in a CLI session's newsConfig.
182
+ const newsConfig = resolveNewsConfig(null);
183
+ const defaultNewsProviders = newsProvidersFor(newsConfig);
120
184
 
121
185
  const session = createTurnSession({
122
186
  memoryDir, graph: codeGraph, lexicon, sessionId, vocabHint,
123
187
  buildExtraOptions: () => ({
124
188
  liveReference: liveReferenceOn, onLiveLookup,
125
189
  synthesisBudget: synthesisBudgetOn,
190
+ newsConfig,
191
+ newsProviders: registeredNewsProviders ?? defaultNewsProviders(),
126
192
  }),
127
193
  // `result.liveReference` mirrors a `/wiki on|off|supplement|always`
128
194
  // command back into this session's own toggle state.
@@ -186,7 +252,7 @@ publishTmctSurface({
186
252
  plan: enginePlan,
187
253
  page: {
188
254
  registerWinkModel, registerReferencePackProvider, registerLiveReferenceProvider,
189
- registerResearchProvider, normFactTerm, vocabExampleHint, memoryStats,
255
+ registerResearchProvider, registerNewsProvider, normFactTerm, vocabExampleHint, memoryStats,
190
256
  openPersistedStore, exportFactsJsonl, researchedFactRows,
191
257
  splitSentences: splitSentencesPreservingPaths,
192
258
  },