@polycode-projects/the-mechanical-code-talker 3.3.0 → 4.0.0

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.
@@ -1,11 +1,13 @@
1
- // mud-browser-entry.mjs — the esbuild entry for mud.html's four-character,
1
+ // mud-browser-entry.mjs — the esbuild entry for mud.html's multi-character,
2
2
  // one-shared-world browser session (public/mud-browser.bundle.js), mirroring
3
3
  // adventure-browser-entry.mjs's own session-factory shape. The difference is
4
4
  // the whole point of the mud demo: adventure-browser-entry.mjs drives ONE
5
- // player through one world; this file drives FOUR independent characters
6
- // through the SAME live world, over the SAME memoryDir.
5
+ // player through one world; this file drives SEVERAL independent characters
6
+ // through the SAME live world, over the SAME memoryDir. Which of the world's
7
+ // animals are played is the caller's choice (pickMudRoster draws them fresh
8
+ // each reset), never a fixed pair baked in here.
7
9
  //
8
- // What's shared across all four characters, and why: the store itself
10
+ // What's shared across every character, and why: the store itself
9
11
  // (memoryDir) — mole-1's dig must be visible to vole-1's very next look — and
10
12
  // ONE planHolder.state, seeded once as "mud-garden is already live" the same
11
13
  // way adventure-browser-entry.mjs seeds it, since "is the world open" is a
@@ -22,41 +24,51 @@
22
24
  // page's chat dock); `autoplayTick(k)` runs mud-turn.mjs's runMudTurn — one
23
25
  // whole scripted turn (investigate, walk toward known food, dig at the
24
26
  // edge). The caller (mud-viz.mjs's own inlined script) is responsible for
25
- // SERIALIZING ticks across the four characters when more than one window is
27
+ // SERIALIZING ticks across the characters when more than one window is
26
28
  // auto-playing at once — this file makes no ordering promise between two
27
29
  // concurrent calls into the same memoryDir, the same way two callers writing
28
30
  // into any shared store concurrently would need their own queue.
29
31
  import { runTurn } from "../../services/chat.mjs";
30
- import { createInMemoryStore, appendFacts, appendRule, loadMemory, readFactRows } from "../../adapters/memory/core.mjs";
32
+ import {
33
+ createInMemoryStore, appendFacts, appendRule, loadMemory, readFactRows, removeFacts,
34
+ } from "../../adapters/memory/core.mjs";
31
35
  import { parseEntities } from "../../domain/codegraph.mjs";
32
36
  import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
33
37
  import {
34
38
  foldWorldState, worldActionRows, worldDigestRows, roomAffordances,
35
39
  personKnowledgeLines, personKnownFoodLines,
40
+ diggableDirections, castInRoom, displayNameOf, isOutOfPlay, outOfPlayReasonOf, outOfPlayPhrase,
41
+ roomKindOf,
36
42
  } from "../../services/adventure.mjs";
43
+ import { relatedForTerm } from "../../domain/skos-view.mjs";
37
44
  import { runMudTurn } from "../../services/mud-turn.mjs";
45
+ import { parseMudEditorText, planMudEditorSync } from "../../services/mud-editor.mjs";
46
+ import { mudSpeciesOf } from "../../domain/game-config.mjs";
38
47
  import { worldProvenanceTag } from "../../domain/worlds-pack.mjs";
39
48
  import { resolveSpriteForClass, SPRITE_REGISTRY, classAncestorChain } from "../../domain/sprite-map.mjs";
40
49
  import { resolveSpriteAsset } from "../../domain/sprite-templates.mjs";
41
50
 
