@polycode-projects/the-mechanical-code-talker 5.0.28 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.28",
3
+ "version": "5.0.29",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -162,9 +162,9 @@
162
162
  "bench:receipts": "node scripts/bench-receipts.mjs",
163
163
  "claims": "node scripts/claims/run-all.mjs",
164
164
  "claim:prose-band": "node scripts/claims/claim-prose-band.mjs",
165
- "claim:openbookqa": "node scripts/claims/claim-openbookqa.mjs",
166
165
  "claim:commonsenseqa": "node scripts/claims/claim-commonsenseqa.mjs",
167
166
  "claim:planner": "node scripts/claims/claim-planner.mjs",
167
+ "claim:syllogist": "node scripts/claims/claim-syllogist.mjs",
168
168
  "roll": "node scripts/roll.mjs",
169
169
  "build:ask-bundle": "node scripts/build-ask-bundle.mjs",
170
170
  "build:chat-bundle": "node scripts/build-chat-bundle.mjs",
@@ -29,33 +29,55 @@ const cellIdOf = (x, y) => `cell-${x}-${y}`;
29
29
 
30
30
  const chebyshevSteps = (ax, ay, bx, by) => Math.max(Math.abs(ax - bx), Math.abs(ay - by));
31
31
 
32
- /** Where `observerSubject` currently believes `targetSubject` to be, as an
33
- * `{ x, y }` cell, or null for no belief at all.
32
+ /** The one three-rung walk `believedCellOf` and `beliefOriginOf` both read,
33
+ * so the cell a panel shows and the "how it knows" label beside it can never
34
+ * disagree about which rung answered. Returns `{ origin, cell }` or null.
34
35
  *
35
- * Four rungs, in order:
36
+ * Three rungs, in order:
36
37
  *
37
38
  * 1. A target the board has removed (eaten, starved, hatched) is believed
38
39
  * nowhere, and no told fact can put it back. A claim about an id that was
39
40
  * never placed at all is a different case and still lands, which is what
40
41
  * keeps deception working.
41
- * 2. Ground truth, when the target's real cell sits within `visionRadius`
42
- * Chebyshev steps of `observerCell`.
43
- * 3. The newest told fact addressed to this observer about this target —
44
- * `opts.toldFacts` rows shaped `{ subject, toAgent, cell, turn }`.
45
- * 4. Otherwise null.
42
+ * 2. Ground truth (`origin: "seen"`), when the target's real cell sits
43
+ * within `visionRadius` Chebyshev steps of `observerCell`.
44
+ * 3. The newest told fact addressed to this observer about this target
45
+ * (`origin: { told: turn }`) — `opts.toldFacts` rows shaped
46
+ * `{ subject, toAgent, cell, turn }`. Otherwise null.
46
47
  *
47
48
  * `state` is a folded world state: `.placements` (subject -> `{ cell }`) and
48
49
  * `.removed` (a Set of subjects off the board). Pure. */
