@polycode-projects/the-mechanical-code-talker 5.0.27 → 5.0.29

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 -2
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-belief.mjs +33 -11
  14. package/src/domain/agent-traits.mjs +282 -0
  15. package/src/domain/choice-question.mjs +259 -6
  16. package/src/domain/el-classify.mjs +55 -7
  17. package/src/domain/fact-phrase.mjs +7 -4
  18. package/src/domain/grammar/ace.mjs +66 -3
  19. package/src/domain/interpret/normalize.mjs +58 -2
  20. package/src/domain/tableau.mjs +101 -14
  21. package/src/domain/town-square-world.mjs +44 -19
  22. package/src/services/adventure.mjs +5 -16
  23. package/src/services/agent-editor.mjs +216 -0
  24. package/src/services/chat-session.mjs +26 -5
  25. package/src/services/chat.mjs +118 -58
  26. package/src/services/mudiii-scene.mjs +32 -5
  27. package/src/services/mudiii-turn.mjs +120 -5
  28. package/src/services/mudiii-viz.mjs +299 -1
  29. package/src/services/predator-prey.mjs +234 -57
  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 +48 -2
  33. package/src/surfaces/web/planner-instances.mjs +64 -3
  34. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -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
@@ -1,5 +1,5 @@
1
1
  // grammar/ace.mjs — tmct's deterministic ACE-OWL sub-fragment parser.
2
- // Implements the 17 controlled-English sentence patterns of
2
+ // Implements the 18 controlled-English sentence patterns of
3
3
  // docs/references/schemas/ace-owl-fragment.md and nothing more: fitting the
4
4
  // grammar is a strong signal, missing it is a FEATURE — parseAce returns null
5
5
  // (or an empty-triples result carrying the unknown words as `residue`) and the
@@ -55,6 +55,8 @@ const PATTERN_DIFFERENT_FROM = "differentFrom";
55
55
  const PATTERN_BARE_EXISTENTIAL = "bareExistential";
56
56
  const PATTERN_TRANSITIVE_ROLE = "transitiveRole";
57
57
  const PATTERN_INVERSE_ROLE = "inverseRole";
58
+ const PATTERN_UNIVERSAL = "universal";
59
+ const PATTERN_SUB_PROPERTY_OF = "subPropertyOf";
58
60
 
59
61
  /** The pattern field's full domain, in the README's table order. */
60
62
  const PATTERNS = Object.freeze([
@@ -62,7 +64,7 @@ const PATTERNS = Object.freeze([
62
64
  PATTERN_CARDINALITY, PATTERN_DISJOINT_WITH, PATTERN_POSSESSIVE, PATTERN_ADJECTIVE,
63
65
  PATTERN_CAPABILITY, PATTERN_UNION, PATTERN_COMPLEMENT, PATTERN_NEGATIVE_TYPE,
64
66
  PATTERN_ENUMERATION, PATTERN_DIFFERENT_FROM, PATTERN_BARE_EXISTENTIAL, PATTERN_TRANSITIVE_ROLE,
65
- PATTERN_INVERSE_ROLE,
67
+ PATTERN_INVERSE_ROLE, PATTERN_UNIVERSAL, PATTERN_SUB_PROPERTY_OF,
66
68
  ]);
67
69
 
68
70
  const DET = new Set(["a", "an", "the"]);
@@ -438,6 +440,47 @@ function parseUnion(lexicon, toks, isIdx) {
438
440
  ]);
439
441
  }
440
442
 
