@polycode-projects/the-mechanical-code-talker 5.0.22 → 5.0.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.
package/bin/tmct.mjs CHANGED
@@ -603,13 +603,14 @@ async function writeStandaloneViewPage(archetype, rest) {
603
603
  const engineBundleJs = await buildEngineBundleJs("build-sprites-bundle.mjs");
604
604
  const { readSpriteTemplateFiles } = await import("../src/adapters/corpus/sprite-template-files.mjs");
605
605
  const { readSpriteLargeTemplateFiles } = await import("../src/adapters/corpus/sprite-large-template-files.mjs");
606
- const { loadSpriteOntologyFactRows, renderSpriteCatalogHtml } = await import("../src/services/sprite-catalog-viz.mjs");
606
+ const { loadSpriteOntologyFactRows, loadAdventureSceneRoomClasses, renderSpriteCatalogHtml } = await import("../src/services/sprite-catalog-viz.mjs");
607
607
  html = renderSpriteCatalogHtml({
608
608
  iconTemplates: readSpriteTemplateFiles(),
609
609
  largeTemplates: readSpriteLargeTemplateFiles(),
610
610
  factRows: await loadSpriteOntologyFactRows(),
611
611
  spritesBundleAvailable: true,
612
612
  engineBundleJs,
613
+ adventureRoomClasses: await loadAdventureSceneRoomClasses(),
613
614
  });
614
615
  } else if (archetype === "spider-fly") {
615
616
  const engineBundleJs = await buildEngineBundleJs("build-spider-fly-bundle.mjs");
@@ -1595,7 +1596,7 @@ async function main() {
1595
1596
  "graph-query tool calls for a compound or maintenance-goal request.\n\n" +
1596
1597
  "Usage:\n" +
1597
1598
  " tmct plan \"<request>\" [--repo <abs>] [--graph <path>] [--config <path>]\n" +
1598
- " [--tools <name,name,...>] [--json]\n\n" +
1599
+ " [--tools <name,name,...>] [--json] [--goals]\n\n" +
1599
1600
  " --repo <abs> target a repo's graph (<abs>/.tmct/graph.json); default: git root/cwd\n" +
1600
1601
  " --graph <path> explicit graph file (repeatable — multiple graphs merge)\n" +
1601
1602
  " --config <path> an alternate tmct.toml location (a file or a directory)\n" +
@@ -1604,7 +1605,9 @@ async function main() {
1604
1605
  " registered capability\n" +
1605
1606
  " --json print the full machine-readable loop result instead of\n" +
1606
1607
  " the human-readable report (a non-zero exit still means\n" +
1607
- " an honest refusal, not a crash)\n\n" +
1608
+ " an honest refusal, not a crash)\n" +
1609
+ " --goals print the declared goals a trace is recognized against,\n" +
1610
+ " with where each came from, and exit\n\n" +
1608
1611
  "Examples:\n" +
1609
1612
  " tmct plan \"of the modules impacted by src/lib/http.mjs, which are untested\"\n" +
1610
1613
  " tmct plan \"what most needs a test in this codebase\"\n" +
@@ -1615,6 +1618,7 @@ async function main() {
1615
1618
  const { strFlag, resolveRuntimeConfig } = await import("../src/services/cli-args.mjs");
1616
1619
  const toolsFlag = strFlag(rest, ["--tools"]);
1617
1620
  const jsonFlag = rest.includes("--json");
1621
+ const goalsFlag = rest.includes("--goals");
1618
1622
  // The request is every argv token that isn't a recognized flag or its value,
1619
1623
  // rejoined with single spaces — so both `tmct plan "quoted request"` and a
1620
1624
  // bare `tmct plan unquoted request words` work.
@@ -1623,11 +1627,11 @@ async function main() {
1623
1627
  for (let i = 0; i < rest.length; i += 1) {
1624
1628
  const a = rest[i];
1625
1629
  if (FLAG_WITH_VALUE.has(a)) { i += 1; continue; }
1626
- if (a === "--json") continue;
1630
+ if (a === "--json" || a === "--goals") continue;
1627
1631
  requestParts.push(a);
1628
1632
  }
1629
1633
  const request = requestParts.join(" ").trim();
1630
- if (!request) {
1634
+ if (!request && !goalsFlag) {
1631
1635
  process.stderr.write("tmct plan: needs a request, e.g. `tmct plan \"of the modules impacted by X, which are untested\"`\n");
1632
1636
  process.exit(2);
1633
1637
  }
@@ -1661,6 +1665,17 @@ async function main() {
1661
1665
  process.exit(2);
1662
1666
  }
1663
1667
  }
1668
+ if (goalsFlag) {
1669
+ const { declaredGoals } = await import("../src/domain/router/recognize.mjs");
1670
+ const { renderDeclaredGoals } = await import("../src/services/chat.mjs");
1671
+ const { loadMemory, readFactRows, readRuleRows } = await import("../src/adapters/memory/core.mjs");
1672
+ const memory = await loadMemory(memoryDir);
1673
+ const goals = declaredGoals({ worldRows: readFactRows(memory), ruleRows: readRuleRows(memory) }, { tools });
1674
+ process.stdout.write(renderDeclaredGoals(goals) + "\n");
1675
+ await closeMemoryStore();
1676
+ for (const dispose of ctx.disposers || []) dispose();
1677
+ return;
1678
+ }
1664
1679
  try {
1665
1680
  const result = await runCapabilityPlan(request, tools, ctx);
1666
1681
  if (jsonFlag) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.22",
3
+ "version": "5.0.24",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -159,8 +159,6 @@
159
159
  "bench:receipts": "node scripts/bench-receipts.mjs",
160
160
  "claims": "node scripts/claims/run-all.mjs",
161
161
  "claim:prose-band": "node scripts/claims/claim-prose-band.mjs",
162
- "claim:paraphrase": "node scripts/claims/claim-paraphrase.mjs",
163
- "claim:definitions": "node scripts/claims/claim-definitions.mjs",
164
162
  "claim:openbookqa": "node scripts/claims/claim-openbookqa.mjs",
165
163
  "claim:planner": "node scripts/claims/claim-planner.mjs",
166
164
  "roll": "node scripts/roll.mjs",
@@ -172,6 +172,7 @@ export const CLI_VERBS = [
172
172
  { flag: "[--config <path>]", prose: ["untested\", \"what most needs a test\") — a real STRIPS/"] },
173
173
  { flag: "[--tools <a,b,...>]", prose: ["PDDL planner (src/domain/router/*), never a guessed call."] },
174
174
  { flag: "[--json]", prose: ["Prints the grounded step sequence + composed answer,", "or an honest \"no plan found\". --tools restricts the", "declared toolset; --json prints the full loop result."] },
175
+ { flag: "[--goals]", prose: ["print the declared goals a trace is recognized", "against, with where each came from, and exit"] },
175
176
  ],
176
177
  },
177
178
  {
@@ -40,10 +40,12 @@ import {
40
40
  compileDomain, stateFromFacts, stateKeyFor, movesFromRules, compileGoal, PlanBudgetError,
41
41
  } from "../domain.mjs";
42
42
  import { findActionPath } from "../planning.mjs";
43
+ import { traceOfCalls, declaredGoals, recognizeGoal } from "./recognize.mjs";
43
44
 
44
45
  export const ROUTER_DRIVER = "resolver-0.8.0";
45
46
  export const GOAL_DRIVER = "goal-0.8.1";
46
47
  export const TAUGHT_DRIVER = "taught-0.1.0";
48
+ export const RECOGNIZE_DRIVER = "recognize-0.1.0";
47
49
 
48
50
  /** Every registered capability's name — the default declared toolset for a
49
51
  * caller that doesn't want to hand-pick a subset. */
@@ -259,13 +261,52 @@ export async function runTaughtPlan(request, tools, ctx) {
259
261
  };
260
262
  }
261
263
 
264
+ // ---- the recognition lane -----------------------------------------------------
265
+
266
+ /** Recognize what an observed trace was doing, as a loopResult the same graders
267
+ * and surfaces read. `ctx.trace` is the observed step source: an array of
268
+ * { name, input } calls (a runCapabilityPlan result, or a transcript's
269
+ * tool_use blocks). Makes no calls and writes nothing — recognition never
270
+ * changes what it is recognizing. */
271
+ export async function runRecognition(tools, ctx) {
272
+ const trace = traceOfCalls(ctx.trace || []);
273
+ const goals = declaredGoals(ctx, { tools });
274
+ const r = recognizeGoal(trace, goals);
275
+ return {
276
+ calls: [], terminated: true, driver: RECOGNIZE_DRIVER,
277
+ refused: r.goal === null,
278
+ proof: r.proof, why: r.why,
279
+ ...(r.goal ? { inferredGoal: r.goal.id } : {}),
280
+ ...(r.reject ? { reject: true } : {}),
281
+ ...(r.ambiguous ? { ambiguousGoals: r.ambiguous.map((g) => g.id) } : {}),
282
+ };
283
+ }
284
+
285
+ /** A ctx carrying an observed trace also gets a `recognition` field on the
286
+ * result: what the trace fits, or the reject class. Additive — it never
287
+ * changes calls, refused, or why, so a caller that ignores it sees exactly
288
+ * the loop result it saw before. */
289
+ async function withRecognition(result, tools, ctx) {
290
+ if (!Array.isArray(ctx.trace) || !ctx.trace.length) return result;
291
+ const r = await runRecognition(tools, ctx);
292
+ return {
293
+ ...result,
294
+ recognition: {
295
+ inferredGoal: r.inferredGoal ?? null,
296
+ reject: r.reject === true,
297
+ ambiguousGoals: r.ambiguousGoals ?? null,
298
+ why: r.why,
299
+ },
300
+ };
301
+ }
302
+
262
303
  /** The full drive: resolver/planner first; a refusal there falls through to
263
304
  * the taught world-goal lane (runTaughtPlan, above), and only a request that
264
305
  * is not a world goal escalates to the closed-world goal-reasoner. Mirrors
265
306
  * test-benchmarks/agentbench's driver-resolver.mjs + driver-goal.mjs composition, with no
266
307
  * test-benchmarks/agentbench/ dependency (test-benchmarks/agentbench/ is dev-only, never shipped). Returns a
267
308
  * loopResult:
268
- * `{ calls, refused, terminated, proof, why, driver, composed?, observed?, candidateResults? }`.
309
+ * `{ calls, refused, terminated, proof, why, driver, composed?, observed?, candidateResults?, recognition? }`.
269
310
  *
270
311
  * A C1 refusal that already carries `candidateResults` (the tied-candidate
271
312
  * composer's enumerate-or-refuse answer) is TERMINAL — it stands as-is rather
@@ -275,15 +316,15 @@ export async function runTaughtPlan(request, tools, ctx) {
275
316
  * plainer refuse with no candidates at all). */
276
317
  export async function runCapabilityPlan(request, tools, ctx) {
277
318
  const c1 = await runResolverPlan(request, tools, ctx);
278
- if (!c1.refused || c1.candidateResults) return c1;
319
+ if (!c1.refused || c1.candidateResults) return withRecognition(c1, tools, ctx);
279
320
  const taught = await runTaughtPlan(request, tools, ctx);
280
- if (taught) return taught.refused ? { ...taught, c1Why: c1.why } : taught;
321
+ if (taught) return withRecognition(taught.refused ? { ...taught, c1Why: c1.why } : taught, tools, ctx);
281
322
  const c2 = await goalReason(request, tools, ctx, { driver: GOAL_DRIVER });
282
323
  // Both stages refused: carry the resolver/planner's own reason alongside the
283
324
  // goal-reasoner's so a caller can show why the direct route AND the
284
325
  // maintenance-goal route both declined,
285
326
  // rather than only the last (often less specific) of the two.
286
- return c2.refused ? { ...c2, c1Why: c1.why } : c2;
327
+ return withRecognition(c2.refused ? { ...c2, c1Why: c1.why } : c2, tools, ctx);
287
328
  }
288
329
 
289
330
  /** Build a real `{ dispatch, resolve, graph, config }` context against a repo's
Binary file
@@ -28,6 +28,13 @@ export function tokenizeSceneText(text) {
28
28
  return tokens;
29
29
  }
30
30
 
31
+ /** The words that end one item's run of preceding modifiers — the articles,
32
+ * joins and placement words the scene sentences themselves are built from.
33
+ * "a moving black cat" walks back past the unrecognized "black" to find the
34
+ * real "moving"; "a cabinet and a moving cat" stops at "and", so a modifier
35
+ * can never jump across to a different item's noun. */
36
+ const MODIFIER_RUN_BREAKERS = new Set(["a", "an", "the", "and", "or", "with", "on", "in", "at", "of", "then", "there", "is", "are"]);
37
+
31
38
  const sceneClassGraphCache = new WeakMap();
32
39
 
33
40
  /** The `classIndex`'s own class names as a resolvable graph, one individual per
@@ -81,15 +88,18 @@ function resolveSpanToClass(graph, classIndex, tokens, used, start, longestClass
81
88
 
82
89
  /** Every real catalog class the free-typed `text` names, in the order each first
83
90
  * appears, paired with the real material label (one of that SAME class's own
84
- * swatch labels — never another class's, never a fabricated one) immediately
85
- * preceding it, or `null`. `classIndex` is `{className: {materials}}` with
86
- * `materials` keyed by lowercase label (sprite-catalog-viz.mjs's own
87
- * `sceneComposerClassIndex` output, or an equivalent test fixture) — a class name
88
- * absent from `classIndex` can never match, and a modifier word that isn't one
89
- * of ITS matched class's own material labels is silently dropped rather than
90
- * guessed at, the same honest-miss posture an unrecognized class name gets (an
91
- * unmatched word, e.g. "red" before a lamp with no red material, is never an
92
- * error, just silently not drawn). Pure. */
91
+ * swatch labels — never another class's, never a fabricated one) among the words
92
+ * immediately preceding it, or `null`, plus `moving: true` when a preceding
93
+ * "moving" names a moving frame that class really has. Modifiers stack ("a
94
+ * moving black cat" reads both words), each consumed at most once, walking
95
+ * back only through still-unclaimed words. `classIndex` is `{className:
96
+ * {materials}}` with `materials` keyed by lowercase label
97
+ * (sprite-catalog-viz.mjs's own `sceneComposerClassIndex` output, or an
98
+ * equivalent test fixture) — a class name absent from `classIndex` can never
99
+ * match, and a modifier word that isn't one of ITS matched class's own labels
100
+ * is silently dropped rather than guessed at, the same honest-miss posture an
101
+ * unrecognized class name gets (an unmatched word, e.g. "red" before a lamp
102
+ * with no red material, is never an error, just silently not drawn). Pure. */
93
103
  export function extractSceneItems(text, classIndex) {
94
104
  const index = classIndex || {};
95
105
  const { graph, longestClassWordCount } = sceneClassGraph(index);
@@ -101,17 +111,45 @@ export function extractSceneItems(text, classIndex) {
101
111
  if (used[i]) continue;
102
112
  const hit = resolveSpanToClass(graph, index, tokens, used, i, longestClassWordCount);
103
113
  if (!hit) continue;
114
+ const materials = index[hit.className]?.materials || {};
104
115
  let materialLabel = null;
105
- if (i > 0 && !used[i - 1]) {
106
- const materials = index[hit.className]?.materials || {};
107
- const prevWord = tokens[i - 1].word;
108
- if (Object.prototype.hasOwnProperty.call(materials, prevWord)) {
109
- materialLabel = prevWord;
110
- used[i - 1] = true;
116
+ let moving = false;
117
+ for (let j = i - 1; j >= 0 && !used[j]; j -= 1) {
118
+ const word = tokens[j].word;
119
+ if (!moving && word === "moving" && Object.prototype.hasOwnProperty.call(materials, "moving")) {
120
+ moving = true;
121
+ used[j] = true;
122
+ continue;
123
+ }
124
+ if (!materialLabel && word !== "moving" && Object.prototype.hasOwnProperty.call(materials, word)) {
125
+ materialLabel = word;
126
+ used[j] = true;
127
+ continue;
111
128
  }
129
+ // A structure word ends this item's modifier run; anything else ("black"
130
+ // before a cat with no black swatch) is an unrecognized modifier — read
131
+ // past it, never consumed, never guessed at.
132
+ if (MODIFIER_RUN_BREAKERS.has(word)) break;
112
133
  }
113
134
  for (let k = 0; k < hit.wordCount; k += 1) used[i + k] = true;
114
- items.push({ className: hit.className, materialLabel });
135
+ items.push({ className: hit.className, materialLabel, moving });
115
136
  }
116
137
  return items;
117
138
  }
139
+
140
+ /** Split a composed scene into the one room that backs it and the entities
141
+ * standing in it. The LAST room named wins the wall — a sentence naming two
142
+ * rooms is read the way a stage direction would be, the latest setting
143
+ * standing. `roomClasses` is the caller's real room vocabulary (an adventure
144
+ * world's own rdf:type room subjects); with none, nothing is a backdrop.
145
+ * Pure. */
146
+ export function splitSceneBackdrop(items, roomClasses) {
147
+ const rooms = new Set(roomClasses || []);
148
+ let backdrop = null;
149
+ const rest = [];
150
+ for (const item of items || []) {
151
+ if (rooms.has(item.className)) backdrop = item;
152
+ else rest.push(item);
153
+ }
154
+ return { backdrop, rest };
155
+ }
@@ -0,0 +1,104 @@
1
+ // scene-random.mjs — the "random scene" button's vocabulary and sentence
2
+ // builder. Every word the generator can pick traces to a real source: class
3
+ // names and material/colour labels from the sprite catalog's own class index
4
+ // (itself read off data/sprites*/ templates), emotion words from the sprite
5
+ // facts' mgx:accept-emotion rows, room names from an adventure world's own
6
+ // rdf:type room facts. Nothing here holds a word list of its own.
7
+ //
8
+ // Randomness is passed in as `rng` (a () => [0,1) function — the browser
9
+ // page hands Math.random over), so everything in this module stays a pure
10
+ // function of its arguments.
11
+
12
+ const EMOTION_ACCEPT_PREDICATE = "mgx:accept-emotion";
13
+ const FACING_LABELS = Object.freeze(["left", "half-left", "half-right", "right"]);
14
+
15
+ /** The room classes a world's fact rows declare (`<subject> rdf:type room`),
16
+ * sorted. Pure. */
17
+ export function roomClassesFromWorldFacts(factRows) {
18
+ const rooms = new Set();
19
+ for (const row of factRows || []) {
20
+ if (row?.predicate === "rdf:type" && row.object === "room" && row.subject) rooms.add(String(row.subject));
21
+ }
22
+ return [...rooms].sort();
23
+ }
24
+
25
+ /** True when `name` is exactly the words a typed sentence would tokenize it
26
+ * back into — a hyphenated class ("drawing-room") fails, so the generator
27
+ * never writes a name the scene parser cannot read back. Pure. */
28
+ export function isSpeakableClassName(name) {
29
+ return /^[a-z]+( [a-z]+)*$/.test(String(name ?? ""));
30
+ }
31
+
32
+ /** The generator's whole vocabulary, derived and nothing else:
33
+ * - `rooms`: `roomClasses` the class index can actually draw, speakably named;
34
+ * - `emotions`: every value the sprite facts' mgx:accept-emotion rows carry;
35
+ * - `classes`: one row per drawable, speakable, non-room class — its plain
36
+ * material/colour labels (facing, pose, emotion and combined labels
37
+ * excluded), which emotions it wears, and whether it has a moving frame.
38
+ * Deterministic for identical inputs: every list is sorted. Pure. */
39
+ export function sceneVocabulary({ classIndex = {}, spriteFactRows = [], roomClasses = [] } = {}) {
40
+ const emotions = new Set();
41
+ for (const row of spriteFactRows || []) {
42
+ if (row?.predicate === EMOTION_ACCEPT_PREDICATE && row.object) emotions.add(String(row.object));
43
+ }
44
+ const emotionList = [...emotions].sort();
45
+ const rooms = (roomClasses || [])
46
+ .filter((name) => isSpeakableClassName(name) && Object.prototype.hasOwnProperty.call(classIndex, name))
47
+ .sort();
48
+ const roomSet = new Set(rooms);
49
+
50
+ const classes = [];
51
+ for (const name of Object.keys(classIndex).sort()) {
52
+ if (!isSpeakableClassName(name) || roomSet.has(name)) continue;
53
+ const labels = Object.keys(classIndex[name]?.materials || {});
54
+ const materials = labels
55
+ .filter((l) => !l.includes("+") && !FACING_LABELS.includes(l) && l !== "moving" && !emotions.has(l))
56
+ .sort();
57
+ const wears = labels.filter((l) => emotions.has(l)).sort();
58
+ classes.push({
59
+ name,
60
+ materials,
61
+ emotions: wears,
62
+ moving: labels.includes("moving"),
63
+ });
64
+ }
65
+ return { rooms, emotions: emotionList, classes };
66
+ }
67
+
68
+ /** One random scene sentence over `vocab`, in the shape the scene parser
69
+ * reads back: a material-coloured thing on a second thing, an emotive
70
+ * role wearing a real emotion, a moving entity, and a room — each part
71
+ * present only when the vocabulary really carries it. `rng` is the one
72
+ * source of chance; identical rng streams give identical sentences. Pure. */
73
+ export function randomSceneSentence(vocab, rng) {
74
+ const pick = (list) => {
75
+ if (!list || !list.length) return null;
76
+ const at = Math.floor(rng() * list.length);
77
+ return list[Math.min(Math.max(at, 0), list.length - 1)];
78
+ };
79
+ const article = (phrase) => (/^[aeiou]/.test(phrase) ? `an ${phrase}` : `a ${phrase}`);
80
+ const classes = vocab?.classes || [];
81
+ const things = classes.filter((c) => !c.emotions.length);
82
+ const actors = classes.filter((c) => c.emotions.length);
83
+ const movers = classes.filter((c) => c.moving);
84
+
85
+ const parts = [];
86
+ const thing = pick(things.length ? things : classes);
87
+ if (thing) {
88
+ const material = pick(thing.materials);
89
+ const rest = pick(things.filter((c) => c !== thing));
90
+ const lead = article(`${material ? `${material} ` : ""}${thing.name}`);
91
+ parts.push(rest ? `${lead} on ${article(rest.name)}` : lead);
92
+ }
93
+ const actor = pick(actors);
94
+ if (actor) parts.push(article(`${pick(actor.emotions)} ${actor.name}`));
95
+ const mover = pick(movers.filter((c) => c !== actor));
96
+ if (mover) {
97
+ const material = pick(mover.materials);
98
+ parts.push(`a moving ${material ? `${material} ` : ""}${mover.name}`);
99
+ }
100
+ const room = pick(vocab?.rooms || []);
101
+ const sentence = parts.join(" and ");
102
+ if (!sentence) return room ? `the ${room}` : "";
103
+ return room ? `${sentence} in the ${room}` : sentence;
104
+ }
@@ -0,0 +1,102 @@
1
+ // sprite-animation.mjs — the pure state machine behind every animated sprite
2
+ // tile: the hover flip-book (static/moving), the focused cell's turning
3
+ // rotation and emotion cycle, and the oscillate-and-turn walk a "moving"
4
+ // scene entity performs. Every function here is a pure function of its
5
+ // arguments — no wall clock, no local counter; the caller passes the tick.
6
+ // They are also self-contained (no outer refs), so a page builder can splice
7
+ // any of them in by `.toString()` exactly the way sprite-catalog-viz.mjs
8
+ // splices its frame-sequence functions, and a browser bundle can export the
9
+ // same functions for a page that loads the engine (the sprites and adventure
10
+ // entries both do).
11
+
12
+ /** The pose word a tile at rest shows, and the one its hover flip names. */
13
+ export const SPRITE_POSE_REST = "static";
14
+ export const SPRITE_POSE_MOVING = "moving";
15
+
16
+ /** A swatch label that IS a moving frame ("moving", "left + moving"), as
17
+ * opposed to a resting tile a moving frame can fold into. Pure;
18
+ * `.toString()`-splice safe. */
19
+ export function isMovingSwatchLabel(label) {
20
+ return label === "moving" || / \+ moving$/.test(String(label ?? ""));
21
+ }
22
+
23
+ /** The label of the moving counterpart frame a resting tile's hover flip
24
+ * alternates with: the plain tile ("default") flips against the bare
25
+ * "moving" frame, a facing tile ("left") against its own combined
26
+ * "left + moving" one. Pure; `.toString()`-splice safe. */
27
+ export function movingCounterpartLabel(restLabel) {
28
+ if (!restLabel || restLabel === "default" || restLabel === "plain") return "moving";
29
+ return restLabel + " + moving";
30
+ }
31
+
32
+ /** The two modes a focused sprite steps between, and the click toggle. */
33
+ export const FOCUS_MODE_ORDER = Object.freeze(["turning", "emotions"]);
34
+
35
+ /** Pure; `.toString()`-splice safe. */
36
+ export function nextFocusMode(mode) {
37
+ return mode === "turning" ? "emotions" : "turning";
38
+ }
39
+
40
+ /** The frame a cycling cell shows at `tick`, looping. Pure;
41
+ * `.toString()`-splice safe. */
42
+ export function frameAtTick(frames, tick) {
43
+ const list = frames || [];
44
+ if (!list.length) return null;
45
+ const step = Math.trunc(Number(tick) || 0);
46
+ return list[((step % list.length) + list.length) % list.length];
47
+ }
48
+
49
+ /** The frame list a focused cell cycles in `mode`. The asked-for axis wins;
50
+ * a class with no art on that axis falls back to the next axis it does
51
+ * have, and a class with fewer than two frames on every axis animates
52
+ * nothing. Pure; `.toString()`-splice safe. */
53
+ export function focusModeFrames(mode, { turnFrames = [], moodFrames = [], movingFrames = [] } = {}) {
54
+ const order = mode === "emotions"
55
+ ? [moodFrames, turnFrames, movingFrames]
56
+ : [turnFrames, movingFrames, moodFrames];
57
+ for (const frames of order) {
58
+ if (frames && frames.length >= 2) return frames;
59
+ }
60
+ return [];
61
+ }
62
+
63
+ /** One step of the oscillate-and-turn walk a moving scene entity performs:
64
+ * walk one way for `legTicks` ticks alternating static/moving, turn on the
65
+ * spot through the half-way facings at the end, walk back, turn again.
66
+ * `offsetFraction` is the horizontal offset in sprite widths, swinging half
67
+ * a sprite width each side of centre. Pure — the same tick always gives the
68
+ * same step. `.toString()`-splice safe. */
69
+ export function oscillateWalkStep(tick, { legTicks = 6 } = {}) {
70
+ const legs = Math.max(2, Math.trunc(legTicks));
71
+ const turnTicks = 3;
72
+ const cycle = 2 * (legs + turnTicks);
73
+ const t = (((Math.trunc(Number(tick) || 0)) % cycle) + cycle) % cycle;
74
+ const stride = (k) => (k % 2 ? "static" : "moving");
75
+ if (t < legs) {
76
+ return { facing: "right", pose: stride(t), offsetFraction: -0.5 + (t + 1) / (legs + 1) };
77
+ }
78
+ if (t < legs + turnTicks) {
79
+ const facing = ["half-right", null, "half-left"][t - legs];
80
+ return { facing, pose: "static", offsetFraction: 0.5 };
81
+ }
82
+ if (t < 2 * legs + turnTicks) {
83
+ const k = t - legs - turnTicks;
84
+ return { facing: "left", pose: stride(k), offsetFraction: 0.5 - (k + 1) / (legs + 1) };
85
+ }
86
+ const facing = ["half-left", null, "half-right"][t - 2 * legs - turnTicks];
87
+ return { facing, pose: "static", offsetFraction: -0.5 };
88
+ }
89
+
90
+ /** The swatch labels worth trying for a walk step, most specific first —
91
+ * the combined facing-and-pose frame, then the facing alone, then the bare
92
+ * moving frame, then the entity's own material swatch. The caller shows
93
+ * the first label its class really carries and falls back to the default
94
+ * sprite past the end. Pure; `.toString()`-splice safe. */
95
+ export function walkFrameLabelCandidates({ facing = null, pose = "static", material = null } = {}) {
96
+ const candidates = [];
97
+ if (facing && pose === "moving") candidates.push(facing + " + moving");
98
+ if (facing) candidates.push(facing);
99
+ if (pose === "moving") candidates.push("moving");
100
+ if (material) candidates.push(material);
101
+ return candidates;
102
+ }
@@ -27,6 +27,7 @@
27
27
  import { findActionPath } from "../domain/planning.mjs";
28
28
  import { loadMemory, readFactRows } from "../adapters/memory/core.mjs";
29
29
  import { baseSubjectOf } from "../domain/world-snapshot.mjs";
30
+ import { declaredGoals } from "../domain/router/recognize.mjs";
30
31
  import { foldWorldState, adventureTurn, worldActionRows } from "./adventure.mjs";
31
32
 
32
33
  const isTypedRow = (rows, subject, type) =>
@@ -101,6 +102,27 @@ function exposedContainers(exposedRows, exposedState) {
101
102
  return [...ids].filter((id) => roomOfSubject(id, exposedRows, exposedState) != null).sort();
102
103
  }
103
104
 
105
+ /** The admissible plans for a world carry goal, searched over the EXPOSED
106
+ * fold only — a plan through ground this run has not walked is not
107
+ * admissible. Each plan is the operator sequence a recognized trace would
108
+ * have to match: one `mgx:currently-in` step per room hop, then the
109
+ * `mgx:located-in` step the final take writes. Returns `[]` when the
110
+ * target's room isn't exposed yet or no seen path reaches it, so the goal
111
+ * is excluded rather than guessed at — this hook stays local to autoplay
112
+ * rather than landing in the shared recognizer, since only autoplay's own
113
+ * exposure-bounded search can tell an admissible plan from a guess. */
114
+ export function expandWorldGoal(goal, { here, exposedRows, exposedState }) {
115
+ if (goal?.source !== "world" || !goal.goalState?.subject) return [];
116
+ const target = goal.goalState.subject;
117
+ if (carriedByPlayer(exposedState, target)) return [[]];
118
+ const targetRoom = roomOfSubject(target, exposedRows || [], exposedState);
119
+ if (!targetRoom) return [];
120
+ if (targetRoom === here) return [["mgx:located-in"]];
121
+ const path = findActionPath(here, (room) => room === targetRoom, exposedExitApplyActions(exposedState));
122
+ if (!path || !path.actions.length) return [];
123
+ return [[...path.actions.map(() => "mgx:currently-in"), "mgx:located-in"]];
124
+ }
125
+
104
126
  /** One tick's worth of progress toward standing in `targetRoom` and then
105
127
  * issuing `finalCommand` once there — the same path-then-act shape the
106
128
  * objective fetch above already uses, generalized so opening/unlocking a
@@ -156,7 +178,20 @@ export async function runAdventureAutoplayTick(memoryDir, opts = {}) {
156
178
 
157
179
  const exposedRows = exposedFacts(rows, exposed);
158
180
  const exposedState = foldWorldState(exposedRows);
159
- const objectiveId = exposedRows.find((r) => r.predicate === "mgx:is-objective" && r.object === "true")?.subject ?? null;
181
+ // The world's objective is one declared goal among N, gathered by the same
182
+ // enumerator /goals prints. Exposure still bounds it: a marker the run has
183
+ // not seen is not in exposedRows, so it is not in this set either.
184
+ const goals = declaredGoals({ worldRows: exposedRows, ruleRows: [] }, {});
185
+ const worldGoals = goals.filter((g) => g.source === "world");
186
+ const objectiveId = worldGoals.length === 1 ? worldGoals[0].goalState.subject : null;
187
+
188
+ if (worldGoals.length > 1) {
189
+ return {
190
+ turn: state.turnCount,
191
+ goal: `stalled — this world declares ${worldGoals.length} objectives (${worldGoals.map((g) => g.goalState.subject).join(", ")}) and nothing says which one to chase.`,
192
+ plan: null, done: false, stalled: true, exposedRoomIds: exposed,
193
+ };
194
+ }
160
195
 
161
196
  // Win: the objective is already carried — checked against the FULL fold,
162
197
  // since what the player itself carries is always self-evidently known,
@@ -274,7 +309,10 @@ export async function runAdventureAutoplayTick(memoryDir, opts = {}) {
274
309
  const path = findActionPath(here, hasUnexposedExit, exposedExitApplyActions(exposedState));
275
310
  if (!path || !path.actions.length) {
276
311
  return {
277
- turn: state.turnCount, goal: "stalled — every reachable room is already explored, and no goal was ever found.",
312
+ turn: state.turnCount,
313
+ goal: goals.length
314
+ ? `stalled — every reachable room is already explored, and nothing I've done fits any of the ${goals.length} declared goals for this world.`
315
+ : "stalled — every reachable room is already explored, and this world declares no goal to head for.",
278
316
  plan: null, done: false, stalled: true, exposedRoomIds: exposed,
279
317
  };
280
318
  }