49
- export function believedCellOf(targetSubject, observerSubject, observerCell, state, opts = {}) {
50
+ function believedRungOf(targetSubject, observerSubject, observerCell, state, opts = {}) {
50
51
  if (state.removed.has(targetSubject)) return null;
51
52
  const { visionRadius = DEFAULT_VISION_RADIUS, toldFacts = [] } = opts;
52
53
  const place = state.placements.get(targetSubject);
53
54
  const at = place ? cellCoordsOf(place.cell) : null;
54
- if (at && chebyshevSteps(observerCell.x, observerCell.y, at.x, at.y) <= visionRadius) return at;
55
+ if (at && chebyshevSteps(observerCell.x, observerCell.y, at.x, at.y) <= visionRadius) {
56
+ return { origin: "seen", cell: at };
57
+ }
55
58
  const told = toldFacts
56
59
  .filter((f) => f.toAgent === observerSubject && f.subject === targetSubject)
57
60
  .sort((a, b) => (b.turn ?? 0) - (a.turn ?? 0))[0];
58
- return told ? cellCoordsOf(told.cell) : null;
61
+ if (!told) return null;
62
+ const cell = cellCoordsOf(told.cell);
63
+ return cell ? { origin: { told: told.turn ?? 0 }, cell } : null;
64
+ }
65
+
66
+ /** Where `observerSubject` currently believes `targetSubject` to be, as an
67
+ * `{ x, y }` cell, or null for no belief at all. See `believedRungOf` for
68
+ * the three-rung walk this reads the cell half of. Pure. */
69
+ export function believedCellOf(targetSubject, observerSubject, observerCell, state, opts = {}) {
70
+ return believedRungOf(targetSubject, observerSubject, observerCell, state, opts)?.cell ?? null;
71
+ }
72
+
73
+ /** Which rung answered `believedCellOf` for this exact call: `"seen"` when
74
+ * the target sits within vision, `{ told: turn }` for the newest told fact
75
+ * that answered, or null when the observer believes nothing. A belief
76
+ * panel's own "how it knows" column reads this beside the cell
77
+ * `believedCellOf` returns, off the same walk (`believedRungOf`), so the two
78
+ * can never drift apart. Pure. */
79
+ export function beliefOriginOf(targetSubject, observerSubject, observerCell, state, opts = {}) {
80
+ return believedRungOf(targetSubject, observerSubject, observerCell, state, opts)?.origin ?? null;
59
81
  }
60
82
 
61
83
  /** The nearest candidate (by believed Chebyshev distance) an observer has
@@ -223,13 +223,24 @@ function readStemNounPhrase(words) {
223
223
  return out.join(" ");
224
224
  }
225
225
 
226
+ /** Strips every leading determiner in a run ("the most fast food
227
+ * restaurants" -> "fast food restaurants"), not just the first — a
228
+ * quantifier stacked on an article is ordinary English, not a special
229
+ * case. */
230
+ function stripLeadingDeterminers(phrase) {
231
+ let out = phrase;
232
+ let m;
233
+ while ((m = LEADING_DETERMINER_RE.exec(out))) out = out.slice(m[0].length);
234
+ return out;
235
+ }
236
+
226
237
  /** Strips a leading determiner, then reads a noun phrase — "" when the
227
238
  * phrase would open on a pronoun or a boundary word, since neither ever
228
239
  * names a source term. Stops at the first comma, so an option-like list
229
240
  * ("a magazine, paper or gum") reads only its first member. */
230
241
  function captureStemNounPhrase(tailText) {
231
242
  const [beforeComma] = String(tailText).split(",", 1);
232
- const stripped = beforeComma.replace(LEADING_DETERMINER_RE, "");
243
+ const stripped = stripLeadingDeterminers(beforeComma);
233
244
  const words = stripped.trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
234
245
  if (words.length === 0 || PRONOUN_TERMS.has(words[0]) || PHRASE_BOUNDARY_WORDS.has(words[0])) return "";
235
246
  return readStemNounPhrase(words);
@@ -291,6 +302,115 @@ const wantToSourceTerm = (stem) => {
291
302
  return captureStemNounPhrase(m[2]) || m[1].toLowerCase();
292
303
  };
293
304
 
305
+ // ---- postponed and mid-sentence wh-shapes ----
306
+ //
307
+ // leadsInterrogative (normalize.mjs) widened its gate to recognize four
308
+ // stem shapes where the wh-word is not the stem's own first word. Passing
309
+ // that gate only says the stem is a real question — it says nothing about
310
+ // where the source term sits inside it, so each shape needs its own
311
+ // extraction template here too. Every template below reads a closed, fixed
312
+ // vocabulary (the same PHRASE_BOUNDARY_WORDS/PREP_WORDS/PRONOUN_TERMS the
313
+ // fronted templates already use) and returns "" rather than guessing when
314
+ // nothing structured is there to read.
315
+
316
+ // A subordinator or preposition opening the clause ahead of a mid-sentence
317
+ // wh-word ("During a shark filled tornado where...") is framing, not the
318
+ // source term itself.
319
+ const SUBORDINATOR_LEAD_RE = /^(?:during|while|when|if|after|before|despite|though|although|because|since|as|without|about|for|in|on|at|with)\s+/i;
320
+
321
+ const BACKWARD_SCAN_STOP_WORDS = new Set([...PHRASE_BOUNDARY_WORDS, "be", "been"]);
322
+
323
+ /** Reads the noun phrase after the first preposition found in `text` — the
324
+ * locative-object reading a declarative lead clause usually wants
325
+ * ("plopped on the bench" -> "bench") over its own grammatical subject.
326
+ * Returns "" when the clause has no preposition to anchor on. */
327
+ function captureLocativeNounPhrase(text) {
328
+ const words = String(text).trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
329
+ const idx = words.findIndex((w) => PREP_WORDS.has(w));
330
+ if (idx === -1 || idx === words.length - 1) return "";
331
+ return captureStemNounPhrase(words.slice(idx + 1).join(" "));
332
+ }
333
+
334
+ /** Reads a short noun phrase backward from the end of `leadText`, skipping
335
+ * any boundary words trailing off the very end, then collecting content
336
+ * words until the next boundary word, pronoun, or the start of the text.
337
+ * Used only when the wh-word is the stem's own last word, where nothing
338
+ * marks the start of the noun phrase the way a template's cue word
339
+ * normally does. */
340
+ function captureTrailingNounPhrase(leadText) {
341
+ const words = String(leadText).trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
342
+ let end = words.length;
343
+ while (end > 0 && BACKWARD_SCAN_STOP_WORDS.has(words[end - 1])) end -= 1;
344
+ const out = [];
345
+ let i = end - 1;
346
+ while (i >= 0 && out.length < 3) {
347
+ const word = words[i];
348
+ if (BACKWARD_SCAN_STOP_WORDS.has(word) || PRONOUN_TERMS.has(word)) break;
349
+ out.unshift(word);
350
+ i -= 1;
351
+ }
352
+ if (out.length === 0) return "";
353
+ const stripped = stripLeadingDeterminers(out.join(" "));
354
+ const strippedWords = stripped.split(/\s+/).filter(Boolean);
355
+ if (strippedWords.length === 0 || PRONOUN_TERMS.has(strippedWords[0])) return "";
356
+ return stripped;
357
+ }
358
+
359
+ // "In what country are the most fast food restaurants?", "From where do
360
+ // aliens arrive?" — a wh-word fronted behind a single preposition, either
361
+ // carrying its own noun ("what country") or bare ("where"). The clause
362
+ // after the auxiliary/copula is where the source term sits.
363
+ const PREP_WH_FRONTED_CAPTURE_RE = new RegExp(
364
+ "^(?:in|at|on|from|by|with|for|of|to|off)\\s+"
365
+ + "(?:(?:what|which)\\s+[a-z][\\w'-]*|where|when|why|how|who)\\s+"
366
+ + "(?:is|are|was|were|do|does|did|can|could|should|would|will|has|have|might|must)\\s+(.+?)[?.!]*$", "i",
367
+ );
368
+ const prepWhFrontedSourceTerm = (stem) => {
369
+ const m = PREP_WH_FRONTED_CAPTURE_RE.exec(stem);
370
+ return m ? captureStemNounPhrase(m[1]) : "";
371
+ };
372
+
373
+ // "During a shark filled tornado where should you not be?" — the wh-word
374
+ // sits mid-sentence, immediately ahead of an auxiliary, with no comma to
375
+ // split on. The source term sits in the clause ahead of the wh-word; a
376
+ // stem where the wh-word is already the first word captures an empty lead
377
+ // here and falls through, since that shape is the fronted templates' own.
378
+ // A lead that itself carries a comma is the trailing-clause shape's own
379
+ // territory instead, so this declines rather than reading across the join.
380
+ const MID_SENTENCE_WH_AUX_CAPTURE_RE = new RegExp(
381
+ "^(.*?)\\b(?:what|who|which|where|when|why|how)\\s+(?:i|you|he|she|it|we|they)?\\s*"
382
+ + "(?:is|are|was|were|do|does|did|can|could|should|would|will|has|have|might|must)\\b", "i",
383
+ );
384
+ const midSentenceWhAuxSourceTerm = (stem) => {
385
+ const m = MID_SENTENCE_WH_AUX_CAPTURE_RE.exec(stem);
386
+ if (!m || !m[1].trim() || m[1].includes(",")) return "";
387
+ return captureStemNounPhrase(m[1].replace(SUBORDINATOR_LEAD_RE, ""));
388
+ };
389
+
390
+ // "The trucker plopped on the bench with a sense of relief, where did he
391
+ // arrive?" — the stem's last comma- or period-delimited clause opens with
392
+ // a question-lead word; the source term sits in the declarative clause(s)
393
+ // ahead of it. A stem with no such split (one clause only) falls through,
394
+ // since there is no "earlier" clause to read.
395
+ const trailingClauseAfterPunctuationSourceTerm = (stem) => {
396
+ const clauses = stem.split(/[.,]+/).map((c) => c.trim()).filter(Boolean);
397
+ if (clauses.length < 2) return "";
398
+ const last = clauses[clauses.length - 1];
399
+ if (!QUESTION_LEAD_RE.test(last)) return "";
400
+ const lead = clauses.slice(0, -1).join(" ");
401
+ return captureLocativeNounPhrase(lead) || captureStemNounPhrase(lead);
402
+ };
403
+
404
+ // "... you will be doing what?", "... arrived at the what?" — a bare
405
+ // wh-word, with an optional leading article, is the stem's own last word
406
+ // before the closing "?". Nothing marks where the source term starts, so
407
+ // this reads backward from the wh-word for the nearest content phrase.
408
+ const TRAILING_BARE_WH_CAPTURE_RE = /^(.*?)\b(?:an?|the)?\s*(?:what|who|which|where|when|why|how)\s*\?\s*$/i;
409
+ const trailingBareWhSourceTerm = (stem) => {
410
+ const m = TRAILING_BARE_WH_CAPTURE_RE.exec(stem);
411
+ return m ? captureTrailingNounPhrase(m[1]) : "";
412
+ };
413
+
294
414
  // Note: a leading "A/An/The <subject> ..." shape is not among these
295
415
  // templates. coreParse gates every input on leadsInterrogative before this
296
416
  // module ever runs, and that gate's QUESTION_LEAD_RE never accepts a line
@@ -304,6 +424,10 @@ function extractStemSourceTerm(stem) {
304
424
  || whereCopulaSourceTerm(stem)
305
425
  || trailingOfClauseSourceTerm(stem)
306
426
  || wantToSourceTerm(stem)
427
+ || prepWhFrontedSourceTerm(stem)
428
+ || midSentenceWhAuxSourceTerm(stem)
429
+ || trailingClauseAfterPunctuationSourceTerm(stem)
430
+ || trailingBareWhSourceTerm(stem)
307
431
  );
308
432
  }
309
433
 
@@ -59,6 +59,7 @@ const isType = (p) => lower(p) === "rdf:type";
59
59
  const isDisjoint = (p) => lower(p) === "owl:disjointwith";
60
60
  const isOnProperty = (p) => lower(p) === "owl:onproperty";
61
61
  const isSomeValuesFrom = (p) => lower(p) === "owl:somevaluesfrom";
62
+ const isAllValuesFrom = (p) => lower(p) === "owl:allvaluesfrom";
62
63
  const isOnClass = (p) => lower(p) === "owl:onclass";
63
64
  const isIntersectionOf = (p) => lower(p) === "owl:intersectionof";
64
65
  const isSubPropertyOf = (p) => lower(p) === "rdfs:subpropertyof";
@@ -89,6 +90,7 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
89
90
  // value) so an axiom's `from` can cite the real stored fact id it rode. ----
90
91
  const onPropertyRow = new Map(); // restriction node -> its owl:onProperty row
91
92
  const someValuesFromRow = new Map(); // restriction node -> its owl:someValuesFrom row
93
+ const allValuesFromRow = new Map(); // restriction node -> its owl:allValuesFrom row
92
94
  const onClassRow = new Map(); // restriction node -> its owl:onClass row
93
95
  const cardinalityRow = new Map(); // restriction node -> its owl:{min,max,}cardinality row
94
96
  const intersectionRows = new Map(); // intersection node -> ordered [owl:intersectionOf row, …]
@@ -102,6 +104,10 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
102
104
  const p = r.predicate;
103
105
  if (isOnProperty(p)) { onPropertyRow.set(r.subject, r); addConcept(r.subject); }
104
106
  else if (isSomeValuesFrom(p)) { someValuesFromRow.set(r.subject, r); addConcept(r.subject); addConcept(r.object); }
107
+ // owl:allValuesFrom is left OUT of addConcept on purpose — EL has no
108
+ // universal restriction, and the restriction node it labels is stripped
109
+ // back out of `concepts` below rather than read as an atomic class.
110
+ else if (isAllValuesFrom(p)) { allValuesFromRow.set(r.subject, r); }
105
111
  else if (isOnClass(p)) { onClassRow.set(r.subject, r); addConcept(r.subject); addConcept(r.object); }
106
112
  else if (isCardinalityPredicate(p)) { cardinalityRow.set(r.subject, r); addConcept(r.subject); }
107
113
  else if (isIntersectionOf(p)) {
@@ -122,6 +128,15 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
122
128
  const someValuesFromRestrictions = new Set(
123
129
  [...onPropertyRow.keys()].filter((r) => someValuesFromRow.has(r)),
124
130
  );
131
+ // EL has no universal restriction: an owl:allValuesFrom restriction node is
132
+ // recognised only so the loop below can skip it rather than fold it in as
133
+ // an atomic concept — and it never earned a concepts entry through this
134
+ // set in the first place (onProperty's own addConcept still ran, so the
135
+ // restriction id is scrubbed back out here).
136
+ const allValuesFromRestrictions = new Set(
137
+ [...onPropertyRow.keys()].filter((r) => allValuesFromRow.has(r)),
138
+ );
139
+ for (const r of allValuesFromRestrictions) concepts.delete(r);
125
140
  const restrictionOf = new Map(); // restriction node -> { role, filler }
126
141
  for (const r of someValuesFromRestrictions) {
127
142
  restrictionOf.set(r, { role: onPropertyRow.get(r).object, filler: someValuesFromRow.get(r).object });
@@ -164,6 +179,7 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
164
179
  axioms.push({ form: "someLeft", role: "has", filler, sup: B, from: [opRow.id, ocRow.id, cardRow.id] });
165
180
  continue;
166
181
  }
182
+ if (allValuesFromRestrictions.has(B)) continue; // no EL universal restriction — skip, never guess an atomic concept
167
183
  axioms.push({ form: "sub", sub: A, sup: B, from: [r.id] });
168
184
  }
169
185
 
@@ -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);
@@ -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;