@polycode-projects/the-mechanical-code-talker 5.0.26 → 5.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/corpus/worlds/index.json.gz +0 -0
  2. package/corpus/worlds/manifest.json +27 -17
  3. package/corpus/worlds/shards/river-crossing.jsonl.gz +0 -0
  4. package/corpus/worlds/shards/town-square-chapel.jsonl.gz +0 -0
  5. package/corpus/worlds/shards/town-square-market.jsonl.gz +0 -0
  6. package/corpus/worlds/shards/town-square.jsonl.gz +0 -0
  7. package/corpus/worlds/src/river-crossing.jsonl +29 -0
  8. package/corpus/worlds/src/town-square-chapel.jsonl +12 -8
  9. package/corpus/worlds/src/town-square-market.jsonl +12 -8
  10. package/corpus/worlds/src/town-square.jsonl +12 -8
  11. package/package.json +2 -1
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-traits.mjs +282 -0
  14. package/src/domain/ask.mjs +19 -6
  15. package/src/domain/choice-question.mjs +135 -6
  16. package/src/domain/codegraph.mjs +8 -1
  17. package/src/domain/el-classify.mjs +39 -7
  18. package/src/domain/fact-phrase.mjs +7 -4
  19. package/src/domain/interpret/normalize.mjs +58 -2
  20. package/src/domain/town-square-world.mjs +44 -19
  21. package/src/services/adventure.mjs +5 -16
  22. package/src/services/agent-editor.mjs +216 -0
  23. package/src/services/chat-session.mjs +26 -5
  24. package/src/services/chat.mjs +221 -58
  25. package/src/services/mudiii-scene.mjs +32 -5
  26. package/src/services/mudiii-turn.mjs +7 -3
  27. package/src/services/mudiii-viz.mjs +215 -1
  28. package/src/services/news-viz.mjs +489 -0
  29. package/src/services/predator-prey.mjs +157 -24
  30. package/src/surfaces/web/chat-browser-entry.mjs +69 -3
  31. package/src/surfaces/web/memory-ask-browser.bundle.js +155 -155
  32. package/src/surfaces/web/mudiii-browser-entry.mjs +35 -0
  33. package/src/surfaces/web/news-browser-entry.mjs +384 -0
  34. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -3040,17 +3040,17 @@ function modifierIsWired(shape, kind, entityType) {
3040
3040
  }
3041
3041
  const TRANSITIVE_MAX_DEPTH = 8; // matches renderImpact's own default (codegraph.mjs)
3042
3042
 
3043
- /** A graph's own vocabulary nodes carry their definition text under this
3044
- * property. A code entity's docstring rides `seon:hasDoc` and shares the
3045
- * plain `doc` key, so the PROP is what separates the two. */
3046
- const SCHEMA_DOC_PROP = "mgx:schemaDoc";
3043
+ /** A graph's own vocabulary nodes carry their definition text under one of
3044
+ * these properties. A code entity's docstring rides `seon:hasDoc` and shares
3045
+ * the plain `doc` key, so this set is what separates the two. */
3046
+ const SCHEMA_DOC_PROPS = new Set(["mgx:schemaDoc", "mgx:lexiconDoc"]);
3047
3047
 
3048
3048
  /** The definition text an individual publishes about itself, or null. Reading
3049
3049
  * the meta lane off this attribute rather than a fixed class-name list lets a
3050
3050
  * graph declare its own documented individual class (a glossary term, say)
3051
3051
  * and have "what is X" answer for it like any other vocabulary node. */
3052
3052
  function schemaDefinitionOf(ind) {
3053
- return (ind?.attributes || []).find((a) => a.prop === SCHEMA_DOC_PROP)?.value || null;
3053
+ return (ind?.attributes || []).find((a) => SCHEMA_DOC_PROPS.has(a.prop))?.value || null;
3054
3054
  }
3055
3055
 
3056
3056
  function schemaKindWordFor(cls) {
@@ -4055,7 +4055,20 @@ function renderCore(parsed, result, graph) {
4055
4055
  miss: true, ambiguous: false,
4056
4056
  };
4057
4057
  }
