@polycode-projects/the-mechanical-code-talker 5.0.21 → 5.0.23
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/README.md +4 -0
- package/bin/tmct.mjs +20 -5
- package/package.json +1 -1
- package/src/adapters/toml-config.mjs +5 -0
- package/src/domain/cli-verbs.mjs +1 -0
- package/src/domain/domain.mjs +8 -0
- package/src/domain/interpret/normalize.mjs +86 -1
- package/src/domain/router/drive.mjs +45 -4
- package/src/domain/router/recognize.mjs +345 -0
- package/src/domain/scene-compose.mjs +54 -16
- package/src/domain/scene-random.mjs +104 -0
- package/src/domain/sprite-animation.mjs +102 -0
- package/src/domain/world-snapshot.mjs +25 -0
- package/src/services/adventure-autoplay.mjs +41 -5
- package/src/services/adventure.mjs +137 -34
- package/src/services/chat-session.mjs +5 -1
- package/src/services/chat.mjs +401 -13
- package/src/services/sprite-catalog-viz.mjs +408 -184
- package/src/surfaces/web/adventure-browser-entry.mjs +11 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +119 -119
- package/src/surfaces/web/sprites-browser-entry.mjs +17 -2
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
// domain/router/recognize.mjs — reading an observed trace of steps back from
|
|
2
|
+
// whatever recorded it: an executed tool-call list, the @turnN rows a played
|
|
3
|
+
// world writes, or the @stepN rows a plan-lane board writes. Also enumerates
|
|
4
|
+
// the declared goals a trace can be checked against, gathered from GOAL_RULES,
|
|
5
|
+
// the capability registry, a world pack's own markers, and taught action
|
|
6
|
+
// families. Pure and read-only — nothing here writes a fact or calls a tool,
|
|
7
|
+
// so a recognition can never change what it is recognizing.
|
|
8
|
+
|
|
9
|
+
import { parseSnapshotSubject } from "../world-snapshot.mjs";
|
|
10
|
+
import { parseStepSubject } from "../domain.mjs";
|
|
11
|
+
import { backwardChain } from "./resolver.mjs";
|
|
12
|
+
import { GOAL_RULES } from "./goal-reasoner.mjs";
|
|
13
|
+
import { capabilities, effectsOf } from "./registry.mjs";
|
|
14
|
+
import { actionFamilies } from "./taught.mjs";
|
|
15
|
+
|
|
16
|
+
/** The default trace cap: enough steps for a multi-hop drill-down without
|
|
17
|
+
* letting a long session make recognition unbounded. The `[recognition]
|
|
18
|
+
* max_trace` tmct.toml knob overrides it per repo. */
|
|
19
|
+
export const MAX_TRACE = 32;
|
|
20
|
+
|
|
21
|
+
/** Fold a normalized tmct.toml's sparse `[recognition]` table over the shipped
|
|
22
|
+
* default, exactly as resolveDiscourseConfig folds `[discourse]`. */
|
|
23
|
+
export function resolveRecognitionConfig(toml) {
|
|
24
|
+
const raw = toml?.recognition?.max_trace;
|
|
25
|
+
const maxTrace = Number.isInteger(raw) && raw > 0 ? raw : MAX_TRACE;
|
|
26
|
+
return { maxTrace };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One observed step. `op` is the declared operator the step exercised — a
|
|
30
|
+
* capability name for a tool trace, an effect predicate for a world trace. */
|
|
31
|
+
// { k: number, actor: string, op: string, args: object, kind: "capability" | "world-effect" }
|
|
32
|
+
|
|
33
|
+
const codepointCompare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
34
|
+
const validTraceCap = (maxTrace) => Number.isInteger(maxTrace) && maxTrace > 0;
|
|
35
|
+
|
|
36
|
+
/** Keep only the newest `maxTrace` entries of an oldest-first list — the
|
|
37
|
+
* oldest steps drop first when a trace overruns the cap. */
|
|
38
|
+
const capToNewest = (items, maxTrace) => (items.length > maxTrace ? items.slice(items.length - maxTrace) : items);
|
|
39
|
+
|
|
40
|
+
/** An executed call list — runCapabilityPlan's `calls`, or a served
|
|
41
|
+
* transcript's tool_use blocks — as an ordered step list. */
|
|
42
|
+
export function traceOfCalls(calls, { maxTrace = MAX_TRACE, actor = "caller" } = {}) {
|
|
43
|
+
if (!validTraceCap(maxTrace)) return [];
|
|
44
|
+
if (!Array.isArray(calls) || !calls.length) return [];
|
|
45
|
+
const capped = capToNewest(calls, maxTrace);
|
|
46
|
+
return capped.map((call, i) => ({
|
|
47
|
+
k: i + 1,
|
|
48
|
+
actor,
|
|
49
|
+
op: call?.name,
|
|
50
|
+
args: call?.input || {},
|
|
51
|
+
kind: "capability",
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @turnN world rows (adventure and NPC passes) as an ordered step list, one
|
|
56
|
+
* step per snapshot row, oldest first, deduplicated by (turn, subject,
|
|
57
|
+
* predicate). Rows for the current epoch only. */
|
|
58
|
+
export function traceOfWorldRows(rows, { maxTrace = MAX_TRACE, actor = "player" } = {}) {
|
|
59
|
+
if (!validTraceCap(maxTrace)) return [];
|
|
60
|
+
if (!Array.isArray(rows) || !rows.length) return [];
|
|
61
|
+
const stamped = [];
|
|
62
|
+
for (const row of rows) {
|
|
63
|
+
const snap = parseSnapshotSubject(row?.subject);
|
|
64
|
+
if (snap) stamped.push({ snap, row });
|
|
65
|
+
}
|
|
66
|
+
if (!stamped.length) return [];
|
|
67
|
+
let epoch = 0;
|
|
68
|
+
for (const { snap } of stamped) if (snap.epoch > epoch) epoch = snap.epoch;
|
|
69
|
+
const current = stamped.filter(({ snap }) => snap.epoch === epoch);
|
|
70
|
+
current.sort((a, b) =>
|
|
71
|
+
codepointCompare(a.snap.turn, b.snap.turn) ||
|
|
72
|
+
codepointCompare(a.snap.base, b.snap.base) ||
|
|
73
|
+
codepointCompare(a.row.predicate, b.row.predicate) ||
|
|
74
|
+
codepointCompare(a.row.object, b.row.object));
|
|
75
|
+
const seen = new Set();
|
|
76
|
+
const deduped = [];
|
|
77
|
+
for (const { snap, row } of current) {
|
|
78
|
+
const key = `${snap.turn}\u001f${snap.base}\u001f${row.predicate}`;
|
|
79
|
+
if (seen.has(key)) continue;
|
|
80
|
+
seen.add(key);
|
|
81
|
+
deduped.push(row);
|
|
82
|
+
}
|
|
83
|
+
const capped = capToNewest(deduped, maxTrace);
|
|
84
|
+
return capped.map((row, i) => ({
|
|
85
|
+
k: i + 1,
|
|
86
|
+
actor,
|
|
87
|
+
op: row.predicate,
|
|
88
|
+
args: { object: row.object },
|
|
89
|
+
kind: "world-effect",
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @stepN board rows (the plan lane's snapshots) as an ordered step list. */
|
|
94
|
+
export function traceOfBoardRows(rows, { maxTrace = MAX_TRACE, actor = "planner" } = {}) {
|
|
95
|
+
if (!validTraceCap(maxTrace)) return [];
|
|
96
|
+
if (!Array.isArray(rows) || !rows.length) return [];
|
|
97
|
+
const stamped = [];
|
|
98
|
+
for (const row of rows) {
|
|
99
|
+
const snap = parseStepSubject(row?.subject);
|
|
100
|
+
if (snap) stamped.push({ snap, row });
|
|
101
|
+
}
|
|
102
|
+
if (!stamped.length) return [];
|
|
103
|
+
stamped.sort((a, b) =>
|
|
104
|
+
codepointCompare(a.snap.step, b.snap.step) ||
|
|
105
|
+
codepointCompare(a.snap.base, b.snap.base) ||
|
|
106
|
+
codepointCompare(a.row.predicate, b.row.predicate) ||
|
|
107
|
+
codepointCompare(a.row.object, b.row.object));
|
|
108
|
+
const seen = new Set();
|
|
109
|
+
const deduped = [];
|
|
110
|
+
for (const { snap, row } of stamped) {
|
|
111
|
+
const key = `${snap.step}\u001f${snap.base}\u001f${row.predicate}`;
|
|
112
|
+
if (seen.has(key)) continue;
|
|
113
|
+
seen.add(key);
|
|
114
|
+
deduped.push(row);
|
|
115
|
+
}
|
|
116
|
+
const capped = capToNewest(deduped, maxTrace);
|
|
117
|
+
return capped.map((row, i) => ({
|
|
118
|
+
k: i + 1,
|
|
119
|
+
actor,
|
|
120
|
+
op: row.predicate,
|
|
121
|
+
args: { object: row.object },
|
|
122
|
+
kind: "world-effect",
|
|
123
|
+
}));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** One declared goal. `plans` holds every admissible operator sequence; a goal
|
|
127
|
+
* whose plans need a world state to search from ships `plans: []` and a
|
|
128
|
+
* `goalState` instead. */
|
|
129
|
+
// {
|
|
130
|
+
// id: "goal:coverage-gap",
|
|
131
|
+
// source: "goal-rules" | "capability" | "world" | "taught",
|
|
132
|
+
// label: "an impactful module must be tested",
|
|
133
|
+
// plans: [["tmct_impact", "tmct_untested"]],
|
|
134
|
+
// goalState: null,
|
|
135
|
+
// provenance: "GOAL_RULES coverage-invariant — an impactful module must be tested",
|
|
136
|
+
// }
|
|
137
|
+
|
|
138
|
+
/** A goal SURVIVES a declared toolset when every operator in every one of its
|
|
139
|
+
* plans is in that toolset — a goal with no plans of its own (world/taught)
|
|
140
|
+
* survives any toolset. `tools === null` means no screen at all. */
|
|
141
|
+
function fitsToolset(plans, tools) {
|
|
142
|
+
if (!Array.isArray(tools)) return true;
|
|
143
|
+
if (!plans.length) return true;
|
|
144
|
+
return plans.every((plan) => plan.every((op) => tools.includes(op)));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Every goal `GOAL_RULES` deduces, one per rule whose sub-goals all
|
|
148
|
+
* backward-chain to a declared capability. A sub-goal that backward-chains
|
|
149
|
+
* to nothing drops the whole goal — it is not achievable in this registry. */
|
|
150
|
+
function goalsFromRules() {
|
|
151
|
+
const goals = [];
|
|
152
|
+
for (const rule of GOAL_RULES) {
|
|
153
|
+
const plan = rule.subGoals.map((topic) => backwardChain(topic)?.name);
|
|
154
|
+
if (plan.some((name) => !name)) continue;
|
|
155
|
+
goals.push({
|
|
156
|
+
id: `goal:${rule.achieves}`,
|
|
157
|
+
source: "goal-rules",
|
|
158
|
+
label: rule.invariant,
|
|
159
|
+
plans: [plan],
|
|
160
|
+
goalState: null,
|
|
161
|
+
provenance: `GOAL_RULES ${rule.id} — ${rule.invariant}`,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
return goals;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Every goal the capability registry declares, one per capability whose
|
|
168
|
+
* add-list carries a `cap:knows` effect. */
|
|
169
|
+
function goalsFromCapabilities() {
|
|
170
|
+
const goals = [];
|
|
171
|
+
for (const cap of capabilities()) {
|
|
172
|
+
for (const effect of effectsOf(cap.name).add) {
|
|
173
|
+
if (effect.pred !== "cap:knows") continue;
|
|
174
|
+
goals.push({
|
|
175
|
+
id: `cap:${effect.topic}`,
|
|
176
|
+
source: "capability",
|
|
177
|
+
label: cap.question,
|
|
178
|
+
plans: [[cap.name]],
|
|
179
|
+
goalState: null,
|
|
180
|
+
provenance: `capability ${cap.name} — add-effect knows(${effect.topic})`,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return goals;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Every goal a world pack's own objective markers declare. `mgx:is-objective`
|
|
188
|
+
* generalises to a family: carrying the marked subject is the win condition
|
|
189
|
+
* the adventure surface already checks, so the goal state names that. */
|
|
190
|
+
function goalsFromWorldRows(worldRows) {
|
|
191
|
+
const goals = [];
|
|
192
|
+
for (const row of worldRows || []) {
|
|
193
|
+
if (row?.predicate !== "mgx:is-objective" || row?.object !== "true") continue;
|
|
194
|
+
goals.push({
|
|
195
|
+
id: `world:carry-${row.subject}`,
|
|
196
|
+
source: "world",
|
|
197
|
+
label: `carry the ${row.subject}`,
|
|
198
|
+
plans: [],
|
|
199
|
+
goalState: { subject: row.subject, predicate: "located-in", object: "player" },
|
|
200
|
+
provenance: `world marker mgx:is-objective on ${row.subject}`,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return goals;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Every goal a taught action family declares. No goal-rule kind exists for a
|
|
207
|
+
* taught domain today, so a family's own effect predicate holding IS its
|
|
208
|
+
* goal state — read in the opposite direction from how backwardChainWorld
|
|
209
|
+
* reads it. Two families sharing an effect predicate contribute one goal,
|
|
210
|
+
* their provenance joined. */
|
|
211
|
+
function goalsFromTaughtActions(ruleRows) {
|
|
212
|
+
const byId = new Map();
|
|
213
|
+
for (const [familyName, family] of actionFamilies(ruleRows || [])) {
|
|
214
|
+
for (const row of family) {
|
|
215
|
+
if (row.kind !== "action-effect") continue;
|
|
216
|
+
const predicate = row.slots?.predicate;
|
|
217
|
+
if (!predicate) continue;
|
|
218
|
+
const id = `taught:${predicate}`;
|
|
219
|
+
const contribution = `taught action ${familyName} — effect ${predicate}`;
|
|
220
|
+
const existing = byId.get(id);
|
|
221
|
+
if (existing) { existing.provenance += `; ${contribution}`; continue; }
|
|
222
|
+
byId.set(id, {
|
|
223
|
+
id,
|
|
224
|
+
source: "taught",
|
|
225
|
+
label: `reach a state where something ${predicate}s`,
|
|
226
|
+
plans: [],
|
|
227
|
+
goalState: { predicate },
|
|
228
|
+
provenance: contribution,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return [...byId.values()];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Every goal the loaded declarations amount to, gathered and never invented.
|
|
237
|
+
* `ctx.worldRows` (optional) supplies the world shard's marker facts;
|
|
238
|
+
* `ctx.ruleRows` (optional) supplies the taught action families. `opts.tools`
|
|
239
|
+
* restricts the set to goals every step of whose plans is in the declared
|
|
240
|
+
* toolset, the same screen `applicableRules` applies. Pure; sorted by id.
|
|
241
|
+
*/
|
|
242
|
+
export function declaredGoals(ctx = {}, { tools = null } = {}) {
|
|
243
|
+
const all = [
|
|
244
|
+
...goalsFromRules(),
|
|
245
|
+
...goalsFromCapabilities(),
|
|
246
|
+
...goalsFromWorldRows(ctx.worldRows),
|
|
247
|
+
...goalsFromTaughtActions(ctx.ruleRows),
|
|
248
|
+
];
|
|
249
|
+
return all
|
|
250
|
+
.filter((g) => fitsToolset(g.plans, tools))
|
|
251
|
+
.sort((a, b) => codepointCompare(a.id, b.id));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** A trace FITS a plan when its operators are a subsequence of the plan's, in
|
|
255
|
+
* an order the plan admits. Exact and deterministic: two pointers, no score. */
|
|
256
|
+
export function fitsPlan(trace, plan) {
|
|
257
|
+
let i = 0;
|
|
258
|
+
for (const step of trace) {
|
|
259
|
+
while (i < plan.length && plan[i] !== step.op) i += 1;
|
|
260
|
+
if (i >= plan.length) return false;
|
|
261
|
+
i += 1;
|
|
262
|
+
}
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** The topic a capability's own `cap:knows` add-effect names, or the operator
|
|
267
|
+
* itself when it declares none (a world/taught effect predicate has no
|
|
268
|
+
* registry entry to look one up in). */
|
|
269
|
+
function operatorTopic(op) {
|
|
270
|
+
for (const effect of effectsOf(op)?.add ?? []) {
|
|
271
|
+
if (effect.pred === "cap:knows" && effect.topic) return effect.topic;
|
|
272
|
+
}
|
|
273
|
+
return op;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** The recognition proof: one `goal-fit` receipt naming the fitting plan, then
|
|
277
|
+
* one `causal-link` per observed step, chained from the graph. A step's own
|
|
278
|
+
* bound argument is the condition it names; a step that took none names the
|
|
279
|
+
* topic its producer supplied instead — the same "what threaded in" reading
|
|
280
|
+
* `drive.mjs`'s own causal-link proofs use. */
|
|
281
|
+
function buildProof(trace, goal, plan) {
|
|
282
|
+
const proof = [{ step: "goal-fit", goal: goal.id, plan, ok: true }];
|
|
283
|
+
for (let k = 1; k <= trace.length; k += 1) {
|
|
284
|
+
const step = trace[k - 1];
|
|
285
|
+
const producer = k === 1 ? "graph" : `step-${k - 1}`;
|
|
286
|
+
const producerOp = k === 1 ? step.op : trace[k - 2].op;
|
|
287
|
+
const values = Object.values(step.args || {});
|
|
288
|
+
const condition = values.length ? String(values[0]) : operatorTopic(producerOp);
|
|
289
|
+
proof.push({ step: "causal-link", producer, condition, consumer: `step-${k}:${step.op}`, role: "recognition", ok: true });
|
|
290
|
+
}
|
|
291
|
+
return proof;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Which declared goal an observed trace fits. Exactly three outcomes, never a
|
|
296
|
+
* fourth:
|
|
297
|
+
* - one goal survives → { goal, reject: false, ambiguous: null, proof, why }
|
|
298
|
+
* - two or more → { goal: null, reject: false, ambiguous: [...], proof: [], why }
|
|
299
|
+
* - none → { goal: null, reject: true, ambiguous: null, proof: [], why }
|
|
300
|
+
* An empty trace rejects, naming that nothing was observed — it does not fit
|
|
301
|
+
* every goal vacuously.
|
|
302
|
+
*
|
|
303
|
+
* `expand(goal)` (optional) returns the admissible plans for a goal that ships
|
|
304
|
+
* none of its own (a world or taught goal, whose plans need a state to search
|
|
305
|
+
* from). A goal with no plans and no expand hook is excluded, not guessed at.
|
|
306
|
+
*/
|
|
307
|
+
export function recognizeGoal(trace, goals, { expand = null } = {}) {
|
|
308
|
+
if (!Array.isArray(trace) || !trace.length) {
|
|
309
|
+
return { goal: null, reject: true, ambiguous: null, proof: [], why: "no steps observed yet — there is nothing to recognize" };
|
|
310
|
+
}
|
|
311
|
+
const declared = Array.isArray(goals) ? goals : [];
|
|
312
|
+
const fits = [];
|
|
313
|
+
for (const goal of declared) {
|
|
314
|
+
let plans = Array.isArray(goal.plans) && goal.plans.length ? goal.plans : null;
|
|
315
|
+
if (!plans) {
|
|
316
|
+
if (typeof expand !== "function") continue; // no plan to test against — excluded, not guessed at
|
|
317
|
+
const expanded = expand(goal);
|
|
318
|
+
plans = Array.isArray(expanded) && expanded.length ? expanded : null;
|
|
319
|
+
if (!plans) continue;
|
|
320
|
+
}
|
|
321
|
+
const fittingPlan = plans.find((plan) => fitsPlan(trace, plan));
|
|
322
|
+
if (fittingPlan) fits.push({ goal, plan: fittingPlan });
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (fits.length === 1) {
|
|
326
|
+
const { goal, plan } = fits[0];
|
|
327
|
+
return {
|
|
328
|
+
goal, reject: false, ambiguous: null,
|
|
329
|
+
proof: buildProof(trace, goal, plan),
|
|
330
|
+
why: `the trace fits ${goal.id} (${goal.label}) — ${trace.length} observed step(s) are a subsequence of ${plan.join(" -> ")}`,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
if (fits.length > 1) {
|
|
334
|
+
const survivors = fits.map((f) => f.goal);
|
|
335
|
+
const ids = survivors.map((g) => g.id);
|
|
336
|
+
return {
|
|
337
|
+
goal: null, reject: false, ambiguous: survivors, proof: [],
|
|
338
|
+
why: `the trace fits ${survivors.length} declared goals (${ids.join(", ")}) — a longer trace narrows it, so I won't pick one`,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
goal: null, reject: true, ambiguous: null, proof: [],
|
|
343
|
+
why: `the trace fits none of the ${declared.length} declared goals — it is off the declared model, which is a reject, not a nearest fit`,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
@@ -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)
|
|
85
|
-
* preceding it, or `null
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
if (Object.prototype.hasOwnProperty.call(materials,
|
|
109
|
-
|
|
110
|
-
used[
|
|
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
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// domain/world-snapshot.mjs — the one grammar for a snapshot subject: bare
|
|
2
|
+
// `base@turnN` while a world stays on epoch 0, `base@epochE@turnN` once a
|
|
3
|
+
// recast has moved it on. Pure, no imports — every reader of this grammar
|
|
4
|
+
// (the adventure lane, autoplay, the recognizer) reads it from here instead
|
|
5
|
+
// of keeping its own copy.
|
|
6
|
+
|
|
7
|
+
const SNAPSHOT_RE = /^(.+?)@(?:epoch(\d+)@)?turn(\d+)$/;
|
|
8
|
+
|
|
9
|
+
/** The snapshot subject a turn writes: bare `base@turnN` while the world is
|
|
10
|
+
* on epoch 0, `base@epochE@turnN` once a recast has moved it on. */
|
|
11
|
+
export function snapshotSubject(base, turn, epoch = 0) {
|
|
12
|
+
return epoch > 0 ? `${base}@epoch${epoch}@turn${turn}` : `${base}@turn${turn}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Read a snapshot subject back: `{ base, epoch, turn }`, or null when the
|
|
16
|
+
* subject carries no snapshot stamp (a base row). Pure. */
|
|
17
|
+
export function parseSnapshotSubject(subject) {
|
|
18
|
+
const m = SNAPSHOT_RE.exec(String(subject || ""));
|
|
19
|
+
return m ? { base: m[1], epoch: m[2] ? Number(m[2]) : 0, turn: Number(m[3]) } : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The base individual a subject names, snapshot-stamped or not. */
|
|
23
|
+
export function baseSubjectOf(subject) {
|
|
24
|
+
return parseSnapshotSubject(subject)?.base ?? subject;
|
|
25
|
+
}
|