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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/corpus/worlds/index.json.gz +0 -0
  2. package/corpus/worlds/manifest.json +27 -17
  3. package/corpus/worlds/shards/river-crossing.jsonl.gz +0 -0
  4. package/corpus/worlds/shards/town-square-chapel.jsonl.gz +0 -0
  5. package/corpus/worlds/shards/town-square-market.jsonl.gz +0 -0
  6. package/corpus/worlds/shards/town-square.jsonl.gz +0 -0
  7. package/corpus/worlds/src/river-crossing.jsonl +29 -0
  8. package/corpus/worlds/src/town-square-chapel.jsonl +12 -8
  9. package/corpus/worlds/src/town-square-market.jsonl +12 -8
  10. package/corpus/worlds/src/town-square.jsonl +12 -8
  11. package/package.json +2 -2
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-belief.mjs +33 -11
  14. package/src/domain/agent-traits.mjs +282 -0
  15. package/src/domain/choice-question.mjs +259 -6
  16. package/src/domain/el-classify.mjs +55 -7
  17. package/src/domain/fact-phrase.mjs +7 -4
  18. package/src/domain/grammar/ace.mjs +66 -3
  19. package/src/domain/interpret/normalize.mjs +58 -2
  20. package/src/domain/tableau.mjs +101 -14
  21. package/src/domain/town-square-world.mjs +44 -19
  22. package/src/services/adventure.mjs +5 -16
  23. package/src/services/agent-editor.mjs +216 -0
  24. package/src/services/chat-session.mjs +26 -5
  25. package/src/services/chat.mjs +118 -58
  26. package/src/services/mudiii-scene.mjs +32 -5
  27. package/src/services/mudiii-turn.mjs +120 -5
  28. package/src/services/mudiii-viz.mjs +299 -1
  29. package/src/services/predator-prey.mjs +234 -57
  30. package/src/surfaces/web/chat-browser-entry.mjs +69 -3
  31. package/src/surfaces/web/memory-ask-browser.bundle.js +155 -155
  32. package/src/surfaces/web/mudiii-browser-entry.mjs +48 -2
  33. package/src/surfaces/web/planner-instances.mjs +64 -3
  34. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -0,0 +1,282 @@
