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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +74 -11
  2. package/bin/tmct.mjs +81 -0
  3. package/corpus/sprites/src/sprite-facts.jsonl +48 -0
  4. package/package.json +5 -1
  5. package/src/adapters/corpus/courtesy.mjs +91 -28
  6. package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
  7. package/src/adapters/corpus/news-sources.mjs +436 -0
  8. package/src/adapters/corpus/research-source.mjs +16 -3
  9. package/src/adapters/corpus/wiktionary-live.mjs +158 -0
  10. package/src/adapters/news-store.mjs +87 -0
  11. package/src/adapters/toml-config.mjs +18 -0
  12. package/src/domain/choice-question.mjs +275 -0
  13. package/src/domain/cli-verbs.mjs +20 -0
  14. package/src/domain/dialogue-acts.mjs +1 -0
  15. package/src/domain/el-classify.mjs +569 -0
  16. package/src/domain/fact-phrase.mjs +70 -0
  17. package/src/domain/feed-normalize.mjs +224 -0
  18. package/src/domain/grammar/ace.mjs +223 -7
  19. package/src/domain/grammar/lexicon-core.json +2 -0
  20. package/src/domain/memory/trust.mjs +15 -0
  21. package/src/domain/news-feed.mjs +219 -0
  22. package/src/domain/reasoning-config.mjs +56 -0
  23. package/src/domain/sprite-animation.mjs +20 -2
  24. package/src/domain/tableau.mjs +1225 -0
  25. package/src/domain/term-ledger.mjs +118 -0
  26. package/src/services/adventure-viz.mjs +89 -7
  27. package/src/services/chat.mjs +495 -27
  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.mjs +918 -0
  32. package/src/services/sprite-catalog-viz.mjs +148 -78
  33. package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
  34. package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
