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

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 (36) hide show
  1. package/README.md +74 -11
  2. package/bin/tmct.mjs +81 -0
  3. package/package.json +6 -1
  4. package/src/adapters/corpus/courtesy.mjs +91 -28
  5. package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
  6. package/src/adapters/corpus/news-sources.mjs +436 -0
  7. package/src/adapters/corpus/research-source.mjs +16 -3
  8. package/src/adapters/corpus/wiktionary-live.mjs +158 -0
  9. package/src/adapters/news-store.mjs +87 -0
  10. package/src/adapters/toml-config.mjs +18 -0
  11. package/src/domain/ask.mjs +19 -6
  12. package/src/domain/choice-question.mjs +275 -0
  13. package/src/domain/cli-verbs.mjs +20 -0
  14. package/src/domain/codegraph.mjs +8 -1
  15. package/src/domain/dialogue-acts.mjs +1 -0
  16. package/src/domain/el-classify.mjs +569 -0
  17. package/src/domain/fact-phrase.mjs +70 -0
  18. package/src/domain/feed-normalize.mjs +224 -0
  19. package/src/domain/grammar/ace.mjs +223 -7
  20. package/src/domain/grammar/lexicon-core.json +2 -0
  21. package/src/domain/memory/trust.mjs +15 -0
  22. package/src/domain/news-feed.mjs +219 -0
  23. package/src/domain/reasoning-config.mjs +56 -0
  24. package/src/domain/sprite-animation.mjs +20 -2
  25. package/src/domain/tableau.mjs +1225 -0
  26. package/src/domain/term-ledger.mjs +118 -0
  27. package/src/services/chat.mjs +523 -20
  28. package/src/services/extract-facts.mjs +91 -1
  29. package/src/services/index.mjs +12 -0
  30. package/src/services/init.mjs +33 -0
  31. package/src/services/news-viz.mjs +489 -0
  32. package/src/services/news.mjs +918 -0
  33. package/src/services/sprite-catalog-viz.mjs +148 -78
  34. package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
  35. package/src/surfaces/web/news-browser-entry.mjs +384 -0
  36. package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