42
- /** A live, shared mud world four characters can each act in. `worldPayload`
51
+ /** A live, shared mud world several characters can each act in. `worldPayload`
43
52
  * is `{ name, facts, rules, opening }` — the same shape adventure-browser-
44
53
  * entry.mjs's own worldPayload takes, read once at build time through the
45
54
  * real Node worlds-pack provider (see mud-viz.mjs's header for why: the
46
55
  * world's canonical source is a Node-only gzipped JSONL shard the browser
47
- * cannot read). `characters` is the roster this page drives (e.g.
48
- * `["mole-1", "vole-1", "badger-1", "groundhog-1"]`) every character
49
- * already placed by the world's own seed facts.
56
+ * cannot read). `characters` is the roster this page drives (e.g. the two
57
+ * ids pickMudRoster drew this reset). The world is opened for exactly that
58
+ * list (worldFactsForCast, below): more animals than mud-garden hand-authors
59
+ * are minted, fewer leaves the ones nobody is playing out of the world
60
+ * altogether.
50
61
  *
51
62
  * Returns `{ memoryDir, windows, snapshot }`. `windows` is a plain object
52
63
  * keyed by character id, each value `{ character, turn, autoplayTick,
53
- * visitedRoomIds }`. `snapshot()` is the one OMNISCIENT read this module
54
- * exposes — the central world map's own data source, never a per-window
55
- * one. */
64
+ * visitedRoomIds, turnsTaken, isOutOfPlay, outOfPlayReason }`. `snapshot()` is
65
+ * the one OMNISCIENT read this module exposes — the central world map's own
66
+ * data source, never a per-window one. */
56
67
  export async function createMudSession(worldPayload, { characters = [] } = {}) {
57
68
  const memoryDir = createInMemoryStore();
58
69
  const tag = worldProvenanceTag(worldPayload.name);
59
- await appendFacts(memoryDir, worldPayload.facts.map((f) => ({
70
+ const seedFacts = worldFactsForCast(worldPayload.facts, characters);
71
+ await appendFacts(memoryDir, seedFacts.map((f) => ({
60
72
  subject: f.subject, predicate: f.predicate, object: f.object, provenance: tag,
61
73
  })));
62
74
  for (const rule of worldPayload.rules) {
@@ -70,11 +82,19 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
70
82
  // shipped "player" individual mud-garden deliberately has none of).
71
83
  const planHolder = { state: { adventure: { world: worldPayload.name } } };
72
84
  const graph = parseEntities({ individuals: [], objectProperties: [] });
85
+ // The world's own minted ids ("groundhog-1", "carrot-2") are declared as
86
+ // vocabulary inside the adventure lane itself, for the length of one world
87
+ // command — see adventure.mjs's own worldLexicon. This page hands over the
88
+ // plain core lexicon and lets the lane do it.
73
89
  const lexicon = loadLexicon();
74
90
 
75
- async function roomOf(character) {
91
+ async function readWorld() {
76
92
  const rows = readFactRows(await loadMemory(memoryDir));
77
- const state = foldWorldState(worldActionRows(rows));
93
+ return { rows, state: foldWorldState(worldActionRows(rows)) };
94
+ }
95
+
96
+ async function roomOf(character) {
97
+ const { state } = await readWorld();
78
98
  return state.placements.get(character)?.object ?? null;
79
99
  }
80
100
 
@@ -88,6 +108,11 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
88
108
  let focus = null;
89
109
  let last = null;
90
110
  const visitedRoomIds = new Set();
111
+ // This character's OWN turns, not the page's shared tick counter: two
112
+ // windows playing at different speeds, or one paused while the other
113
+ // runs, have genuinely different counts, and showing the shared one under
114
+ // both animals says something untrue about each.
115
+ let turnsTaken = 0;
91
116
  const startRoom = await roomOf(character);
92
117
  if (startRoom) visitedRoomIds.add(startRoom);
93
118
 
@@ -115,6 +140,7 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
115
140
  focus = result.focus;
116
141
  last = result.last;
117
142
  if ("planState" in result) planHolder.state = result.planState;
143
+ turnsTaken += 1;
118
144
  const here = await roomOf(character);
119
145
  if (here) visitedRoomIds.add(here);
120
146
  return { answer: result.answer, end: Boolean(result.end) };
@@ -130,6 +156,9 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
130
156
  * dig-flourish triggers straight off `actions`. */
131
157
  async autoplayTick(k) {
132
158
  const result = await runMudTurn(character, { world: worldPayload.name, memoryDir, env: {}, graph, k });
159
+ // A turn that ended in starvation still happened, and still counts —
160
+ // only a DECLINED turn (no room to act in) leaves the tally alone.
161
+ if (result.room) turnsTaken += 1;
133
162
  if (result.roomAfter) visitedRoomIds.add(result.roomAfter);
134
163
  return result;
135
164
  },
@@ -137,6 +166,26 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
137
166
  /** This character's own discovered-room history — real fog of war,
138
167
  * never merged with a sibling window's. */
139
168
  visitedRoomIds: () => [...visitedRoomIds],
169
+
170
+ /** How many turns THIS character has taken — its own scripted ticks and
171
+ * its own typed commands, and nobody else's. */
172
+ turnsTaken: () => turnsTaken,
173
+
174
+ /** True once this character's run has ended — a predator ate it, or its
175
+ * mass ran out. It takes no further turns and every command it gives
176
+ * declines, so a caller can stop ticking it and say so on screen. */
177
+ async isOutOfPlay() {
178
+ const { state } = await readWorld();
179
+ return isOutOfPlay(state, character);
180
+ },
181
+
182
+ /** WHICH ending it was — "eaten" or "starved" — or null while it is still
183
+ * playing. The two read nothing alike on screen, so a pane showing a
184
+ * fate needs the reason, not just the fact. */
185
+ async outOfPlayReason() {
186
+ const { state } = await readWorld();
187
+ return outOfPlayReasonOf(state, character);
188
+ },
140
189
  };
141
190
  }
142
191
 
@@ -150,7 +199,118 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
150
199
  return { rows, state };
151
200
  }
152
201
 
153
- return { memoryDir, windows, snapshot };
202
+ /** The world editor's own store sync: parse `text` (mud-editor.mjs's own
203
+ * parseMudEditorText), plan the writes it implies, and apply them — scoped to
204
+ * THIS world's provenance tag only. Returns `{ unrecognized, added, removed }`.
205
+ *
206
+ * Two things this does that a fresh, unplayed world would not need.
207
+ * Retractions run only when the WHOLE document parsed cleanly, so a half-typed
208
+ * line is never read as "this fact is gone". And a fold-versioned write
209
+ * (a placement, an openness, a mass) is stamped `subject@turnN` at one past
210
+ * the world's own turn count, exactly the way every in-game action's commit
211
+ * writes: the fold takes the newest turn, so an untagged row would sit at turn
212
+ * zero and lose to the snapshot the last played turn already left behind —
213
+ * the edit would look accepted and change nothing. */
214
+ async function applyEdit(text) {
215
+ const allRows = readFactRows(await loadMemory(memoryDir));
216
+ const worldRows = allRows.filter((r) => typeof r.provenance === "string" && r.provenance.indexOf(tag) === 0);
217
+ const state = foldWorldState(worldRows);
218
+ const { triples, unrecognized } = parseMudEditorText(text);
219
+ const { toAppend, toRemoveIds } = planMudEditorSync(worldRows, state, triples);
220
+ const editTurn = state.turnCount + 1;
221
+ if (toAppend.length) {
222
+ await appendFacts(memoryDir, toAppend.map((f) => ({
223
+ subject: f.kind === "other" ? f.subject : `${f.subject}@turn${editTurn}`,
224
+ predicate: f.predicate,
225
+ object: f.object,
226
+ provenance: f.kind === "other" ? tag : `${tag}:turn${editTurn}`,
227
+ })));
228
+ }
229
+ const removed = unrecognized.length === 0 && toRemoveIds.length
230
+ ? (await removeFacts(memoryDir, toRemoveIds)).removed.length
231
+ : 0;
232
+ return { unrecognized, added: toAppend.length, removed };
233
+ }
234
+
235
+ return { memoryDir, windows, snapshot, applyEdit };
236
+ }
237
+
238
+ /** `count` entries drawn at random from `roster`, in random order, without
239
+ * repeats — which animals this visit is played with. Called fresh on every
240
+ * reset, so the same page gives a different pairing each time and the world
241
+ * never reads as one fixed cast. `random` is injectable so a caller can pin
242
+ * the draw; the world engine itself still writes no randomness anywhere, and
243
+ * this picks the players, never anything the world folds. */
244
+ export function pickMudRoster(roster, { count = 2, random = Math.random } = {}) {
245
+ const pool = [...(roster || [])];
246
+ for (let i = pool.length - 1; i > 0; i -= 1) {
247
+ const j = Math.floor(random() * (i + 1));
248
+ [pool[i], pool[j]] = [pool[j], pool[i]];
249
+ }
250
+ return pool.slice(0, Math.min(count, pool.length));
251
+ }
252
+
253
+ /** `roster` grown to `size` ids by numbering more instances of the species it
254
+ * already names — "mole-2", "vole-3" — so a page can cast more animals than
255
+ * the world hand-authors individuals for. The authored ids come first and
256
+ * keep their own numbers; a minted id never collides with one. The species
257
+ * round-robins, so the extras stay spread across the roster's animals rather
258
+ * than piling ten moles into the garden. Pure. */
259
+ export function expandMudRoster(roster, size) {
260
+ const ids = [...(roster || [])];
261
+ if (!ids.length) return ids;
262
+ const used = new Set(ids);
263
+ const species = [...new Set(ids.map(mudSpeciesOf))];
264
+ for (let instance = 1; ids.length < size; instance += 1) {
265
+ for (const kind of species) {
266
+ if (ids.length >= size) break;
267
+ const id = `${kind}-${instance}`;
268
+ if (used.has(id)) continue;
269
+ used.add(id);
270
+ ids.push(id);
271
+ }
272
+ }
273
+ return ids;
274
+ }
275
+
276
+ /** The facts that place `characters` the world's own `facts` never placed —
277
+ * each one copied wholesale from an authored individual of the same species,
278
+ * with the subject swapped. Copying rather than composing is what keeps a
279
+ * minted animal an ORDINARY one: it arrives with the same type, the same
280
+ * starting room and the same mass mud-garden gives its own mole, and it
281
+ * picks up anything a later edit adds to that mole for free. A species the
282
+ * world authors nobody of is skipped rather than guessed at. Pure. */
283
+ export function mintedCharacterFacts(facts, characters) {
284
+ const rows = facts || [];
285
+ const placedIn = (subject) => rows.some((f) => f.subject === subject && f.predicate === "mgx:currently-in");
286
+ const minted = [];
287
+ for (const character of characters || []) {
288
+ if (placedIn(character) || minted.some((f) => f.subject === character)) continue;
289
+ const species = mudSpeciesOf(character);
290
+ const template = rows.find((f) => f.predicate === "mgx:currently-in" && mudSpeciesOf(f.subject) === species);
291
+ if (!template) continue;
292
+ for (const fact of rows) {
293
+ if (fact.subject !== template.subject) continue;
294
+ minted.push({ subject: character, predicate: fact.predicate, object: fact.object });
295
+ }
296
+ }
297
+ return minted;
298
+ }
299
+
300
+ /** `facts` opened for exactly `characters`: the playable animals nobody is
301
+ * playing are left out of the world, and the characters the world authors
302
+ * nobody for are minted in. The first half is what keeps the cast honest —
303
+ * an authored animal nobody drives stands in its starting room for the whole
304
+ * run, shows up in every room description and answers when talked to, all
305
+ * without ever taking a turn. The fox, a den's resident mouse and every prop
306
+ * are untouched: they are the world, not the cast. Pure. */
307
+ export function worldFactsForCast(facts, characters) {
308
+ const rows = facts || [];
309
+ const cast = new Set(characters || []);
310
+ const uncast = new Set(rows
311
+ .filter((f) => f.predicate === "rdf:type" && f.object === "adventurer" && !cast.has(f.subject))
312
+ .map((f) => f.subject));
313
+ return rows.filter((f) => !uncast.has(f.subject)).concat(mintedCharacterFacts(rows, characters));
154
314
  }
155
315
 
156
316
  // Re-exported so mud-viz.mjs's own inlined script never duplicates sprite
@@ -158,7 +318,13 @@ export async function createMudSession(worldPayload, { characters = [] } = {}) {
158
318
  // chat pills already need — the same reach-through-the-global posture
159
319
  // adventure-browser-entry.mjs's own globalThis.tmctAdventure takes.
160
320
  globalThis.tmctMud = {
161
- createMudSession, resolveSpriteForClass, SPRITE_REGISTRY, classAncestorChain, resolveSpriteAsset,
321
+ createMudSession, pickMudRoster, expandMudRoster, mintedCharacterFacts, worldFactsForCast,
322
+ resolveSpriteForClass, SPRITE_REGISTRY, classAncestorChain, resolveSpriteAsset,
162
323
  foldWorldState, worldActionRows, worldDigestRows, roomAffordances,
163
324
  personKnowledgeLines, personKnownFoodLines,
325
+ diggableDirections, castInRoom, displayNameOf, isOutOfPlay, outOfPlayReasonOf, outOfPlayPhrase,
326
+ roomKindOf,
327
+ // The edit mode's own reach-throughs: the SKOS neighbourhood and the is-a
328
+ // chain its cursor-suggestion pills read, neither of which is splice-safe.
329
+ relatedForTerm,
164
330
  };
@@ -0,0 +1,39 @@
1
+ // p2p-browser-entry.mjs — the esbuild entry for public/vendor/p2p.js, the ONE
2
+ // shared networking asset every page that joins a world imports at runtime.
3
+ // Same arrangement as ./vendor/wink.js: an ESM module, same-origin, one cached
4
+ // copy site-wide, imported dynamically by a page's own inline script rather
5
+ // than bundled into each page's engine bundle.
6
+ //
7
+ // A page imports it LAZILY, off the boot path, so networking nobody asked for
8
+ // never delays a first answer. The service worker precaches it anyway, which
9
+ // is what lets two laptops on a LAN with no internet still invite each other
10
+ // on a return visit.
11
+ //
12
+ // This module re-exports only; every rule lives in the layers below. The
13
+ // memory core rides along because p2p-room.mjs merges through appendFacts, and
14
+ // this asset therefore holds its own copy of that code separate from the page's
15
+ // engine bundle. The two copies operate on the SAME handle object the page
16
+ // passes in, and appendFacts rebuilds its lookup index from the payload on
17
+ // every mutation, so neither copy can read the other's stale index.
18
+ export {
19
+ createP2pRoom,
20
+ PRESENCE_SCOPE,
21
+ ROOM_IDLE,
22
+ ROOM_SHARING,
23
+ ROOM_ANSWERING,
24
+ ROOM_CONNECTING,
25
+ ROOM_CONNECTED,
26
+ ROOM_FAILED,
27
+ } from "../../services/p2p-room.mjs";
28
+ export { createTransport } from "../../adapters/p2p/webrtc-transport.mjs";
29
+ export { generatePeerId, generateWorldId, generateDisplayName } from "../../domain/p2p/peer-id.mjs";
30
+ export { chatSyncableFacts, mudSyncableFacts } from "../../domain/p2p/sync-filter.mjs";
31
+ export { decodeInviteBlob, encodeInviteBlob } from "../../domain/p2p/wire.mjs";
32
+ export {
33
+ latestProvenanceTimestamp,
34
+ isRecentWave,
35
+ latestFact,
36
+ NODE_NAME_PREDICATE,
37
+ WORLD_NAME_PREDICATE,
38
+ WAVED_PREDICATE,
39
+ } from "../../domain/p2p/facts.mjs";