443
+ /** Pattern 18 — "every N1 VERB only N2" → allValuesFrom universal
444
+ * restriction: N1 ⊑ ∀VERB.N2, mirroring pattern 15's bare-existential
445
+ * node-naming convention (`all-<pred>-<filler>` beside
446
+ * `some-<pred>-<filler>`). Tried before the bare-existential arm so "only"
447
+ * claims the sentence first — "every heart contains only valves" never
448
+ * reaches pattern 15, and "every heart contains a valve" (no "only") always
449
+ * falls through to it unchanged. */
450
+ function parseUniversal(lexicon, toks, lower) {
451
+ const ns = lexicon.ns;
452
+ for (let i = 2; i < toks.length - 1; i += 1) {
453
+ const verb = lookupVerb(lexicon, lower[i]);
454
+ if (!verb) continue;
455
+ let objStart = i + 1;
456
+ if (verb.prep) {
457
+ if (lower[objStart] !== verb.prep) continue;
458
+ objStart += 1;
459
+ if (objStart >= toks.length) continue;
460
+ }
461
+ if (lower[objStart] !== "only") continue;
462
+ const fillerStart = objStart + 1;
463
+ if (fillerStart >= toks.length) continue;
464
+ const np1 = resolveNP(lexicon, toks.slice(1, i));
465
+ // Same homonym-tolerance as parseBareExistential: a subject that fails to
466
+ // resolve at THIS verb position tries the next candidate rather than
467
+ // committing to a miss that would shadow another pattern.
468
+ if (np1.term == null) continue;
469
+ const np2 = resolveNP(lexicon, toks.slice(fillerStart));
470
+ if (np2.term == null) return missOrNull(PATTERN_UNIVERSAL, [np1, np2]);
471
+ if (np1.individual || np2.individual) return null;
472
+ const pred = predicateOf(verb, ns);
473
+ const r = `${ns}all-${local(lexicon, pred)}-${local(lexicon, np2.term)}`;
474
+ return hit(PATTERN_UNIVERSAL, [np1, np2], [
475
+ { subject: r, predicate: "rdf:type", object: "owl:Restriction", kind: "owl:allValuesFrom" },
476
+ { subject: r, predicate: "owl:onProperty", object: pred, kind: "owl:allValuesFrom" },
477
+ { subject: r, predicate: "owl:allValuesFrom", object: np2.term, kind: "owl:allValuesFrom" },
478
+ { subject: np1.term, predicate: "rdfs:subClassOf", object: r, kind: "owl:allValuesFrom" },
479
+ ]);
480
+ }
481
+ return null;
482
+ }
483
+
441
484
  /** Pattern 15 — "every N1 VERB [det] N2" → someValuesFrom bare existential
442
485
  * restriction: "every heart has a valve" (the `has` verb), and the general
443
486
  * verb form "every heart contains a valve". Tried after the `that` and
@@ -487,6 +530,8 @@ function parseEvery(lexicon, toks, lower) {
487
530
  if (hasIdx > 1 && (lower[hasIdx + 1] === "at" || lower[hasIdx + 1] === "exactly")) {
488
531
  return parseCardinality(lexicon, toks, lower, hasIdx);
489
532
  }
533
+ const universal = parseUniversal(lexicon, toks, lower);
534
+ if (universal) return universal;
490
535
  const bareExistential = parseBareExistential(lexicon, toks, lower);
491
536
  if (bareExistential) return bareExistential;
492
537
  const isIdx = lower.indexOf("is");
@@ -638,6 +683,20 @@ function parseInverseRole(lexicon, toks, lower) {
638
683
  ]);
639
684
  }
640
685
 
686
+ /** Pattern 19 — "V1 implies V2" → rdfs:subPropertyOf from V1's minted
687
+ * predicate to V2's minted predicate, one row, one direction — a
688
+ * subproperty relation is directional, unlike pattern 17's owl:inverseOf.
689
+ * Both sides accept the same 3sg-or-gerund fold patterns 16 and 17 already
690
+ * share, through the same verbPredicateFromSurface. */
691
+ function parseSubProperty(lexicon, toks, lower) {
692
+ const p1 = verbPredicateFromSurface(lexicon, lower[0]);
693
+ const p2 = verbPredicateFromSurface(lexicon, lower[2]);
694
+ if (!p1 || !p2) return null;
695
+ return hit(PATTERN_SUB_PROPERTY_OF, [], [
696
+ { subject: p1, predicate: "rdfs:subPropertyOf", object: p2, kind: "rdfs:subPropertyOf" },
697
+ ]);
698
+ }
699
+
641
700
  /** Pattern 7 — "N1's N2 is VALUE" / "the N2 of N1 is VALUE": data or object
642
701
  * property assertion per the possessive noun's DECLARED typing (undeclared
643
702
  * typing defaults to data — a literal value is the honest floor). */
@@ -721,7 +780,7 @@ function parseCopula(lexicon, toks, lower, isIdx) {
721
780
  ]);
722
781
  }
723
782
 
724
- /** Parse one sentence against the 17-pattern ACE-OWL sub-fragment. See the
783
+ /** Parse one sentence against the 18-pattern ACE-OWL sub-fragment. See the
725
784
  * file header for the result contract; `lexicon` defaults to the committed
726
785
  * core under the library's own neutral DEFAULT_NS ("ex:") when the caller
727
786
  * doesn't supply one. */