4058
- const entityWord = nounFor(parsed.entityType || "Module", 2);
4058
+ // No entity type was parsed (a bare "what denotes X" names no grain), so the
4059
+ // word for what was searched comes off the kind's own object classes in the
4060
+ // loaded graph rather than defaulting to "modules" — a kind like `denotes`
4061
+ // never targets a module at all, and saying so would misname what was searched.
4062
+ // When the graph holds no edges of this kind at all, there is nothing to
4063
+ // read a class from, and "Module" stays the plain default.
4064
+ const entityWord = parsed.entityType
4065
+ ? nounFor(parsed.entityType, 2)
4066
+ : (() => {
4067
+ const kindClasses = [...classesForKinds(graph, kindsFor(parsed.kind))];
4068
+ if (kindClasses.length === 1) return nounFor(kindClasses[0], 2);
4069
+ if (kindClasses.length > 1) return kindClasses.map((c) => nounFor(c, 2)).join(" or ");
4070
+ return nounFor("Module", 2);
4071
+ })();
4059
4072
  // Name the resolved antecedent, not the raw pronoun: "who touched it" that
4060
4073
  // bound "it" to fnAlpha must say so, or the receipt reads as though nothing
4061
4074
  // was resolved at all. Scoped to a context pronoun so a typed term keeps the
@@ -170,13 +170,142 @@ function findAcceptedLabelSequence(text) {
170
170
  return accepted;
171
171
  }
172
172
 
