@polycode-projects/the-mechanical-code-talker 5.0.30 → 5.0.31

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.30",
3
+ "version": "5.0.31",
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.",
@@ -165,7 +165,8 @@ export async function normalizeConfig(raw, { configDir } = {}) {
165
165
  // PASS-THROUGH, same discipline as [games.*]/[research]/[recognition] —
166
166
  // the raw `[reasoning]` table (syllogise_budget/syllogise_depth/
167
167
  // classify_budget/classify_rounds/max_environments/prove_steps/
168
- // prove_branches/prove_nodes, snake_case) rides through unmodified;
168
+ // prove_branches/prove_nodes/ask_prove_fallback/ask_prove_steps/
169
+ // ask_prove_branches/ask_prove_nodes, snake_case) rides through unmodified;
169
170
  // mapping onto the internal camelCase shape and default-filling is
170
171
  // resolveReasoningConfig's job.
171
172
  if (src.reasoning !== undefined) cfg.reasoning = src.reasoning;
@@ -16,6 +16,13 @@ export const DEFAULT_REASONING_CONFIG = Object.freeze({
16
16
  proveSteps: 5000,
17
17
  proveBranches: 256,
18
18
  proveNodes: 512,
19
+ // The automatic /prove fallback's OWN, tighter budget — kept apart from
20
+ // prove_steps/branches/nodes above so raising the command's budget never
21
+ // slows every ordinary question that falls through to it on a miss.
22
+ askProveFallback: true,
23
+ askProveSteps: 1000,
24
+ askProveBranches: 64,
25
+ askProveNodes: 128,
19
26
  });
20
27
 
21
28
  // snake_case tmct.toml key -> camelCase internal key — mirrors game-config.mjs's own KEY_MAP tables.
@@ -28,6 +35,16 @@ const REASONING_KEY_MAP = Object.freeze({
28
35
  prove_steps: "proveSteps",
29
36
  prove_branches: "proveBranches",
30
37
  prove_nodes: "proveNodes",
38
+ ask_prove_steps: "askProveSteps",
39
+ ask_prove_branches: "askProveBranches",
40
+ ask_prove_nodes: "askProveNodes",
41
+ });
42
+
43
+ // The one boolean knob in this table — folded through clampBoolean, never
44
+ // clampPositiveInt, because clampPositiveInt rejects 0 and would silently
45
+ // restore the default the moment someone tried to set ask_prove_fallback = 0.
46
+ const REASONING_BOOLEAN_KEY_MAP = Object.freeze({
47
+ ask_prove_fallback: "askProveFallback",
31
48
  });
32
49
 
33
50
  /** A positive-integer knob, clamped to its shipped default when the raw value
@@ -38,6 +55,13 @@ function clampPositiveInt(raw, fallback) {
38
55
  return Number.isInteger(n) && n > 0 ? n : fallback;
39
56
  }
40
57
 
58
+ /** A boolean knob, clamped to its shipped default when the raw value isn't
59
+ * literally `true` or `false` — the same corrupt-value-degrades-to-default
60
+ * contract clampPositiveInt gives every numeric knob. */
61
+ function clampBoolean(raw, fallback) {
62
+ return typeof raw === "boolean" ? raw : fallback;
63
+ }
64
+
41
65
  /**
42
66
  * Fold a normalized tmct.toml's `reasoning` table (the raw sparse pass-through
43
67
  * src/adapters/toml-config.mjs's normalizeConfig produces — snake_case keys,
@@ -52,5 +76,8 @@ export function resolveReasoningConfig(toml) {
52
76
  for (const [tomlKey, camelKey] of Object.entries(REASONING_KEY_MAP)) {
53
77
  if (raw[tomlKey] !== undefined) out[camelKey] = clampPositiveInt(raw[tomlKey], DEFAULT_REASONING_CONFIG[camelKey]);
54
78
  }
79
+ for (const [tomlKey, camelKey] of Object.entries(REASONING_BOOLEAN_KEY_MAP)) {
80
+ if (raw[tomlKey] !== undefined) out[camelKey] = clampBoolean(raw[tomlKey], DEFAULT_REASONING_CONFIG[camelKey]);
81
+ }
55
82
  return out;
56
83
  }
@@ -132,6 +132,37 @@ function clampNonNegativeInt(value, fallback) {
132
132
 
133
133
  const CODE_REF_SHAPE = /[./\\#:@]/;
134
134
 
135
+ /** Which terms count as named individuals, widened past a bare type
136
+ * declaration: a term chained to an already TYPE-DECLARED individual by an
137
+ * asserted relation (a `candidateRows` row — the same predicate-outside-the-
138
+ * recognised-vocabulary test both buildTableauKb and extractTableauModule
139
+ * apply before calling this) is itself a named individual too, one hop at a
140
+ * time until nothing new is found. Without this, a chain of taught
141
+ * relations between DECLARED PROPER NAMES that are never separately typed
142
+ * ("GitHub is a module" types github; "GitHub contains GitLab; GitLab
143
+ * contains Polycode" never types gitlab or polycode at all) reads its first
144
+ * hop as an ABox edge and every later hop as a class-level relation between
145
+ * two unrecognised terms — silently dropping the very edges a role-
146
+ * hierarchy or transitive-role proof needs to walk. Seeded ONLY from
147
+ * `seedNames` (never from a CODE_REF_SHAPE match) so a code-reference-looking
148
+ * term related to an ordinary class never promotes that class to individual
149
+ * status by chaining — CODE_REF_SHAPE stays its own, separate per-term test
150
+ * at the `isIndividualTerm` call sites. Bounded by `candidateRows.length`
151
+ * passes, and `candidateRows` is always already module-extracted (small)
152
+ * rather than the raw store. Pure. */
153
+ function chainedIndividualTerms(seedNames, candidateRows) {
154
+ const names = new Set(seedNames);
155
+ let grew = true;
156
+ while (grew) {
157
+ grew = false;
158
+ for (const r of candidateRows) {
159
+ if (names.has(r.subject) && !names.has(r.object)) { names.add(r.object); grew = true; }
160
+ if (names.has(r.object) && !names.has(r.subject)) { names.add(r.subject); grew = true; }
161
+ }
162
+ }
163
+ return names;
164
+ }
165
+
135
166
  // ---- role hierarchy closure -------------------------------------------
136
167
 
137
168
  /** A memoized forward walk over `edges` ([[from, to], …]): returns a
@@ -165,24 +196,51 @@ function buildForwardWalk(edges) {
165
196
  * edges count as that role's own edges under `rdfs:subPropertyOf` —
166
197
  * every role at or below it in the hierarchy. `subPropertyEdges` is
167
198
  * `[[sub, sup], …]`. Precomputed once per KB, so a rule reading "does this
168
- * edge satisfy role X" is one Set lookup, not a walk. */
199
+ * edge satisfy role X" is one Set lookup, not a walk. Every role name is
200
+ * folded through `localRoleName` on the way in, so the closure is keyed and
201
+ * valued in one canonical form regardless of whether a caller's role names
202
+ * came from a term (already namespace-stripped, e.g. an owl:onProperty
203
+ * object) or from an edge's own literal predicate (an asserted role
204
+ * assertion's `r`, kept verbatim elsewhere for citation) — roleCountsAs
205
+ * folds an edge's role the same way before ever consulting this map. */
169
206
  function buildRoleClosure(subPropertyEdges, roleNames) {
170
- const subRolesOf = buildForwardWalk((subPropertyEdges || []).map(([sub, sup]) => [sup, sub]));
207
+ const edges = (subPropertyEdges || []).map(([sub, sup]) => [localRoleName(sub), localRoleName(sup)]);
208
+ const subRolesOf = buildForwardWalk(edges.map(([sub, sup]) => [sup, sub]));
171
209
  const closure = new Map();
172
- for (const role of roleNames) closure.set(role, new Set([role, ...subRolesOf(role)]));
210
+ for (const role of roleNames) {
211
+ const key = localRoleName(role);
212
+ closure.set(key, new Set([key, ...subRolesOf(key)]));
213
+ }
173
214
  return closure;
174
215
  }
175
216
 
217
+ /** An asserted ABox role edge's own `r` keeps its citation-facing spelling
218
+ * verbatim (kb.roleAssertions, so a rendered answer can quote the real
219
+ * predicate — "tmct:contains", not "contains"). Every role-AXIOM value
220
+ * (owl:onProperty's object, rdfs:subPropertyOf's and owl:inverseOf's
221
+ * subject/object, a transitive-property declaration's subject) is a TERM,
222
+ * and every writer already strips a term's CURIE namespace before storage
223
+ * (normFactTerm) — so the two spellings of the SAME role diverge unless
224
+ * role-hierarchy/transitivity/inverse matching folds an edge's role through
225
+ * the same normalization before comparing. */
226
+ const localRoleName = (role) => normFactTerm(role);
227
+
176
228
  /** Does an edge labelled `edgeRole` satisfy a rule asking for `role`? True
177
229
  * when they're the same role, or when `edgeRole` is a declared sub-role of
178
230
  * `role` under the KB's precomputed role closure. With no closure entry for
179
231
  * `role` (it never appeared in a stored `owl:onProperty` or
180
232
  * `rdfs:subPropertyOf` row), only an exact match counts — the same
181
- * behaviour every rule had before role hierarchies existed. */
233
+ * behaviour every rule had before role hierarchies existed. Both arguments
234
+ * are folded through `localRoleName` before comparing: `role` is usually
235
+ * already-normalized (threaded from an axiom's own `expr.r`, itself read
236
+ * from a stripped owl:onProperty object), but a hand-built KB with no
237
+ * restriction at all may pass an edge's own literal spelling on both sides. */
182
238
  function roleCountsAs(kb, edgeRole, role) {
183
- if (edgeRole === role) return true;
184
- const counted = kb && kb.roleClosure ? kb.roleClosure.get(role) : null;
185
- return counted ? counted.has(edgeRole) : false;
239
+ const normEdgeRole = localRoleName(edgeRole);
240
+ const normRole = localRoleName(role);
241
+ if (normEdgeRole === normRole) return true;
242
+ const counted = kb && kb.roleClosure ? kb.roleClosure.get(normRole) : null;
243
+ return counted ? counted.has(normEdgeRole) : false;
186
244
  }
187
245
 
188
246
  /** Every target a role-`role` edge from `nodeId` reaches, reading BOTH the
@@ -198,7 +256,7 @@ function roleEdgeTargets(branch, kb, nodeId, role) {
198
256
  if (e.from === nodeId && roleCountsAs(kb, e.r, role)) {
199
257
  targets.push({ to: e.to, fromFacts: e.fromFacts });
200
258
  } else if (e.to === nodeId) {
201
- const inv = kb && kb.inverseOf ? kb.inverseOf.get(e.r) : null;
259
+ const inv = kb && kb.inverseOf ? kb.inverseOf.get(localRoleName(e.r)) : null;
202
260
  if (inv && roleCountsAs(kb, inv, role)) targets.push({ to: e.from, fromFacts: e.fromFacts });
203
261
  }
204
262
  }
@@ -227,6 +285,11 @@ export const DEFAULT_MODULE_HOPS = 4;
227
285
  * size bound for termination, applied after sorting so truncation is
228
286
  * deterministic rather than arrival-ordered. */
229
287
  export const MAX_ROLE_ASSERTIONS = 256;
288
+ /** Caps how many distinct case-analysis disjuncts a proved verdict names —
289
+ * a rendered-sentence bound, not a search bound: a proof that split fifty
290
+ * ways should read as one sentence naming a count, never a paragraph.
291
+ * Applied after the sort, so truncation is deterministic. */
292
+ export const MAX_PROVEN_CASES = 6;
230
293
 
231
294
  // ---- identity: the UNA-lite merge machinery --------------------------------
232
295
  //
@@ -442,7 +505,10 @@ function cloneBranch(branch) {
442
505
  successorCount: node.successorCount,
443
506
  });