1
+ // agent-traits.mjs — what drives an agent class or instance, read from rows
2
+ // alone: display name, avatar, mass, drain per turn, vision radius, whether
3
+ // it is marked a predator, and the classes it pursues, evades, consumes and
4
+ // guards. One instance's own rows override its class; a class with nothing
5
+ // stated has no drive, never a JS-invented default.
6
+ //
7
+ // The chain walk itself (classChainOf) is the same breadth-first walk
8
+ // src/services/adventure.mjs's objectClassChain already performs over
9
+ // rdf:type/rdfs:subClassOf, lifted here so the two callers — the adventure
10
+ // lane's mass-drain read and this module's trait resolver — share one walk
11
+ // instead of drifting apart. adventure.mjs imports it back down (services
12
+ // may import domain) and applies its own world-row filter before calling it;
13
+ // this module makes no such filter, since a domain module reads whatever
14
+ // rows it is given.
15
+ //
16
+ // Every list this module returns is sorted in codepoint order before it is
17
+ // returned, and every resolver here is a pure function of the row SET, never
18
+ // of the order the rows arrived in — the same rule p2p-room.mjs's
19
+ // sortFactIndividualsById holds for a merged fact store, so two callers who
20
+ // built the same rows in different orders never read a different answer.
21
+
22
+ /** Every predicate a spawn copies from a class onto an instance, and that the
23
+ * resolver reads back off the class chain. Sorted, frozen, closed: a
24
+ * predicate not on this list is world state, not an imperative, and a spawn
25
+ * leaves it alone. */
26
+ export const AGENT_TRAIT_PREDICATES = Object.freeze([
27
+ "mgx:consumes",
28
+ "mgx:display-name",
29
+ "mgx:evades",
30
+ "mgx:guards",
31
+ "mgx:hasMass",
32
+ "mgx:is-predator",
33
+ "mgx:mass-drain-per-turn",
34
+ "mgx:model",
35
+ "mgx:pursues",
36
+ "mgx:vision-radius",
37
+ ]);
38
+
39
+ /** The subset of AGENT_TRAIT_PREDICATES that read as a set of rows rather
40
+ * than a single value: every row on the nearest chain link that declares
41
+ * any, not just the first. */
42
+ export const AGENT_TRAIT_MULTI = Object.freeze(new Set([
43
+ "mgx:consumes",
44
+ "mgx:evades",
45
+ "mgx:guards",
46
+ "mgx:pursues",
47
+ ]));
48
+
49
+ const objectsOf = (rows, subject, predicate) =>
50
+ (rows || []).filter((r) => r.subject === subject && r.predicate === predicate).map((r) => r.object);
51
+
52
+ const sortedUnique = (values) => [...new Set(values)].sort();
53
+
54
+ /** `subject`'s own class chain, nearest first, starting with `subject`
55
+ * itself: a breadth-first walk over its rdf:type and rdfs:subClassOf rows.
56
+ * A cycle stops the walk rather than looping. Pure — reads exactly the rows
57
+ * it is given, with no provenance filter of its own. */
58
+ export function classChainOf(rows, subject) {
59
+ const parentsOf = (node) => (rows || [])
60
+ .filter((r) => r.subject === node && (r.predicate === "rdf:type" || r.predicate === "rdfs:subClassOf"))
61
+ .map((r) => r.object);
62
+ const seen = new Set([subject]);
63
+ const chain = [subject];
64
+ const queue = [...parentsOf(subject)];
65
+ while (queue.length) {
66
+ const node = queue.shift();
67
+ if (seen.has(node)) continue;
68
+ seen.add(node);
69
+ chain.push(node);
70
+ queue.push(...parentsOf(node));
71
+ }
72
+ return chain;
73
+ }
74
+
75
+ /** The single declared value of `predicate` on `subject`'s own class chain,
76
+ * nearest first — an instance's own row wins over its class's. Null when no
77
+ * chain link declares one, which reads as "nobody has said anything about
78
+ * this yet", never as an invented default. When a single node writes more
79
+ * than one value for the same predicate (an ill-formed world), the choice
80
+ * is the sorted-first value, so the answer never depends on which order the
81
+ * rows arrived in. Pure. */
82
+ export function traitValueOf(rows, subject, predicate) {
83
+ for (const node of classChainOf(rows, subject)) {
84
+ const values = objectsOf(rows, node, predicate);
85
+ if (values.length) return sortedUnique(values)[0];
86
+ }
87
+ return null;
88
+ }
89
+
90
+ /** Every declared value of `predicate` on the FIRST chain link (nearest
91
+ * first) that declares any, sorted and deduped — so an instance's own
92
+ * `mgx:evades` row replaces its class's set rather than adding to it. Empty
93
+ * when no chain link declares one. Pure. */
94
+ export function traitValuesOf(rows, subject, predicate) {
95
+ for (const node of classChainOf(rows, subject)) {
96
+ const values = objectsOf(rows, node, predicate);
97
+ if (values.length) return sortedUnique(values);
98
+ }
99
+ return [];
100
+ }
101
+
102
+ /** Which chain link answered `traitValueOf`/`traitValuesOf` for this
103
+ * predicate: `"instance"` when `subject` itself declares it, the class name
104
+ * that declares it otherwise, or `null` when no chain link does. Pure. */
105
+ export function traitOriginOf(rows, subject, predicate) {
106
+ const chain = classChainOf(rows, subject);
107
+ for (const node of chain) {
108
+ if (objectsOf(rows, node, predicate).length) return node === subject ? "instance" : node;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ const numberOrNull = (value) => {
114
+ if (value === null) return null;
115
+ const n = Number(value);
116
+ return Number.isFinite(n) ? n : null;
117
+ };
118
+
119
+ /** Every trait `subject` reads off its own class chain, flat and fully
120
+ * populated so no caller has to remember which key is a list. `classes` is
121
+ * the chain of ancestor class names, nearest first, excluding `subject`
122
+ * itself. A trait nobody declared reads as `null` (single-valued) or `[]`
123
+ * (multi-valued), never as a JS-side default. Pure. */
124
+ export function agentTraitsOf(rows, subject) {
125
+ return {
126
+ subject,
127
+ classes: classChainOf(rows, subject).slice(1),
128
+ displayName: traitValueOf(rows, subject, "mgx:display-name"),
129
+ model: traitValueOf(rows, subject, "mgx:model"),
130
+ mass: numberOrNull(traitValueOf(rows, subject, "mgx:hasMass")),
131
+ massDrainPerTurn: numberOrNull(traitValueOf(rows, subject, "mgx:mass-drain-per-turn")),
132
+ visionRadius: numberOrNull(traitValueOf(rows, subject, "mgx:vision-radius")),
133
+ isPredator: traitValueOf(rows, subject, "mgx:is-predator") === "true",
134
+ pursues: traitValuesOf(rows, subject, "mgx:pursues"),
135
+ evades: traitValuesOf(rows, subject, "mgx:evades"),
136
+ consumes: traitValuesOf(rows, subject, "mgx:consumes"),
137
+ guards: traitValuesOf(rows, subject, "mgx:guards"),
138
+ };
139
+ }
140
+
141
+ /** `className`'s own trait rows — the rows a class-tab editor renders for
142
+ * that class alone, never an ancestor's. Sorted by (predicate, object).
143
+ * Pure. */
144
+ export function classFactRowsFor(rows, className) {
145
+ return (rows || [])
146
+ .filter((r) => r.subject === className && AGENT_TRAIT_PREDICATES.includes(r.predicate))
147
+ .map((r) => ({ subject: r.subject, predicate: r.predicate, object: r.object }))
148
+ .sort(compareRows);
149
+ }
150
+
151
+ function compareRows(a, b) {
152
+ if (a.predicate !== b.predicate) return a.predicate < b.predicate ? -1 : 1;
153
+ if (a.object !== b.object) return a.object < b.object ? -1 : 1;
154
+ return 0;
155
+ }
156
+
157
+ const DRIVE_PREDICATES = Object.freeze(["mgx:consumes", "mgx:evades", "mgx:pursues"]);
158
+
159
+ /** Whether any row states a drive (`mgx:pursues`, `mgx:evades` or
160
+ * `mgx:consumes`). A world that states none is a world whose cast is still
161
+ * driven by its injected roles object and config numbers alone. Pure. */
162
+ export function rowsDeclareDrives(rows) {
163
+ return (rows || []).some((r) => DRIVE_PREDICATES.includes(r.predicate));
164
+ }
165
+
166
+ /** The class an appetite belongs to: the consuming subject's own bare
167
+ * `rdf:type` class when it is an instance, otherwise the subject itself. */
168
+ function consumerClassOf(rows, subject) {
169
+ const typed = (rows || []).find((r) => r.subject === subject && r.predicate === "rdf:type");
170
+ return typed ? typed.object : subject;
171
+ }
172
+
173
+ /** The class names `subject` moves away from: its own chain's `mgx:evades`
174
+ * rows when any are declared, otherwise the inverse of `mgx:consumes` —
175
+ * every class whose members declare an appetite for a class on `subject`'s
176
+ * own chain. The inverse is what keeps a prey fleeing its eater without the
177
+ * world stating the fear twice; a declared `mgx:evades` set replaces it
178
+ * entirely, so one instance can be taught a different fear (or a fear of
179
+ * something absent) without inheriting the derived one back. Sorted. Pure. */
180
+ export function fearedClassesOf(rows, subject) {
181
+ const declared = traitValuesOf(rows, subject, "mgx:evades");
182
+ if (declared.length) return declared;
183
+ const chain = new Set(classChainOf(rows, subject));
184
+ const consumers = new Set();
185
+ for (const row of rows || []) {
186
+ if (row.predicate !== "mgx:consumes" || !chain.has(row.object)) continue;
187
+ consumers.add(consumerClassOf(rows, row.subject));
188
+ }
189
+ return [...consumers].sort();
190
+ }
191
+
192
+ /** The cast a world's own rows state, in the `{ predator, prey, food }` shape
193
+ * the town-square engine's `roles` parameter already takes. A predator class
194
+ * is one whose declared `mgx:pursues`/`mgx:consumes` names another class that
195
+ * itself declares a drive; the prey class is the one it names. `fallback`
196
+ * fills whatever the rows say nothing about — the food kinds always come
197
+ * from it, since a spawned and a placed food differ by who put them there,
198
+ * which no trait row states. Null when the rows state no cast at all and no
199
+ * fallback was given. Sorted-first on ties, so two row orders build the same
200
+ * cast. Pure. */
201
+ export function castFromFacts(rows, { fallback = null } = {}) {
202
+ const driveSubjects = new Set(
203
+ (rows || []).filter((r) => DRIVE_PREDICATES.includes(r.predicate)).map((r) => r.subject),
204
+ );
205
+ const driveClasses = new Set([...driveSubjects].map((s) => consumerClassOf(rows, s)));
206
+ let predatorKind = null;
207
+ let preyKind = null;
208
+ for (const kind of [...driveClasses].sort()) {
209
+ const targets = [...traitValuesOf(rows, kind, "mgx:pursues"), ...traitValuesOf(rows, kind, "mgx:consumes")]
210
+ .filter((target) => target !== kind && driveClasses.has(target))
211
+ .sort();
212
+ if (targets.length) { predatorKind = kind; preyKind = targets[0]; break; }
213
+ }
214
+ if (!predatorKind) return fallback;
215
+ return {
216
+ predator: { role: "predator", kind: predatorKind, idPrefix: predatorKind, hunts: preyKind ? "prey" : null },
217
+ prey: preyKind
218
+ ? { role: "prey", kind: preyKind, idPrefix: preyKind, hunts: null }
219
+ : (fallback?.prey ?? null),
220
+ food: fallback?.food ?? null,
221
+ };
222
+ }
223
+
224
+ const compareConstraints = (a, b) => {
225
+ if (a.left !== b.left) return a.left < b.left ? -1 : 1;
226
+ if (a.right !== b.right) return a.right < b.right ? -1 : 1;
227
+ if (a.guard !== b.guard) return a.guard < b.guard ? -1 : 1;
228
+ return 0;
229
+ };
230
+
231
+ /** The action-constraint slot sets a world's own drive facts imply, in the
232
+ * `{ left, right, guard }` shape src/domain/domain.mjs compiles: for every
233
+ * `X mgx:consumes Y` row, every `Z mgx:guards X` row yields a constraint
234
+ * saying X and Y may not share a place unless Z is there too — the farmer
235
+ * guarding the wolf's own appetite, not the goat it threatens. A consumes
236
+ * pair with no guard row yields no constraint, which is why the town
237
+ * square (the fox eats goblins and nobody guards anything) states none.
238
+ * Sorted by (left, right, guard) and deduped, so a fact set that states
239
+ * the same guard twice, or in either row order, yields one constraint
240
+ * list. Pure. */
241
+ export function constraintsFromDrives(rows) {
242
+ const guardsOfConsumer = new Map();
243
+ for (const row of rows || []) {
244
+ if (row.predicate !== "mgx:guards") continue;
245
+ if (!guardsOfConsumer.has(row.object)) guardsOfConsumer.set(row.object, new Set());
246
+ guardsOfConsumer.get(row.object).add(row.subject);
247
+ }
248
+ const seen = new Set();
249
+ const out = [];
250
+ for (const row of rows || []) {
251
+ if (row.predicate !== "mgx:consumes") continue;
252
+ for (const guard of guardsOfConsumer.get(row.subject) || []) {
253
+ const key = `${row.subject}\0${row.object}\0${guard}`;
254
+ if (seen.has(key)) continue;
255
+ seen.add(key);
256
+ out.push({ left: row.subject, right: row.object, guard });
257
+ }
258
+ }
259
+ return out.sort(compareConstraints);
260
+ }
261
+
262
+ /** The instance's own rows for a fresh spawn of `className`: one row per
263
+ * trait `className`'s own class chain declares, subject rewritten to
264
+ * `instanceId`, plus the `rdf:type` row. Sorted by (predicate, object) so
265
+ * two callers building the same spawn build the same list. Returns rows, it
266
+ * does not write them — the caller appends them through `appendFacts`,
267
+ * whose content-addressed ids make a second spawn of the same instance a
268
+ * no-op rather than a duplicate. Pure. */
269
+ export function instanceFactsFrom(rows, className, instanceId) {
270
+ const out = [{ subject: instanceId, predicate: "rdf:type", object: className }];
271
+ for (const predicate of AGENT_TRAIT_PREDICATES) {
272
+ if (AGENT_TRAIT_MULTI.has(predicate)) {
273
+ for (const object of traitValuesOf(rows, className, predicate)) {
274
+ out.push({ subject: instanceId, predicate, object });
275
+ }
276
+ } else {
277
+ const value = traitValueOf(rows, className, predicate);
278
+ if (value !== null) out.push({ subject: instanceId, predicate, object: value });
279
+ }
280
+ }
281
+ return out.sort(compareRows);
282
+ }
@@ -170,13 +170,266 @@ function findAcceptedLabelSequence(text) {
170
170
  return accepted;
171
171
  }
172
172
 
173
- // The one closed frame this module extracts a source term from directly:
174
- // "where would you find/see/keep/put/store/place X ..." — the shape the
175
- // rig's own enumerated stems take. Anything else yields "", which the
176
- // contract states is a valid outcome, not a failure.
177
- const PLACEMENT_VERB_RE = /\b(?:find|see|keep|put|store|place)\s+([a-z][\w'-]*)/i;
173
+ // ---- stem source-term extraction ----
174
+ //
175
+ // A closed set of sentence templates, tried in order, each reading only the
176
+ // stem text — never a fixture's own question_concept, which the real lane
177
+ // never sees either. Every template ends the same way: hand the text after
178
+ // its cue word to captureStemNounPhrase, which trims determiners, pronouns
179
+ // and clause boundaries down to a short noun phrase. Anything no template
180
+ // matches yields "", which the contract states is a valid outcome, not a
181
+ // failure.
182
+
183
+ // Determiners and possessives stripped off the front of a captured phrase —
184
+ // closed classes, not open vocabulary.
185
+ const LEADING_DETERMINER_RE = /^(?:an?|the|some|any|few|many|several|more|most|my|your|his|its|our|their)\s+/i;
186
+
187
+ // Pronouns that can open a captured phrase but never name a source term —
188
+ // "where are you" and "what should he use" have no noun there to read.
189
+ const PRONOUN_TERMS = new Set([
190
+ "you", "i", "it", "he", "she", "they", "we", "there", "someone",
191
+ "something", "one", "him", "her", "them", "who",
192
+ "himself", "herself", "itself", "themselves", "myself", "yourself",
193
+ ]);
194
+
195
+ // Words that end a captured phrase rather than folding into it: the closed
196
+ // prepositions this module already uses elsewhere (PREP_WORDS), plus the
197
+ // conjunctions, clause-openers and auxiliary/modal verbs that mark a clause
198
+ // boundary in the sentence shapes CommonsenseQA's stems actually use.
199
+ const PHRASE_BOUNDARY_WORDS = new Set([
200
+ ...PREP_WORDS, "to", "behind", "before", "near", "next",
201
+ "along", "alongside", "under", "over", "between", "among", "during",
202
+ "without", "about", "by", "as", "like",
203
+ "that", "if", "when", "while", "being", "because", "since", "until",
204
+ "so", "and", "but", "or",
205
+ "immediately", "likely", "usually", "normally", "currently",
206
+ "is", "are", "was", "were", "do", "does", "did",
207
+ "has", "have", "had", "will", "would", "could", "should", "might", "must", "can",
208
+ ]);
209
+
210
+ /** Reads a short noun phrase (at most three words) off the front of `words`,
211
+ * stopping at the first phrase-boundary word. A possessive ("restaurant's")
212
+ * ends the phrase right after the word it marks, its "'s" dropped — the
213
+ * next word belongs to a different noun ("restaurant's phone number" reads
214
+ * as "restaurant", not the number). */
215
+ function readStemNounPhrase(words) {
216
+ const out = [];
217
+ for (const word of words) {
218
+ if (out.length >= 3 || PHRASE_BOUNDARY_WORDS.has(word)) break;
219
+ const possessive = word.endsWith("'s");
220
+ out.push(possessive ? word.slice(0, -2) : word);
221
+ if (possessive) break;
222
+ }
223
+ return out.join(" ");
224
+ }
225
+
226
+ /** Strips every leading determiner in a run ("the most fast food
227
+ * restaurants" -> "fast food restaurants"), not just the first — a
228
+ * quantifier stacked on an article is ordinary English, not a special
229
+ * case. */
230
+ function stripLeadingDeterminers(phrase) {
231
+ let out = phrase;
232
+ let m;
233
+ while ((m = LEADING_DETERMINER_RE.exec(out))) out = out.slice(m[0].length);
234
+ return out;
235
+ }
236
+
237
+ /** Strips a leading determiner, then reads a noun phrase — "" when the
238
+ * phrase would open on a pronoun or a boundary word, since neither ever
239
+ * names a source term. Stops at the first comma, so an option-like list
240
+ * ("a magazine, paper or gum") reads only its first member. */
241
+ function captureStemNounPhrase(tailText) {
242
+ const [beforeComma] = String(tailText).split(",", 1);
243
+ const stripped = stripLeadingDeterminers(beforeComma);
244
+ const words = stripped.trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
245
+ if (words.length === 0 || PRONOUN_TERMS.has(words[0]) || PHRASE_BOUNDARY_WORDS.has(words[0])) return "";
246
+ return readStemNounPhrase(words);
247
+ }
248
+
249
+ // "where would you find/see/keep/put/store/place/buy/get/locate/hide/wear/
250
+ // carry/use/take/open/cross X" — the placement and possession verbs whose
251
+ // direct object is the term the question is about. Not anchored to "where":
252
+ // the same object slot holds the source term in "what would you put X into"
253
+ // too, and the verb match already carries the whole signal.
254
+ const PLACEMENT_VERB_RE = /\b(?:find|found|see|keep|put|store|place|buy|get|locate|hide|wear|carry|use|take|open|cross)\s+(.+)$/i;
255
+ const placementVerbSourceTerm = (stem) => {
256
+ const m = PLACEMENT_VERB_RE.exec(stem);
257
+ return m ? captureStemNounPhrase(m[1]) : "";
258
+ };
259
+
260
+ // "what do/does/did <subject> do/use/need/require" — the do-support shape
261
+ // CommonsenseQA's "what"-led stems lean on most: the subject sits between
262
+ // the auxiliary and the closing verb.
263
+ const WHAT_DO_SUBJECT_RE = /\bwhat\s+(?:do|does|did)\s+(.+?)\s+(?:primarily\s+)?(?:do|does|did|use|need|require)\b/i;
264
+ const whatDoSubjectSourceTerm = (stem) => {
265
+ const m = WHAT_DO_SUBJECT_RE.exec(stem);
266
+ return m ? captureStemNounPhrase(m[1]) : "";
267
+ };
268
+
269
+ // "what uses/needs/requires/has/holds/contains/involves X" — the shape
270
+ // where "what" is itself the subject and the source term is the verb's
271
+ // direct object instead.
272
+ const WHAT_VERB_OBJECT_RE = /^what\s+(?:uses|needs|requires|has|holds|contains|involves)\s+(.+)$/i;
273
+ const whatVerbObjectSourceTerm = (stem) => {
274
+ const m = WHAT_VERB_OBJECT_RE.exec(stem);
275
+ return m ? captureStemNounPhrase(m[1]) : "";
276
+ };
277
+
278
+ // "where is/are/was/were X" — the copula shape ("where is a doormat likely
279
+ // to be") that PLACEMENT_VERB_RE's action verbs never match.
280
+ const WHERE_COPULA_RE = /\bwhere\s+(?:is|are|was|were)\s+(.+)$/i;
281
+ const whereCopulaSourceTerm = (stem) => {
282
+ const m = WHERE_COPULA_RE.exec(stem);
283
+ return m ? captureStemNounPhrase(m[1]) : "";
284
+ };
178
285
 
179
- const extractStemSourceTerm = (stem) => PLACEMENT_VERB_RE.exec(stem)?.[1]?.toLowerCase() ?? "";
286
+ // "... of the/a X?" at the very end of the stem — "what is the habitat of
287
+ // the fox?" names its term in a trailing relational clause, not its subject.
288
+ const TRAILING_OF_CLAUSE_RE = /\bof\s+(?:an?|the)\s+([a-z][\w'-]*(?:\s+[a-z][\w'-]*){0,2})\s*\??\s*$/i;
289
+ const trailingOfClauseSourceTerm = (stem) => {
290
+ const m = TRAILING_OF_CLAUSE_RE.exec(stem);
291
+ return m ? captureStemNounPhrase(m[1]) : "";
292
+ };
293
+
294
+ // "... want(s/ed/ing) to <verb> [object]" — the desire-cue stems. The object
295
+ // grounds better than the bare verb when there is one ("want to open a
296
+ // steakhouse" -> "steakhouse"); the verb itself is the fallback for an
297
+ // intransitive want with nothing following it ("want to smoke?" -> "smoke").
298
+ const WANT_TO_RE = /\bwant(?:s|ed|ing)?\s+to\s+([a-z][\w'-]*)\b(.*)$/i;
299
+ const wantToSourceTerm = (stem) => {
300
+ const m = WANT_TO_RE.exec(stem);
301
+ if (!m) return "";
302
+ return captureStemNounPhrase(m[2]) || m[1].toLowerCase();
303
+ };
304
+
305
+ // ---- postponed and mid-sentence wh-shapes ----
306
+ //
307
+ // leadsInterrogative (normalize.mjs) widened its gate to recognize four
308
+ // stem shapes where the wh-word is not the stem's own first word. Passing
309
+ // that gate only says the stem is a real question — it says nothing about
310
+ // where the source term sits inside it, so each shape needs its own
311
+ // extraction template here too. Every template below reads a closed, fixed
312
+ // vocabulary (the same PHRASE_BOUNDARY_WORDS/PREP_WORDS/PRONOUN_TERMS the
313
+ // fronted templates already use) and returns "" rather than guessing when
314
+ // nothing structured is there to read.
315
+
316
+ // A subordinator or preposition opening the clause ahead of a mid-sentence
317
+ // wh-word ("During a shark filled tornado where...") is framing, not the
318
+ // source term itself.
319
+ const SUBORDINATOR_LEAD_RE = /^(?:during|while|when|if|after|before|despite|though|although|because|since|as|without|about|for|in|on|at|with)\s+/i;
320
+
321
+ const BACKWARD_SCAN_STOP_WORDS = new Set([...PHRASE_BOUNDARY_WORDS, "be", "been"]);
322
+
323
+ /** Reads the noun phrase after the first preposition found in `text` — the
324
+ * locative-object reading a declarative lead clause usually wants
325
+ * ("plopped on the bench" -> "bench") over its own grammatical subject.
326
+ * Returns "" when the clause has no preposition to anchor on. */
327
+ function captureLocativeNounPhrase(text) {
328
+ const words = String(text).trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
329
+ const idx = words.findIndex((w) => PREP_WORDS.has(w));
330
+ if (idx === -1 || idx === words.length - 1) return "";
331
+ return captureStemNounPhrase(words.slice(idx + 1).join(" "));
332
+ }
333
+
334
+ /** Reads a short noun phrase backward from the end of `leadText`, skipping
335
+ * any boundary words trailing off the very end, then collecting content
336
+ * words until the next boundary word, pronoun, or the start of the text.
337
+ * Used only when the wh-word is the stem's own last word, where nothing
338
+ * marks the start of the noun phrase the way a template's cue word
339
+ * normally does. */
340
+ function captureTrailingNounPhrase(leadText) {
341
+ const words = String(leadText).trim().toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
342
+ let end = words.length;
343
+ while (end > 0 && BACKWARD_SCAN_STOP_WORDS.has(words[end - 1])) end -= 1;
344
+ const out = [];
345
+ let i = end - 1;
346
+ while (i >= 0 && out.length < 3) {
347
+ const word = words[i];
348
+ if (BACKWARD_SCAN_STOP_WORDS.has(word) || PRONOUN_TERMS.has(word)) break;
349
+ out.unshift(word);
350
+ i -= 1;
351
+ }
352
+ if (out.length === 0) return "";
353
+ const stripped = stripLeadingDeterminers(out.join(" "));
354
+ const strippedWords = stripped.split(/\s+/).filter(Boolean);
355
+ if (strippedWords.length === 0 || PRONOUN_TERMS.has(strippedWords[0])) return "";
356
+ return stripped;
357
+ }
358
+
359
+ // "In what country are the most fast food restaurants?", "From where do
360
+ // aliens arrive?" — a wh-word fronted behind a single preposition, either
361
+ // carrying its own noun ("what country") or bare ("where"). The clause
362
+ // after the auxiliary/copula is where the source term sits.
363
+ const PREP_WH_FRONTED_CAPTURE_RE = new RegExp(
364
+ "^(?:in|at|on|from|by|with|for|of|to|off)\\s+"
365
+ + "(?:(?:what|which)\\s+[a-z][\\w'-]*|where|when|why|how|who)\\s+"
366
+ + "(?:is|are|was|were|do|does|did|can|could|should|would|will|has|have|might|must)\\s+(.+?)[?.!]*$", "i",
367
+ );
368
+ const prepWhFrontedSourceTerm = (stem) => {
369
+ const m = PREP_WH_FRONTED_CAPTURE_RE.exec(stem);
370
+ return m ? captureStemNounPhrase(m[1]) : "";
371
+ };
372
+
373
+ // "During a shark filled tornado where should you not be?" — the wh-word
374
+ // sits mid-sentence, immediately ahead of an auxiliary, with no comma to
375
+ // split on. The source term sits in the clause ahead of the wh-word; a
376
+ // stem where the wh-word is already the first word captures an empty lead
377
+ // here and falls through, since that shape is the fronted templates' own.
378
+ // A lead that itself carries a comma is the trailing-clause shape's own
379
+ // territory instead, so this declines rather than reading across the join.
380
+ const MID_SENTENCE_WH_AUX_CAPTURE_RE = new RegExp(
381
+ "^(.*?)\\b(?:what|who|which|where|when|why|how)\\s+(?:i|you|he|she|it|we|they)?\\s*"
382
+ + "(?:is|are|was|were|do|does|did|can|could|should|would|will|has|have|might|must)\\b", "i",
383
+ );
384
+ const midSentenceWhAuxSourceTerm = (stem) => {
385
+ const m = MID_SENTENCE_WH_AUX_CAPTURE_RE.exec(stem);
386
+ if (!m || !m[1].trim() || m[1].includes(",")) return "";
387
+ return captureStemNounPhrase(m[1].replace(SUBORDINATOR_LEAD_RE, ""));
388
+ };
389
+
390
+ // "The trucker plopped on the bench with a sense of relief, where did he
391
+ // arrive?" — the stem's last comma- or period-delimited clause opens with
392
+ // a question-lead word; the source term sits in the declarative clause(s)
393
+ // ahead of it. A stem with no such split (one clause only) falls through,
394
+ // since there is no "earlier" clause to read.
395
+ const trailingClauseAfterPunctuationSourceTerm = (stem) => {
396
+ const clauses = stem.split(/[.,]+/).map((c) => c.trim()).filter(Boolean);
397
+ if (clauses.length < 2) return "";
398
+ const last = clauses[clauses.length - 1];
399
+ if (!QUESTION_LEAD_RE.test(last)) return "";
400
+ const lead = clauses.slice(0, -1).join(" ");
401
+ return captureLocativeNounPhrase(lead) || captureStemNounPhrase(lead);
402
+ };
403
+
404
+ // "... you will be doing what?", "... arrived at the what?" — a bare
405
+ // wh-word, with an optional leading article, is the stem's own last word
406
+ // before the closing "?". Nothing marks where the source term starts, so
407
+ // this reads backward from the wh-word for the nearest content phrase.
408
+ const TRAILING_BARE_WH_CAPTURE_RE = /^(.*?)\b(?:an?|the)?\s*(?:what|who|which|where|when|why|how)\s*\?\s*$/i;
409
+ const trailingBareWhSourceTerm = (stem) => {
410
+ const m = TRAILING_BARE_WH_CAPTURE_RE.exec(stem);
411
+ return m ? captureTrailingNounPhrase(m[1]) : "";
412
+ };
413
+
414
+ // Note: a leading "A/An/The <subject> ..." shape is not among these
415
+ // templates. coreParse gates every input on leadsInterrogative before this
416
+ // module ever runs, and that gate's QUESTION_LEAD_RE never accepts a line
417
+ // starting with a determiner — so a stem in that shape is declined before
418
+ // reaching extractStemSourceTerm, and a template for it would never fire.
419
+ function extractStemSourceTerm(stem) {
420
+ return (
421
+ placementVerbSourceTerm(stem)
422
+ || whatDoSubjectSourceTerm(stem)
423
+ || whatVerbObjectSourceTerm(stem)
424
+ || whereCopulaSourceTerm(stem)
425
+ || trailingOfClauseSourceTerm(stem)
426
+ || wantToSourceTerm(stem)
427
+ || prepWhFrontedSourceTerm(stem)
428
+ || midSentenceWhAuxSourceTerm(stem)
429
+ || trailingClauseAfterPunctuationSourceTerm(stem)
430
+ || trailingBareWhSourceTerm(stem)
431
+ );
432
+ }
180
433
 
181
434
  function parseLabelledEnumerated(text) {
182
435
  const accepted = findAcceptedLabelSequence(text);
@@ -59,6 +59,7 @@ const isType = (p) => lower(p) === "rdf:type";
59
59
  const isDisjoint = (p) => lower(p) === "owl:disjointwith";
60
60
  const isOnProperty = (p) => lower(p) === "owl:onproperty";
61
61
  const isSomeValuesFrom = (p) => lower(p) === "owl:somevaluesfrom";
62
+ const isAllValuesFrom = (p) => lower(p) === "owl:allvaluesfrom";
62
63
  const isOnClass = (p) => lower(p) === "owl:onclass";
63
64
  const isIntersectionOf = (p) => lower(p) === "owl:intersectionof";
64
65
  const isSubPropertyOf = (p) => lower(p) === "rdfs:subpropertyof";
@@ -89,6 +90,7 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
89
90
  // value) so an axiom's `from` can cite the real stored fact id it rode. ----
90
91
  const onPropertyRow = new Map(); // restriction node -> its owl:onProperty row
91
92
  const someValuesFromRow = new Map(); // restriction node -> its owl:someValuesFrom row
93
+ const allValuesFromRow = new Map(); // restriction node -> its owl:allValuesFrom row
92
94
  const onClassRow = new Map(); // restriction node -> its owl:onClass row
93
95
  const cardinalityRow = new Map(); // restriction node -> its owl:{min,max,}cardinality row
94
96
  const intersectionRows = new Map(); // intersection node -> ordered [owl:intersectionOf row, …]
@@ -102,6 +104,10 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
102
104
  const p = r.predicate;
103
105
  if (isOnProperty(p)) { onPropertyRow.set(r.subject, r); addConcept(r.subject); }
104
106
  else if (isSomeValuesFrom(p)) { someValuesFromRow.set(r.subject, r); addConcept(r.subject); addConcept(r.object); }
107
+ // owl:allValuesFrom is left OUT of addConcept on purpose — EL has no
108
+ // universal restriction, and the restriction node it labels is stripped
109
+ // back out of `concepts` below rather than read as an atomic class.
110
+ else if (isAllValuesFrom(p)) { allValuesFromRow.set(r.subject, r); }
105
111
  else if (isOnClass(p)) { onClassRow.set(r.subject, r); addConcept(r.subject); addConcept(r.object); }
106
112
  else if (isCardinalityPredicate(p)) { cardinalityRow.set(r.subject, r); addConcept(r.subject); }
107
113
  else if (isIntersectionOf(p)) {
@@ -122,6 +128,15 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
122
128
  const someValuesFromRestrictions = new Set(
123
129
  [...onPropertyRow.keys()].filter((r) => someValuesFromRow.has(r)),
124
130
  );
131
+ // EL has no universal restriction: an owl:allValuesFrom restriction node is
132
+ // recognised only so the loop below can skip it rather than fold it in as
133
+ // an atomic concept — and it never earned a concepts entry through this
134
+ // set in the first place (onProperty's own addConcept still ran, so the
135
+ // restriction id is scrubbed back out here).
136
+ const allValuesFromRestrictions = new Set(
137
+ [...onPropertyRow.keys()].filter((r) => allValuesFromRow.has(r)),
138
+ );
139
+ for (const r of allValuesFromRestrictions) concepts.delete(r);
125
140
  const restrictionOf = new Map(); // restriction node -> { role, filler }
126
141
  for (const r of someValuesFromRestrictions) {
127
142
  restrictionOf.set(r, { role: onPropertyRow.get(r).object, filler: someValuesFromRow.get(r).object });
@@ -164,6 +179,7 @@ export function normalizeElTBox(rows, { budget = 500 } = {}) {
164
179
  axioms.push({ form: "someLeft", role: "has", filler, sup: B, from: [opRow.id, ocRow.id, cardRow.id] });
165
180
  continue;
166
181
  }
182
+ if (allValuesFromRestrictions.has(B)) continue; // no EL universal restriction — skip, never guess an atomic concept
167
183
  axioms.push({ form: "sub", sub: A, sup: B, from: [r.id] });
168
184
  }
169
185
 
@@ -477,6 +493,44 @@ export const EL_RULE_CONFIDENCE = 0.95;
477
493
  export const DEFAULT_EL_BUDGET = 2000;
478
494
  export const DEFAULT_EL_ROUNDS = 64;
479
495
 
496
+ /** The two-pass saturation `classifyEl` runs internally (plain TBox first, to
497
+ * learn each concept's real subsumer set, then goal-seeded re-saturation),
498
+ * factored out so a read-only caller — the phase-5 consistency check below,
499
+ * `elUnsatisfiableClasses` — can run the identical computation without
500
+ * `classifyEl`'s own store write. Pure, no I/O. */
501
+ function elSaturateTwoPass(rows, { budget = DEFAULT_EL_BUDGET, rounds = DEFAULT_EL_ROUNDS, focus = null } = {}) {
502
+ const normalized = normalizeElTBox(rows, { budget });
503
+ const firstPass = saturateEl(normalized, { budget, rounds, focus });
504
+ const goals = elGoalAxioms(normalized, firstPass.subsumers);
505
+ const goalInfo = new Map(goals.map((g) => [g.sup, { role: g.role, filler: g.filler }]));
506
+ const withGoals = { ...normalized, axioms: [...normalized.axioms, ...goals] };
507
+ const finalPass = saturateEl(withGoals, { budget, rounds, focus });
508
+ const truncated = normalized.truncated || firstPass.truncated || finalPass.truncated;
509
+ return { normalized, goals, goalInfo, finalPass, truncated };
510
+ }
511
+
512
+ /**
513
+ * The unsatisfiable half of an EL classification pass, with nothing written
514
+ * to the store — `classifyEl`'s own materialising write stays an explicit,
515
+ * separate step (the `/classify` command and `tmct classify`). A consistency
516
+ * report reads this instead: every class whose own subclass/intersection/
517
+ * disjointness structure saturates to `bot`, cited back to the fact ids that
518
+ * derived it. Pure, no I/O.
519
+ *
520
+ * Returns { unsatisfiable, premisesOf, truncated } — `unsatisfiable` is the
521
+ * same sorted array `classifyEl` returns from the same computation;
522
+ * `premisesOf(className)` is the ordered fact-id list its `bot` derivation
523
+ * rests on.
524
+ */
525
+ export function elUnsatisfiableClasses(rows, opts = {}) {
526
+ const { finalPass, truncated } = elSaturateTwoPass(rows, opts);
527
+ return {
528
+ unsatisfiable: finalPass.unsatisfiable,
529
+ premisesOf: (className) => finalPass.derivationOf.get(`${className}${SEP}${BOT}`) || [],
530
+ truncated,
531
+ };
532
+ }
533
+
480
534
  /**
481
535
  * Run one bounded EL classification pass over the memory graph under `repoDir`.
482
536
  * Normalizes, saturates once to find real subsumers, mints batch goals from that
@@ -500,13 +554,7 @@ export async function classifyEl(repoDir, {
500
554
  void maxEnvironments;
501
555
  const memory = await loadMemory(repoDir);
502
556
  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;
557
+ const { normalized, goals, goalInfo, finalPass, truncated } = elSaturateTwoPass(rows, { budget, rounds, focus });
510
558
 
511
559
  const trustByTriple = new Map();
512
560
  for (const r of rows) trustByTriple.set(`${r.subject}${SEP}${r.predicate}${SEP}${r.object}`, r.trust);