@polycode-projects/the-mechanical-code-talker 2.7.22 → 2.7.24

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.
@@ -19,6 +19,7 @@ import { appendFacts, loadMemory, readFactRows } from "../adapters/memory/core.m
19
19
  import { worldProvenanceTag } from "../domain/worlds-pack.mjs";
20
20
  import { mulberry32 } from "../domain/seeded-random.mjs";
21
21
  import { fnv1a32 } from "../domain/hash.mjs";
22
+ import { DEFAULT_GAME_CONFIG } from "../domain/game-config.mjs";
22
23
 
23
24
  // ---- tunable constants (starting values, not fixed — the vision radius and
24
25
  // mass economy all want checking against a real playable board) -------------
@@ -187,18 +188,20 @@ export function gridApplyActions(factRows) {
187
188
  export const spiderPathStateKey = (state) => cellId(state.x, state.y);
188
189
 
189
190
  /** Whether (x, y) is currently webbed — the static home zone (always active)
190
- * OR a live spider-built web (mgx:web-built-at-turn + WEB_DURATION_TURNS >
191
+ * OR a live spider-built web (mgx:web-built-at-turn + webDurationTurns >
191
192
  * turn). The one predicate every eat precondition and the fly's movement
192
193
  * gate consult, so the static zone and dynamic webs are ONE concept. `state`
193
194
  * may be omitted (or carry no `webs` map) — the static-zone check alone
194
195
  * still answers correctly, just blind to dynamic webs; every real caller
195
- * threads the folded state through. */
196
- export function hasActiveWebAt(x, y, state, turn) {
196
+ * threads the folded state through. `webDurationTurns` defaults to the
197
+ * shipped WEB_DURATION_TURNS; a caller holding a resolved game config passes
198
+ * its own webDurationTurns instead. */
199
+ export function hasActiveWebAt(x, y, state, turn, webDurationTurns = WEB_DURATION_TURNS) {
197
200
  if (isInWebBlock(x, y)) return true;
198
201
  if (!state?.webs?.size) return false;
199
202
  const target = cellId(x, y);
200
203
  for (const { cell, builtAtTurn } of state.webs.values()) {
201
- if (cell === target && builtAtTurn + WEB_DURATION_TURNS > turn) return true;
204
+ if (cell === target && builtAtTurn + webDurationTurns > turn) return true;
202
205
  }
203
206
  return false;
204
207
  }
@@ -210,11 +213,12 @@ export function hasActiveWebAt(x, y, state, turn) {
210
213
  * only on the fixed target), so this returns null — an honest "no path to
211
214
  * an eat" rather than a path toward a cell that would never satisfy the eat
212
215
  * condition. Null also covers "no believed target at all." `state`/`turn`
213
- * are optional, defaulting to "static web zone only" (see hasActiveWebAt). */
214
- export function planSpiderPath(spiderCell, believedFlyCell, applyActions, state, turn) {
216
+ * are optional, defaulting to "static web zone only" (see hasActiveWebAt).
217
+ * `webDurationTurns` forwards to hasActiveWebAt unchanged. */
218
+ export function planSpiderPath(spiderCell, believedFlyCell, applyActions, state, turn, webDurationTurns = WEB_DURATION_TURNS) {
215
219
  if (!believedFlyCell) return null;
216
220
  const isGoal = (s) =>
217
- s.x === believedFlyCell.x && s.y === believedFlyCell.y && hasActiveWebAt(s.x, s.y, state, turn);
221
+ s.x === believedFlyCell.x && s.y === believedFlyCell.y && hasActiveWebAt(s.x, s.y, state, turn, webDurationTurns);
218
222
  return findActionPath(spiderCell, isGoal, applyActions, { stateKey: spiderPathStateKey });
219
223
  }
220
224
 
@@ -362,13 +366,20 @@ function mostRecentEaterSpider(state, eatenDeltaBySpider) {
362
366
  * never starve-checked, so callers that don't track spider mass, e.g. older
363
367
  * tests, see no behavior change). `state` is the PRE-move fold (for history:
364
368
  * prior flies-eaten counts, prior eggs, prior eaten turns, live webs).
369
+ * `config` (default DEFAULT_GAME_CONFIG.spiderFly) supplies every tunable
370
+ * this pass reads: the initial masses a fallback/hatch/spawn mints, the
371
+ * eggs-eaten lay threshold, the hatch delay, the spawn interval, and the web
372
+ * duration the eat precondition checks against.
365
373
  * Returns `{ writes, events }` — writes to append alongside the turn's
366
374
  * movement facts, events for the tick's own return payload. Pure.
367
375
  */
368
- export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, postMoveMassBySpider = new Map(), turn }) {
376
+ export function runEcologyPass({
377
+ state, postMovePlacements, postMoveMassByFly, postMoveMassBySpider = new Map(), turn,
378
+ config = DEFAULT_GAME_CONFIG.spiderFly,
379
+ }) {
369
380
  const k = turn;
370
381
  const writes = [];
371
- const events = { eaten: [], starved: [], laid: null, hatched: [], spawned: null, massAfterEating: new Map() };
382
+ const events = { eaten: [], starved: [], laid: null, hatched: [], spawned: null, spawnedCell: null, massAfterEating: new Map() };
372
383
 
373
384
  const spiders = [...postMovePlacements.keys()].filter((id) => /^spider-\d+$/.test(id)).sort();
374
385
  const flies = [...postMovePlacements.keys()].filter((id) => /^fly-\d+$/.test(id)).sort();
@@ -381,7 +392,7 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
381
392
  const eatenMassBySpider = new Map();
382
393
  for (const spiderId of spiders) {
383
394
  const sCell = postMovePlacements.get(spiderId);
384
- if (!hasActiveWebAt(sCell.x, sCell.y, state, k)) continue;
395
+ if (!hasActiveWebAt(sCell.x, sCell.y, state, k, config.webDurationTurns)) continue;
385
396
  for (const flyId of flies) {
386
397
  if (claimedFlies.has(flyId)) continue;
387
398
  const fCell = postMovePlacements.get(flyId);
@@ -396,7 +407,7 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
396
407
  for (const [spiderId, delta] of eatenDeltaBySpider) {
397
408
  const newCount = (state.fliesEaten.get(spiderId)?.value ?? 0) + delta;
398
409
  writes.push({ subject: `${spiderId}@turn${k}`, predicate: "mgx:flies-eaten", object: String(newCount) });
399
- const priorSpiderMass = postMoveMassBySpider.get(spiderId) ?? (state.mass.get(spiderId)?.value ?? SPIDER_INITIAL_MASS);
410
+ const priorSpiderMass = postMoveMassBySpider.get(spiderId) ?? (state.mass.get(spiderId)?.value ?? config.spiderInitialMass);
400
411
  const newSpiderMass = priorSpiderMass + (eatenMassBySpider.get(spiderId) ?? 0);
401
412
  writes.push({ subject: `${spiderId}@turn${k}`, predicate: "mgx:mass", object: String(newSpiderMass) });
402
413
  events.massAfterEating.set(spiderId, newSpiderMass);
@@ -427,7 +438,7 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
427
438
  const liveEggId = [...state.laidAtTurn.keys()].find((id) => !state.removed.has(id));
428
439
  if (!liveEggId) {
429
440
  const sinceTurn = mostRecentEggLaidTurn(state);
430
- const threshold = sinceTurn === -1 ? 1 : EGGS_EATEN_THRESHOLD;
441
+ const threshold = sinceTurn === -1 ? 1 : config.eggsEatenThreshold;
431
442
  let eatsSince = events.eaten.length;
432
443
  for (const { turn: eatenTurn } of state.eatenBy.values()) if (eatenTurn > sinceTurn) eatsSince += 1;
433
444
  if (eatsSince >= threshold) {
@@ -442,18 +453,18 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
442
453
  }
443
454
  }
444
455
 
445
- // 4. Hatch — any live egg laid exactly EGG_HATCH_DELAY_TURNS turns ago.
456
+ // 4. Hatch — any live egg laid exactly config.eggHatchDelayTurns turns ago.
446
457
  const liveEggIds = [...state.laidAtTurn.keys()].filter((id) => !state.removed.has(id)).sort();
447
458
  let nextSpiderNum = 1 + maxIdSuffix(state.placements.keys(), /^spider-(\d+)$/);
448
459
  for (const eggId of liveEggIds) {
449
460
  const laidTurn = state.laidAtTurn.get(eggId).value;
450
- if (laidTurn + EGG_HATCH_DELAY_TURNS !== k) continue;
461
+ if (laidTurn + config.eggHatchDelayTurns !== k) continue;
451
462
  const eggCell = state.placements.get(eggId)?.cell;
452
463
  if (!eggCell) continue;
453
464
  const newSpiderId = `spider-${nextSpiderNum}`;
454
465
  nextSpiderNum += 1;
455
466
  writes.push({ subject: `${newSpiderId}@turn${k}`, predicate: "mgx:currently-in", object: eggCell });
456
- writes.push({ subject: `${newSpiderId}@turn${k}`, predicate: "mgx:mass", object: String(SPIDER_INITIAL_MASS) });
467
+ writes.push({ subject: `${newSpiderId}@turn${k}`, predicate: "mgx:mass", object: String(config.spiderInitialMass) });
457
468
  writes.push({ subject: `${eggId}@turn${k}`, predicate: "mgx:hatched-into", object: newSpiderId });
458
469
  events.hatched.push({ egg: eggId, spider: newSpiderId, cell: eggCell });
459
470
  }
@@ -461,7 +472,7 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
461
472
  // 5. Spawn — every third turn, a new fly at a seeded pick among the
462
473
  // currently-uncontested perimeter cells (never Math.random — see
463
474
  // seededPick's own header comment).
464
- if (k % FLY_SPAWN_INTERVAL_TURNS === 0) {
475
+ if (k % config.flySpawnIntervalTurns === 0) {
465
476
  const occupied = new Set();
466
477
  for (const spiderId of spiders) { const c = postMovePlacements.get(spiderId); occupied.add(cellId(c.x, c.y)); }
467
478
  for (const flyId of flies) {
@@ -479,8 +490,9 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
479
490
  const newFlyId = `fly-${1 + maxIdSuffix(state.placements.keys(), /^fly-(\d+)$/)}`;
480
491
  const cell = seededPick(uncontested, `${WORLD_NAME}:${k}:${newFlyId}:spawn`);
481
492
  writes.push({ subject: `${newFlyId}@turn${k}`, predicate: "mgx:currently-in", object: cell });
482
- writes.push({ subject: `${newFlyId}@turn${k}`, predicate: "mgx:mass", object: String(FLY_INITIAL_MASS) });
493
+ writes.push({ subject: `${newFlyId}@turn${k}`, predicate: "mgx:mass", object: String(config.flyInitialMass) });
483
494
  events.spawned = newFlyId;
495
+ events.spawnedCell = cell;
484
496
  }
485
497
  }
486
498
 
@@ -493,15 +505,16 @@ export function runEcologyPass({ state, postMovePlacements, postMoveMassByFly, p
493
505
  * board perimeter — a fresh session's own starting state, never part of
494
506
  * the shipped (reusable, static) world pack itself. A no-op when spider-1
495
507
  * already exists (idempotent — safe to call from a caller unsure whether
496
- * the game has already started). */
497
- export async function startSpiderFlyGame(memoryDir, { flyCount = 1 } = {}) {
508
+ * the game has already started). `config` (default
509
+ * DEFAULT_GAME_CONFIG.spiderFly) supplies the starting masses. */
510
+ export async function startSpiderFlyGame(memoryDir, { flyCount = 1, config = DEFAULT_GAME_CONFIG.spiderFly } = {}) {
498
511
  const state = foldSpiderFlyState(readFactRows(await loadMemory(memoryDir)));
499
512
  if (state.placements.has("spider-1")) return { started: false, facts: [] };
500
513
 
501
514
  const perimeter = perimeterCells();
502
515
  const facts = [
503
516
  { subject: "spider-1", predicate: "mgx:currently-in", object: cellId(WEB_HOME.x, WEB_HOME.y) },
504
- { subject: "spider-1", predicate: "mgx:mass", object: String(SPIDER_INITIAL_MASS) },
517
+ { subject: "spider-1", predicate: "mgx:mass", object: String(config.spiderInitialMass) },
505
518
  ];
506
519
  const occupied = new Set([cellId(WEB_HOME.x, WEB_HOME.y)]);
507
520
  for (let i = 0; i < flyCount; i += 1) {
@@ -510,7 +523,7 @@ export async function startSpiderFlyGame(memoryDir, { flyCount = 1 } = {}) {
510
523
  const cell = seededPick(uncontested.length ? uncontested : perimeter, `${WORLD_NAME}:0:${flyId}:spawn`);
511
524
  occupied.add(cell);
512
525
  facts.push({ subject: flyId, predicate: "mgx:currently-in", object: cell });
513
- facts.push({ subject: flyId, predicate: "mgx:mass", object: String(FLY_INITIAL_MASS) });
526
+ facts.push({ subject: flyId, predicate: "mgx:mass", object: String(config.flyInitialMass) });
514
527
  }
515
528
  await appendFacts(memoryDir, facts.map((f) => ({ ...f, provenance: worldProvenanceTag(WORLD_NAME) })));
516
529
  return { started: true, facts };
@@ -533,11 +546,13 @@ function goalLineFor(subject, believed, arrived, kind) {
533
546
  * web(s) minted THIS tick before they've been written/read back), as a
534
547
  * plain array of { id, cell, builtAtTurn, expiresAtTurn }. Excludes the
535
548
  * always-on static home zone (that's WEB_HOME/WEB_RADIUS, drawn separately —
536
- * this is only the spider-built kind), for a renderer to draw distinctly. */
537
- export function liveWebs(websMap, turn) {
549
+ * this is only the spider-built kind), for a renderer to draw distinctly.
550
+ * `webDurationTurns` defaults to the shipped WEB_DURATION_TURNS; a caller
551
+ * holding a resolved game config passes its own webDurationTurns instead. */
552
+ export function liveWebs(websMap, turn, webDurationTurns = WEB_DURATION_TURNS) {
538
553
  const out = [];
539
554
  for (const [id, { cell, builtAtTurn }] of websMap) {
540
- if (builtAtTurn + WEB_DURATION_TURNS > turn) out.push({ id, cell, builtAtTurn, expiresAtTurn: builtAtTurn + WEB_DURATION_TURNS });
555
+ if (builtAtTurn + webDurationTurns > turn) out.push({ id, cell, builtAtTurn, expiresAtTurn: builtAtTurn + webDurationTurns });
541
556
  }
542
557
  return out;
543
558
  }
@@ -559,9 +574,15 @@ export function liveWebs(websMap, turn) {
559
574
  * eaten/starved/laid/hatched/spawned event summary; `activeWebs` is every
560
575
  * currently-live dynamic web (static home zone excluded — that's fixed grid
561
576
  * geometry, not runtime state), for a renderer to draw distinctly.
577
+ *
578
+ * `opts.config` (default DEFAULT_GAME_CONFIG.spiderFly) supplies every
579
+ * tunable this tick reads: the vision radius, both agents' starting/decrement
580
+ * masses, and the web duration, and is forwarded unchanged into
581
+ * runEcologyPass.
562
582
  */
563
583
  export async function runSpiderFlyTick(memoryDir, opts = {}) {
564
- const { visionRadius = DEFAULT_VISION_RADIUS, toldFacts = [] } = opts;
584
+ const { toldFacts = [], config = DEFAULT_GAME_CONFIG.spiderFly } = opts;
585
+ const visionRadius = config.visionRadius;
565
586
  const rows = readFactRows(await loadMemory(memoryDir));
566
587
  const state = foldSpiderFlyState(rows);
567
588
  const k = state.turnCount + 1;
@@ -580,8 +601,8 @@ export async function runSpiderFlyTick(memoryDir, opts = {}) {
580
601
 
581
602
  for (const spiderId of spiders) {
582
603
  const spiderCell = parseCellId(state.placements.get(spiderId).cell);
583
- const priorMass = state.mass.get(spiderId)?.value ?? SPIDER_INITIAL_MASS;
584
- const newMass = Math.max(0, priorMass - SPIDER_MASS_DECREMENT_PER_TURN);
604
+ const priorMass = state.mass.get(spiderId)?.value ?? config.spiderInitialMass;
605
+ const newMass = Math.max(0, priorMass - config.spiderMassDecrementPerTurn);
585
606
  postMoveMassBySpider.set(spiderId, newMass);
586
607
 
587
608
  // Priority 1: avoid any OTHER live spider believed visible.
@@ -598,7 +619,7 @@ export async function runSpiderFlyTick(memoryDir, opts = {}) {
598
619
  const target = nearestBelievedTarget(spiderId, spiderCell, flies, state, { visionRadius, toldFacts });
599
620
  if (target) {
600
621
  nextCell = spiderCell;
601
- const path = planSpiderPath(spiderCell, target.cell, applyActions, state, k);
622
+ const path = planSpiderPath(spiderCell, target.cell, applyActions, state, k, config.webDurationTurns);
602
623
  if (path) {
603
624
  if (path.actions.length) { nextCell = path.states[1]; plan = path.actions; }
604
625
  } else {
@@ -610,14 +631,14 @@ export async function runSpiderFlyTick(memoryDir, opts = {}) {
610
631
  // already at its closest reachable cell but still a step away
611
632
  // (Chebyshev-adjacent isn't co-located; has-exit-* edges have no
612
633
  // diagonal hop).
613
- const arrived = nextCell.x === target.cell.x && nextCell.y === target.cell.y && hasActiveWebAt(nextCell.x, nextCell.y, state, k);
634
+ const arrived = nextCell.x === target.cell.x && nextCell.y === target.cell.y && hasActiveWebAt(nextCell.x, nextCell.y, state, k, config.webDurationTurns);
614
635
  goal = goalLineFor(spiderId, target, arrived, "spider");
615
636
  } else {
616
637
  // Priority 3: hold position, and build/refresh a web there unless an
617
638
  // unexpired web already covers this exact cell.
618
639
  nextCell = spiderCell;
619
640
  const heldCellId = cellId(spiderCell.x, spiderCell.y);
620
- if (!hasActiveWebAt(spiderCell.x, spiderCell.y, state, k)) {
641
+ if (!hasActiveWebAt(spiderCell.x, spiderCell.y, state, k, config.webDurationTurns)) {
621
642
  const webId = `web-${nextWebNum}`;
622
643
  nextWebNum += 1;
623
644
  tickWebs.set(webId, { cell: heldCellId, builtAtTurn: k });
@@ -639,19 +660,19 @@ export async function runSpiderFlyTick(memoryDir, opts = {}) {
639
660
  for (const flyId of flies) {
640
661
  const flyCell = parseCellId(state.placements.get(flyId).cell);
641
662
  const believedSpider = nearestBelievedTarget(flyId, flyCell, spiders, state, { visionRadius, toldFacts });
642
- const webbed = hasActiveWebAt(flyCell.x, flyCell.y, state, k);
663
+ const webbed = hasActiveWebAt(flyCell.x, flyCell.y, state, k, config.webDurationTurns);
643
664
  const nextCell = webbed ? flyCell : greedyFlyMove(flyCell, believedSpider?.cell ?? null, applyActions, k, flyId);
644
665
  postMovePlacements.set(flyId, nextCell);
645
666
  movementWrites.push({ subject: `${flyId}@turn${k}`, predicate: "mgx:currently-in", object: cellId(nextCell.x, nextCell.y) });
646
- const priorMass = state.mass.get(flyId)?.value ?? FLY_INITIAL_MASS;
647
- const newMass = Math.max(0, priorMass - FLY_MASS_DECREMENT_PER_TURN);
667
+ const priorMass = state.mass.get(flyId)?.value ?? config.flyInitialMass;
668
+ const newMass = Math.max(0, priorMass - config.flyMassDecrementPerTurn);
648
669
  postMoveMassByFly.set(flyId, newMass);
649
670
  movementWrites.push({ subject: `${flyId}@turn${k}`, predicate: "mgx:mass", object: String(newMass) });
650
671
  const goal = webbed ? "trapped in an active web — can't move." : goalLineFor(flyId, believedSpider, true, "fly");
651
672
  agents[flyId] = { cell: cellId(nextCell.x, nextCell.y), goal, mass: newMass };
652
673
  }
653
674
 
654
- const ecology = runEcologyPass({ state, postMovePlacements, postMoveMassByFly, postMoveMassBySpider, turn: k });
675
+ const ecology = runEcologyPass({ state, postMovePlacements, postMoveMassByFly, postMoveMassBySpider, turn: k, config });
655
676
  // Every agent's goal was assigned during movement, before this same tick's
656
677
  // ecology pass resolves eating/starving — so a THIRD agent's goal can name
657
678
  // a subject that dies in this exact tick just as easily as the dying
@@ -697,9 +718,21 @@ export async function runSpiderFlyTick(memoryDir, opts = {}) {
697
718
  }
698
719
  }
699
720
  for (const flyId of ecology.events.starved) delete agents[flyId];
721
+ // A hatched spider or a spawned fly is minted by the ecology pass, which
722
+ // runs AFTER the movement loops above already built `agents` from the
723
+ // pre-tick roster — so without this, a brand-new individual is absent from
724
+ // this tick's own returned agents (and so invisible on the board/HUD) even
725
+ // though the very same tick's event text already announces it, only
726
+ // catching up the following tick once the fold picks it up naturally.
727
+ for (const h of ecology.events.hatched) {
728
+ agents[h.spider] = { cell: h.cell, goal: "just hatched — no goal yet.", plan: null, mass: config.spiderInitialMass };
729
+ }
730
+ if (ecology.events.spawned && ecology.events.spawnedCell) {
731
+ agents[ecology.events.spawned] = { cell: ecology.events.spawnedCell, goal: "just arrived — no goal yet.", mass: config.flyInitialMass };
732
+ }
700
733
  const writes = [...movementWrites, ...ecology.writes];
701
734
  const provenance = `${worldProvenanceTag(WORLD_NAME)}:turn${k}`;
702
735
  await appendFacts(memoryDir, writes.map((f) => ({ ...f, provenance })));
703
736
 
704
- return { turn: k, writes, agents, ecology: ecology.events, activeWebs: liveWebs(tickWebs, k) };
737
+ return { turn: k, writes, agents, ecology: ecology.events, activeWebs: liveWebs(tickWebs, k, config.webDurationTurns) };
705
738
  }
@@ -13,30 +13,39 @@
13
13
  // rationale) — the bootstrap below then just appends it, exactly the shape
14
14
  // openAdventure() itself writes for a real chat session.
15
15
  //
16
- // This session exposes ONLY a raw autoplay tick and a read-only snapshot
17
- // no chat dock. Every state-changing command adventure.mjs's own
18
- // runWorldCommand issues (go/take/open/...) already re-narrates itself
19
- // through the extractive completions digest on every turn (the
20
- // "auto-relook"), so this bundle carries the same wink-nlp/completions
21
- // dependency chain chat.mjs's own runTurn does; a second, lighter path was
22
- // not available to duck under it. Nothing here calls runTurn, though the
23
- // one entry point exercised is adventureTurn itself, via
24
- // adventure-autoplay.mjs, which is the "auto-play is a caller of the
25
- // existing interpreter, never a second one" contract this whole feature
26
- // rests on.
16
+ // This session exposes a raw autoplay tick, a read-only snapshot, AND
17
+ // (mirroring createSpiderFlySession's own `turn(line)`) a full chat-dock
18
+ // entry point: `turn(line)` runs the exact same runTurn the CLI and every
19
+ // other viz page's chat dock run, over this session's own memoryDir/graph/
20
+ // lexicon, threading `focus`/`last`/`planState` across calls the same way a
21
+ // real chat session does. `planState` and `autoplayTick`'s own `planHolder`
22
+ // share ONE mutable holder here, so a manual chat command and an auto-play
23
+ // tick can never disagree about whether the adventure is still open, mid a
24
+ // number game, etc. whichever ran last leaves the holder as the other's
25
+ // starting point. `planHolder.state` starts as adventureTurn's own opened-
26
+ // world shape, so BOTH entry points treat every call as a live, already-open
27
+ // world rather than a fresh opening line: ordinary in-game commands (look/
28
+ // go/take/open/talk/examine/...) dispatch through adventure.mjs's own
29
+ // adventureTurn exactly as autoplayTick's calls already do, and anything not
30
+ // game-shaped falls through to the ordinary conversational layer, exactly
31
+ // like a real CLI session.
32
+ import { runTurn } from "../../services/chat.mjs";
27
33
  import {
28
34
  createInMemoryStore, appendFacts, appendRule, loadMemory, readFactRows,
29
35
  } from "../../adapters/memory/core.mjs";
30
- import { foldWorldState, worldDigestRows } from "../../services/adventure.mjs";
36
+ import { parseEntities } from "../../domain/codegraph.mjs";
37
+ import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
38
+ import { foldWorldState, worldDigestRows, roomAffordances } from "../../services/adventure.mjs";
31
39
  import { runAdventureAutoplayTick } from "../../services/adventure-autoplay.mjs";
32
40
  import { resolveSpriteForClass, SPRITE_REGISTRY } from "../../domain/sprite-map.mjs";
33
41
 
34
- /** A live in-memory adventure this page's ticker drives one auto-play tick
35
- * at a time. Returns `{ memoryDir, autoplayTick, snapshot }`.
42
+ /** A live in-memory adventure this page's ticker AND chat dock can both
43
+ * drive. Returns `{ memoryDir, autoplayTick, turn, snapshot }`.
36
44
  * `worldPayload.facts`/`.rules` seed the store exactly the way
37
45
  * openAdventure() itself does for a real session; `planHolder.state` is set
38
- * the same way, so adventureTurn treats every subsequent call as a live,
39
- * already-open world rather than a fresh opening line. */
46
+ * the same way, so adventureTurn treats every subsequent call auto-play's
47
+ * own or a visitor's typed one — as a live, already-open world rather than
48
+ * a fresh opening line. */
40
49
  export async function createAdventureSession(worldPayload) {
41
50
  const memoryDir = createInMemoryStore();
42
51
  const tag = `world:${worldPayload.name}`;
@@ -54,6 +63,11 @@ export async function createAdventureSession(worldPayload) {
54
63
  const openingHere = foldWorldState(openingRows).placements.get("player")?.object ?? null;
55
64
  if (openingHere) exposedRoomIds = new Set([openingHere]);
56
65
 
66
+ const graph = parseEntities({ individuals: [], objectProperties: [] });
67
+ const lexicon = loadLexicon();
68
+ let focus = null;
69
+ let last = null;
70
+
57
71
  return {
58
72
  memoryDir,
59
73
 
@@ -69,8 +83,30 @@ export async function createAdventureSession(worldPayload) {
69
83
  return result;
70
84
  },
71
85
 
86
+ /** One dispatched chat turn — the SAME runTurn the CLI and every other
87
+ * viz page's own chat dock run, over this session's own memoryDir. A
88
+ * throwing runTurn must never kill the session — the page has no other
89
+ * chance to show this turn's answer. */
90
+ async turn(line) {
91
+ let result;
92
+ try {
93
+ result = await runTurn(line, {
94
+ config: null, source: null, graph, focus, last, memoryDir, sessionId,
95
+ env: {}, lexicon, vocabHint: "", planState: planHolder.state,
96
+ });
97
+ } catch (e) {
98
+ const message = e instanceof Error ? e.message : String(e);
99
+ return { answer: `Something went wrong answering that (${message}). Try rephrasing, or /help.`, end: false, record: null, plan: null };
100
+ }
101
+ focus = result.focus;
102
+ last = result.last;
103
+ if ("planState" in result) planHolder.state = result.planState;
104
+ return { answer: result.answer, end: Boolean(result.end), record: result.record ?? null, plan: result.plan ?? null };
105
+ },
106
+
72
107
  /** A read-only fold of the current room — no engine advance — for the
73
- * page's own redraw after boot and after every tick. */
108
+ * page's own redraw after boot, after every tick, and after every
109
+ * manual chat turn. */
74
110
  async snapshot() {
75
111
  const rows = readFactRows(await loadMemory(memoryDir));
76
112
  const state = foldWorldState(rows);
@@ -81,8 +117,9 @@ export async function createAdventureSession(worldPayload) {
81
117
  }
82
118
 
83
119
  // Re-exported so the page's own rendering script (adventure-viz.mjs) never
84
- // has to duplicate sprite resolution or the digest reader the same posture
120
+ // has to duplicate sprite resolution, the digest reader, or the room
121
+ // affordances the chat dock's own pills read from — the same posture
85
122
  // spider-fly-browser-entry.mjs's own globalThis.tmctSpiderFly re-export takes.
86
123
  globalThis.tmctAdventure = {
87
- createAdventureSession, resolveSpriteForClass, SPRITE_REGISTRY, worldDigestRows,
124
+ createAdventureSession, resolveSpriteForClass, SPRITE_REGISTRY, worldDigestRows, roomAffordances,
88
125
  };
@@ -23587,6 +23587,48 @@ ${JSON.stringify(envelope, null, 2)}`;
23587
23587
  init_core();
23588
23588
  init_hash();
23589
23589
 
23590
+ // src/domain/game-config.mjs
23591
+ var DEFAULT_GAME_CONFIG = Object.freeze({
23592
+ spiderFly: Object.freeze({
23593
+ spiderInitialMass: 15,
23594
+ spiderMassDecrementPerTurn: 0.5,
23595
+ flyInitialMass: 10,
23596
+ flyMassDecrementPerTurn: 1,
23597
+ visionRadius: 4,
23598
+ eggHatchDelayTurns: 3,
23599
+ flySpawnIntervalTurns: 3,
23600
+ eggsEatenThreshold: 2,
23601
+ webDurationTurns: 10
23602
+ }),
23603
+ guessNumber: Object.freeze({
23604
+ defaultLo: 1,
23605
+ defaultHi: 100,
23606
+ maxBound: 1e9
23607
+ }),
23608
+ planning: Object.freeze({
23609
+ maxDepth: 300
23610
+ })
23611
+ });
23612
+ var SPIDER_FLY_KEY_MAP = Object.freeze({
23613
+ spider_initial_mass: "spiderInitialMass",
23614
+ spider_mass_decrement_per_turn: "spiderMassDecrementPerTurn",
23615
+ fly_initial_mass: "flyInitialMass",
23616
+ fly_mass_decrement_per_turn: "flyMassDecrementPerTurn",
23617
+ vision_radius: "visionRadius",
23618
+ egg_hatch_delay_turns: "eggHatchDelayTurns",
23619
+ fly_spawn_interval_turns: "flySpawnIntervalTurns",
23620
+ eggs_eaten_threshold: "eggsEatenThreshold",
23621
+ web_duration_turns: "webDurationTurns"
23622
+ });
23623
+ var GUESS_NUMBER_KEY_MAP = Object.freeze({
23624
+ default_lo: "defaultLo",
23625
+ default_hi: "defaultHi",
23626
+ max_bound: "maxBound"
23627
+ });
23628
+ var PLANNING_KEY_MAP = Object.freeze({
23629
+ max_depth: "maxDepth"
23630
+ });
23631
+
23590
23632
  // src/services/spider-fly-turn.mjs
23591
23633
  init_core();
23592
23634
  var SPIDER_FLY_TOLD_RE = new RegExp(