173
- // The one closed frame this module extracts a source term from directly:
174
- // "where would you find/see/keep/put/store/place X ..." — the shape the
175
- // rig's own enumerated stems take. Anything else yields "", which the
176
- // contract states is a valid outcome, not a failure.
177
- const PLACEMENT_VERB_RE = /\b(?:find|see|keep|put|store|place)\s+([a-z][\w'-]*)/i;
173
+ // ---- stem source-term extraction ----
174
+ //
175
+ // A closed set of sentence templates, tried in order, each reading only the
176
+ // stem text — never a fixture's own question_concept, which the real lane
177
+ // never sees either. Every template ends the same way: hand the text after
178
+ // its cue word to captureStemNounPhrase, which trims determiners, pronouns
179
+ // and clause boundaries down to a short noun phrase. Anything no template
180
+ // matches yields "", which the contract states is a valid outcome, not a
181
+ // failure.
182
+
183
+ // Determiners and possessives stripped off the front of a captured phrase —
184
+ // closed classes, not open vocabulary.
185
+ const LEADING_DETERMINER_RE = /^(?:an?|the|some|any|few|many|several|more|most|my|your|his|its|our|their)\s+/i;
186
+
187
+ // Pronouns that can open a captured phrase but never name a source term —
188
+ // "where are you" and "what should he use" have no noun there to read.
189
+ const PRONOUN_TERMS = new Set([
190
+ "you", "i", "it", "he", "she", "they", "we", "there", "someone",
191
+ "something", "one", "him", "her", "them", "who",
192
+ "himself", "herself", "itself", "themselves", "myself", "yourself",
193
+ ]);
194
+
195
+ // Words that end a captured phrase rather than folding into it: the closed
196
+ // prepositions this module already uses elsewhere (PREP_WORDS), plus the
197
+ // conjunctions, clause-openers and auxiliary/modal verbs that mark a clause
198
+ // boundary in the sentence shapes CommonsenseQA's stems actually use.
199
+ const PHRASE_BOUNDARY_WORDS = new Set([
200
+ ...PREP_WORDS, "to", "behind", "before", "near", "next",
201
+ "along", "alongside", "under", "over", "between", "among", "during",
202
+ "without", "about", "by", "as", "like",
203
+ "that", "if", "when", "while", "being", "because", "since", "until",
204
+ "so", "and", "but", "or",
205
+ "immediately", "likely", "usually", "normally", "currently",
206
+ "is", "are", "was", "were", "do", "does", "did",
207
+ "has", "have", "had", "will", "would", "could", "should", "might", "must", "can",
208
+ ]);
209
+
210
+ /** Reads a short noun phrase (at most three words) off the front of `words`,
211
+ * stopping at the first phrase-boundary word. A possessive ("restaurant's")
212
+ * ends the phrase right after the word it marks, its "'s" dropped — the
213
+ * next word belongs to a different noun ("restaurant's phone number" reads
214
+ * as "restaurant", not the number). */
215
+ function readStemNounPhrase(words) {
216
+ const out = [];
217
+ for (const word of words) {
218
+ if (out.length >= 3 || PHRASE_BOUNDARY_WORDS.has(word)) break;
219
+ const possessive = word.endsWith("'s");
220
+ out.push(possessive ? word.slice(0, -2) : word);
221
+ if (possessive) break;
222
+ }
223
+ return out.join(" ");
224
+ }
225
+
226
+ /** Strips a leading determiner, then reads a noun phrase — "" when the
227
+ * phrase would open on a pronoun or a boundary word, since neither ever
228
+ * names a source term. Stops at the first comma, so an option-like list
229
+ * ("a magazine, paper or gum") reads only its first member. */
230
+ function captureStemNounPhrase(tailText) {
231
+ const [beforeComma] = String(tailText).split(",", 1);
232
+ const stripped = beforeComma.replace(LEADING_DETERMINER_RE, "");
233
+ const words = stripped.trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
234
+ if (words.length === 0 || PRONOUN_TERMS.has(words[0]) || PHRASE_BOUNDARY_WORDS.has(words[0])) return "";
235
+ return readStemNounPhrase(words);
236
+ }
237
+
238
+ // "where would you find/see/keep/put/store/place/buy/get/locate/hide/wear/
239
+ // carry/use/take/open/cross X" — the placement and possession verbs whose
240
+ // direct object is the term the question is about. Not anchored to "where":
241
+ // the same object slot holds the source term in "what would you put X into"
242
+ // too, and the verb match already carries the whole signal.
243
+ const PLACEMENT_VERB_RE = /\b(?:find|found|see|keep|put|store|place|buy|get|locate|hide|wear|carry|use|take|open|cross)\s+(.+)$/i;
244
+ const placementVerbSourceTerm = (stem) => {
245
+ const m = PLACEMENT_VERB_RE.exec(stem);
246
+ return m ? captureStemNounPhrase(m[1]) : "";
247
+ };
248
+
249
+ // "what do/does/did <subject> do/use/need/require" — the do-support shape
250
+ // CommonsenseQA's "what"-led stems lean on most: the subject sits between
251
+ // the auxiliary and the closing verb.
252
+ const WHAT_DO_SUBJECT_RE = /\bwhat\s+(?:do|does|did)\s+(.+?)\s+(?:primarily\s+)?(?:do|does|did|use|need|require)\b/i;
253
+ const whatDoSubjectSourceTerm = (stem) => {
254
+ const m = WHAT_DO_SUBJECT_RE.exec(stem);
255
+ return m ? captureStemNounPhrase(m[1]) : "";
256
+ };
257
+
258
+ // "what uses/needs/requires/has/holds/contains/involves X" — the shape
259
+ // where "what" is itself the subject and the source term is the verb's
260
+ // direct object instead.
261
+ const WHAT_VERB_OBJECT_RE = /^what\s+(?:uses|needs|requires|has|holds|contains|involves)\s+(.+)$/i;
262
+ const whatVerbObjectSourceTerm = (stem) => {
263
+ const m = WHAT_VERB_OBJECT_RE.exec(stem);
264
+ return m ? captureStemNounPhrase(m[1]) : "";
265
+ };
178
266
 
179
- const extractStemSourceTerm = (stem) => PLACEMENT_VERB_RE.exec(stem)?.[1]?.toLowerCase() ?? "";
267
+ // "where is/are/was/were X" — the copula shape ("where is a doormat likely
268
+ // to be") that PLACEMENT_VERB_RE's action verbs never match.
269
+ const WHERE_COPULA_RE = /\bwhere\s+(?:is|are|was|were)\s+(.+)$/i;
270
+ const whereCopulaSourceTerm = (stem) => {
271
+ const m = WHERE_COPULA_RE.exec(stem);
272
+ return m ? captureStemNounPhrase(m[1]) : "";
273
+ };
274
+
275
+ // "... of the/a X?" at the very end of the stem — "what is the habitat of
276
+ // the fox?" names its term in a trailing relational clause, not its subject.
277
+ const TRAILING_OF_CLAUSE_RE = /\bof\s+(?:an?|the)\s+([a-z][\w'-]*(?:\s+[a-z][\w'-]*){0,2})\s*\??\s*$/i;
278
+ const trailingOfClauseSourceTerm = (stem) => {
279
+ const m = TRAILING_OF_CLAUSE_RE.exec(stem);
280
+ return m ? captureStemNounPhrase(m[1]) : "";
281
+ };
282
+
283
+ // "... want(s/ed/ing) to <verb> [object]" — the desire-cue stems. The object
284
+ // grounds better than the bare verb when there is one ("want to open a
285
+ // steakhouse" -> "steakhouse"); the verb itself is the fallback for an
286
+ // intransitive want with nothing following it ("want to smoke?" -> "smoke").
287
+ const WANT_TO_RE = /\bwant(?:s|ed|ing)?\s+to\s+([a-z][\w'-]*)\b(.*)$/i;
288
+ const wantToSourceTerm = (stem) => {
289
+ const m = WANT_TO_RE.exec(stem);
290
+ if (!m) return "";
291
+ return captureStemNounPhrase(m[2]) || m[1].toLowerCase();
292
+ };
293
+
294
+ // Note: a leading "A/An/The <subject> ..." shape is not among these
295
+ // templates. coreParse gates every input on leadsInterrogative before this
296
+ // module ever runs, and that gate's QUESTION_LEAD_RE never accepts a line
297
+ // starting with a determiner — so a stem in that shape is declined before
298
+ // reaching extractStemSourceTerm, and a template for it would never fire.
299
+ function extractStemSourceTerm(stem) {
300
+ return (
301
+ placementVerbSourceTerm(stem)
302
+ || whatDoSubjectSourceTerm(stem)
303
+ || whatVerbObjectSourceTerm(stem)
304
+ || whereCopulaSourceTerm(stem)
305
+ || trailingOfClauseSourceTerm(stem)
306
+ || wantToSourceTerm(stem)
307
+ );
308
+ }
180
309
 
181
310
  function parseLabelledEnumerated(text) {
182
311
  const accepted = findAcceptedLabelSequence(text);
@@ -119,6 +119,8 @@ export function relationKind(group) {
119
119
  if (/\b(touch|chang|modif)/.test(pred)) return "touches";
120
120
  if (/\bcontain/.test(pred)) return "contains";
121
121
  if (/\b(inherit|subclass|extend|specializ)/.test(pred)) return "inherits";
122
+ if (/denot/.test(pred)) return "denotes";
123
+ if (/\bserve/.test(pred)) return "serves";
122
124
  return null;
123
125
  }
124
126
 
@@ -386,6 +388,11 @@ export function impactClosure(graph, ind, { maxDepth = 8 } = {}) {
386
388
  if (!coveredBy.has(e.object)) coveredBy.set(e.object, []);
387
389
  coveredBy.get(e.object).push(e.subjectLabel || e.subject);
388
390
  }
391
+ } else if (kind === "serves") {
392
+ // serves runs subject-provides-object (a handler serves a route), the
393
+ // opposite of imports/calls' subject-depends-on-object — so the
394
+ // dependent here is the OBJECT, not the subject.
395
+ for (const e of g.edges) addDependent(e.subject, e.object, e.objectLabel || e.object, g.predicate);
389
396
  }
390
397
  }
391
398
 
@@ -435,7 +442,7 @@ export function renderImpact(graph, ind, { maxDepth = 8 } = {}) {
435
442
  });
436
443
  const truncatedStructural = graph.truncated.filter((t) => {
437
444
  const kind = relationKind({ predicate: t.predicate });
438
- return kind === "imports" || kind === "calls" || kind === "callsSymbol" || kind === "tests";
445
+ return kind === "imports" || kind === "calls" || kind === "callsSymbol" || kind === "tests" || kind === "serves";
439
446
  });
440
447
  if (truncatedStructural.length) {
441
448
  lines.push(
@@ -477,6 +477,44 @@ export const EL_RULE_CONFIDENCE = 0.95;
477
477
  export const DEFAULT_EL_BUDGET = 2000;
478
478
  export const DEFAULT_EL_ROUNDS = 64;
479
479
 
480
+ /** The two-pass saturation `classifyEl` runs internally (plain TBox first, to
481
+ * learn each concept's real subsumer set, then goal-seeded re-saturation),
482
+ * factored out so a read-only caller — the phase-5 consistency check below,
483
+ * `elUnsatisfiableClasses` — can run the identical computation without
484
+ * `classifyEl`'s own store write. Pure, no I/O. */
485
+ function elSaturateTwoPass(rows, { budget = DEFAULT_EL_BUDGET, rounds = DEFAULT_EL_ROUNDS, focus = null } = {}) {
486
+ const normalized = normalizeElTBox(rows, { budget });
487
+ const firstPass = saturateEl(normalized, { budget, rounds, focus });
488
+ const goals = elGoalAxioms(normalized, firstPass.subsumers);
489
+ const goalInfo = new Map(goals.map((g) => [g.sup, { role: g.role, filler: g.filler }]));
490
+ const withGoals = { ...normalized, axioms: [...normalized.axioms, ...goals] };
491
+ const finalPass = saturateEl(withGoals, { budget, rounds, focus });
492
+ const truncated = normalized.truncated || firstPass.truncated || finalPass.truncated;
493
+ return { normalized, goals, goalInfo, finalPass, truncated };
494
+ }
495
+
496
+ /**
497
+ * The unsatisfiable half of an EL classification pass, with nothing written
498
+ * to the store — `classifyEl`'s own materialising write stays an explicit,
499
+ * separate step (the `/classify` command and `tmct classify`). A consistency
500
+ * report reads this instead: every class whose own subclass/intersection/
501
+ * disjointness structure saturates to `bot`, cited back to the fact ids that
502
+ * derived it. Pure, no I/O.
503
+ *
504
+ * Returns { unsatisfiable, premisesOf, truncated } — `unsatisfiable` is the
505
+ * same sorted array `classifyEl` returns from the same computation;
506
+ * `premisesOf(className)` is the ordered fact-id list its `bot` derivation
507
+ * rests on.
508
+ */
509
+ export function elUnsatisfiableClasses(rows, opts = {}) {
510
+ const { finalPass, truncated } = elSaturateTwoPass(rows, opts);
511
+ return {
512
+ unsatisfiable: finalPass.unsatisfiable,
513
+ premisesOf: (className) => finalPass.derivationOf.get(`${className}${SEP}${BOT}`) || [],
514
+ truncated,
515
+ };
516
+ }
517
+
480
518
  /**
481
519
  * Run one bounded EL classification pass over the memory graph under `repoDir`.
482
520
  * Normalizes, saturates once to find real subsumers, mints batch goals from that
@@ -500,13 +538,7 @@ export async function classifyEl(repoDir, {
500
538
  void maxEnvironments;
501
539
  const memory = await loadMemory(repoDir);
502
540
  const rows = readFactRows(memory);
503
- const normalized = normalizeElTBox(rows, { budget });
504
- const firstPass = saturateEl(normalized, { budget, rounds, focus });
505
- const goals = elGoalAxioms(normalized, firstPass.subsumers);
506
- const goalInfo = new Map(goals.map((g) => [g.sup, { role: g.role, filler: g.filler }]));
507
- const withGoals = { ...normalized, axioms: [...normalized.axioms, ...goals] };
508
- const finalPass = saturateEl(withGoals, { budget, rounds, focus });
509
- const truncated = normalized.truncated || firstPass.truncated || finalPass.truncated;
541
+ const { normalized, goals, goalInfo, finalPass, truncated } = elSaturateTwoPass(rows, { budget, rounds, focus });
510
542
 
511
543
  const trustByTriple = new Map();
512
544
  for (const r of rows) trustByTriple.set(`${r.subject}${SEP}${r.predicate}${SEP}${r.object}`, r.trust);
@@ -1,9 +1,7 @@
1
1
  // fact-phrase.mjs — the one predicate -> English-phrase table, shared by the
2
2
  // news paraphrase renderer and chat's own fact read-back instead of growing a
3
- // twin (PLAN_NEWS_FEED.md section 8.1). The table is copied verbatim from
4
- // chat.mjs's private FACT_PREDICATE_PHRASES; test/domain/fact-phrase.test.mjs
5
- // pins the two identical until chat.mjs is repointed at this module to import
6
- // it instead of holding its own copy.
3
+ // twin. chat.mjs imports FACT_PREDICATE_PHRASES from here rather than holding
4
+ // its own copy.
7
5
  //
8
6
  // This module's own `predicatePhrase`/`factSentence` are the plain reader a
9
7
  // domain module can offer without chat.mjs's surrounding machinery (polarity
@@ -53,6 +51,11 @@ export const FACT_PREDICATE_PHRASES = Object.freeze({
53
51
  "mgx:fixed-in": "is fixed in",
54
52
  "mgx:stands-locked-in": "stands locked in",
55
53
  "mgx:works-in": "works in",
54
+ "mgx:pursues": "pursues",
55
+ "mgx:evades": "evades",
56
+ "mgx:consumes": "eats",
57
+ "mgx:vision-radius": "sees within",
58
+ "mgx:guards": "guards",
56
59
  });
57
60
 
58
61
  /** A table hit, or the predicate's local name (the segment after its first
@@ -416,15 +416,71 @@ export function fillerClausePrefix(text) {
416
416
  return { prefix: m[0].trim(), remainder };
417
417
  }
418
418
 
419
+ // ---- postponed-wh lead shapes: a fronted "what is X" isn't the only real
420
+ // question lead. English also postpones the wh-word behind a declarative
421
+ // clause ("... you will be doing what?", "The trucker plopped on the bench
422
+ // ..., where did he arrive?"), fronts it behind one preposition ("In what
423
+ // country ...?"), or inverts around it mid-sentence with no comma to split
424
+ // on ("During a shark filled tornado where should you not be?"). Each shape
425
+ // below is a closed, deterministic template read off the same QUESTION_LEAD_RE
426
+ // word set the fronted check already uses, and every one requires the line
427
+ // to actually end in "?" — a teach declarative that never ends with a
428
+ // question mark can't trip any of them.
429
+ const WH_WORD_SRC = "what|who|which|where|when|why|how";
430
+ const AUX_WORD_SRC = "is|are|was|were|do|does|did|can|could|should|would|will|has|have|might|must";
431
+
432
+ /** A bare wh-word, with an optional leading article, is the last word before
433
+ * the closing "?": "... you will be doing what?", "... arrived at the
434
+ * what?". The wh-word carries the whole question; everything ahead of it is
435
+ * the declarative lead-in this stem shape favors. */
436
+ const TRAILING_WH_LEAD_RE = new RegExp(`\\b(?:an?|the)?\\s*(?:${WH_WORD_SRC})\\s*\\?\\s*$`, "i");
437
+
438
+ /** A single fronted preposition immediately ahead of a wh-word: "In what
439
+ * country ...?", "From where would you ...?" — the preposition-fronted
440
+ * reading of "what country ... in" / "where ... from". */
441
+ const PREP_WH_LEAD_RE = new RegExp(`^(?:in|at|on|from|by|with|for|of|to|off)\\s+(?:${WH_WORD_SRC})\\b`, "i");
442
+
443
+ /** A wh-word sits mid-sentence, immediately (past at most one subject
444
+ * pronoun) ahead of an auxiliary/modal — the subject-aux inversion
445
+ * signature of a real embedded question with no preceding comma to split
446
+ * on: "... where should you not be?", "... where you can find marmot?". */
447
+ const MID_WH_AUX_RE = new RegExp(
448
+ `\\b(?:${WH_WORD_SRC})\\s+(?:i|you|he|she|it|we|they)?\\s*(?:${AUX_WORD_SRC})\\b`, "i",
449
+ );
450
+
451
+ /** The line's LAST comma- or period-delimited clause opens with a
452
+ * QUESTION_LEAD_RE word: "The trucker plopped on the bench ..., where did
453
+ * he arrive?", "Bart entered his horse into the contest. Where did he do
454
+ * this?" — a declarative lead-in followed by the real question as its own
455
+ * clause or sentence. */
456
+ function lastClauseLeadsInterrogative(line) {
457
+ const clauses = line.split(/[.,]+/).map((c) => c.trim()).filter(Boolean);
458
+ const last = clauses[clauses.length - 1];
459
+ return Boolean(last && QUESTION_LEAD_RE.test(last));
460
+ }
461
+
419
462
  /** QUESTION_LEAD_RE is anchored to the FIRST word, so a closed filler clause
420
463
  * in front of a question moves the interrogative off word one and every
421
464
  * write gate reads the line as a declarative. Peel once, then re-check the
422
- * same question underneath. */
465
+ * same question underneath. Beyond the fronted lead, a line that ends in
466
+ * "?" also passes if it matches one of the postponed-wh shapes above —
467
+ * checked against the first line only, since a caller building a
468
+ * stem-then-options block (a closed multiple-choice question) appends the
469
+ * options after a newline and the question mark lives at the end of the
470
+ * stem, not the end of that block. */
423
471
  export function leadsInterrogative(text) {
424
472
  const line = String(text || "").trim();
425
473
  if (QUESTION_LEAD_RE.test(line)) return true;
426
474
  const peel = fillerClausePrefix(line);
427
- return Boolean(peel && QUESTION_LEAD_RE.test(peel.remainder));
475
+ if (peel && QUESTION_LEAD_RE.test(peel.remainder)) return true;
476
+ const firstLine = line.split("\n")[0].trim();
477
+ if (!/\?\s*$/.test(firstLine)) return false;
478
+ return (
479
+ TRAILING_WH_LEAD_RE.test(firstLine)
480
+ || PREP_WH_LEAD_RE.test(firstLine)
481
+ || MID_WH_AUX_RE.test(firstLine)
482
+ || lastClauseLeadsInterrogative(firstLine)
483
+ );
428
484
  }
429
485
 
430
486
  /** Strippable leading framing clause: "since/[even] though/although/while/
@@ -382,12 +382,42 @@ export function* worldFactRows(lay) {
382
382
 
383
383
  const pluralize = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
384
384
 
385
+ /** The two cast classes' own trait rows: vision, starting mass, drain, and
386
+ * the pursue/consume links that make the predator a predator. These are the
387
+ * rows the turn engine reads back per subject, so on a shipped board the
388
+ * world's own statement — not the config table — is what drives the cast;
389
+ * the config numbers remain the fallback for a world that states nothing.
390
+ * The values quote game-config.mjs so the shipped statement and the shipped
391
+ * fallback can never disagree. Every object is a string, because a fact
392
+ * object is a term. The prey's fear is deliberately NOT stated: it derives
393
+ * from the predator's own `mgx:consumes` row, so one fact carries both the
394
+ * appetite and the flight. */
395
+ export function* castTraitFactRows(lay) {
396
+ const fact = (subject, predicate, object) => ({ world: lay.name, kind: "fact", subject, predicate, object });
397
+ const knobs = DEFAULT_GAME_CONFIG.mudiii;
398
+ const { predator, prey, spawnedFood, placedFood } = CAST_KINDS;
399
+
400
+ yield fact(predator, "mgx:vision-radius", String(knobs.predatorVisionRadius));
401
+ yield fact(predator, "mgx:hasMass", String(knobs.predatorInitialMass));
402
+ yield fact(predator, "mgx:mass-drain-per-turn", String(knobs.predatorMassDecrementPerTurn));
403
+ yield fact(predator, "mgx:pursues", prey);
404
+ yield fact(predator, "mgx:consumes", prey);
405
+ yield fact(prey, "mgx:vision-radius", String(knobs.preyVisionRadius));
406
+ yield fact(prey, "mgx:hasMass", String(knobs.preyInitialMass));
407
+ yield fact(prey, "mgx:mass-drain-per-turn", String(knobs.preyMassDecrementPerTurn));
408
+ yield fact(prey, "mgx:consumes", spawnedFood);
409
+ yield fact(prey, "mgx:consumes", placedFood);
410
+ }
411
+
385
412
  /** The board, the props and the cast restated as askable facts, so "what is
386
413
  * the board?" and "what is the vision radius?" ground instead of missing.
387
- * Every number is either fixed layout geometry or a shipped tuning default
388
- * from game-config.mjs; the tunable ones say "by default", because a slider
389
- * drag or a tmct.toml override moves them and a fact a slider falsifies is a
390
- * lie. */
414
+ * Every number is either fixed layout geometry, a trait the world itself
415
+ * states (castTraitFactRows), or a shipped tuning default from
416
+ * game-config.mjs; only the config-tunable ones say "by default", because a
417
+ * tmct.toml override moves them and a fact an override falsifies is a lie.
418
+ * The per-class vision/mass/drain numbers carry no hedge: after the engine's
419
+ * fact read they are the world's own statement, and the config number is
420
+ * only the fallback for a world that states nothing. */
391
421
  export function* structuralFactRows(lay) {
392
422
  const fact = (subject, predicate, object) => ({ world: lay.name, kind: "fact", subject, predicate, object });
393
423
  const knobs = DEFAULT_GAME_CONFIG.mudiii;
@@ -404,29 +434,24 @@ export function* structuralFactRows(lay) {
404
434
  yield fact("square", "mgx:hasA", `limit of ${pluralize(knobs.maxPreyPopulation, prey)} and ${pluralize(knobs.maxFoodItems, "food item")} at once by default`);
405
435
  yield fact("prop", "mgx:cover", "one cell each, which nothing can walk into");
406
436
 
407
- yield fact(predator, "mgx:hasA", `vision radius of ${pluralize(knobs.predatorVisionRadius, "cell")} by default`);
408
- yield fact(predator, "mgx:start-with", `mass ${knobs.predatorInitialMass} by default`);
409
- yield fact(predator, "mgx:lose", `${knobs.predatorMassDecrementPerTurn} mass per turn by default`);
410
- yield fact(prey, "mgx:hasA", `vision radius of ${pluralize(knobs.preyVisionRadius, "cell")} by default`);
411
- yield fact(prey, "mgx:start-with", `mass ${knobs.preyInitialMass} by default`);
412
- yield fact(prey, "mgx:lose", `${knobs.preyMassDecrementPerTurn} mass per turn by default`);
437
+ yield* castTraitFactRows(lay);
413
438
  yield fact(prey, "mgx:arrive", `every ${pluralize(knobs.preySpawnIntervalTurns, "turn")} at the edge of the board by default`);
414
439
  yield fact(spawnedFood, "mgx:arrive", `every ${pluralize(knobs.foodSpawnIntervalTurns, "turn")} on any open cell by default`);
415
440
  yield fact(spawnedFood, "mgx:start-with", `mass ${knobs.spawnedFoodMass} by default`);
416
441
  yield fact(placedFood, "mgx:start-with", `mass ${knobs.placedFoodMass} by default`);
417
442
  yield fact(placedFood, "mgx:arrive", "where the player puts it");
418
443
 
419
- // The page's own slider label is "vision radius", so that exact term has to
420
- // describe too, not just the per-class rows above. One combined row while
421
- // the two class defaults agree, one row per class once they split — never a
422
- // combined claim the config doesn't make. This cast splits them: the
423
- // predator sees further than the prey, and the one-cell band that opens is
424
- // the point.
444
+ // The dashboard's own term for the belief gate is "vision radius", so that
445
+ // exact term has to describe too, not just the per-class rows above. One
446
+ // combined row while the two class numbers agree, one row per class once
447
+ // they split — never a combined claim the trait rows don't make. This cast
448
+ // splits them: the predator sees further than the prey, and the one-cell
449
+ // band that opens is the point.
425
450
  if (knobs.predatorVisionRadius === knobs.preyVisionRadius) {
426
- yield fact("vision radius", "mgx:hasProperty", `${pluralize(knobs.predatorVisionRadius, "cell")} for both the ${predator} and the ${prey} by default`);
451
+ yield fact("vision radius", "mgx:hasProperty", `${pluralize(knobs.predatorVisionRadius, "cell")} for both the ${predator} and the ${prey}`);
427
452
  } else {
428
- yield fact("vision radius", "mgx:hasProperty", `${pluralize(knobs.predatorVisionRadius, "cell")} for the ${predator} by default`);
429
- yield fact("vision radius", "mgx:hasProperty", `${pluralize(knobs.preyVisionRadius, "cell")} for the ${prey} by default`);
453
+ yield fact("vision radius", "mgx:hasProperty", `${pluralize(knobs.predatorVisionRadius, "cell")} for the ${predator}`);
454
+ yield fact("vision radius", "mgx:hasProperty", `${pluralize(knobs.preyVisionRadius, "cell")} for the ${prey}`);
430
455
  }
431
456
  }
432
457
 
@@ -9,6 +9,7 @@
9
9
  // share the slot.
10
10
 
11
11
  import { worldProvenanceTag } from "../domain/worlds-pack.mjs";
12
+ import { classChainOf } from "../domain/agent-traits.mjs";
12
13
  import { parseSnapshotSubject, snapshotSubject } from "../domain/world-snapshot.mjs";
13
14
  import { parseImperative, OBJECT_PRONOUNS } from "../domain/grammar/ace.mjs";
14
15
  import { loadLexicon, withProperNames, classify } from "../domain/grammar/lexicon.mjs";
@@ -976,23 +977,11 @@ export function objectLookProperties(rows, state, object, actingSubject = "playe
976
977
  * with the object itself ("housekeeper → person"): a breadth-first walk up
977
978
  * the world's OWN rdf:type and rdfs:subClassOf edges (worldActionRows, so a
978
979
  * merged corpus's taxonomy for the same word never joins the chain), the same
979
- * upward-class rendering chat's "what do you know about X" shows. Pure. */
980
+ * upward-class rendering chat's "what do you know about X" shows. The walk
981
+ * itself is agent-traits.mjs's classChainOf, shared with that module's trait
982
+ * resolver so the tree holds one chain walk rather than two. Pure. */
980
983
  export function objectClassChain(rows, object) {
981
- const worldRows = worldActionRows(rows);
982
- const parentsOf = (node) => worldRows
983
- .filter((r) => r.subject === node && (r.predicate === "rdf:type" || r.predicate === "rdfs:subClassOf"))
984
- .map((r) => r.object);
985
- const seen = new Set([object]);
986
- const chain = [object];
987
- const queue = [...parentsOf(object)];
988
- while (queue.length) {
989
- const node = queue.shift();
990
- if (seen.has(node)) continue;
991
- seen.add(node);
992
- chain.push(node);
993
- queue.push(...parentsOf(node));
994
- }
995
- return chain;
984
+ return classChainOf(worldActionRows(rows), object);
996
985
  }
997
986
 
998
987
  async function worldDigest(prompt, { memoryDir, memory, rows, state, graph, actingSubject = "player" }) {