444
507
  }
445
- return { nodes, edges: branch.edges.slice(), closed: false, clash: null, inequalityFrom: new Map(branch.inequalityFrom) };
508
+ return {
509
+ nodes, edges: branch.edges.slice(), closed: false, clash: null,
510
+ inequalityFrom: new Map(branch.inequalityFrom), choices: (branch.choices || []).slice(),
511
+ };
446
512
  }
447
513
 
448
514
  // ---- the expansion rules, fixed priority -----------------------------
@@ -540,6 +606,33 @@ function wouldClashFrom(node, expr) {
540
606
  return other ? other.from : null;
541
607
  }
542
608
 
609
+ /** Is this disjunction a genuine case analysis — an owl:unionOf/owl:oneOf's
610
+ * own unwrapped `orE(members)` — rather than the ⊑-rule's routine TBox
611
+ * internalization (`mkAxiom`'s own `orE([notE(sub), sup])`, ALWAYS carrying
612
+ * a top-level negated member and firing on every axiom, union or not)? The
613
+ * two shapes are reliably told apart structurally, with no need to trace
614
+ * back to which fact row minted the axiom: a routine internalization's
615
+ * disjunct list always has at least one top-level `not`; a genuine
616
+ * union/oneOf split — reached only once its OWN wrapping internalization
617
+ * step has already fired and unwrapped it onto the node — never does. */
618
+ /** Is this disjunction a genuine case analysis — an owl:unionOf/owl:oneOf's
619
+ * own unwrapped `orE(members)` — rather than the ⊑-rule's routine TBox
620
+ * internalization (`mkAxiom`'s own `orE([notE(sub), sup])`, which fires on
621
+ * every axiom, union axioms included in BOTH directions, and is not a case
622
+ * analysis)? Two conditions together, since either alone has a false
623
+ * positive: `from` tracing to a real owl:unionOf/owl:oneOf fact id alone
624
+ * still matches the union axiom's OWN internalization step (same `from`,
625
+ * but a `¬union ∨ …`-shaped disjunct list); every member being a bare atom
626
+ * or nominal alone still matches an unrelated axiom's internalization
627
+ * after double-negation happens to cancel out a `not` tag. Together they
628
+ * land on exactly the moment a union/oneOf's own members reach a node
629
+ * unwrapped — the union's synthesized name has already been eliminated by
630
+ * then, kept only in `from`'s provenance, never as a disjunct. */
631
+ function isGenuineDisjunction(kb, cs, from) {
632
+ return from.some((id) => kb.unionOrOneOfIds && kb.unionOrOneOfIds.has(id))
633
+ && cs.every((c) => c.t === "atom" || c.t === "nom");
634
+ }
635
+
543
636
  /** The disjunctive rule. Non-branching shortcuts first (a disjunct already
544
637
  * present needs no branch; only one live disjunct needs no branch; zero
545
638
  * live disjuncts closes the branch outright) — each is sound, since the
@@ -547,8 +640,11 @@ function wouldClashFrom(node, expr) {
547
640
  * skip branches whose outcome is already decided. An eliminated disjunct's
548
641
  * own clash provenance carries forward into whatever survives it, so a
549
642
  * proof's premise set names the fact that ruled the alternative out, not
550
- * just the axiom that offered it. */
551
- function applyOrRule(branch) {
643
+ * just the axiom that offered it. A genuine (isGenuineDisjunction) firing
644
+ * also returns `choice: { cs, from }` — the full disjunct list offered,
645
+ * BEFORE elimination, so a proved conclusion can name every case it
646
+ * reasoned over, not just the one that survived. */
647
+ function applyOrRule(branch, kb) {
552
648
  for (const node of branch.nodes.values()) {
553
649
  for (const [key, { expr, from }] of sortedLabelEntries(node)) {
554
650
  if (expr.t !== "or") continue;
@@ -561,19 +657,21 @@ function applyOrRule(branch) {
561
657
  const evaluated = cs.map((c) => ({ c, clashFrom: wouldClashFrom(node, c) }));
562
658
  const survivors = evaluated.filter((e) => e.clashFrom === null).map((e) => e.c);
563
659
  const eliminatedFrom = evaluated.filter((e) => e.clashFrom !== null).flatMap((e) => e.clashFrom);
660
+ const choice = isGenuineDisjunction(kb, cs, from) ? { cs, from } : null;
564
661
  if (survivors.length === 0) {
565
662
  return {
566
663
  kind: "clash",
567
664
  clash: { nodeId: node.id, keyA: canonicalKey(cs[0]), keyB: canonicalKey(toNNF(notE(cs[0]))), premises: sortedUnique([...from, ...eliminatedFrom]) },
665
+ choice,
568
666
  };
569
667
  }
570
668
  if (survivors.length === 1) {
571
669
  node.branchedOn.add(key);
572
670
  addLabel(node, survivors[0], [...from, ...eliminatedFrom]);
573
- return { kind: "applied", touched: [node.id] };
671
+ return { kind: "applied", touched: [node.id], choice };
574
672
  }
575
673
  node.branchedOn.add(key);
576
- return { kind: "split", node, from, disjuncts: survivors };
674
+ return { kind: "split", node, from, disjuncts: survivors, choice };
577
675
  }
578
676
  }
579
677
  return { kind: "none" };
@@ -711,9 +809,15 @@ function stepOnce(branch, kb) {
711
809
  const tbox_ = applyTboxRule(branch, kb);
712
810
  if (tbox_.applied) return afterTouch(branch, tbox_.touched);
713
811
 
714
- const or_ = applyOrRule(branch);
812
+ const or_ = applyOrRule(branch, kb);
715
813
  if (or_.kind === "clash") return or_;
716
- if (or_.kind === "applied") return afterTouch(branch, or_.touched);
814
+ if (or_.kind === "applied") {
815
+ // A single-survivor elimination never clones — the SAME branch keeps
816
+ // running, so its own choice list is the one true record of every
817
+ // genuine case this branch's proof actually reasoned through.
818
+ if (or_.choice) branch.choices.push(or_.choice);
819
+ return afterTouch(branch, or_.touched);
820
+ }
717
821
  if (or_.kind === "split") return or_;
718
822
 
719
823
  const atMost_ = applyAtMostRule(branch, kb);
@@ -764,7 +868,12 @@ function search(initialBranch, kb, opts) {
764
868
  for (;;) {
765
869
  const result = stepOnce(branch, kb);
766
870
  if (result.kind === "clash") {
767
- closedClashes.push(result.clash);
871
+ // applyOrRule's own clash (every disjunct of a genuine union/oneOf
872
+ // split eliminated — the disjunction itself is what closes this
873
+ // branch) carries its own fresh choice on `result.choice`, on top
874
+ // of whatever this branch already accumulated from earlier firings.
875
+ const choices = result.choice ? [...branch.choices, result.choice] : branch.choices.slice();
876
+ closedClashes.push({ ...result.clash, choices });
768
877
  break;
769
878
  }
770
879
  if (result.kind === "applied") {
@@ -778,10 +887,11 @@ function search(initialBranch, kb, opts) {
778
887
  if (steps > maxSteps) return { status: "exhausted", reason: "steps", steps, branches: branchesOpened };
779
888
  const children = result.disjuncts.map((d) => {
780
889
  const clone = cloneBranch(branch);
890
+ if (result.choice) clone.choices.push(result.choice);
781
891
  const cnode = clone.nodes.get(result.node.id);
782
892
  addLabel(cnode, d, result.from);
783
893
  const clash = detectClash(cnode);
784
- if (clash) { clone.closed = true; clone.clash = clash; }
894
+ if (clash) { clone.closed = true; clone.clash = { ...clash, choices: clone.choices.slice() }; }
785
895
  return clone;
786
896
  });
787
897
  for (let i = children.length - 1; i >= 0; i -= 1) {
@@ -799,7 +909,7 @@ function search(initialBranch, kb, opts) {
799
909
  const keepId = mergeNodes(clone, kb, a, b);
800
910
  const keepNode = clone.nodes.get(keepId);
801
911
  const clash = keepNode && detectClash(keepNode);
802
- if (clash) { clone.closed = true; clone.clash = clash; }
912
+ if (clash) { clone.closed = true; clone.clash = { ...clash, choices: clone.choices.slice() }; }
803
913
  return clone;
804
914
  });
805
915
  for (let i = children.length - 1; i >= 0; i -= 1) {
@@ -855,7 +965,7 @@ function buildInitialBranch(kb, extraAssertions) {
855
965
  edges.push({ from: ra.a, r: ra.r, to: ra.b, fromFacts: ra.from.slice() });
856
966
  }
857
967
 
858
- return { nodes, edges, closed: false, clash: null, inequalityFrom };
968
+ return { nodes, edges, closed: false, clash: null, inequalityFrom, choices: [] };
859
969
  }
860
970
 
861
971
  /** Is the KB plus the given assertions satisfiable? `extraAssertions` is
@@ -870,7 +980,7 @@ export function isSatisfiable(kb, extraAssertions = [], opts = {}) {
870
980
  // not just the ones the search loop discovers along the way.
871
981
  for (const node of branch.nodes.values()) {
872
982
  const clash = detectClash(node);
873
- if (clash) { branch.closed = true; branch.clash = clash; break; }
983
+ if (clash) { branch.closed = true; branch.clash = { ...clash, choices: [] }; break; }
874
984
  }
875
985
  const result = search(branch, kb, opts);
876
986
  if (result.status === "exhausted") {
@@ -887,7 +997,22 @@ function proveByRefutation(kb, extraAssertions, opts) {
887
997
  if (result.satisfiable === null) return { status: "exhausted", reason: result.exhausted, steps: result.steps, branches: result.branches };
888
998
  if (result.satisfiable === false) {
889
999
  const premises = sortedUnique(result.closedClashes.flatMap((c) => c?.premises || []));
890
- return { status: "proved", premises, steps: result.steps, branches: result.branches };
1000
+ // The distinct case-analysis disjuncts every closed branch actually
1001
+ // reasoned over — the union node's own genuine split (isGenuineDisjunction),
1002
+ // never the ⊑-rule's routine internalization disjunction every proof
1003
+ // passes through regardless of a union/oneOf premise. Deduped by
1004
+ // canonicalKey (the SAME union offered on two different branches names
1005
+ // its cases once), sorted for determinism, capped for readability.
1006
+ const caseExprsByKey = new Map();
1007
+ for (const clash of result.closedClashes) {
1008
+ for (const choice of clash?.choices || []) {
1009
+ for (const expr of choice.cs) caseExprsByKey.set(canonicalKey(expr), expr);
1010
+ }
1011
+ }
1012
+ const sortedCaseKeys = [...caseExprsByKey.keys()].sort();
1013
+ const cases = sortedCaseKeys.slice(0, MAX_PROVEN_CASES).map((k) => caseExprsByKey.get(k));
1014
+ const casesTotal = sortedCaseKeys.length;
1015
+ return { status: "proved", premises, cases, casesTotal, steps: result.steps, branches: result.branches };
891
1016
  }
892
1017
  return { status: "disproved", model: result.model, steps: result.steps, branches: result.branches };
893
1018
  }
@@ -914,6 +1039,19 @@ export function proveSubsumption(kb, subClass, superClass, opts = {}) {
914
1039
  return proveByRefutation(kb, [{ ind: "fresh-0", expr: query, from: [] }], opts);
915
1040
  }
916
1041
 
1042
+ /** Class subsumption of a NEGATED superclass by refutation: does the KB
1043
+ * entail `subClass ⊑ ¬superClass`? Same fresh-individual technique as
1044
+ * proveSubsumption, asserting `subClass ⊓ superClass` (unsatisfiable ⟺ the
1045
+ * negation is entailed) rather than `subClass ⊓ ¬superClass`. The
1046
+ * class-level counterpart of calling proveEntailment with `notE(concept)`
1047
+ * directly — proveSubsumption's own signature takes a class name rather
1048
+ * than an arbitrary concept, so there is no concept argument to negate at
1049
+ * that call site. */
1050
+ export function proveSubsumptionOfNegation(kb, subClass, superClass, opts = {}) {
1051
+ const query = toNNF(andE([atom(subClass), atom(superClass)]));
1052
+ return proveByRefutation(kb, [{ ind: "fresh-0", expr: query, from: [] }], opts);
1053
+ }
1054
+
917
1055
  // ---- reading the store into a KB -------------------------------------------
918
1056
 
919
1057
  function describeClashKind(clash) {
@@ -996,7 +1134,8 @@ export function buildTableauKb(rows) {
996
1134
  const obj = String(r.object || "").toLowerCase();
997
1135
  if (!META_TYPE_OBJECTS.has(obj)) individualNamesFromType.add(r.subject);
998
1136
  }
999
- const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
1137
+ const individualNames = chainedIndividualTerms(individualNamesFromType, roleAssertionCandidates);
1138
+ const isIndividualTerm = (term) => individualNames.has(term) || CODE_REF_SHAPE.test(term);
1000
1139
 
1001
1140
  // An asserted role edge between two named individuals: any predicate
1002
1141
  // outside the recognised OWL/RDFS vocabulary, both of whose terms resolve
@@ -1131,9 +1270,19 @@ export function buildTableauKb(rows) {
1131
1270
  ])].sort();
1132
1271
  const namedIndividuals = new Set(individuals);
1133
1272
 
1273
+ // Every owl:unionOf/owl:oneOf row's own fact id — how applyOrRule tells a
1274
+ // genuine case-analysis disjunction (a union/oneOf's own unwrapped
1275
+ // members) from the ⊑-rule's routine TBox-internalization disjunction,
1276
+ // which every axiom (union axioms included, in BOTH directions) also
1277
+ // fires and which must never be read as a case split.
1278
+ const unionOrOneOfIds = new Set([
1279
+ ...[...unionMembersOf.values()].flatMap((rows) => rows.map((r) => r.id)),
1280
+ ...[...oneOfMembersOf.values()].flatMap((rows) => rows.map((r) => r.id)),
1281
+ ]);
1282
+
1134
1283
  return {
1135
1284
  axioms, assertions, roles: [...roles].sort(), individuals, transitiveRoles, roleClosure,
1136
- namedIndividuals, nominalIndividuals, differentFrom, inverseOf, roleAssertions,
1285
+ namedIndividuals, nominalIndividuals, differentFrom, inverseOf, roleAssertions, unionOrOneOfIds,
1137
1286
  };
1138
1287
  }
1139
1288
 
@@ -1150,6 +1299,7 @@ function restrictKbToIndividual(kb, ind) {
1150
1299
  nominalIndividuals: kb.nominalIndividuals,
1151
1300
  differentFrom: kb.differentFrom,
1152
1301
  inverseOf: kb.inverseOf,
1302
+ unionOrOneOfIds: kb.unionOrOneOfIds,
1153
1303
  };
1154
1304
  }
1155
1305
 
@@ -1220,7 +1370,9 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
1220
1370
  const obj = String(r.object || "").toLowerCase();
1221
1371
  if (!META_TYPE_OBJECTS.has(obj)) individualNamesFromType.add(r.subject);
1222
1372
  }
1223
- const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
1373
+ const roleAssertionCandidateRows = list.filter((r) => !RECOGNISED_KB_PREDICATES.has(String(r.predicate).trim().toLowerCase()));
1374
+ const individualNames = chainedIndividualTerms(individualNamesFromType, roleAssertionCandidateRows);
1375
+ const isIndividualTerm = (term) => individualNames.has(term) || CODE_REF_SHAPE.test(term);
1224
1376
 
1225
1377
  for (const r of list) {
1226
1378
  const p = String(r.predicate).trim().toLowerCase();
@@ -1237,9 +1389,19 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
1237
1389
  }
1238
1390
  }
1239
1391
 
1392
+ // Memoized by CONNECTED COMPONENT, not by term: subClassOf is followed as an
1393
+ // undirected edge here, so every term in one taxonomy component shares the
1394
+ // exact same reachable set. Caching a fresh Set per term (one BFS each) costs
1395
+ // O(component² ) Sets on a component of size V — a natural-language IsA graph
1396
+ // routinely converges on a few hub terms ("thing", "object"), so cache/its
1397
+ // ~9,700-term component alone once allocated ~9,700 separate ~9,700-entry
1398
+ // Sets. Populating the cache for every member of a freshly-computed Set with
1399
+ // that SAME Set reference makes every later call an O(1) hit instead of a
1400
+ // fresh O(V) BFS, so the whole extraction pays for the component once.
1240
1401
  const subClosureCache = new Map();
1241
1402
  function subClosure(term) {
1242
- if (subClosureCache.has(term)) return subClosureCache.get(term);
1403
+ const cached = subClosureCache.get(term);
1404
+ if (cached) return cached;
1243
1405
  const seen = new Set();
1244
1406
  const stack = [...(subUp.get(term) || []), ...(subDown.get(term) || [])];
1245
1407
  while (stack.length) {
@@ -1250,6 +1412,7 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
1250
1412
  for (const next of subDown.get(n) || []) if (!seen.has(next)) stack.push(next);
1251
1413
  }
1252
1414
  subClosureCache.set(term, seen);
1415
+ for (const member of seen) if (!subClosureCache.has(member)) subClosureCache.set(member, seen);
1253
1416
  return seen;
1254
1417
  }
1255
1418
 
@@ -1298,15 +1461,49 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
1298
1461
  for (const other of roleAssertionEndpoints.get(term) || []) enqueue(other, hopBudget);
1299
1462
  }
1300
1463
 
1464
+ // rolesUsed is compared below against a rdfs:subPropertyOf/owl:inverseOf/
1465
+ // transitive-property row's own SUBJECT — a term, already namespace-stripped
1466
+ // by every writer (normFactTerm) — so a role assertion's own predicate
1467
+ // (kept verbatim elsewhere for citation) is normalized the same way
1468
+ // buildTableauKb's own role-hierarchy matching is (see localRoleName there).
1301
1469
  const rolesUsed = new Set();
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);
1470
+ for (const [restriction, role] of onPropertyOf) if (included.has(restriction)) rolesUsed.add(localRoleName(role));
1471
+ for (const r of roleAssertionRows) if (included.has(r.subject) || included.has(r.object)) rolesUsed.add(localRoleName(r.predicate));
1304
1472
 
1305
1473
  return list.filter((r) => {
1306
1474
  if (included.has(r.subject) || included.has(r.object)) return true;
1307
1475
  const p = String(r.predicate).trim().toLowerCase();
1308
- if (p === "rdfs:subpropertyof" || p === "owl:inverseof") return rolesUsed.has(r.subject);
1309
- if (p === "rdf:type" && String(r.object).toLowerCase() === "transitiveproperty") return rolesUsed.has(r.subject);
1476
+ if (p === "rdfs:subpropertyof" || p === "owl:inverseof") return rolesUsed.has(localRoleName(r.subject));
1477
+ if (p === "rdf:type" && String(r.object).toLowerCase() === "transitiveproperty") return rolesUsed.has(localRoleName(r.subject));
1310
1478
  return false;
1311
1479
  });
1312
1480
  }