@@ -737,6 +796,10 @@ export function parseAce(sentence, lexicon = loadLexicon()) {
737
796
  const inverse = parseInverseRole(lexicon, toks, lower);
738
797
  if (inverse) return inverse;
739
798
  }
799
+ if (toks.length === 3 && lower[1] === "implies") {
800
+ const subProperty = parseSubProperty(lexicon, toks, lower);
801
+ if (subProperty) return subProperty;
802
+ }
740
803
  if (lower[0] === "everything" && lower[1] === "that") return parseComplement(lexicon, toks, lower);
741
804
  if (lower[0] === "every") return parseEvery(lexicon, toks, lower);
742
805
  if (lower[0] === "no") return parseDisjoint(lexicon, toks, lower);
@@ -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/
@@ -47,6 +47,7 @@ const notE = (c) => ({ t: "not", c });
47
47
  const andE = (cs) => ({ t: "and", cs });
48
48
  const orE = (cs) => ({ t: "or", cs });
49
49
  const someE = (r, c) => ({ t: "some", r, c });
50
+ const allE = (r, c) => ({ t: "all", r, c });
50
51
 
51
52
  /** A stable string key for a concept expression. Sorting, dedup and clash
52
53
  * detection all go through this, so two structurally equal expressions are
@@ -222,6 +223,10 @@ export const DEFAULT_PROVE_NODES = 512;
222
223
  * module never sees, so the caller pairs this with entailedTrustFrom. */
223
224
  export const TABLEAU_RULE_CONFIDENCE = 0.95;
224
225
  export const DEFAULT_MODULE_HOPS = 4;
226
+ /** Caps how many asserted ABox role edges one KB admits — a data-structure
227
+ * size bound for termination, applied after sorting so truncation is
228
+ * deterministic rather than arrival-ordered. */
229
+ export const MAX_ROLE_ASSERTIONS = 256;
225
230
 
226
231
  // ---- identity: the UNA-lite merge machinery --------------------------------
227
232
  //
@@ -838,7 +843,19 @@ function buildInitialBranch(kb, extraAssertions) {
838
843
  inequalityFrom.set(key, existing ? sortedUnique([...existing, ...pair.from]) : sortedUnique(pair.from));
839
844
  }
840
845
 
841
- return { nodes, edges: [], closed: false, clash: null, inequalityFrom };
846
+ // An asserted ABox role edge — the only source of a branch edge besides
847
+ // the ∃/≥-rules' own generated successors. Pushed in the KB's own sorted
848
+ // order (buildTableauKb sorts roleAssertions by subject/predicate/object
849
+ // before returning), so the branch is byte-identical whatever order the
850
+ // underlying rows arrived in.
851
+ const edges = [];
852
+ for (const ra of kb.roleAssertions || []) {
853
+ ensureNode(ra.a);
854
+ ensureNode(ra.b);
855
+ edges.push({ from: ra.a, r: ra.r, to: ra.b, fromFacts: ra.from.slice() });
856
+ }
857
+
858
+ return { nodes, edges, closed: false, clash: null, inequalityFrom };
842
859
  }
843
860
 