@@ -0,0 +1,1225 @@
1
+ // tableau.mjs — a SHOIQ description-logic tableau prover: satisfiability,
2
+ // individual entailment, and class subsumption, over a KB read from the
3
+ // memory graph's stored OWL fragment. Query-time only, never materialised —
4
+ // a case-split conclusion depends on every branch of its proof, and batch
5
+ // provenance for that shape is a later problem.
6
+ //
7
+ // The letters, one increment each: ALC's core connectives (top, bottom,
8
+ // atomic negation, intersection, union, existential and universal
9
+ // restriction); S transitive roles (owl:TransitiveProperty propagates the
10
+ // universal rule through a role's own successors, and blocking runs as
11
+ // equality blocking throughout so that propagation still terminates); H
12
+ // role hierarchies (rdfs:subPropertyOf lets a narrower role's edge satisfy
13
+ // a wider one, read through a role closure precomputed once per KB); O
14
+ // nominals (owl:oneOf gives a singleton concept, and two nodes labelled the
15
+ // same nominal must be the same individual — the nominal-merge rule); Q
16
+ // qualified cardinality (owl:minCardinality/maxCardinality/cardinality with
17
+ // owl:onClass — the ≥-rule generates n pairwise-distinct successors, the
18
+ // ≤-rule merges surplus successors under the same identity side-condition
19
+ // the nominal merge uses); I inverse roles (owl:inverseOf lets every rule
20
+ // that reads a role edge read it backwards too, and upgrades blocking from
21
+ // equality to pairwise, per Horrocks & Sattler's SHOIQ decision procedure).
22
+ //
23
+ // UNA-lite (PLAN_SYLLOGIST_EL_DL.md section 4): a declared name is distinct
24
+ // from every other declared name unless owl:sameAs says otherwise. The
25
+ // tableau applies it at exactly two points: the merge rules' identity
26
+ // side-condition (the nominal merge, the ≤-rule's own successor merge) and
27
+ // ordinary clash detection. Attempting to merge two nodes UNA-lite forbids
28
+ // is itself a clash, not a step the search takes silently.
29
+ //
30
+ // Deterministic throughout: fixed rule-application priority, a fixed branch
31
+ // stack (LIFO, no JS-call recursion — a deep existential chain must not
32
+ // depend on the interpreter's own stack), sorted candidate lists everywhere
33
+ // a Map or Set is iterated, no wall clock. Feeding the same fact rows in two
34
+ // different orders yields a byte-identical KB and proof result.
35
+ //
36
+ // Budgets are part of the semantics, not a tuning knob: exceeding the step,
37
+ // branch or node ceiling aborts the WHOLE call with `exhausted`, never a
38
+ // partial verdict. A prover that runs out of budget has found nothing —
39
+ // abstention, not a guess.
40
+
41
+ import { normFactTerm } from "./hash.mjs";
42
+
43
+ // ---- concept-expression AST --------------------------------------------
44
+
45
+ const atom = (name) => ({ t: "atom", name });
46
+ const notE = (c) => ({ t: "not", c });
47
+ const andE = (cs) => ({ t: "and", cs });
48
+ const orE = (cs) => ({ t: "or", cs });
49
+ const someE = (r, c) => ({ t: "some", r, c });
50
+
51
+ /** A stable string key for a concept expression. Sorting, dedup and clash
52
+ * detection all go through this, so two structurally equal expressions are
53
+ * one key. Pure. */
54
+ export function canonicalKey(expr) {
55
+ if (!expr || typeof expr !== "object" || typeof expr.t !== "string") {
56
+ throw new TypeError("canonicalKey: expr must be a concept-expression object carrying a t tag");
57
+ }
58
+ switch (expr.t) {
59
+ case "top": return "top";
60
+ case "bot": return "bot";
61
+ case "atom": return `atom(${expr.name})`;
62
+ case "nom": return `nom(${expr.ind})`;
63
+ case "not": return `not(${canonicalKey(expr.c)})`;
64
+ case "and": return `and(${expr.cs.map(canonicalKey).sort().join(",")})`;
65
+ case "or": return `or(${expr.cs.map(canonicalKey).sort().join(",")})`;
66
+ case "some": return `some(${expr.r},${canonicalKey(expr.c)})`;
67
+ case "all": return `all(${expr.r},${canonicalKey(expr.c)})`;
68
+ case "atLeast": return `atLeast(${expr.n},${expr.r},${canonicalKey(expr.c)})`;
69
+ case "atMost": return `atMost(${expr.n},${expr.r},${canonicalKey(expr.c)})`;
70
+ default: throw new TypeError(`canonicalKey: unknown expression tag "${expr.t}"`);
71
+ }
72
+ }
73
+
74
+ function pushNegation(expr, negate) {
75
+ if (!expr || typeof expr !== "object" || typeof expr.t !== "string") {
76
+ throw new TypeError("toNNF: expr must be a concept-expression object carrying a t tag");
77
+ }
78
+ switch (expr.t) {
79
+ case "top": return negate ? { t: "bot" } : { t: "top" };
80
+ case "bot": return negate ? { t: "top" } : { t: "bot" };
81
+ case "atom": return negate ? { t: "not", c: { t: "atom", name: expr.name } } : { t: "atom", name: expr.name };
82
+ case "nom": return negate ? { t: "not", c: { t: "nom", ind: expr.ind } } : { t: "nom", ind: expr.ind };
83
+ case "not": return pushNegation(expr.c, !negate);
84
+ case "and":
85
+ case "or": {
86
+ const flip = expr.t === "and" ? "or" : "and";
87
+ const cs = expr.cs.map((c) => pushNegation(c, negate));
88
+ cs.sort((a, b) => canonicalKey(a).localeCompare(canonicalKey(b)));
89
+ return { t: negate ? flip : expr.t, cs };
90
+ }
91
+ case "some":
92
+ case "all": {
93
+ const flip = expr.t === "some" ? "all" : "some";
94
+ const c = pushNegation(expr.c, negate);
95
+ return { t: negate ? flip : expr.t, r: expr.r, c };
96
+ }
97
+ case "atLeast":
98
+ case "atMost": {
99
+ // The filler concept keeps its own polarity — only the cardinality
100
+ // connective and its threshold flip: ¬(≥n R.C) ≡ ≤(n−1) R.C,
101
+ // ¬(≤n R.C) ≡ ≥(n+1) R.C.
102
+ const c = pushNegation(expr.c, false);
103
+ if (!negate) return { t: expr.t, n: expr.n, r: expr.r, c };
104
+ return expr.t === "atLeast" ? { t: "atMost", n: expr.n - 1, r: expr.r, c } : { t: "atLeast", n: expr.n + 1, r: expr.r, c };
105
+ }
106
+ default: throw new TypeError(`toNNF: unknown expression tag "${expr.t}"`);
107
+ }
108
+ }
109
+
110
+ /** Negation normal form: push every ¬ inward to the atoms/nominals. Pure. */
111
+ export function toNNF(expr) {
112
+ return pushNegation(expr, false);
113
+ }
114
+
115
+ // ---- shared helpers ------------------------------------------------------
116
+
117
+ function sortedUnique(list) {
118
+ const set = new Set((Array.isArray(list) ? list : []).filter(Boolean));
119
+ return [...set].sort();
120
+ }
121
+
122
+ function clampPositiveInt(value, fallback) {
123
+ const n = Number(value);
124
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
125
+ }
126
+
127
+ function clampNonNegativeInt(value, fallback) {
128
+ const n = Number(value);
129
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
130
+ }
131
+
132
+ const CODE_REF_SHAPE = /[./\\#:@]/;
133
+
134
+ // ---- role hierarchy closure -------------------------------------------
135
+
136
+ /** A memoized forward walk over `edges` ([[from, to], …]): returns a
137
+ * function from a node to the full set of nodes reachable by following
138
+ * `edges`, transitively. One adjacency map built once, cached per query —
139
+ * the same shape syllogise.mjs's own buildAncestorCloser uses. */
140
+ function buildForwardWalk(edges) {
141
+ const succ = new Map();
142
+ for (const [a, b] of edges || []) {
143
+ if (!a || !b || a === b) continue;
144
+ if (!succ.has(a)) succ.set(a, new Set());
145
+ succ.get(a).add(b);
146
+ }
147
+ const cache = new Map();
148
+ return (start) => {
149
+ if (cache.has(start)) return cache.get(start);
150
+ const seen = new Set();
151
+ const stack = [...(succ.get(start) || [])];
152
+ while (stack.length) {
153
+ const n = stack.pop();
154
+ if (seen.has(n)) continue;
155
+ seen.add(n);
156
+ for (const next of succ.get(n) || []) if (!seen.has(next)) stack.push(next);
157
+ }
158
+ cache.set(start, seen);
159
+ return seen;
160
+ };
161
+ }
162
+
163
+ /** For every role in `roleNames`, the set of roles (including itself) whose
164
+ * edges count as that role's own edges under `rdfs:subPropertyOf` —
165
+ * every role at or below it in the hierarchy. `subPropertyEdges` is
166
+ * `[[sub, sup], …]`. Precomputed once per KB, so a rule reading "does this
167
+ * edge satisfy role X" is one Set lookup, not a walk. */
168
+ function buildRoleClosure(subPropertyEdges, roleNames) {
169
+ const subRolesOf = buildForwardWalk((subPropertyEdges || []).map(([sub, sup]) => [sup, sub]));
170
+ const closure = new Map();
171
+ for (const role of roleNames) closure.set(role, new Set([role, ...subRolesOf(role)]));
172
+ return closure;
173
+ }
174
+
175
+ /** Does an edge labelled `edgeRole` satisfy a rule asking for `role`? True
176
+ * when they're the same role, or when `edgeRole` is a declared sub-role of
177
+ * `role` under the KB's precomputed role closure. With no closure entry for
178
+ * `role` (it never appeared in a stored `owl:onProperty` or
179
+ * `rdfs:subPropertyOf` row), only an exact match counts — the same
180
+ * behaviour every rule had before role hierarchies existed. */
181
+ function roleCountsAs(kb, edgeRole, role) {
182
+ if (edgeRole === role) return true;
183
+ const counted = kb && kb.roleClosure ? kb.roleClosure.get(role) : null;
184
+ return counted ? counted.has(edgeRole) : false;
185
+ }
186
+
187
+ /** Every target a role-`role` edge from `nodeId` reaches, reading BOTH the
188
+ * forward direction (an outgoing edge whose own role counts as `role`) and,
189
+ * when the KB declares an inverse for an edge's role, the reverse direction
190
+ * (an INCOMING edge whose role's registered inverse counts as `role`) —
191
+ * the ∃/∀/≥/≤ rules all read role edges through this one function, so
192
+ * every one of them is inverse-aware for free. With no inverses declared
193
+ * this reduces to the plain forward walk every rule had before. */
194
+ function roleEdgeTargets(branch, kb, nodeId, role) {
195
+ const targets = [];
196
+ for (const e of branch.edges) {
197
+ if (e.from === nodeId && roleCountsAs(kb, e.r, role)) {
198
+ targets.push({ to: e.to, fromFacts: e.fromFacts });
199
+ } else if (e.to === nodeId) {
200
+ const inv = kb && kb.inverseOf ? kb.inverseOf.get(e.r) : null;
201
+ if (inv && roleCountsAs(kb, inv, role)) targets.push({ to: e.from, fromFacts: e.fromFacts });
202
+ }
203
+ }
204
+ return targets;
205
+ }
206
+
207
+ // Meta-vocabulary objects a `rdf:type` row can carry that describe the
208
+ // tableau's OWN scaffolding (a restriction node, a role's transitivity tag,
209
+ // a class-expression node's own type tag) rather than an ABox assertion
210
+ // about a real individual. Every writer strips the CURIE prefix before
211
+ // storage, so these are the post-normalization local names.
212
+ const META_TYPE_OBJECTS = new Set(["restriction", "transitiveproperty", "class"]);
213
+
214
+ // ---- tri-state budgets ----------------------------------------------------
215
+
216
+ export const DEFAULT_PROVE_STEPS = 5000;
217
+ export const DEFAULT_PROVE_BRANCHES = 256;
218
+ export const DEFAULT_PROVE_NODES = 512;
219
+ /** Same sub-1 discount as CAX_DW_RULE_CONFIDENCE in syllogise.mjs, same
220
+ * reason: a case-split conclusion never outranks its weakest premise. Not
221
+ * used inside this module — trust computation needs premise trusts this
222
+ * module never sees, so the caller pairs this with entailedTrustFrom. */
223
+ export const TABLEAU_RULE_CONFIDENCE = 0.95;
224
+ export const DEFAULT_MODULE_HOPS = 4;
225
+
226
+ // ---- identity: the UNA-lite merge machinery --------------------------------
227
+ //
228
+ // One general-purpose merge, built here for the ≤-rule's surplus-successor
229
+ // merge and reused as-is once the nominal-merge rule lands. The identity
230
+ // side-condition is the same wherever a merge is attempted: never merge two
231
+ // nodes that carry distinct declared individual names, and never merge two
232
+ // nodes an inequality already separates — attempting either is itself a
233
+ // clash (section 8.3), not a step the search takes silently.
234
+
235
+ // A synthetic successor id always ends in ".<positive integer>" (the ∃/≥
236
+ // rules mint `${parent.id}.${count}`) — the one shape a real declared name
237
+ // never takes in this corpus (a code-ref name ends in an extension or a
238
+ // symbol, never a bare digit run).
239
+ const SYNTHETIC_SUCCESSOR_SUFFIX = /\.\d+$/;
240
+
241
+ /** Is `id` a name UNA-lite treats as a distinct declared individual? A
242
+ * subsumption proof's own fresh individual ("fresh-0", and anything it
243
+ * generates) is explicitly excluded — it is an arbitrary hypothetical
244
+ * instance, never a declared name. */
245
+ function isNamedForUnaLite(kb, id) {
246
+ if (id === "fresh-0") return false;
247
+ if (kb && kb.namedIndividuals && kb.namedIndividuals.has(id)) return true;
248
+ return !SYNTHETIC_SUCCESSOR_SUFFIX.test(id);
249
+ }
250
+
251
+ function pairKey(a, b) {
252
+ return a < b ? `${a}␟${b}` : `${b}␟${a}`;
253
+ }
254
+
255
+ function markDistinct(branch, a, b, from) {
256
+ if (a === b) return;
257
+ const key = pairKey(a, b);
258
+ const existing = branch.inequalityFrom.get(key);
259
+ branch.inequalityFrom.set(key, existing ? sortedUnique([...existing, ...from]) : sortedUnique(from));
260
+ }
261
+
262
+ /** May `a` and `b` never be merged? Either both are UNA-lite-distinct
263
+ * declared names, or the branch already carries an explicit inequality
264
+ * between them (from a stored owl:differentFrom row, or from the ≥-rule's
265
+ * own pairwise-distinct successor bookkeeping). */
266
+ function isMergeBlocked(branch, kb, a, b) {
267
+ if (a === b) return false;
268
+ if (isNamedForUnaLite(kb, a) && isNamedForUnaLite(kb, b)) return true;
269
+ return branch.inequalityFrom.has(pairKey(a, b));
270
+ }
271
+
272
+ /** The stored reason `a` and `b` are inequal, if any — empty when the block
273
+ * came purely from both being distinct declared names (a UNA-lite policy
274
+ * fact, not a stored one). */
275
+ function mergeBlockPremises(branch, a, b) {
276
+ const stored = branch.inequalityFrom.get(pairKey(a, b));
277
+ return stored ? stored.slice() : [];
278
+ }
279
+
280
+ function pickMergeSurvivor(kb, aId, bId) {
281
+ const aNamed = isNamedForUnaLite(kb, aId);
282
+ const bNamed = isNamedForUnaLite(kb, bId);
283
+ if (aNamed && !bNamed) return [aId, bId];
284
+ if (bNamed && !aNamed) return [bId, aId];
285
+ return aId < bId ? [aId, bId] : [bId, aId];
286
+ }
287
+
288
+ /** Merge two nodes in place: the survivor (a named individual if either
289
+ * side is one, else the lexicographically first id) absorbs the other's
290
+ * labels, edges redirect and de-dup, any inequality pair naming the
291
+ * removed node remaps onto the survivor, and any other node's parent
292
+ * pointer follows too. Returns the surviving node's id. Never called on a
293
+ * blocked pair — the caller checks isMergeBlocked first. */
294
+ function mergeNodes(branch, kb, aId, bId) {
295
+ if (aId === bId) return aId;
296
+ const [keepId, removeId] = pickMergeSurvivor(kb, aId, bId);
297
+ const keep = branch.nodes.get(keepId);
298
+ const remove = branch.nodes.get(removeId);
299
+ if (!keep || !remove) return keepId;
300
+
301
+ for (const [key, { expr, from }] of remove.labels) {
302
+ const existing = keep.labels.get(key);
303
+ keep.labels.set(key, { expr, from: existing ? sortedUnique([...existing.from, ...from]) : from.slice() });
304
+ }
305
+
306
+ const redirected = [];
307
+ const seenEdges = new Map();
308
+ for (const e of branch.edges) {
309
+ const from = e.from === removeId ? keepId : e.from;
310
+ const to = e.to === removeId ? keepId : e.to;
311
+ const dedupeKey = `${from}␟${e.r}␟${to}`;
312
+ const already = seenEdges.get(dedupeKey);
313
+ if (already) already.fromFacts = sortedUnique([...already.fromFacts, ...e.fromFacts]);
314
+ else {
315
+ const merged = { from, r: e.r, to, fromFacts: e.fromFacts.slice() };
316
+ seenEdges.set(dedupeKey, merged);
317
+ redirected.push(merged);
318
+ }
319
+ }
320
+ branch.edges = redirected;
321
+
322
+ for (const node of branch.nodes.values()) {
323
+ if (node.parent === removeId) node.parent = keepId;
324
+ }
325
+
326
+ const remapped = new Map();
327
+ for (const [rawKey, from] of branch.inequalityFrom) {
328
+ const [x, y] = rawKey.split("␟");
329
+ const nx = x === removeId ? keepId : x;
330
+ const ny = y === removeId ? keepId : y;
331
+ if (nx === ny) continue;
332
+ const newKey = pairKey(nx, ny);
333
+ const already = remapped.get(newKey);
334
+ remapped.set(newKey, already ? sortedUnique([...already, ...from]) : from);
335
+ }
336
+ branch.inequalityFrom = remapped;
337
+
338
+ branch.nodes.delete(removeId);
339
+ return keepId;
340
+ }
341
+
342
+ // ---- nodes, edges, branches ------------------------------------------------
343
+
344
+ function makeNode(id, parent) {
345
+ return {
346
+ id,
347
+ labels: new Map(), // canonicalKey -> { expr, from: string[] }
348
+ parent: parent ?? null,
349
+ branchedOn: new Set(), // or-label keys already resolved in this branch
350
+ appliedAxioms: new Set(), // TBox axiom indices already internalized on this node
351
+ successorCount: 0,
352
+ };
353
+ }
354
+
355
+ function addLabel(node, expr, from) {
356
+ const key = canonicalKey(expr);
357
+ if (node.labels.has(key)) return false;
358
+ node.labels.set(key, { expr, from: sortedUnique(from) });
359
+ return true;
360
+ }
361
+
362
+ function sortedLabelEntries(node) {
363
+ return [...node.labels.entries()].sort((a, b) => a[0].localeCompare(b[0]));
364
+ }
365
+
366
+ /** A node clashes when its label set holds bottom, or holds both an
367
+ * expression and that expression's NNF negation. Returns the first clash
368
+ * found in sorted-key order (deterministic), or null. */
369
+ function detectClash(node) {
370
+ if (node.labels.has("bot")) {
371
+ return { nodeId: node.id, keyA: "bot", keyB: "bot", premises: node.labels.get("bot").from.slice() };
372
+ }
373
+ const keys = [...node.labels.keys()].sort();
374
+ for (const key of keys) {
375
+ const { expr, from } = node.labels.get(key);
376
+ const compKey = canonicalKey(toNNF(notE(expr)));
377
+ if (compKey <= key) continue; // each unordered pair is reported once, from its smaller key
378
+ const other = node.labels.get(compKey);
379
+ if (other) return { nodeId: node.id, keyA: key, keyB: compKey, premises: sortedUnique([...from, ...other.from]) };
380
+ }
381
+ return null;
382
+ }
383
+
384
+ /** The set of role labels on edges INTO `nodeId` — what pairwise blocking
385
+ * (below) compares between a candidate and its ancestor once inverse roles
386
+ * exist. */
387
+ function predecessorRoleLabels(branch, nodeId) {
388
+ const set = new Set();
389
+ for (const e of branch.edges) if (e.to === nodeId) set.add(e.r);
390
+ return set;
391
+ }
392
+
393
+ // Equality blocking: a node is blocked only by an ancestor whose label set is
394
+ // exactly the same, not merely a superset. Subset blocking is sound and
395
+ // complete for plain ALC, but a transitive role's ∀-rule copies a universal
396
+ // label onto every successor down the transitive chain (below), and subset
397
+ // blocking can stop that copy one step early, before the copied universal
398
+ // has actually produced the same consequences the blocking ancestor already
399
+ // carries. Equality blocking is the standard SHIQ-family fix, adopted here
400
+ // once transitive roles exist rather than only when a KB happens to declare
401
+ // one, so the same blocking rule runs every time.
402
+ //
403
+ // Pairwise blocking (Horrocks & Sattler): once inverse roles let a rule read
404
+ // an edge backwards, a candidate and its blocking ancestor must also match
405
+ // on the ROLE LABELS of their own incoming edges, not just their concept
406
+ // labels — otherwise a node whose real predecessor differs from its
407
+ // ancestor's could silently inherit the wrong incoming-edge behaviour. Only
408
+ // checked when the KB actually declares an inverse; with none declared this
409
+ // is byte-identical to plain equality blocking.
410
+ function isBlocked(node, branch, kb) {
411
+ const keys = [...node.labels.keys()];
412
+ const pairwise = !!(kb && kb.inverseOf && kb.inverseOf.size > 0);
413
+ const nodePred = pairwise ? predecessorRoleLabels(branch, node.id) : null;
414
+ let ancestorId = node.parent;
415
+ while (ancestorId) {
416
+ const ancestor = branch.nodes.get(ancestorId);
417
+ if (!ancestor) break;
418
+ if (keys.length === ancestor.labels.size && keys.every((k) => ancestor.labels.has(k))) {
419
+ if (!pairwise) return true;
420
+ const ancestorPred = predecessorRoleLabels(branch, ancestor.id);
421
+ if (nodePred.size === ancestorPred.size && [...nodePred].every((r) => ancestorPred.has(r))) return true;
422
+ }
423
+ ancestorId = ancestor.parent;
424
+ }
425
+ return false;
426
+ }
427
+
428
+ function cloneBranch(branch) {
429
+ const nodes = new Map();
430
+ for (const [id, node] of branch.nodes) {
431
+ nodes.set(id, {
432
+ id: node.id,
433
+ labels: new Map(node.labels),
434
+ parent: node.parent,
435
+ branchedOn: new Set(node.branchedOn),
436
+ appliedAxioms: new Set(node.appliedAxioms),
437
+ successorCount: node.successorCount,
438
+ });
439
+ }
440
+ return { nodes, edges: branch.edges.slice(), closed: false, clash: null, inequalityFrom: new Map(branch.inequalityFrom) };
441
+ }
442
+
443
+ // ---- the expansion rules, fixed priority -----------------------------
444
+
445
+ function applyAndRule(branch) {
446
+ for (const node of branch.nodes.values()) {
447
+ for (const [, { expr, from }] of sortedLabelEntries(node)) {
448
+ if (expr.t !== "and") continue;
449
+ let changed = false;
450
+ for (const c of expr.cs) if (addLabel(node, c, from)) changed = true;
451
+ if (changed) return { applied: true, touched: [node.id] };
452
+ }
453
+ }
454
+ return { applied: false, touched: [] };
455
+ }
456
+
457
+ /** Two nodes labelled with the SAME nominal must be the same individual —
458
+ * there is no alternative to branch over, so this is a deterministic
459
+ * action, unlike the ≤-rule's choice of which pair to merge. Picks the
460
+ * first (sorted) nominal key that has 2+ carriers and the first (sorted)
461
+ * pair among them, so the result is the same regardless of iteration
462
+ * order. */
463
+ function applyNominalMergeRule(branch, kb) {
464
+ const byNom = new Map();
465
+ for (const node of branch.nodes.values()) {
466
+ for (const key of node.labels.keys()) {
467
+ if (!key.startsWith("nom(")) continue;
468
+ if (!byNom.has(key)) byNom.set(key, []);
469
+ byNom.get(key).push(node.id);
470
+ }
471
+ }
472
+ const keys = [...byNom.keys()].sort();
473
+ for (const key of keys) {
474
+ const ids = [...new Set(byNom.get(key))].sort();
475
+ if (ids.length < 2) continue;
476
+ const [a, b] = ids;
477
+ if (isMergeBlocked(branch, kb, a, b)) {
478
+ const fromA = branch.nodes.get(a).labels.get(key)?.from || [];
479
+ const fromB = branch.nodes.get(b).labels.get(key)?.from || [];
480
+ return {
481
+ kind: "clash",
482
+ clash: { nodeId: a, keyA: key, keyB: `merge(${a},${b})`, premises: sortedUnique([...fromA, ...fromB, ...mergeBlockPremises(branch, a, b)]) },
483
+ };
484
+ }
485
+ return { kind: "merge", a, b };
486
+ }
487
+ return { kind: "none" };
488
+ }
489
+
490
+ /** The universal rule. For a transitive role, an r-successor also receives
491
+ * the universal label itself, not just its filler — that is what lets
492
+ * ∀r.C reach an r-successor's own r-successor with no separate rule: the
493
+ * copied label fires this same rule again, one hop further, the next time
494
+ * the search loop revisits it. Reads role edges through roleEdgeTargets,
495
+ * so a declared inverse lets an incoming edge satisfy the universal too. */
496
+ function applyAllRule(branch, kb) {
497
+ const transitiveRoles = kb && kb.transitiveRoles instanceof Set ? kb.transitiveRoles : null;
498
+ for (const node of branch.nodes.values()) {
499
+ for (const [, { expr, from }] of sortedLabelEntries(node)) {
500
+ if (expr.t !== "all") continue;
501
+ const touched = [];
502
+ for (const { to, fromFacts } of roleEdgeTargets(branch, kb, node.id, expr.r)) {
503
+ const succ = branch.nodes.get(to);
504
+ if (!succ) continue;
505
+ const succFrom = [...from, ...fromFacts];
506
+ if (addLabel(succ, expr.c, succFrom)) touched.push(succ.id);
507
+ if (transitiveRoles && transitiveRoles.has(expr.r) && addLabel(succ, expr, succFrom)) touched.push(succ.id);
508
+ }
509
+ if (touched.length) return { applied: true, touched };
510
+ }
511
+ }
512
+ return { applied: false, touched: [] };
513
+ }
514
+
515
+ function applyTboxRule(branch, kb) {
516
+ for (const node of branch.nodes.values()) {
517
+ for (let i = 0; i < kb.axioms.length; i += 1) {
518
+ if (node.appliedAxioms.has(i)) continue;
519
+ const axiom = kb.axioms[i];
520
+ node.appliedAxioms.add(i);
521
+ if (addLabel(node, axiom.disjunction, axiom.from)) return { applied: true, touched: [node.id] };
522
+ }
523
+ }
524
+ return { applied: false, touched: [] };
525
+ }
526
+
527
+ /** null when `expr` would NOT immediately clash on `node`; otherwise the
528
+ * `from` provenance of whatever already-present label makes it clash — the
529
+ * reason a disjunct got eliminated, which the survivor(s) it leaves behind
530
+ * must carry forward as part of their own justification. */
531
+ function wouldClashFrom(node, expr) {
532
+ if (canonicalKey(expr) === "bot") return [];
533
+ const compKey = canonicalKey(toNNF(notE(expr)));
534
+ const other = node.labels.get(compKey);
535
+ return other ? other.from : null;
536
+ }
537
+
538
+ /** The disjunctive rule. Non-branching shortcuts first (a disjunct already
539
+ * present needs no branch; only one live disjunct needs no branch; zero
540
+ * live disjuncts closes the branch outright) — each is sound, since the
541
+ * branching case below always explores every disjunct anyway, these just
542
+ * skip branches whose outcome is already decided. An eliminated disjunct's
543
+ * own clash provenance carries forward into whatever survives it, so a
544
+ * proof's premise set names the fact that ruled the alternative out, not
545
+ * just the axiom that offered it. */
546
+ function applyOrRule(branch) {
547
+ for (const node of branch.nodes.values()) {
548
+ for (const [key, { expr, from }] of sortedLabelEntries(node)) {
549
+ if (expr.t !== "or") continue;
550
+ if (node.branchedOn.has(key)) continue;
551
+ const cs = [...expr.cs].sort((a, b) => canonicalKey(a).localeCompare(canonicalKey(b)));
552
+ if (cs.some((c) => node.labels.has(canonicalKey(c)))) {
553
+ node.branchedOn.add(key);
554
+ continue;
555
+ }
556
+ const evaluated = cs.map((c) => ({ c, clashFrom: wouldClashFrom(node, c) }));
557
+ const survivors = evaluated.filter((e) => e.clashFrom === null).map((e) => e.c);
558
+ const eliminatedFrom = evaluated.filter((e) => e.clashFrom !== null).flatMap((e) => e.clashFrom);
559
+ if (survivors.length === 0) {
560
+ return {
561
+ kind: "clash",
562
+ clash: { nodeId: node.id, keyA: canonicalKey(cs[0]), keyB: canonicalKey(toNNF(notE(cs[0]))), premises: sortedUnique([...from, ...eliminatedFrom]) },
563
+ };
564
+ }
565
+ if (survivors.length === 1) {
566
+ node.branchedOn.add(key);
567
+ addLabel(node, survivors[0], [...from, ...eliminatedFrom]);
568
+ return { kind: "applied", touched: [node.id] };
569
+ }
570
+ node.branchedOn.add(key);
571
+ return { kind: "split", node, from, disjuncts: survivors };
572
+ }
573
+ }
574
+ return { kind: "none" };
575
+ }
576
+
577
+ function applySomeRule(branch, kb) {
578
+ for (const node of branch.nodes.values()) {
579
+ if (isBlocked(node, branch, kb)) continue; // generating rule — blocked nodes create no successors
580
+ for (const [, { expr, from }] of sortedLabelEntries(node)) {
581
+ if (expr.t !== "some") continue;
582
+ const cKey = canonicalKey(expr.c);
583
+ const hasWitness = roleEdgeTargets(branch, kb, node.id, expr.r).some((t) => branch.nodes.get(t.to)?.labels.has(cKey));
584
+ if (hasWitness) continue;
585
+ node.successorCount += 1;
586
+ const child = makeNode(`${node.id}.${node.successorCount}`, node.id);
587
+ addLabel(child, expr.c, from);
588
+ branch.nodes.set(child.id, child);
589
+ branch.edges.push({ from: node.id, r: expr.r, to: child.id, fromFacts: from.slice() });
590
+ return { applied: true, touched: [child.id] };
591
+ }
592
+ }
593
+ return { applied: false, touched: [] };
594
+ }
595
+
596
+ /** The ≤-rule. When a node's r/C-witnesses (read inverse-aware, through
597
+ * roleEdgeTargets) outnumber the cardinality's threshold, some pair must
598
+ * merge. A surplus with fewer than 2 witnesses to pair (n=0 with exactly
599
+ * one witness) can never be brought down by merging at all — an
600
+ * unconditional clash, citing the witness's own filler-label premises too,
601
+ * so it names both restrictions. Otherwise, every pair blocked by the
602
+ * UNA-lite identity side-condition is a direct clash (both the
603
+ * cardinality's own premises and the blocking inequality's — the E5
604
+ * shape); with at least one mergeable pair, branches over each, in a fixed
605
+ * pair order, exactly like the ⊔-rule's own disjunct branching. */
606
+ function applyAtMostRule(branch, kb) {
607
+ for (const node of branch.nodes.values()) {
608
+ for (const [key, { expr, from }] of sortedLabelEntries(node)) {
609
+ if (expr.t !== "atMost") continue;
610
+ const cKey = canonicalKey(expr.c);
611
+ const witnesses = [...new Set(roleEdgeTargets(branch, kb, node.id, expr.r).map((t) => t.to))]
612
+ .filter((id) => branch.nodes.get(id)?.labels.has(cKey))
613
+ .sort();
614
+ if (witnesses.length <= expr.n) continue;
615
+ const pairs = [];
616
+ for (let i = 0; i < witnesses.length; i += 1) {
617
+ for (let j = i + 1; j < witnesses.length; j += 1) pairs.push([witnesses[i], witnesses[j]]);
618
+ }
619
+ if (pairs.length === 0) {
620
+ const witnessFrom = branch.nodes.get(witnesses[0])?.labels.get(cKey)?.from || [];
621
+ return {
622
+ kind: "clash",
623
+ clash: { nodeId: node.id, keyA: key, keyB: `witness(${witnesses[0]})`, premises: sortedUnique([...from, ...witnessFrom]) },
624
+ };
625
+ }
626
+ const mergeable = pairs.filter(([a, b]) => !isMergeBlocked(branch, kb, a, b));
627
+ if (mergeable.length === 0) {
628
+ const [a, b] = pairs[0];
629
+ return {
630
+ kind: "clash",
631
+ clash: { nodeId: node.id, keyA: key, keyB: `merge(${a},${b})`, premises: sortedUnique([...from, ...mergeBlockPremises(branch, a, b)]) },
632
+ };
633
+ }
634
+ return { kind: "split-merge", pairs: mergeable };
635
+ }
636
+ }
637
+ return { kind: "none" };
638
+ }
639
+
640
+ /** The ≥-rule. A generating rule — never fires on a blocked node, and
641
+ * (like the ∃-rule) creates exactly ONE fresh successor per invocation, so
642
+ * the step budget scales with n rather than a whole restriction landing in
643
+ * a single step. The search loop re-invokes it until the node's r/C-
644
+ * witnesses (read inverse-aware, through roleEdgeTargets) reach the
645
+ * threshold. Each fresh successor is marked pairwise-distinct from every
646
+ * witness that already existed when it was created — that is what a ≥n
647
+ * restriction actually means (n DISTINCT fillers), and
648
+ * it is the bookkeeping the ≤-rule's identity side-condition later reads. */
649
+ function applyAtLeastRule(branch, kb) {
650
+ for (const node of branch.nodes.values()) {
651
+ if (isBlocked(node, branch, kb)) continue;
652
+ for (const [, { expr, from }] of sortedLabelEntries(node)) {
653
+ if (expr.t !== "atLeast") continue;
654
+ const cKey = canonicalKey(expr.c);
655
+ const existing = [...new Set(roleEdgeTargets(branch, kb, node.id, expr.r).map((t) => t.to))]
656
+ .filter((id) => branch.nodes.get(id)?.labels.has(cKey))
657
+ .sort();
658
+ if (existing.length >= expr.n) continue;
659
+ node.successorCount += 1;
660
+ const child = makeNode(`${node.id}.${node.successorCount}`, node.id);
661
+ addLabel(child, expr.c, from);
662
+ branch.nodes.set(child.id, child);
663
+ branch.edges.push({ from: node.id, r: expr.r, to: child.id, fromFacts: from.slice() });
664
+ for (const otherId of existing) markDistinct(branch, child.id, otherId, from);
665
+ return { applied: true, touched: [child.id] };
666
+ }
667
+ }
668
+ return { applied: false, touched: [] };
669
+ }
670
+
671
+ function checkTouched(branch, touched) {
672
+ for (const id of touched) {
673
+ const node = branch.nodes.get(id);
674
+ const clash = node && detectClash(node);
675
+ if (clash) return clash;
676
+ }
677
+ return null;
678
+ }
679
+
680
+ function afterTouch(branch, touched) {
681
+ const clash = checkTouched(branch, touched);
682
+ return clash ? { kind: "clash", clash } : { kind: "applied" };
683
+ }
684
+
685
+ /** Apply the first rule (in fixed priority order) that has any applicable
686
+ * instance, and report what happened. Never recurses — each call performs
687
+ * exactly one rule application (or one branch-point discovery); the caller
688
+ * loops. Order: deterministic non-generating rules first (⊓, ∀, ⊑), then
689
+ * the non-deterministic ⊔ and ≤ (each a genuine choice among several sound
690
+ * continuations), then the two generating rules last (≥, ∃) so a model
691
+ * grows only once nothing smaller finishes it. */
692
+ function stepOnce(branch, kb) {
693
+ const and_ = applyAndRule(branch);
694
+ if (and_.applied) return afterTouch(branch, and_.touched);
695
+
696
+ const all_ = applyAllRule(branch, kb);
697
+ if (all_.applied) return afterTouch(branch, all_.touched);
698
+
699
+ const nomMerge_ = applyNominalMergeRule(branch, kb);
700
+ if (nomMerge_.kind === "clash") return nomMerge_;
701
+ if (nomMerge_.kind === "merge") {
702
+ const keepId = mergeNodes(branch, kb, nomMerge_.a, nomMerge_.b);
703
+ return afterTouch(branch, [keepId]);
704
+ }
705
+
706
+ const tbox_ = applyTboxRule(branch, kb);
707
+ if (tbox_.applied) return afterTouch(branch, tbox_.touched);
708
+
709
+ const or_ = applyOrRule(branch);
710
+ if (or_.kind === "clash") return or_;
711
+ if (or_.kind === "applied") return afterTouch(branch, or_.touched);
712
+ if (or_.kind === "split") return or_;
713
+
714
+ const atMost_ = applyAtMostRule(branch, kb);
715
+ if (atMost_.kind === "clash") return atMost_;
716
+ if (atMost_.kind === "split-merge") return atMost_;
717
+
718
+ const atLeast_ = applyAtLeastRule(branch, kb);
719
+ if (atLeast_.applied) return afterTouch(branch, atLeast_.touched);
720
+
721
+ const some_ = applySomeRule(branch, kb);
722
+ if (some_.applied) return afterTouch(branch, some_.touched);
723
+
724
+ return { kind: "done" };
725
+ }
726
+
727
+ // ---- the branch-stack search driver ---------------------------------------
728
+
729
+ function serializeBranch(branch) {
730
+ const nodes = [...branch.nodes.values()]
731
+ .map((node) => ({
732
+ id: node.id,
733
+ parent: node.parent,
734
+ labels: [...node.labels.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([, { expr, from }]) => ({ expr, from })),
735
+ }));
736
+ const edges = branch.edges.map(({ from, r, to, fromFacts }) => ({ from, r, to, fromFacts: fromFacts.slice() }));
737
+ return { nodes, edges };
738
+ }
739
+
740
+ /** Runs the explicit branch stack to either exhaustion (every branch
741
+ * closed — the KB is unsatisfiable), a found model (one branch complete
742
+ * and clash-free), or a budget breach. No recursion: branching pushes
743
+ * clones onto `stack`, an ordinary array used as a LIFO. */
744
+ function search(initialBranch, kb, opts) {
745
+ const maxSteps = clampPositiveInt(opts.maxSteps, DEFAULT_PROVE_STEPS);
746
+ const maxBranches = clampPositiveInt(opts.maxBranches, DEFAULT_PROVE_BRANCHES);
747
+ const maxNodes = clampPositiveInt(opts.maxNodes, DEFAULT_PROVE_NODES);
748
+
749
+ const stack = [initialBranch];
750
+ let steps = 0;
751
+ let branchesOpened = 1;
752
+ const closedClashes = [];
753
+
754
+ while (stack.length) {
755
+ const branch = stack.pop();
756
+ if (branch.closed) { closedClashes.push(branch.clash); continue; }
757
+ if (branch.nodes.size > maxNodes) return { status: "exhausted", reason: "nodes", steps, branches: branchesOpened };
758
+
759
+ for (;;) {
760
+ const result = stepOnce(branch, kb);
761
+ if (result.kind === "clash") {
762
+ closedClashes.push(result.clash);
763
+ break;
764
+ }
765
+ if (result.kind === "applied") {
766
+ steps += 1;
767
+ if (steps > maxSteps) return { status: "exhausted", reason: "steps", steps, branches: branchesOpened };
768
+ if (branch.nodes.size > maxNodes) return { status: "exhausted", reason: "nodes", steps, branches: branchesOpened };
769
+ continue;
770
+ }
771
+ if (result.kind === "split") {
772
+ steps += 1;
773
+ if (steps > maxSteps) return { status: "exhausted", reason: "steps", steps, branches: branchesOpened };
774
+ const children = result.disjuncts.map((d) => {
775
+ const clone = cloneBranch(branch);
776
+ const cnode = clone.nodes.get(result.node.id);
777
+ addLabel(cnode, d, result.from);
778
+ const clash = detectClash(cnode);
779
+ if (clash) { clone.closed = true; clone.clash = clash; }
780
+ return clone;
781
+ });
782
+ for (let i = children.length - 1; i >= 0; i -= 1) {
783
+ branchesOpened += 1;
784
+ if (branchesOpened > maxBranches) return { status: "exhausted", reason: "branches", steps, branches: branchesOpened };
785
+ stack.push(children[i]);
786
+ }
787
+ break;
788
+ }
789
+ if (result.kind === "split-merge") {
790
+ steps += 1;
791
+ if (steps > maxSteps) return { status: "exhausted", reason: "steps", steps, branches: branchesOpened };
792
+ const children = result.pairs.map(([a, b]) => {
793
+ const clone = cloneBranch(branch);
794
+ const keepId = mergeNodes(clone, kb, a, b);
795
+ const keepNode = clone.nodes.get(keepId);
796
+ const clash = keepNode && detectClash(keepNode);
797
+ if (clash) { clone.closed = true; clone.clash = clash; }
798
+ return clone;
799
+ });
800
+ for (let i = children.length - 1; i >= 0; i -= 1) {
801
+ branchesOpened += 1;
802
+ if (branchesOpened > maxBranches) return { status: "exhausted", reason: "branches", steps, branches: branchesOpened };
803
+ stack.push(children[i]);
804
+ }
805
+ break;
806
+ }
807
+ return { status: "satisfiable", model: serializeBranch(branch), steps, branches: branchesOpened };
808
+ }
809
+ if (branchesOpened > maxBranches) return { status: "exhausted", reason: "branches", steps, branches: branchesOpened };
810
+ }
811
+ return { status: "unsatisfiable", clashes: closedClashes, steps, branches: branchesOpened };
812
+ }
813
+
814
+ function buildInitialBranch(kb, extraAssertions) {
815
+ const nodes = new Map();
816
+ const ensureNode = (id) => {
817
+ if (!nodes.has(id)) nodes.set(id, makeNode(id, null));
818
+ return nodes.get(id);
819
+ };
820
+ for (const ind of kb.individuals || []) ensureNode(ind);
821
+ for (const a of kb.assertions || []) addLabel(ensureNode(a.ind), a.expr, a.from);
822
+ for (const extra of extraAssertions || []) {
823
+ if (!extra || !extra.ind || !extra.expr) continue;
824
+ addLabel(ensureNode(extra.ind), toNNF(extra.expr), extra.from || []);
825
+ }
826
+ // Every nominal individual is trivially a member of its own singleton —
827
+ // seed that self-label now, so the nominal-merge rule has something to
828
+ // find the first time another node gets forced into the same nominal.
829
+ for (const [ind, from] of kb.nominalIndividuals || []) {
830
+ addLabel(ensureNode(ind), { t: "nom", ind }, from);
831
+ }
832
+
833
+ const inequalityFrom = new Map();
834
+ for (const pair of kb.differentFrom || []) {
835
+ if (!pair || !pair.a || !pair.b || pair.a === pair.b) continue;
836
+ const key = pairKey(pair.a, pair.b);
837
+ const existing = inequalityFrom.get(key);
838
+ inequalityFrom.set(key, existing ? sortedUnique([...existing, ...pair.from]) : sortedUnique(pair.from));
839
+ }
840
+
841
+ return { nodes, edges: [], closed: false, clash: null, inequalityFrom };
842
+ }
843
+
844
+ /** Is the KB plus the given assertions satisfiable? `extraAssertions` is
845
+ * `[{ ind, expr, from }, …]`; `ind` need not already be a KB individual — a
846
+ * proof query mints its own node (see proveEntailment/proveSubsumption).
847
+ * Pure, no I/O. */
848
+ export function isSatisfiable(kb, extraAssertions = [], opts = {}) {
849
+ const branch = buildInitialBranch(kb, extraAssertions);
850
+ // The base assertions alone (with no rule fired yet) can already clash —
851
+ // e.g. two directly-stated complementary types on one individual — so the
852
+ // initial branch needs the same clash check every rule application gets,
853
+ // not just the ones the search loop discovers along the way.
854
+ for (const node of branch.nodes.values()) {
855
+ const clash = detectClash(node);
856
+ if (clash) { branch.closed = true; branch.clash = clash; break; }
857
+ }
858
+ const result = search(branch, kb, opts);
859
+ if (result.status === "exhausted") {
860
+ return { satisfiable: null, exhausted: result.reason, steps: result.steps, branches: result.branches };
861
+ }
862
+ if (result.status === "satisfiable") {
863
+ return { satisfiable: true, model: result.model, steps: result.steps, branches: result.branches };
864
+ }
865
+ return { satisfiable: false, closedClashes: result.clashes, steps: result.steps, branches: result.branches };
866
+ }
867
+
868
+ function proveByRefutation(kb, extraAssertions, opts) {
869
+ const result = isSatisfiable(kb, extraAssertions, opts);
870
+ if (result.satisfiable === null) return { status: "exhausted", reason: result.exhausted, steps: result.steps, branches: result.branches };
871
+ if (result.satisfiable === false) {
872
+ const premises = sortedUnique(result.closedClashes.flatMap((c) => c?.premises || []));
873
+ return { status: "proved", premises, steps: result.steps, branches: result.branches };
874
+ }
875
+ return { status: "disproved", model: result.model, steps: result.steps, branches: result.branches };
876
+ }
877
+
878
+ /** Entailment by refutation: does the KB entail `subject : concept`,
879
+ * `subject` a named individual? Asserts NNF(¬concept) on the subject and
880
+ * checks satisfiability. Every branch closed → proved. An open branch →
881
+ * disproved, with the branch as a counter-model. Any budget hit →
882
+ * exhausted, never a verdict. */
883
+ export function proveEntailment(kb, subject, concept, opts = {}) {
884
+ return proveByRefutation(kb, [{ ind: subject, expr: toNNF(notE(concept)), from: [] }], opts);
885
+ }
886
+
887
+ /** Class subsumption by refutation: does the KB entail `subClass ⊑
888
+ * superClass`? Mints one fresh individual, named "fresh-0", that touches
889
+ * nothing else in the KB — a subsumption proof owns its own namespace,
890
+ * disjoint from every real successor buildTableauKb or the ∃-rule could
891
+ * ever name — asserts `subClass ⊓ ¬superClass` on it, and checks
892
+ * satisfiability exactly as proveEntailment does. Same tri-state result.
893
+ * The fresh individual never touches kb.individuals and never appears in a
894
+ * rendered answer. */
895
+ export function proveSubsumption(kb, subClass, superClass, opts = {}) {
896
+ const query = toNNF(andE([atom(subClass), notE(atom(superClass))]));
897
+ return proveByRefutation(kb, [{ ind: "fresh-0", expr: query, from: [] }], opts);
898
+ }
899
+
900
+ // ---- reading the store into a KB -------------------------------------------
901
+
902
+ function describeClashKind(clash) {
903
+ if (!clash) return "unsatisfiable";
904
+ if (clash.keyA === "bot") return "bottom";
905
+ return `complement:${clash.keyA}~${clash.keyB}`;
906
+ }
907
+
908
+ /** Build the tableau knowledge base from a row set — on a real question,
909
+ * the output of extractTableauModule, never the raw store. Pure. Returns
910
+ * { axioms, assertions, roles, individuals, transitiveRoles, roleClosure,
911
+ * namedIndividuals, nominalIndividuals, differentFrom, inverseOf }. */
912
+ export function buildTableauKb(rows) {
913
+ const list = Array.isArray(rows) ? rows.filter((r) => r && r.subject && r.predicate) : [];
914
+
915
+ const onPropertyOf = new Map(); // restriction -> { object, id }
916
+ const someValuesFromOf = new Map();
917
+ const onClassOf = new Map();
918
+ const cardinalityOf = new Map(); // restriction -> { kind, n, id }
919
+ const unionMembersOf = new Map(); // union node -> [row, …]
920
+ const complementOf = new Map(); // complement node -> row
921
+ const oneOfMembersOf = new Map(); // enumerated class -> [row, …]
922
+ const subClassRows = [];
923
+ const disjointRows = [];
924
+ const typeRows = [];
925
+ const negTypeRows = [];
926
+ const transitiveRoles = new Set();
927
+ const subPropertyRows = [];
928
+ const differentFromRows = [];
929
+ const inverseOfRows = [];
930
+
931
+ const pushMap = (map, key, value) => {
932
+ if (!map.has(key)) map.set(key, []);
933
+ map.get(key).push(value);
934
+ };
935
+
936
+ for (const r of list) {
937
+ const p = String(r.predicate).trim().toLowerCase();
938
+ if (p === "owl:onproperty") onPropertyOf.set(r.subject, { object: r.object, id: r.id });
939
+ else if (p === "owl:somevaluesfrom") someValuesFromOf.set(r.subject, { object: r.object, id: r.id });
940
+ else if (p === "owl:onclass") onClassOf.set(r.subject, { object: r.object, id: r.id });
941
+ else if (p === "owl:mincardinality") cardinalityOf.set(r.subject, { kind: "min", n: Number(r.object), id: r.id });
942
+ else if (p === "owl:maxcardinality") cardinalityOf.set(r.subject, { kind: "max", n: Number(r.object), id: r.id });
943
+ else if (p === "owl:cardinality") cardinalityOf.set(r.subject, { kind: "exact", n: Number(r.object), id: r.id });
944
+ else if (p === "rdfs:subclassof") subClassRows.push(r);
945
+ else if (p === "owl:disjointwith") disjointRows.push(r);
946
+ else if (p === "rdf:type") {
947
+ typeRows.push(r);
948
+ if (String(r.object || "").toLowerCase() === "transitiveproperty") transitiveRoles.add(r.subject);
949
+ }
950
+ else if (p === "mgxneg:subclassof") negTypeRows.push(r);
951
+ else if (p === "owl:unionof") pushMap(unionMembersOf, r.subject, r);
952
+ else if (p === "owl:complementof") complementOf.set(r.subject, r);
953
+ else if (p === "rdfs:subpropertyof") subPropertyRows.push(r);
954
+ else if (p === "owl:differentfrom") differentFromRows.push(r);
955
+ else if (p === "owl:oneof") pushMap(oneOfMembersOf, r.subject, r);
956
+ else if (p === "owl:inverseof") inverseOfRows.push(r);
957
+ }
958
+
959
+ const individualNamesFromType = new Set();
960
+ for (const r of typeRows) {
961
+ const obj = String(r.object || "").toLowerCase();
962
+ if (!META_TYPE_OBJECTS.has(obj)) individualNamesFromType.add(r.subject);
963
+ }
964
+ const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
965
+
966
+ const mkAxiom = (sub, sup, from) => ({ sub, sup, from: sortedUnique(from), disjunction: toNNF(orE([notE(sub), sup])) });
967
+
968
+ const axioms = [];
969
+ const assertions = [];
970
+
971
+ for (const r of subClassRows) {
972
+ const restriction = r.object;
973
+ if (!onPropertyOf.has(restriction)) {
974
+ axioms.push(mkAxiom(atom(r.subject), atom(restriction), [r.id]));
975
+ continue;
976
+ }
977
+ const propRow = onPropertyOf.get(restriction);
978
+ const svfRow = someValuesFromOf.get(restriction);
979
+ if (svfRow) {
980
+ axioms.push(mkAxiom(atom(r.subject), someE(propRow.object, atom(svfRow.object)), [r.id, propRow.id, svfRow.id]));
981
+ continue;
982
+ }
983
+ const cardRow = cardinalityOf.get(restriction);
984
+ const onClassRow = onClassOf.get(restriction);
985
+ if (cardRow && onClassRow) {
986
+ const cardIds = [r.id, propRow.id, onClassRow.id, cardRow.id];
987
+ if (cardRow.kind === "min") {
988
+ axioms.push(mkAxiom(atom(r.subject), { t: "atLeast", n: cardRow.n, r: propRow.object, c: atom(onClassRow.object) }, cardIds));
989
+ } else if (cardRow.kind === "max") {
990
+ axioms.push(mkAxiom(atom(r.subject), { t: "atMost", n: cardRow.n, r: propRow.object, c: atom(onClassRow.object) }, cardIds));
991
+ } else if (cardRow.kind === "exact") {
992
+ axioms.push(mkAxiom(atom(r.subject), { t: "atLeast", n: cardRow.n, r: propRow.object, c: atom(onClassRow.object) }, cardIds));
993
+ axioms.push(mkAxiom(atom(r.subject), { t: "atMost", n: cardRow.n, r: propRow.object, c: atom(onClassRow.object) }, cardIds));
994
+ }
995
+ }
996
+ // An unqualified restriction (no owl:onClass) isn't representable as a
997
+ // qualified-cardinality axiom yet — skipped, not guessed at.
998
+ }
999
+
1000
+ for (const r of disjointRows) {
1001
+ if (isIndividualTerm(r.subject)) assertions.push({ ind: r.subject, expr: toNNF(notE(atom(r.object))), from: [r.id] });
1002
+ else axioms.push(mkAxiom(atom(r.subject), toNNF(notE(atom(r.object))), [r.id]));
1003
+ }
1004
+
1005
+ for (const r of typeRows) {
1006
+ if (META_TYPE_OBJECTS.has(String(r.object || "").toLowerCase())) continue; // scaffolding, not an ABox fact
1007
+ assertions.push({ ind: r.subject, expr: atom(r.object), from: [r.id] });
1008
+ }
1009
+
1010
+ for (const r of negTypeRows) assertions.push({ ind: r.subject, expr: toNNF(notE(atom(r.object))), from: [r.id] });
1011
+
1012
+ for (const [unionId, memberRows] of unionMembersOf) {
1013
+ const sorted = [...memberRows].sort((a, b) => String(a.object).localeCompare(String(b.object)));
1014
+ const cs = sorted.map((mr) => atom(mr.object));
1015
+ const ids = sorted.map((mr) => mr.id);
1016
+ const orExpr = toNNF(orE(cs));
1017
+ axioms.push(mkAxiom(atom(unionId), orExpr, ids));
1018
+ axioms.push(mkAxiom(orExpr, atom(unionId), ids));
1019
+ }
1020
+
1021
+ for (const [complementId, r] of complementOf) {
1022
+ const notAtom = toNNF(notE(atom(r.object)));
1023
+ axioms.push(mkAxiom(atom(complementId), notAtom, [r.id]));
1024
+ axioms.push(mkAxiom(notAtom, atom(complementId), [r.id]));
1025
+ }
1026
+
1027
+ // owl:oneOf: the enumerated class is subsumed by the union of its members'
1028
+ // singleton (nominal) concepts, and each member's singleton is in turn
1029
+ // subsumed by the enumerated class — a closed class, per section 8.6.
1030
+ // Every member also gets its own self-label ({ind} ⊑ {ind}, trivially
1031
+ // true) seeded at branch-init time (buildInitialBranch), so the nominal-
1032
+ // merge rule has a real carrier of the nominal to merge an outsider into.
1033
+ const nominalIndividuals = new Map(); // ind -> fact ids that declared it
1034
+ for (const [classId, memberRows] of oneOfMembersOf) {
1035
+ const sorted = [...memberRows].sort((a, b) => String(a.object).localeCompare(String(b.object)));
1036
+ const nomExprs = sorted.map((mr) => ({ t: "nom", ind: mr.object }));
1037
+ const ids = sorted.map((mr) => mr.id);
1038
+ axioms.push(mkAxiom(atom(classId), toNNF(orE(nomExprs)), ids));
1039
+ for (const mr of sorted) {
1040
+ axioms.push(mkAxiom({ t: "nom", ind: mr.object }, atom(classId), [mr.id]));
1041
+ const existing = nominalIndividuals.get(mr.object);
1042
+ nominalIndividuals.set(mr.object, existing ? sortedUnique([...existing, mr.id]) : [mr.id]);
1043
+ }
1044
+ }
1045
+
1046
+ const differentFrom = differentFromRows
1047
+ .map((r) => ({ a: r.subject, b: r.object, from: [r.id] }))
1048
+ .sort((a, b) => a.a.localeCompare(b.a) || a.b.localeCompare(b.b));
1049
+
1050
+ // owl:inverseOf is stored symmetrically by the grammar (both directions
1051
+ // minted), but this reads either direction alone too, defensively.
1052
+ const inverseOf = new Map();
1053
+ for (const r of inverseOfRows) {
1054
+ inverseOf.set(r.subject, r.object);
1055
+ if (!inverseOf.has(r.object)) inverseOf.set(r.object, r.subject);
1056
+ }
1057
+
1058
+ const roles = new Set();
1059
+ for (const { object } of onPropertyOf.values()) roles.add(object);
1060
+
1061
+ const subPropertyEdges = subPropertyRows
1062
+ .map((r) => [r.subject, r.object])
1063
+ .sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1]));
1064
+ const roleNames = new Set([...roles, ...subPropertyEdges.flat(), ...inverseOf.keys(), ...inverseOf.values()]);
1065
+ const roleClosure = buildRoleClosure(subPropertyEdges, roleNames);
1066
+
1067
+ axioms.sort((a, b) =>
1068
+ canonicalKey(a.sub).localeCompare(canonicalKey(b.sub)) ||
1069
+ canonicalKey(a.sup).localeCompare(canonicalKey(b.sup)) ||
1070
+ a.from.join(",").localeCompare(b.from.join(",")));
1071
+ assertions.sort((a, b) => a.ind.localeCompare(b.ind) || canonicalKey(a.expr).localeCompare(canonicalKey(b.expr)));
1072
+
1073
+ const individuals = [...new Set(assertions.map((a) => a.ind))].sort();
1074
+ const namedIndividuals = new Set(individuals);
1075
+
1076
+ return {
1077
+ axioms, assertions, roles: [...roles].sort(), individuals, transitiveRoles, roleClosure,
1078
+ namedIndividuals, nominalIndividuals, differentFrom, inverseOf,
1079
+ };
1080
+ }
1081
+
1082
+ function restrictKbToIndividual(kb, ind) {
1083
+ return {
1084
+ axioms: kb.axioms,
1085
+ assertions: (kb.assertions || []).filter((a) => a.ind === ind),
1086
+ roles: kb.roles,
1087
+ individuals: [ind],
1088
+ transitiveRoles: kb.transitiveRoles,
1089
+ roleClosure: kb.roleClosure,
1090
+ namedIndividuals: kb.namedIndividuals,
1091
+ nominalIndividuals: kb.nominalIndividuals,
1092
+ differentFrom: kb.differentFrom,
1093
+ inverseOf: kb.inverseOf,
1094
+ };
1095
+ }
1096
+
1097
+ /** Every clash the KB produces on its own, with both premises named. Pure.
1098
+ * `subjects` defaults to every individual the KB asserts something about.
1099
+ * A subject whose own check exhausts its budget is omitted, never reported
1100
+ * as clean — a partial check must never look like a clean bill. */
1101
+ export function findTableauViolations(kb, subjects = null, opts = {}) {
1102
+ const list = [...new Set(Array.isArray(subjects) && subjects.length ? subjects : kb.individuals || [])].sort();
1103
+ const violations = [];
1104
+ for (const subject of list) {
1105
+ const restricted = restrictKbToIndividual(kb, subject);
1106
+ if (!restricted.assertions.length) continue;
1107
+ const result = isSatisfiable(restricted, [], opts);
1108
+ if (result.satisfiable === null || result.satisfiable === true) continue;
1109
+ const premises = sortedUnique(result.closedClashes.flatMap((c) => c?.premises || []));
1110
+ violations.push({ subject, premises, kind: describeClashKind(result.closedClashes[0]) });
1111
+ }
1112
+ violations.sort((a, b) => a.subject.localeCompare(b.subject));
1113
+ return violations;
1114
+ }
1115
+
1116
+ // ---- KB module extraction ---------------------------------------------------
1117
+
1118
+ function addToSetMap(map, key, value) {
1119
+ if (!map.has(key)) map.set(key, new Set());
1120
+ map.get(key).add(value);
1121
+ }
1122
+
1123
+ /** Restrict fact rows to the signature-connected module around a set of
1124
+ * seed terms. `rdfs:subClassOf` closes unbounded in both directions (it is
1125
+ * 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. */
1135
+ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HOPS } = {}) {
1136
+ const list = Array.isArray(rows) ? rows.filter((r) => r && r.subject && r.predicate) : [];
1137
+ const hopBudget = clampNonNegativeInt(hops, DEFAULT_MODULE_HOPS);
1138
+
1139
+ const subUp = new Map();
1140
+ const subDown = new Map();
1141
+ const onPropertyOf = new Map(); // restriction -> role
1142
+ const fillerOf = new Map(); // restriction -> filler term
1143
+ const fillerBack = new Map(); // filler term -> Set(restriction)
1144
+ const unionMembers = new Map();
1145
+ const memberUnions = new Map();
1146
+ const complementPair = new Map();
1147
+ const memberComplements = new Map();
1148
+ const oneOfMembers = new Map();
1149
+ const memberOneOf = new Map();
1150
+
1151
+ for (const r of list) {
1152
+ const p = String(r.predicate).trim().toLowerCase();
1153
+ if (p === "rdfs:subclassof") { addToSetMap(subUp, r.subject, r.object); addToSetMap(subDown, r.object, r.subject); }
1154
+ 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); }
1156
+ else if (p === "owl:unionof") { addToSetMap(unionMembers, r.subject, r.object); addToSetMap(memberUnions, r.object, r.subject); }
1157
+ else if (p === "owl:complementof") { complementPair.set(r.subject, r.object); addToSetMap(memberComplements, r.object, r.subject); }
1158
+ else if (p === "owl:oneof") { addToSetMap(oneOfMembers, r.subject, r.object); addToSetMap(memberOneOf, r.object, r.subject); }
1159
+ }
1160
+
1161
+ const subClosureCache = new Map();
1162
+ function subClosure(term) {
1163
+ if (subClosureCache.has(term)) return subClosureCache.get(term);
1164
+ const seen = new Set();
1165
+ const stack = [...(subUp.get(term) || []), ...(subDown.get(term) || [])];
1166
+ while (stack.length) {
1167
+ const n = stack.pop();
1168
+ if (seen.has(n)) continue;
1169
+ seen.add(n);
1170
+ for (const next of subUp.get(n) || []) if (!seen.has(next)) stack.push(next);
1171
+ for (const next of subDown.get(n) || []) if (!seen.has(next)) stack.push(next);
1172
+ }
1173
+ subClosureCache.set(term, seen);
1174
+ return seen;
1175
+ }
1176
+
1177
+ const included = new Set();
1178
+ const bestHopsLeft = new Map();
1179
+ const queue = [];
1180
+ function enqueue(term, hopsLeft) {
1181
+ if (!term) return;
1182
+ const prior = bestHopsLeft.get(term);
1183
+ if (prior !== undefined && prior >= hopsLeft) return;
1184
+ bestHopsLeft.set(term, hopsLeft);
1185
+ queue.push({ term, hopsLeft });
1186
+ }
1187
+
1188
+ const seeds = [...new Set((Array.isArray(seedTerms) ? seedTerms : []).map((t) => normFactTerm(t)).filter(Boolean))];
1189
+ for (const s of seeds) enqueue(s, hopBudget);
1190
+
1191
+ let cursor = 0;
1192
+ while (cursor < queue.length) {
1193
+ const { term, hopsLeft } = queue[cursor];
1194
+ cursor += 1;
1195
+ if (bestHopsLeft.get(term) !== hopsLeft) continue; // a better visit already superseded this one
1196
+
1197
+ included.add(term);
1198
+ for (const s of subClosure(term)) {
1199
+ included.add(s);
1200
+ enqueue(s, hopsLeft); // unbounded — free, no hop cost, no reseed
1201
+ }
1202
+ if (hopsLeft <= 0) continue;
1203
+
1204
+ if (fillerOf.has(term)) enqueue(fillerOf.get(term), hopBudget); // restriction -> filler, reseeds
1205
+ for (const r of fillerBack.get(term) || []) enqueue(r, hopBudget); // filler -> restriction, reseeds
1206
+
1207
+ for (const m of unionMembers.get(term) || []) enqueue(m, hopsLeft - 1);
1208
+ for (const u of memberUnions.get(term) || []) enqueue(u, hopsLeft - 1);
1209
+ if (complementPair.has(term)) enqueue(complementPair.get(term), hopsLeft - 1);
1210
+ for (const c of memberComplements.get(term) || []) enqueue(c, hopsLeft - 1);
1211
+ for (const m of oneOfMembers.get(term) || []) enqueue(m, hopsLeft - 1);
1212
+ for (const c of memberOneOf.get(term) || []) enqueue(c, hopsLeft - 1);
1213
+ }
1214
+
1215
+ const rolesUsed = new Set();
1216
+ for (const [restriction, role] of onPropertyOf) if (included.has(restriction)) rolesUsed.add(role);
1217
+
1218
+ return list.filter((r) => {
1219
+ if (included.has(r.subject) || included.has(r.object)) return true;
1220
+ const p = String(r.predicate).trim().toLowerCase();
1221
+ if (p === "rdfs:subpropertyof" || p === "owl:inverseof") return rolesUsed.has(r.subject);
1222
+ if (p === "rdf:type" && String(r.object).toLowerCase() === "transitiveproperty") return rolesUsed.has(r.subject);
1223
+ return false;
1224
+ });
1225
+ }