1481
+
1482
+ // The row shapes a plain subclass chase (the isa ladder, /classify,
1483
+ // /syllogise) never reads — moduleHasDlShape's own vocabulary, kept apart
1484
+ // from RECOGNISED_KB_PREDICATES above since that set also names shapes the
1485
+ // chases DO read (owl:onProperty, owl:someValuesFrom, owl:onClass,
1486
+ // rdfs:subClassOf, owl:disjointWith, rdf:type, mgxneg:subClassOf).
1487
+ const DL_SHAPE_PREDICATES = new Set([
1488
+ "owl:unionof", "owl:complementof", "owl:oneof", "owl:allvaluesfrom",
1489
+ "owl:mincardinality", "owl:maxcardinality", "owl:cardinality",
1490
+ "rdfs:subpropertyof", "owl:inverseof",
1491
+ ]);
1492
+
1493
+ /** Does this module hold any axiom shape the plain subclass chases cannot
1494
+ * read? True when some row's predicate is owl:unionOf, owl:complementOf,
1495
+ * owl:oneOf, owl:allValuesFrom, a cardinality predicate, or a role axiom
1496
+ * (rdfs:subPropertyOf, owl:inverseOf, or a `rdf:type
1497
+ * owl:TransitiveProperty` declaration). Without one of these the tableau
1498
+ * can only redo the subclass walk the chases just finished, so running it
1499
+ * would spend a budget to reach the same miss they already reached —
1500
+ * this is the gate that keeps chat's automatic /prove fallback off the
1501
+ * ordinary hot path. Pure, no I/O. */
1502
+ export function moduleHasDlShape(rows) {
1503
+ const list = Array.isArray(rows) ? rows : [];
1504
+ return list.some((r) => {
1505
+ const p = String(r?.predicate || "").trim().toLowerCase();
1506
+ if (DL_SHAPE_PREDICATES.has(p)) return true;
1507
+ return p === "rdf:type" && String(r?.object || "").toLowerCase() === "transitiveproperty";
1508
+ });
1509
+ }