844
861
  /** Is the KB plus the given assertions satisfiable? `extraAssertions` is
@@ -905,15 +922,30 @@ function describeClashKind(clash) {
905
922
  return `complement:${clash.keyA}~${clash.keyB}`;
906
923
  }
907
924
 
925
+ // The closed OWL/RDFS vocabulary buildTableauKb's own predicate dispatch
926
+ // recognises (lower-cased, matching the `p` this file always compares
927
+ // against). Shared with extractTableauModule so both agree on what counts
928
+ // as a role assertion — any row whose predicate is NOT in this set — rather
929
+ // than drifting into two separate definitions of "recognised vocabulary".
930
+ const RECOGNISED_KB_PREDICATES = new Set([
931
+ "owl:onproperty", "owl:somevaluesfrom", "owl:allvaluesfrom", "owl:onclass",
932
+ "owl:mincardinality", "owl:maxcardinality", "owl:cardinality",
933
+ "rdfs:subclassof", "owl:disjointwith", "rdf:type", "mgxneg:subclassof",
934
+ "owl:unionof", "owl:complementof", "rdfs:subpropertyof", "owl:differentfrom",
935
+ "owl:oneof", "owl:inverseof",
936
+ ]);
937
+
908
938
  /** Build the tableau knowledge base from a row set — on a real question,
909
939
  * the output of extractTableauModule, never the raw store. Pure. Returns
910
940
  * { axioms, assertions, roles, individuals, transitiveRoles, roleClosure,
911
- * namedIndividuals, nominalIndividuals, differentFrom, inverseOf }. */
941
+ * namedIndividuals, nominalIndividuals, differentFrom, inverseOf,
942
+ * roleAssertions }. */
912
943
  export function buildTableauKb(rows) {
913
944
  const list = Array.isArray(rows) ? rows.filter((r) => r && r.subject && r.predicate) : [];
914
945
 
915
946
  const onPropertyOf = new Map(); // restriction -> { object, id }
916
947
  const someValuesFromOf = new Map();
948
+ const allValuesFromOf = new Map();
917
949
  const onClassOf = new Map();
918
950
  const cardinalityOf = new Map(); // restriction -> { kind, n, id }
919
951
  const unionMembersOf = new Map(); // union node -> [row, …]
@@ -927,6 +959,7 @@ export function buildTableauKb(rows) {
927
959
  const subPropertyRows = [];
928
960
  const differentFromRows = [];
929
961
  const inverseOfRows = [];
962
+ const roleAssertionCandidates = [];
930
963
 
931
964
  const pushMap = (map, key, value) => {
932
965
  if (!map.has(key)) map.set(key, []);
@@ -937,6 +970,7 @@ export function buildTableauKb(rows) {
937
970
  const p = String(r.predicate).trim().toLowerCase();
938
971
  if (p === "owl:onproperty") onPropertyOf.set(r.subject, { object: r.object, id: r.id });
939
972
  else if (p === "owl:somevaluesfrom") someValuesFromOf.set(r.subject, { object: r.object, id: r.id });
973
+ else if (p === "owl:allvaluesfrom") allValuesFromOf.set(r.subject, { object: r.object, id: r.id });
940
974
  else if (p === "owl:onclass") onClassOf.set(r.subject, { object: r.object, id: r.id });
941
975
  else if (p === "owl:mincardinality") cardinalityOf.set(r.subject, { kind: "min", n: Number(r.object), id: r.id });
942
976
  else if (p === "owl:maxcardinality") cardinalityOf.set(r.subject, { kind: "max", n: Number(r.object), id: r.id });
@@ -954,6 +988,7 @@ export function buildTableauKb(rows) {
954
988
  else if (p === "owl:differentfrom") differentFromRows.push(r);
955
989
  else if (p === "owl:oneof") pushMap(oneOfMembersOf, r.subject, r);
956
990
  else if (p === "owl:inverseof") inverseOfRows.push(r);
991
+ else roleAssertionCandidates.push(r);
957
992
  }
958
993
 
959
994
  const individualNamesFromType = new Set();
@@ -963,6 +998,20 @@ export function buildTableauKb(rows) {
963
998
  }
964
999
  const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
965
1000
 
1001
+ // An asserted role edge between two named individuals: any predicate
1002
+ // outside the recognised OWL/RDFS vocabulary, both of whose terms resolve
1003
+ // as individuals — a class-level relation ("human mgx:capableOf think")
1004
+ // is not read as an ABox edge. Classification waits for
1005
+ // individualNamesFromType above to exist, so candidates are collected in
1006
+ // the predicate-dispatch pass and filtered here, in a second pass. Sorted
1007
+ // by subject, then predicate, then object, and capped AFTER sorting so
1008
+ // truncation is deterministic rather than arrival-ordered.
1009
+ const roleAssertions = roleAssertionCandidates
1010
+ .filter((r) => isIndividualTerm(r.subject) && isIndividualTerm(r.object))
1011
+ .sort((a, b) => a.subject.localeCompare(b.subject) || a.predicate.localeCompare(b.predicate) || a.object.localeCompare(b.object))
1012
+ .slice(0, MAX_ROLE_ASSERTIONS)
1013
+ .map((r) => ({ a: r.subject, r: r.predicate, b: r.object, from: [r.id] }));
1014
+
966
1015
  const mkAxiom = (sub, sup, from) => ({ sub, sup, from: sortedUnique(from), disjunction: toNNF(orE([notE(sub), sup])) });
967
1016
 
968
1017
  const axioms = [];
@@ -980,6 +1029,11 @@ export function buildTableauKb(rows) {
980
1029
  axioms.push(mkAxiom(atom(r.subject), someE(propRow.object, atom(svfRow.object)), [r.id, propRow.id, svfRow.id]));
981
1030
  continue;
982
1031
  }
1032
+ const avfRow = allValuesFromOf.get(restriction);
1033
+ if (avfRow) {
1034
+ axioms.push(mkAxiom(atom(r.subject), allE(propRow.object, atom(avfRow.object)), [r.id, propRow.id, avfRow.id]));
1035
+ continue;
1036
+ }
983
1037
  const cardRow = cardinalityOf.get(restriction);
984
1038
  const onClassRow = onClassOf.get(restriction);
985
1039
  if (cardRow && onClassRow) {
@@ -1057,6 +1111,7 @@ export function buildTableauKb(rows) {
1057
1111
 
1058
1112
  const roles = new Set();
1059
1113
  for (const { object } of onPropertyOf.values()) roles.add(object);
1114
+ for (const ra of roleAssertions) roles.add(ra.r);
1060
1115
 
1061
1116
  const subPropertyEdges = subPropertyRows
1062
1117
  .map((r) => [r.subject, r.object])
@@ -1070,12 +1125,15 @@ export function buildTableauKb(rows) {
1070
1125
  a.from.join(",").localeCompare(b.from.join(",")));
1071
1126
  assertions.sort((a, b) => a.ind.localeCompare(b.ind) || canonicalKey(a.expr).localeCompare(canonicalKey(b.expr)));
1072
1127
 
1073
- const individuals = [...new Set(assertions.map((a) => a.ind))].sort();
1128
+ const individuals = [...new Set([
1129
+ ...assertions.map((a) => a.ind),
1130
+ ...roleAssertions.flatMap((ra) => [ra.a, ra.b]),
1131
+ ])].sort();
1074
1132
  const namedIndividuals = new Set(individuals);
1075
1133
 
1076
1134
  return {
1077
1135
  axioms, assertions, roles: [...roles].sort(), individuals, transitiveRoles, roleClosure,
1078
- namedIndividuals, nominalIndividuals, differentFrom, inverseOf,
1136
+ namedIndividuals, nominalIndividuals, differentFrom, inverseOf, roleAssertions,
1079
1137
  };
1080
1138
  }
1081
1139
 
@@ -1086,6 +1144,7 @@ function restrictKbToIndividual(kb, ind) {
1086
1144
  roles: kb.roles,
1087
1145
  individuals: [ind],
1088
1146
  transitiveRoles: kb.transitiveRoles,
1147
+ roleAssertions: kb.roleAssertions,
1089
1148
  roleClosure: kb.roleClosure,
1090
1149
  namedIndividuals: kb.namedIndividuals,
1091
1150
  nominalIndividuals: kb.nominalIndividuals,
@@ -1123,15 +1182,20 @@ function addToSetMap(map, key, value) {
1123
1182
  /** Restrict fact rows to the signature-connected module around a set of
1124
1183
  * seed terms. `rdfs:subClassOf` closes unbounded in both directions (it is
1125
1184
  * always followed, at no hop cost); a restriction's filler (owl:onProperty
1126
- * / owl:someValuesFrom / owl:onClass) and owl:unionOf / owl:complementOf /
1127
- * owl:oneOf membership are hop-bounded structural edges. Reaching a term
1128
- * through a restriction's filler edge re-seeds that term's own walk at the
1129
- * full hop budget, so a chain of restrictions extends the module without
1130
- * an unbounded hop count; a union/complement/oneOf membership edge simply
1131
- * spends one hop. The returned rows are every row whose subject or object
1132
- * lands in the resulting signature, plus any role axiom naming a role a
1133
- * included restriction uses. Pure, no I/O. Returns the restricted row
1134
- * array, in the input's own row order. */
1185
+ * / owl:someValuesFrom / owl:allValuesFrom / owl:onClass) and owl:unionOf /
1186
+ * owl:complementOf / owl:oneOf membership are hop-bounded structural edges.
1187
+ * Reaching a term through a restriction's filler edge re-seeds that term's
1188
+ * own walk at the full hop budget, so a chain of restrictions extends the
1189
+ * module without an unbounded hop count; a union/complement/oneOf
1190
+ * membership edge simply spends one hop. An asserted ABox role edge
1191
+ * (buildTableauKb's own role-assertion reader test: a predicate outside
1192
+ * the recognised OWL/RDFS vocabulary, both terms individuals) reseeds its
1193
+ * far endpoint's own walk the same way a restriction filler does — a chain
1194
+ * of asserted edges extends the module without an unbounded hop count
1195
+ * either. The returned rows are every row whose subject or object lands in
1196
+ * the resulting signature, plus any role axiom naming a role an included
1197
+ * restriction or role assertion uses. Pure, no I/O. Returns the restricted
1198
+ * row array, in the input's own row order. */
1135
1199
  export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HOPS } = {}) {
1136
1200
  const list = Array.isArray(rows) ? rows.filter((r) => r && r.subject && r.predicate) : [];
1137
1201
  const hopBudget = clampNonNegativeInt(hops, DEFAULT_MODULE_HOPS);
@@ -1147,15 +1211,30 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
1147
1211
  const memberComplements = new Map();
1148
1212
  const oneOfMembers = new Map();
1149
1213
  const memberOneOf = new Map();
1214
+ const roleAssertionRows = []; // { subject, predicate, object } — same reader test as buildTableauKb
1215
+ const roleAssertionEndpoints = new Map(); // term -> Set(other endpoint), both directions
1216
+
1217
+ const individualNamesFromType = new Set();
1218
+ for (const r of list) {
1219
+ if (String(r.predicate).trim().toLowerCase() !== "rdf:type") continue;
1220
+ const obj = String(r.object || "").toLowerCase();
1221
+ if (!META_TYPE_OBJECTS.has(obj)) individualNamesFromType.add(r.subject);
1222
+ }
1223
+ const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
1150
1224
 
1151
1225
  for (const r of list) {
1152
1226
  const p = String(r.predicate).trim().toLowerCase();
1153
1227
  if (p === "rdfs:subclassof") { addToSetMap(subUp, r.subject, r.object); addToSetMap(subDown, r.object, r.subject); }
1154
1228
  else if (p === "owl:onproperty") onPropertyOf.set(r.subject, r.object);
1155
- else if (p === "owl:somevaluesfrom" || p === "owl:onclass") { fillerOf.set(r.subject, r.object); addToSetMap(fillerBack, r.object, r.subject); }
1229
+ else if (p === "owl:somevaluesfrom" || p === "owl:allvaluesfrom" || p === "owl:onclass") { fillerOf.set(r.subject, r.object); addToSetMap(fillerBack, r.object, r.subject); }
1156
1230
  else if (p === "owl:unionof") { addToSetMap(unionMembers, r.subject, r.object); addToSetMap(memberUnions, r.object, r.subject); }
1157
1231
  else if (p === "owl:complementof") { complementPair.set(r.subject, r.object); addToSetMap(memberComplements, r.object, r.subject); }
1158
1232
  else if (p === "owl:oneof") { addToSetMap(oneOfMembers, r.subject, r.object); addToSetMap(memberOneOf, r.object, r.subject); }
1233
+ else if (!RECOGNISED_KB_PREDICATES.has(p) && isIndividualTerm(r.subject) && isIndividualTerm(r.object)) {
1234
+ roleAssertionRows.push(r);
1235
+ addToSetMap(roleAssertionEndpoints, r.subject, r.object);
1236
+ addToSetMap(roleAssertionEndpoints, r.object, r.subject);
1237
+ }
1159
1238
  }
1160
1239
 
1161
1240
  const subClosureCache = new Map();
@@ -1210,10 +1289,18 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
1210
1289
  for (const c of memberComplements.get(term) || []) enqueue(c, hopsLeft - 1);
1211
1290
  for (const m of oneOfMembers.get(term) || []) enqueue(m, hopsLeft - 1);
1212
1291
  for (const c of memberOneOf.get(term) || []) enqueue(c, hopsLeft - 1);
1292
+
1293
+ // A role-assertion edge reseeds its far endpoint's own walk, the same
1294
+ // discipline a restriction chain gets — otherwise a question about one
1295
+ // end of an asserted edge extracts a module that does not contain the
1296
+ // edge, and the far endpoint's own facts (its type, its restrictions)
1297
+ // never enter the module either.
1298
+ for (const other of roleAssertionEndpoints.get(term) || []) enqueue(other, hopBudget);
1213
1299
  }
1214
1300
 
1215
1301
  const rolesUsed = new Set();
1216
1302
  for (const [restriction, role] of onPropertyOf) if (included.has(restriction)) rolesUsed.add(role);
1303
+ for (const r of roleAssertionRows) if (included.has(r.subject) || included.has(r.object)) rolesUsed.add(r.predicate);
1217
1304
 
1218
1305
  return list.filter((r) => {
1219
1306
  if (included.has(r.subject) || included.has(r.object)) return true;
@@ -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" }) {