@@ -0,0 +1,569 @@
1
+ // el-classify.mjs — the EL saturation classifier: ELK-style normal forms plus
2
+ // the seven completion rules from Baader, Brandt and Lutz, "Pushing the EL
3
+ // Envelope" (IJCAI 2005). Offline, deterministic, polynomial: normalizes the
4
+ // stored TBox to four normal forms, then forward-chains the completion rules
5
+ // to a fixpoint. Same operational shape as syllogise.mjs's own materialising
6
+ // pass — a batch job off the hot path, budget and round caps, focus scoping,
7
+ // conclusions written under entailed:el-* provenance, retractable because a
8
+ // purely-entailed fact is deleted and re-verified rather than trusted by
9
+ // citation alone.
10
+ //
11
+ // Reads five stored shapes into normal form (normalizeElTBox), saturates them
12
+ // (saturateEl), mints the goal axioms that let a query reach a class
13
+ // expression the graph never declared as a node (elGoalAxioms/elGoalFor),
14
+ // and materialises the result (classifyEl). classifyEl runs saturateEl twice:
15
+ // once over the plain TBox to learn each concept's real subsumer set, once
16
+ // more with goal axioms minted from that first pass added in, so a query like
17
+ // "does a heart have a flap" can be answered from a batch pass alone.
18
+
19
+ import { normFactTerm } from "./hash.mjs";
20
+ import {
21
+ SUBCLASS_PREDICATE, ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE, TYPE_PREDICATE,
22
+ DEFAULT_MAX_ENVIRONMENTS, buildCardinalityRestrictions,
23
+ } from "./syllogise.mjs";
24
+
25
+ const SEP = "␟"; // an in-key separator no fact term can contain — same convention as syllogise.mjs's own SEP
26
+
27
+ /** The two reserved concept names every EL derivation is built from. Neither
28
+ * can collide with a stored term: normFactTerm never produces them from a
29
+ * class noun, and normalizeElTBox drops any row that literally names one. */
30
+ export const TOP = "top";
31
+ export const BOT = "bot";
32
+
33
+ function requireStore(store, needed, caller) {
34
+ for (const name of needed) {
35
+ if (typeof store?.[name] !== "function") {
36
+ throw new TypeError(`${caller} needs a store option carrying { ${needed.join(", ")} } (memory/core.mjs's read/write functions) — missing ${name}`);
37
+ }
38
+ }
39
+ return store;
40
+ }
41
+
42
+ /** Normalize a focus hint (Set|array of terms) into the same normalized-term
43
+ * space stored facts live in, or null for "no focus → whole graph". Local
44
+ * copy of syllogise.mjs's own private normalizeFocus — not exported there. */
45
+ function normalizeFocus(focus) {
46
+ if (!focus) return null;
47
+ const arr = focus instanceof Set ? [...focus] : Array.isArray(focus) ? focus : [];
48
+ const out = new Set();
49
+ for (const t of arr) {
50
+ const n = normFactTerm(t);
51
+ if (n) out.add(n);
52
+ }
53
+ return out.size ? out : null;
54
+ }
55
+
56
+ const lower = (p) => String(p || "").trim().toLowerCase();
57
+ const isSubClassOf = (p) => lower(p) === "rdfs:subclassof";
58
+ const isType = (p) => lower(p) === "rdf:type";
59
+ const isDisjoint = (p) => lower(p) === "owl:disjointwith";
60
+ const isOnProperty = (p) => lower(p) === "owl:onproperty";
61
+ const isSomeValuesFrom = (p) => lower(p) === "owl:somevaluesfrom";
62
+ const isOnClass = (p) => lower(p) === "owl:onclass";
63
+ const isIntersectionOf = (p) => lower(p) === "owl:intersectionof";
64
+ const isSubPropertyOf = (p) => lower(p) === "rdfs:subpropertyof";
65
+ const CARDINALITY_PREDICATES = new Set(["owl:cardinality", "owl:mincardinality", "owl:maxcardinality"]);
66
+ const isCardinalityPredicate = (p) => CARDINALITY_PREDICATES.has(lower(p));
67
+
68
+ /**
69
+ * Fold stored fact rows into normalized EL axioms. Pure, no I/O.
70
+ * Returns { axioms, roleAxioms, concepts, roles, restrictionOf, truncated }.
71
+ *
72
+ * `concepts`/`roles` are the REAL names the graph already declares — every
73
+ * subject/object a row actually carries, minus the synthetic intermediate
74
+ * names an intersection fold mints (`${m1}-and-${m2}`) and minus "top"/"bot".
75
+ * A synthetic fold name is scaffolding for the completion rules, never a
76
+ * concept to seed CR0 with or to write back as a stored class.
77
+ */
78
+ export function normalizeElTBox(rows, { budget = 500 } = {}) {
79
+ const input = (Array.isArray(rows) ? rows : []).filter((r) => r && r.id && r.subject && r.predicate && r.object !== undefined && r.object !== null);
80
+ const sorted = [...input].sort((a, b) => String(a.id).localeCompare(String(b.id)));
81
+ const truncated = sorted.length > budget;
82
+ const used = truncated ? sorted.slice(0, budget) : sorted;
83
+
84
+ const concepts = new Set();
85
+ const roles = new Set();
86
+ const addConcept = (t) => { if (t && t !== TOP && t !== BOT) concepts.add(t); };
87
+
88
+ // ---- pass 1: categorize every row, tracking the row itself (not just its
89
+ // value) so an axiom's `from` can cite the real stored fact id it rode. ----
90
+ const onPropertyRow = new Map(); // restriction node -> its owl:onProperty row
91
+ const someValuesFromRow = new Map(); // restriction node -> its owl:someValuesFrom row
92
+ const onClassRow = new Map(); // restriction node -> its owl:onClass row
93
+ const cardinalityRow = new Map(); // restriction node -> its owl:{min,max,}cardinality row
94
+ const intersectionRows = new Map(); // intersection node -> ordered [owl:intersectionOf row, …]
95
+ const subClassRows = [];
96
+ const disjointRows = [];
97
+ const transitiveRoleRow = new Map(); // role -> first p rdf:type owl:TransitiveProperty row
98
+ const subPropertyRows = [];
99
+
100
+ for (const r of used) {
101
+ if (r.subject === TOP || r.subject === BOT || r.object === TOP || r.object === BOT) continue; // reserved-name collision — drop, never crash
102
+ const p = r.predicate;
103
+ if (isOnProperty(p)) { onPropertyRow.set(r.subject, r); addConcept(r.subject); }
104
+ else if (isSomeValuesFrom(p)) { someValuesFromRow.set(r.subject, r); addConcept(r.subject); addConcept(r.object); }
105
+ else if (isOnClass(p)) { onClassRow.set(r.subject, r); addConcept(r.subject); addConcept(r.object); }
106
+ else if (isCardinalityPredicate(p)) { cardinalityRow.set(r.subject, r); addConcept(r.subject); }
107
+ else if (isIntersectionOf(p)) {
108
+ if (!intersectionRows.has(r.subject)) intersectionRows.set(r.subject, []);
109
+ intersectionRows.get(r.subject).push(r);
110
+ addConcept(r.subject); addConcept(r.object);
111
+ } else if (isSubClassOf(p)) { subClassRows.push(r); addConcept(r.subject); addConcept(r.object); }
112
+ else if (isDisjoint(p)) { disjointRows.push(r); addConcept(r.subject); addConcept(r.object); }
113
+ else if (isType(p) && r.object === "transitiveproperty") {
114
+ if (!transitiveRoleRow.has(r.subject)) transitiveRoleRow.set(r.subject, r);
115
+ roles.add(r.subject);
116
+ } else if (isSubPropertyOf(p)) { subPropertyRows.push(r); roles.add(r.subject); roles.add(r.object); }
117
+ }
118
+
119
+ // Someone-values-from restrictions (rule 2) and cardinality-as-existential
120
+ // restrictions (rule 3, n>=1 min/exactly, reusing buildCardinalityRestrictions
121
+ // so the HAS_PROPERTY_KEY gate and cardinality-kind table stay one definition).
122
+ const someValuesFromRestrictions = new Set(
123
+ [...onPropertyRow.keys()].filter((r) => someValuesFromRow.has(r)),
124
+ );
125
+ const restrictionOf = new Map(); // restriction node -> { role, filler }
126
+ for (const r of someValuesFromRestrictions) {
127
+ restrictionOf.set(r, { role: onPropertyRow.get(r).object, filler: someValuesFromRow.get(r).object });
128
+ }
129
+ const cardinalityAsExistential = new Map(); // restriction node -> filler class
130
+ for (const rec of buildCardinalityRestrictions(used)) {
131
+ if (rec.kind !== "min" && rec.kind !== "exactly") continue;
132
+ if (!(rec.n >= 1)) continue;
133
+ if (someValuesFromRestrictions.has(rec.restriction)) continue; // rule 2 already claimed it
134
+ if (!onPropertyRow.has(rec.restriction) || !onClassRow.has(rec.restriction) || !cardinalityRow.has(rec.restriction)) continue;
135
+ cardinalityAsExistential.set(rec.restriction, rec.onClass);
136
+ restrictionOf.set(rec.restriction, { role: "has", filler: rec.onClass });
137
+ }
138
+
139
+ const intersectionNodes = new Set(intersectionRows.keys());
140
+ const axioms = [];
141
+ const intersectionTargetRow = new Map(); // intersection node -> its "I rdfsSubClassOf B" row
142
+
143
+ for (const r of subClassRows) {
144
+ const A = r.subject;
145
+ const B = r.object;
146
+ if (intersectionNodes.has(A)) {
147
+ if (!intersectionTargetRow.has(A)) intersectionTargetRow.set(A, r); // first-wins, deterministic (sorted input)
148
+ continue;
149
+ }
150
+ if (someValuesFromRestrictions.has(B)) {
151
+ const { role, filler } = restrictionOf.get(B);
152
+ const opRow = onPropertyRow.get(B);
153
+ const svRow = someValuesFromRow.get(B);
154
+ axioms.push({ form: "someRight", sub: A, role, filler, from: [r.id, opRow.id, svRow.id] });
155
+ axioms.push({ form: "someLeft", role, filler, sup: B, from: [opRow.id, svRow.id] });
156
+ continue;
157
+ }
158
+ if (cardinalityAsExistential.has(B)) {
159
+ const filler = cardinalityAsExistential.get(B);
160
+ const opRow = onPropertyRow.get(B);
161
+ const ocRow = onClassRow.get(B);
162
+ const cardRow = cardinalityRow.get(B);
163
+ axioms.push({ form: "someRight", sub: A, role: "has", filler, from: [r.id, opRow.id, ocRow.id, cardRow.id] });
164
+ axioms.push({ form: "someLeft", role: "has", filler, sup: B, from: [opRow.id, ocRow.id, cardRow.id] });
165
+ continue;
166
+ }
167
+ axioms.push({ form: "sub", sub: A, sup: B, from: [r.id] });
168
+ }
169
+
170
+ // ---- intersection folds: I ⊓ … ⊑ B → a left-folded chain of binary NF2 axioms ----
171
+ for (const [node, memberRows] of intersectionRows) {
172
+ const targetRow = intersectionTargetRow.get(node);
173
+ if (!targetRow) continue; // no "I rdfsSubClassOf B" row — nothing to derive
174
+ const rowByMember = new Map(); // dedupe: first row per distinct member value
175
+ for (const mr of memberRows) if (!rowByMember.has(mr.object)) rowByMember.set(mr.object, mr);
176
+ const members = [...rowByMember.keys()].sort();
177
+ if (members.length < 2) continue;
178
+
179
+ let acc = members[0];
180
+ let accFromIds = [rowByMember.get(members[0]).id];
181
+ for (let i = 1; i < members.length; i += 1) {
182
+ const m = members[i];
183
+ const isLast = i === members.length - 1;
184
+ const sup = isLast ? targetRow.object : `${acc}-and-${m}`;
185
+ const subs = [acc, m].sort();
186
+ const memberFrom = rowByMember.get(m).id;
187
+ const from = isLast ? [...accFromIds, memberFrom, targetRow.id] : [...accFromIds, memberFrom];
188
+ axioms.push({ form: "and", subs, sup, from });
189
+ accFromIds = [...accFromIds, memberFrom];
190
+ acc = sup;
191
+ }
192
+ }
193
+
194
+ // ---- disjointness: EL⊥ ----
195
+ for (const r of disjointRows) {
196
+ axioms.push({ form: "and", subs: [r.subject, r.object].sort(), sup: BOT, from: [r.id] });
197
+ }
198
+
199
+ const roleAxioms = [];
200
+ for (const role of [...transitiveRoleRow.keys()].sort()) {
201
+ roleAxioms.push({ kind: "transitive", role, from: [transitiveRoleRow.get(role).id] });
202
+ }
203
+ for (const r of [...subPropertyRows].sort((a, b) => `${a.subject}${SEP}${a.object}`.localeCompare(`${b.subject}${SEP}${b.object}`))) {
204
+ roleAxioms.push({ kind: "sub", sub: r.subject, sup: r.object, from: [r.id] });
205
+ }
206
+
207
+ return { axioms, roleAxioms, concepts, roles, restrictionOf, truncated };
208
+ }
209
+
210
+ // ---- the seven completion rules ----
211
+
212
+ const EMPTY_SET = new Set();
213
+
214
+ /**
215
+ * Saturate the normalized TBox to a fixpoint. Pure, no I/O.
216
+ * Returns { subsumers, roleEdges, unsatisfiable, derivationOf, rounds, truncated }.
217
+ */
218
+ export function saturateEl(normalized, { budget = 2000, rounds = 64, focus = null } = {}) {
219
+ const axioms = normalized?.axioms || [];
220
+ const roleAxioms = normalized?.roleAxioms || [];
221
+ const concepts = [...(normalized?.concepts || [])].sort();
222
+ const focusSet = focus instanceof Set ? (focus.size ? focus : null) : normalizeFocus(focus);
223
+ const inFocus = (...terms) => !focusSet || terms.some((t) => focusSet.has(t));
224
+
225
+ const nf1BySub = new Map(); // sub -> [{ sup, from }]
226
+ const nf2ByOperand = new Map(); // one operand -> [{ other, sup, from }] (both directions indexed)
227
+ const nf3BySub = new Map(); // sub -> [{ role, filler, from }]
228
+ const nf4ByRoleFiller = new Map(); // "role␟filler" -> [{ sup, from }]
229
+ for (const ax of axioms) {
230
+ if (ax.form === "sub") {
231
+ if (!nf1BySub.has(ax.sub)) nf1BySub.set(ax.sub, []);
232
+ nf1BySub.get(ax.sub).push({ sup: ax.sup, from: ax.from });
233
+ } else if (ax.form === "and") {
234
+ const [x1, x2] = ax.subs;
235
+ for (const [self, other] of [[x1, x2], [x2, x1]]) {
236
+ if (!nf2ByOperand.has(self)) nf2ByOperand.set(self, []);
237
+ nf2ByOperand.get(self).push({ other, sup: ax.sup, from: ax.from });
238
+ }
239
+ } else if (ax.form === "someRight") {
240
+ if (!nf3BySub.has(ax.sub)) nf3BySub.set(ax.sub, []);
241
+ nf3BySub.get(ax.sub).push({ role: ax.role, filler: ax.filler, from: ax.from });
242
+ } else if (ax.form === "someLeft") {
243
+ const key = `${ax.role}${SEP}${ax.filler}`;
244
+ if (!nf4ByRoleFiller.has(key)) nf4ByRoleFiller.set(key, []);
245
+ nf4ByRoleFiller.get(key).push({ sup: ax.sup, from: ax.from });
246
+ }
247
+ }
248
+ const roleSubRoles = new Map(); // role -> [{ sup, from }] (r ⊑ s)
249
+ const transitiveRoles = new Set();
250
+ const transitiveFrom = new Map();
251
+ for (const ra of roleAxioms) {
252
+ if (ra.kind === "sub") {
253
+ if (!roleSubRoles.has(ra.sub)) roleSubRoles.set(ra.sub, []);
254
+ roleSubRoles.get(ra.sub).push({ sup: ra.sup, from: ra.from });
255
+ } else if (ra.kind === "transitive") {
256
+ transitiveRoles.add(ra.role);
257
+ if (!transitiveFrom.has(ra.role)) transitiveFrom.set(ra.role, ra.from);
258
+ }
259
+ }
260
+
261
+ // CR0: every concept name gets itself and top — the worklist's seed, in
262
+ // sorted concept order.
263
+ const subsumers = new Map();
264
+ for (const A of concepts) subsumers.set(A, new Set([A, TOP]));
265
+ const roleEdges = new Map(); // role -> Set("A␟B")
266
+ const subsumerProv = new Map(); // "A␟X" -> from[] (derivationOf, once genuinely derived)
267
+ const roleEdgeProv = new Map(); // "role␟A␟B" -> from[]
268
+
269
+ const subProv = (a, x) => (a === x ? [] : subsumerProv.get(`${a}${SEP}${x}`) || []);
270
+ const roleProv = (role, edgeKey) => roleEdgeProv.get(`${role}${SEP}${edgeKey}`) || [];
271
+ const dedupConcat = (...lists) => {
272
+ const seen = new Set();
273
+ const out = [];
274
+ for (const list of lists) {
275
+ for (const id of list || []) {
276
+ if (!id || seen.has(id)) continue;
277
+ seen.add(id);
278
+ out.push(id);
279
+ }
280
+ }
281
+ return out;
282
+ };
283
+
284
+ let committed = 0;
285
+ let reachedFixpoint = false;
286
+ let roundsRun = 0;
287
+ for (let round = 0; round < rounds; round += 1) {
288
+ roundsRun += 1;
289
+ const additions = [];
290
+
291
+ // CR1: A' ∈ S(A), NF1 A' ⊑ B ⊨ B ∈ S(A)
292
+ for (const [A, xs] of subsumers) {
293
+ for (const Xp of xs) {
294
+ for (const { sup, from } of nf1BySub.get(Xp) || []) {
295
+ if (xs.has(sup)) continue;
296
+ if (!inFocus(A, Xp, sup)) continue;
297
+ additions.push({ kind: "sub", A, X: sup, from: dedupConcat(subProv(A, Xp), from), sortKey: `1${SEP}${A}${SEP}${sup}${SEP}${Xp}` });
298
+ }
299
+ }
300
+ }
301
+ // CR2: A1,A2 ∈ S(A), NF2 A1⊓A2⊑B ⊨ B ∈ S(A)
302
+ for (const [A, xs] of subsumers) {
303
+ for (const X1 of xs) {
304
+ for (const { other, sup, from } of nf2ByOperand.get(X1) || []) {
305
+ if (!xs.has(other)) continue;
306
+ if (xs.has(sup)) continue;
307
+ if (!inFocus(A, X1, other, sup)) continue;
308
+ additions.push({ kind: "sub", A, X: sup, from: dedupConcat(subProv(A, X1), subProv(A, other), from), sortKey: `2${SEP}${A}${SEP}${sup}${SEP}${[X1, other].sort().join(SEP)}` });
309
+ }
310
+ }
311
+ }
312
+ // CR3: A' ∈ S(A), NF3 A'⊑∃r.B ⊨ (A,B) ∈ R(r)
313
+ for (const [A, xs] of subsumers) {
314
+ for (const Xp of xs) {
315
+ for (const { role, filler, from } of nf3BySub.get(Xp) || []) {
316
+ const edgeKey = `${A}${SEP}${filler}`;
317
+ if ((roleEdges.get(role) || EMPTY_SET).has(edgeKey)) continue;
318
+ if (!inFocus(A, Xp, filler)) continue;
319
+ additions.push({ kind: "role", role, A, B: filler, from: dedupConcat(subProv(A, Xp), from), sortKey: `3${SEP}${role}${SEP}${A}${SEP}${filler}${SEP}${Xp}` });
320
+ }
321
+ }
322
+ }
323
+ // CR4: (A,B) ∈ R(r), B' ∈ S(B), NF4 ∃r.B'⊑C ⊨ C ∈ S(A)
324
+ for (const [role, edges] of roleEdges) {
325
+ for (const edgeKey of edges) {
326
+ const [A, B] = edgeKey.split(SEP);
327
+ const bSubsumers = subsumers.get(B) || EMPTY_SET;
328
+ for (const Bp of bSubsumers) {
329
+ for (const { sup, from } of nf4ByRoleFiller.get(`${role}${SEP}${Bp}`) || []) {
330
+ const aSet = subsumers.get(A);
331
+ if (!aSet || aSet.has(sup)) continue;
332
+ if (!inFocus(A, B, Bp, sup)) continue;
333
+ additions.push({ kind: "sub", A, X: sup, from: dedupConcat(roleProv(role, edgeKey), subProv(B, Bp), from), sortKey: `4${SEP}${A}${SEP}${sup}${SEP}${role}${SEP}${B}${SEP}${Bp}` });
334
+ }
335
+ }
336
+ }
337
+ }
338
+ // CR5: (A,B) ∈ R(r), bot ∈ S(B) ⊨ bot ∈ S(A)
339
+ for (const [role, edges] of roleEdges) {
340
+ for (const edgeKey of edges) {
341
+ const [A, B] = edgeKey.split(SEP);
342
+ if (!(subsumers.get(B) || EMPTY_SET).has(BOT)) continue;
343
+ const aSet = subsumers.get(A);
344
+ if (!aSet || aSet.has(BOT)) continue;
345
+ if (!inFocus(A, B)) continue;
346
+ additions.push({ kind: "sub", A, X: BOT, from: dedupConcat(roleProv(role, edgeKey), subProv(B, BOT)), sortKey: `5${SEP}${A}${SEP}${role}${SEP}${B}` });
347
+ }
348
+ }
349
+ // CR6: (A,B) ∈ R(r), r⊑s ⊨ (A,B) ∈ R(s)
350
+ for (const [role, edges] of roleEdges) {
351
+ for (const { sup, from } of roleSubRoles.get(role) || []) {
352
+ for (const edgeKey of edges) {
353
+ if ((roleEdges.get(sup) || EMPTY_SET).has(edgeKey)) continue;
354
+ const [A, B] = edgeKey.split(SEP);
355
+ if (!inFocus(A, B)) continue;
356
+ additions.push({ kind: "role", role: sup, A, B, from: dedupConcat(roleProv(role, edgeKey), from), sortKey: `6${SEP}${sup}${SEP}${A}${SEP}${B}${SEP}${role}` });
357
+ }
358
+ }
359
+ }
360
+ // CR7: (A,B),(B,C) ∈ R(r), r transitive ⊨ (A,C) ∈ R(r)
361
+ for (const role of [...transitiveRoles].sort()) {
362
+ const edges = roleEdges.get(role);
363
+ if (!edges) continue;
364
+ for (const edgeKey1 of edges) {
365
+ const [A, B] = edgeKey1.split(SEP);
366
+ for (const edgeKey2 of edges) {
367
+ const [B2, C] = edgeKey2.split(SEP);
368
+ if (B2 !== B) continue;
369
+ const outKey = `${A}${SEP}${C}`;
370
+ if (edges.has(outKey)) continue;
371
+ if (!inFocus(A, B, C)) continue;
372
+ additions.push({ kind: "role", role, A, B: C, from: dedupConcat(roleProv(role, edgeKey1), roleProv(role, edgeKey2), transitiveFrom.get(role)), sortKey: `7${SEP}${role}${SEP}${A}${SEP}${C}${SEP}${B}` });
373
+ }
374
+ }
375
+ }
376
+
377
+ if (!additions.length) { reachedFixpoint = true; break; }
378
+ additions.sort((a, b) => (a.sortKey < b.sortKey ? -1 : a.sortKey > b.sortKey ? 1 : 0));
379
+
380
+ let progressed = false;
381
+ for (const add of additions) {
382
+ if (committed >= budget) break;
383
+ if (add.kind === "sub") {
384
+ const set = subsumers.get(add.A);
385
+ if (!set || set.has(add.X)) continue;
386
+ set.add(add.X);
387
+ subsumerProv.set(`${add.A}${SEP}${add.X}`, add.from);
388
+ committed += 1; progressed = true;
389
+ } else {
390
+ if (!roleEdges.has(add.role)) roleEdges.set(add.role, new Set());
391
+ const set = roleEdges.get(add.role);
392
+ const key = `${add.A}${SEP}${add.B}`;
393
+ if (set.has(key)) continue;
394
+ set.add(key);
395
+ roleEdgeProv.set(`${add.role}${SEP}${key}`, add.from);
396
+ committed += 1; progressed = true;
397
+ }
398
+ }
399
+ if (committed >= budget) break;
400
+ if (!progressed) { reachedFixpoint = true; break; }
401
+ }
402
+
403
+ const unsatisfiable = [...subsumers.entries()].filter(([, xs]) => xs.has(BOT)).map(([a]) => a).sort();
404
+
405
+ return {
406
+ subsumers, roleEdges, unsatisfiable, derivationOf: subsumerProv,
407
+ rounds: roundsRun, truncated: !reachedFixpoint,
408
+ };
409
+ }
410
+
411
+ /**
412
+ * Mint the bounded goal set for a batch pass, from the already-saturated
413
+ * `subsumers` index a first `saturateEl` pass built — not the raw normalized
414
+ * TBox. Pure. Returns an array of NF4 axioms.
415
+ */
416
+ export function elGoalAxioms(normalized, subsumers, { budget = 200 } = {}) {
417
+ const nf3 = (normalized?.axioms || []).filter((ax) => ax.form === "someRight");
418
+ const sorted = [...nf3].sort((a, b) => {
419
+ const ka = `${a.role}${SEP}${a.filler}${SEP}${a.sub}`;
420
+ const kb = `${b.role}${SEP}${b.filler}${SEP}${b.sub}`;
421
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
422
+ });
423
+ const goals = [];
424
+ const seen = new Set();
425
+ for (const ax of sorted) {
426
+ const fillerSet = subsumers?.get(ax.filler) || new Set([ax.filler, TOP]);
427
+ const fillerSubsumers = [...fillerSet].filter((c) => c !== TOP && c !== BOT).sort();
428
+ for (const Bp of fillerSubsumers) {
429
+ const name = `some-${ax.role}-${Bp}`;
430
+ if (seen.has(name)) continue;
431
+ seen.add(name);
432
+ goals.push({ form: "someLeft", role: ax.role, filler: Bp, sup: name, from: [] });
433
+ if (goals.length >= budget) return goals;
434
+ }
435
+ }
436
+ return goals;
437
+ }
438
+
439
+ /**
440
+ * Mint the single goal axiom for "does a <sub> <role> a <filler>?". Pure.
441
+ * Returns { axiom, name }.
442
+ */
443
+ export function elGoalFor(role, filler) {
444
+ const roleN = normFactTerm(role);
445
+ const fillerN = normFactTerm(filler);
446
+ const name = `some-${roleN}-${fillerN}`;
447
+ return { axiom: { form: "someLeft", role: roleN, filler: fillerN, sup: name, from: [] }, name };
448
+ }
449
+
450
+ /**
451
+ * Bounded query-rooted EL proof. Normalizes, adds the one goal, saturates,
452
+ * and reports whether `sub` acquired the goal name. Pure, no I/O.
453
+ * Returns { proved: true, premises } | { proved: false, exhausted }
454
+ */
455
+ export function proveElSubsumption(rows, sub, { role, filler }, { budget = 2000, rounds = 64 } = {}) {
456
+ const subN = normFactTerm(sub);
457
+ const normalized = normalizeElTBox(rows, { budget });
458
+ const { axiom, name } = elGoalFor(role, filler);
459
+ const concepts = new Set(normalized.concepts);
460
+ concepts.add(subN);
461
+ concepts.add(axiom.filler);
462
+ const withGoal = { ...normalized, axioms: [...normalized.axioms, axiom], concepts };
463
+ const sat = saturateEl(withGoal, { budget, rounds });
464
+ const proved = (sat.subsumers.get(subN) || EMPTY_SET).has(name);
465
+ if (proved) return { proved: true, premises: sat.derivationOf.get(`${subN}${SEP}${name}`) || [] };
466
+ return { proved: false, exhausted: sat.truncated };
467
+ }
468
+
469
+ // ---- the materialising pass ----
470
+
471
+ export const EL_SUBSUMPTION_RULE = "elSubsumption";
472
+ export const ENTAILED_EL_PROVENANCE = `entailed:${EL_SUBSUMPTION_RULE}`;
473
+ export const EL_RESTRICTION_RULE = "elRestriction";
474
+ export const ENTAILED_EL_RESTRICTION_PROVENANCE = `entailed:${EL_RESTRICTION_RULE}`;
475
+ /** Same sub-1 discount as CAX_DW_RULE_CONFIDENCE, same reason. */
476
+ export const EL_RULE_CONFIDENCE = 0.95;
477
+ export const DEFAULT_EL_BUDGET = 2000;
478
+ export const DEFAULT_EL_ROUNDS = 64;
479
+
480
+ /**
481
+ * Run one bounded EL classification pass over the memory graph under `repoDir`.
482
+ * Normalizes, saturates once to find real subsumers, mints batch goals from that
483
+ * saturation, saturates again with the goals in place, and materialises each new
484
+ * named subsumption via `appendFacts` under its entailed provenance.
485
+ *
486
+ * opts: `budget`, `rounds`, `focus`, `maxEnvironments`, `store` (REQUIRED —
487
+ * { loadMemory, readFactRows, appendFacts }).
488
+ *
489
+ * Returns { derived, count, budget, rounds, truncated, unsatisfiable, goalCount }.
490
+ */
491
+ export async function classifyEl(repoDir, {
492
+ budget = DEFAULT_EL_BUDGET, rounds = DEFAULT_EL_ROUNDS, focus = null,
493
+ // Accepted for API symmetry with syllogise()'s store contract; unused today
494
+ // because an EL conclusion carries exactly one environment (no alternate-
495
+ // environment discovery step yet — see the module doc comment above).
496
+ maxEnvironments = DEFAULT_MAX_ENVIRONMENTS,
497
+ store,
498
+ } = {}) {
499
+ const { loadMemory, readFactRows, appendFacts } = requireStore(store, ["loadMemory", "readFactRows", "appendFacts"], "classifyEl");
500
+ void maxEnvironments;
501
+ const memory = await loadMemory(repoDir);
502
+ const rows = readFactRows(memory);
503
+ const normalized = normalizeElTBox(rows, { budget });
504
+ const firstPass = saturateEl(normalized, { budget, rounds, focus });
505
+ const goals = elGoalAxioms(normalized, firstPass.subsumers);
506
+ const goalInfo = new Map(goals.map((g) => [g.sup, { role: g.role, filler: g.filler }]));
507
+ const withGoals = { ...normalized, axioms: [...normalized.axioms, ...goals] };
508
+ const finalPass = saturateEl(withGoals, { budget, rounds, focus });
509
+ const truncated = normalized.truncated || firstPass.truncated || finalPass.truncated;
510
+
511
+ const trustByTriple = new Map();
512
+ for (const r of rows) trustByTriple.set(`${r.subject}${SEP}${r.predicate}${SEP}${r.object}`, r.trust);
513
+ const rowById = new Map(rows.map((r) => [r.id, r]));
514
+ const premiseTrustsFor = (factIds) => (factIds || [])
515
+ .map((id) => rowById.get(id)?.trust)
516
+ .filter((t) => typeof t === "number");
517
+ const storedSubClassPairs = new Set(rows.filter((r) => isSubClassOf(r.predicate)).map((r) => `${r.subject}${SEP}${r.object}`));
518
+
519
+ const toWrite = [];
520
+ const derivedMeta = []; // { toWriteIndex, subject, object, rule }
521
+ const restrictionScaffoldWritten = new Set();
522
+
523
+ const subjects = [...finalPass.subsumers.keys()].sort();
524
+ for (const A of subjects) {
525
+ const sSet = finalPass.subsumers.get(A);
526
+ if (sSet.has(BOT)) continue; // an unsatisfiable class is reported, never materialised
527
+ const members = [...sSet].filter((b) => b !== A && b !== TOP && b !== BOT).sort();
528
+ for (const B of members) {
529
+ const pairKey = `${A}${SEP}${B}`;
530
+ if (storedSubClassPairs.has(pairKey)) continue;
531
+ const from = finalPass.derivationOf.get(pairKey) || [];
532
+ const goal = goalInfo.get(B);
533
+ if (goal) {
534
+ if (!restrictionScaffoldWritten.has(B)) {
535
+ restrictionScaffoldWritten.add(B);
536
+ toWrite.push({ subject: B, predicate: TYPE_PREDICATE, object: "owl:Restriction", provenance: ENTAILED_EL_RESTRICTION_PROVENANCE, justification: [from] });
537
+ toWrite.push({ subject: B, predicate: ON_PROPERTY_PREDICATE, object: goal.role, provenance: ENTAILED_EL_RESTRICTION_PROVENANCE, justification: [from] });
538
+ toWrite.push({ subject: B, predicate: SOME_VALUES_FROM_PREDICATE, object: goal.filler, provenance: ENTAILED_EL_RESTRICTION_PROVENANCE, justification: [from] });
539
+ }
540
+ const premiseTrusts = premiseTrustsFor(from);
541
+ const idx = toWrite.length;
542
+ toWrite.push({
543
+ subject: A, predicate: SUBCLASS_PREDICATE, object: B,
544
+ provenance: ENTAILED_EL_RESTRICTION_PROVENANCE, justification: [from],
545
+ ...(premiseTrusts.length ? { premiseTrusts, ruleConfidence: EL_RULE_CONFIDENCE } : {}),
546
+ });
547
+ derivedMeta.push({ toWriteIndex: idx, subject: A, object: B, rule: EL_RESTRICTION_RULE });
548
+ } else if (normalized.concepts.has(B)) {
549
+ const premiseTrusts = premiseTrustsFor(from);
550
+ const idx = toWrite.length;
551
+ toWrite.push({
552
+ subject: A, predicate: SUBCLASS_PREDICATE, object: B,
553
+ provenance: ENTAILED_EL_PROVENANCE, justification: [from],
554
+ ...(premiseTrusts.length ? { premiseTrusts, ruleConfidence: EL_RULE_CONFIDENCE } : {}),
555
+ });
556
+ derivedMeta.push({ toWriteIndex: idx, subject: A, object: B, rule: EL_SUBSUMPTION_RULE });
557
+ }
558
+ // else: a synthetic intersection-fold intermediate — never materialised.
559
+ }
560
+ }
561
+
562
+ const { ids } = await appendFacts(repoDir, toWrite);
563
+ const derived = derivedMeta.map((d) => ({ id: ids[d.toWriteIndex], subject: d.subject, object: d.object, rule: d.rule }));
564
+
565
+ return {
566
+ derived, count: derived.length, budget, rounds, truncated,
567
+ unsatisfiable: finalPass.unsatisfiable, goalCount: goals.length,
568
+ };
569
+ }
@@ -0,0 +1,70 @@
1
+ // fact-phrase.mjs — the one predicate -> English-phrase table, shared by the
2
+ // news paraphrase renderer and chat's own fact read-back instead of growing a
3
+ // twin (PLAN_NEWS_FEED.md section 8.1). The table is copied verbatim from
4
+ // chat.mjs's private FACT_PREDICATE_PHRASES; test/domain/fact-phrase.test.mjs
5
+ // pins the two identical until chat.mjs is repointed at this module to import
6
+ // it instead of holding its own copy.
7
+ //
8
+ // This module's own `predicatePhrase`/`factSentence` are the plain reader a
9
+ // domain module can offer without chat.mjs's surrounding machinery (polarity
10
+ // flips, comparative/participle surface forms, teach-lane verb minting): a
11
+ // table hit, or the predicate's bare local name.
12
+
13
+ export const FACT_PREDICATE_PHRASES = Object.freeze({
14
+ "rdfs:subClassOf": "is a kind of",
15
+ "mgxneg:subClassOf": "is not a kind of",
16
+ "rdf:type": "is a",
17
+ "owl:disjointWith": "is not a",
18
+ "owl:unionOf": "is either",
19
+ "owl:complementOf": "is anything that is not",
20
+ "owl:oneOf": "includes exactly",
21
+ "owl:differentFrom": "is not the same as",
22
+ "mgx:partOf": "is part of",
23
+ "mgx:memberOf": "is a member of",
24
+ "mgx:collectionOf": "is a collection of",
25
+ "mgx:hasA": "has",
26
+ "mgx:usedFor": "is used for",
27
+ "mgx:capableOf": "can",
28
+ "mgx:atLocation": "is found in",
29
+ "mgx:causes": "causes",
30
+ "mgx:hasProperty": "is",
31
+ "mgx:madeOf": "is made of",
32
+ "mgx:receivesAction": "can be",
33
+ "mgx:createdBy": "is created by",
34
+ "mgx:mannerOf": "is a way to",
35
+ "mgx:desires": "wants",
36
+ "mgx:locatedNear": "is typically near",
37
+ "mgx:motivatedByGoal": "is motivated by",
38
+ "mgx:obstructedBy": "can be prevented by",
39
+ "mgx:causesDesire": "makes you want to",
40
+ "mgx:hasSubevent": "involves",
41
+ "mgx:hasFirstSubevent": "begins with",
42
+ "mgx:hasLastSubevent": "ends with",
43
+ "mgx:hasPrerequisite": "requires",
44
+ "mgx:ownedBy": "is owned by", // the teach lane's ownership frame ("Priya owns tasks.mjs")
45
+ "mgx:rendersAs": "renders as", // the render-template binding ("a disk renders as a block")
46
+ "mgx:synonym": "means the same as",
47
+ "mgx:antonym": "is the opposite of",
48
+ "mgx:similarTo": "is similar to",
49
+ "mgx:relatedTo": "is related to",
50
+ "mgx:symbolOf": "is a symbol of",
51
+ "mgx:currently-in": "is in",
52
+ "mgx:located-in": "is in",
53
+ "mgx:fixed-in": "is fixed in",
54
+ "mgx:stands-locked-in": "stands locked in",
55
+ "mgx:works-in": "works in",
56
+ });
57
+
58
+ /** A table hit, or the predicate's local name (the segment after its first
59
+ * colon, or the whole string when there is none). */
60
+ export function predicatePhrase(predicate) {
61
+ if (FACT_PREDICATE_PHRASES[predicate]) return FACT_PREDICATE_PHRASES[predicate];
62
+ const s = String(predicate ?? "");
63
+ const colon = s.indexOf(":");
64
+ return colon === -1 ? s : s.slice(colon + 1);
65
+ }
66
+
67
+ /** "a heart has a valve" from one { subject, predicate, object } fact row. */
68
+ export function factSentence(row) {
69
+ return `${row.subject} ${predicatePhrase(row.predicate)} ${row.object}`;
70
+ }