@polycode-projects/the-mechanical-code-talker 5.0.25 → 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.
@@ -46,7 +46,7 @@ import { setConstructionBanks } from "../domain/interpret/strategies/constructio
46
46
  import { nlpAdapter } from "../adapters/ask-nlp.mjs";
47
47
  import { readConstructionFiles } from "../adapters/corpus/construction-banks.mjs";
48
48
  import { fuzzyMatchInSet, fuzzyBound } from "../domain/interpret/fuzzy.mjs";
49
- import { loadLexicon, lookupNoun, lookupVerb, lookupAdjective, lookupProperName, readsAsIndividualName } from "../domain/grammar/lexicon.mjs";
49
+ import { loadLexicon, lookupNoun, lookupVerb, lookupAdjective, lookupProperName, readsAsIndividualName, CODE_REF_SHAPE } from "../domain/grammar/lexicon.mjs";
50
50
  import { pickPhrase } from "../domain/answer-variants.mjs";
51
51
  import {
52
52
  REFERENCE_PACK_NAME, cleanMissReferenceTerm, renderReferenceAnswer, referenceProvenanceTag,
@@ -62,6 +62,7 @@ import { loadResearchQueue, saveResearchQueue } from "../adapters/research-queue
62
62
  import { CHILD_PACK_NAME, childProvenanceTag } from "../domain/child-pack.mjs";
63
63
  import { getChildPackProvider } from "../adapters/corpus/child-pack.mjs";
64
64
  import { dialogueActForLane } from "../domain/dialogue-acts.mjs";
65
+ import { splitChoiceQuestion } from "../domain/choice-question.mjs";
65
66
  import { subClassParents, subClassChildren, descendantSet, ancestryChain, clusterSenses } from "../domain/sense-split.mjs";
66
67
  import { ANSWER_STOP_SET } from "../domain/hub-terms.mjs";
67
68
  import { relatedForTerm } from "../domain/skos-view.mjs";
@@ -3675,6 +3676,40 @@ async function isAnchorableTerm(term, lex, memoryDir, cache = null, graph = null
3675
3676
  }
3676
3677
  export { isAnchorableTerm };
3677
3678
 
3679
+ /** Per-option grounding for the closed multiple-choice lane (splitChoiceQuestion,
3680
+ * choice-question.mjs): for each option, looks for a stored Fact row whose
3681
+ * {subject, object} pair is {sourceTerm, option} in either direction, under
3682
+ * any predicate. This is PAIR-level grounding, not the term-level check
3683
+ * isAnchorableTerm runs above — almost every option answers "is this term
3684
+ * known at all", but only a stated relation between the source term and THAT
3685
+ * option decides a choice question, which is what this function tests.
3686
+ *
3687
+ * Reads the same rows the rest of chat reads (factRows/factRowsCache), and
3688
+ * pulls the child pack for `sourceTerm` ONCE per turn, only when memory holds
3689
+ * no fact for it yet — the same childPackFactsForKey the learn-on-miss
3690
+ * cascade calls elsewhere in this file. Never pulls per option: seeding the
3691
+ * graph from the question's own distractors would ground every option for
3692
+ * free, which is a slow way to guess rather than an honest probe.
3693
+ *
3694
+ * `chain` stays null on every entry here — a direct-edge probe only. A
3695
+ * bounded findIsaChain chase for an option with no direct edge is later work
3696
+ * (rung 3), which is why `graph` already rides this signature unused. */
3697
+ async function probeChoiceOptions(parsed, { memoryDir, env, cache, graph, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3698
+ const sourceVariants = factTermVariants(normFactTermStatic, parsed.sourceTerm);
3699
+ let rows = await factRows(memoryDir, cache);
3700
+ const hasSourceFacts = rows.some((f) => sourceVariants.has(f.subject) || sourceVariants.has(f.object));
3701
+ if (!hasSourceFacts && memoryDir) {
3702
+ const learned = await childPackFactsForKey(parsed.sourceTerm, { memoryDir, env, cache, synthesisBudget });
3703
+ if (learned) rows = await factRows(memoryDir, cache);
3704
+ }
3705
+ return parsed.options.map((option) => {
3706
+ const optionVariants = factTermVariants(normFactTermStatic, option.text);
3707
+ const facts = rows.filter((f) => (sourceVariants.has(f.subject) && optionVariants.has(f.object))
3708
+ || (sourceVariants.has(f.object) && optionVariants.has(f.subject)));
3709
+ return { label: option.label, text: option.text, grounds: facts.length > 0, facts, chain: null };
3710
+ });
3711
+ }
3712
+
3678
3713
  /** The "both sides ungrounded" grounding NUDGE: reuses teachSuggestion's own
3679
3714
  * "compute a hint, APPEND it to the existing honest-miss message, never
3680
3715
  * replace/silently guess" pattern (see its docblock, above, and the
@@ -5634,6 +5669,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
5634
5669
  // through to the ordinary cascade exactly as it always has.
5635
5670
  if (retractNotMatch) {
5636
5671
  const { loadMemory: loadMemForNeg, normFactTerm: normTermForNeg, readFactRows: readRowsForNeg } = await import("../adapters/memory/core.mjs");
5672
+ const { DISJOINT_PREDICATE: NEG_DISJOINT_PREDICATE } = await import("../domain/syllogise.mjs");
5637
5673
  const negSubject = normTermForNeg(retractSubject);
5638
5674
  const negObject = normTermForNeg(retractObject);
5639
5675
  const priorRows = readRowsForNeg(await loadMemForNeg(memoryDir));
@@ -5663,13 +5699,41 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
5663
5699
  // declining exactly as it always has — this widens which NOUN pairs
5664
5700
  // read as an exclusion, never which property claims do.
5665
5701
  const singularNegation = retractSrc.match(SINGULAR_NEGATION_TEACH_RE);
5666
- if (singularNegation && lookupNoun(loadLexicon(), singularNegation[2])) {
5702
+ if (singularNegation) {
5667
5703
  const [, negationSubject, negationObject] = singularNegation;
5668
- const negUniversal = await mintNegativeUniversal(negationSubject, negationObject, {
5669
- memoryDir, sessionId, observedAt, dateText,
5670
- ackText: `noted — remembered: no ${negationSubject} is a ${negationObject}`,
5671
- });
5672
- if (negUniversal) return negUniversal;
5704
+ const objectIsDeclaredNoun = !!lookupNoun(loadLexicon(), negationObject);
5705
+ // WIDENED ARM — an individual-level negative stores with no lexicon
5706
+ // entry required at all, so long as (a) the subject reads as an
5707
+ // individual — a declared proper name, a code-ref shape, or a term
5708
+ // this store already carries as an rdf:type/subClassOf subject — and
5709
+ // (b) the object is a class this store already carries (the object
5710
+ // of a taught isa fact, or either side of a taught disjointness),
5711
+ // never a bare adjective. TAUGHT facts only (never corpus background)
5712
+ // decide both checks, the same discipline isTaughtFact applies
5713
+ // elsewhere in this file — a corpus row mentioning "mortal" must never
5714
+ // be able to smuggle an adjective past the guard "zeus is not mortal"
5715
+ // keeps.
5716
+ const isTaughtRow = (r) => !String(r.provenance || "").includes("corpus:") && !String(r.provenance || "").includes("web:");
5717
+ const normNegationSubject = normTermForNeg(negationSubject);
5718
+ const normNegationObject = normTermForNeg(negationObject);
5719
+ const objectIsStoredClass = !objectIsDeclaredNoun && priorRows.some((r) => isTaughtRow(r) && (
5720
+ (ISA_PREDICATES.has(r.predicate) && r.object === normNegationObject)
5721
+ || (r.predicate === NEG_DISJOINT_PREDICATE && (r.subject === normNegationObject || r.object === normNegationObject))
5722
+ ));
5723
+ const subjectIsIndividual = objectIsStoredClass && (
5724
+ !!lookupProperName(loadLexicon(), negationSubject)
5725
+ || CODE_REF_SHAPE.test(negationSubject)
5726
+ || priorRows.some((r) => isTaughtRow(r) && r.subject === normNegationSubject && ISA_PREDICATES.has(r.predicate))
5727
+ );
5728
+ if (objectIsDeclaredNoun || subjectIsIndividual) {
5729
+ const negUniversal = await mintNegativeUniversal(negationSubject, negationObject, {
5730
+ memoryDir, sessionId, observedAt, dateText,
5731
+ ackText: objectIsDeclaredNoun
5732
+ ? `noted — remembered: no ${negationSubject} is a ${negationObject}`
5733
+ : `noted — remembered: ${negationSubject} is not a ${negationObject}`,
5734
+ });
5735
+ if (negUniversal) return negUniversal;
5736
+ }
5673
5737
  }
5674
5738
 
5675
5739
  // Nothing stored to disagree with. The gate above is right to refuse
@@ -7418,6 +7482,7 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7418
7482
  ["/capabilities", "what /plan can plan over: the built-in graph tools plus your taught actions"],
7419
7483
  ["/goals", "the goals a trace can be recognized against: the maintenance invariants, the tool goals, this world's objective, and your taught actions"],
7420
7484
  ["/syllogise <term>", "work out and remember what follows from the facts about a term (needed for chains longer than 2 hops)"],
7485
+ ["/classify <term>", "run the EL classifier and remember what follows from a term (reaches restriction-shaped conclusions /syllogise's chains can't)"],
7421
7486
  ["/export <path>", "write the memory store to a file, as JSONL (the same shape `tmct memory --export` writes)"],
7422
7487
  ["/ingest <path>", "read a local text file and store every fact the recognizer grounds from it (same recognizer as `tmct extract`)"],
7423
7488
  ["remember <X> is a <Y>", "teach a fact in plain English (\"every X is a Y\" and a bare \"X is a Y\" work too)"],
@@ -7586,6 +7651,10 @@ const FACT_PREDICATE_PHRASES = {
7586
7651
  "mgxneg:subClassOf": "is not a kind of",
7587
7652
  "rdf:type": "is a",
7588
7653
  "owl:disjointWith": "is not a",
7654
+ "owl:unionOf": "is either",
7655
+ "owl:complementOf": "is anything that is not",
7656
+ "owl:oneOf": "includes exactly",
7657
+ "owl:differentFrom": "is not the same as",
7589
7658
  "mgx:partOf": "is part of",
7590
7659
  "mgx:memberOf": "is a member of",
7591
7660
  "mgx:collectionOf": "is a collection of",
@@ -7639,6 +7708,15 @@ const WORLD_INTERNAL_PREDICATES = new Set([
7639
7708
  "mgx:is-container", "mgx:is-open",
7640
7709
  ]);
7641
7710
 
7711
+ /** A `<role> rdf:type owl:TransitiveProperty` declaration is role scaffolding,
7712
+ * not a fact about the role a reader wants listed back in English — it never
7713
+ * renders as a plain fact line, the same discipline that keeps the
7714
+ * restriction scaffolding predicates (owl:onProperty, owl:someValuesFrom, …)
7715
+ * out of FACT_PREDICATE_PHRASES. */
7716
+ function isTransitivePropertyDeclaration(f) {
7717
+ return f.predicate === TYPE_PREDICATE && f.object === "transitiveproperty";
7718
+ }
7719
+
7642
7720
  /** The world PLACEMENT predicates carry curated phrases above so they render as
7643
7721
  * English, but they must stay OUT of the query-marker families derived from
7644
7722
  * FACT_PREDICATE_PHRASES — "what is in the study" is a members-of-class query,
@@ -7805,6 +7883,41 @@ function renderFactLine(f) {
7805
7883
  return `i learned: ${factPhrase(f)}${cite}`;
7806
7884
  }
7807
7885
 
7886
+ /** A union node's stored triples read back as ONE sentence rather than a
7887
+ * row-per-member dump: "every pet is a cat or a dog (source: …)". `node` is
7888
+ * the `<parent> rdfs:subClassOf <unionNode>` fact row (the parent and the
7889
+ * citation both come from it); `members` are the union node's own
7890
+ * `owl:unionOf` rows, sorted here by member name so the same union always
7891
+ * reads back the same way regardless of the order its rows arrived in.
7892
+ * Pure — takes the fact rows, returns one line. */
7893
+ function renderUnionLine(node, members) {
7894
+ const sorted = [...members].sort((a, b) => a.object.localeCompare(b.object));
7895
+ const cite = node.provenance ? ` (source: ${citationProvenance(node.provenance)})` : "";
7896
+ const arms = sorted.map((m) => `${indefiniteArticleFor(m.object)} ${m.object}`).join(" or ");
7897
+ return `every ${node.subject} is ${arms}${cite}`;
7898
+ }
7899
+
7900
+ /** An enumerated class's stored `owl:oneOf` triples read back as ONE sentence:
7901
+ * "the primary colours are exactly red, yellow and blue (source: …)". `cls`
7902
+ * is the enumerated class's own term; `members` are its `owl:oneOf` rows,
7903
+ * sorted here by member name for the same order-independence renderUnionLine
7904
+ * keeps. The class name pluralizes through the same naive "+s/+es/+ies" fold
7905
+ * thirdPersonSingularSurface already applies to a verb lemma — the same
7906
+ * accepted trade documented there. Pure — takes the fact rows, returns one
7907
+ * line. */
7908
+ function renderEnumerationLine(cls, members) {
7909
+ const sorted = [...members].sort((a, b) => a.object.localeCompare(b.object));
7910
+ const names = sorted.map((m) => m.object);
7911
+ const list = names.length > 1
7912
+ ? `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`
7913
+ : names.join("");
7914
+ const citeSource = sorted.find((m) => m.provenance)?.provenance;
7915
+ const cite = citeSource ? ` (source: ${citationProvenance(citeSource)})` : "";
7916
+ const plural = thirdPersonSingularSurface(String(cls || "").replace(/-/g, " "));
7917
+ return `the ${plural} are exactly ${list}${cite}`;
7918
+ }
7919
+ export { renderUnionLine, renderEnumerationLine };
7920
+
7808
7921
  const SENSE_CITE_RE = / \(source: [^)]*\)$/;
7809
7922
 
7810
7923
  /** Append an is-a object's superclass chain to its rendered fact line, before
@@ -8426,6 +8539,14 @@ function apposedFactTerm(term, rows, normFactTerm) {
8426
8539
  * factReadBack(...)` — never both). */
8427
8540
  const CAN_ASK_RE = /^(?:can|could)\s+(all\s+|every\s+)?(?:an?\s+)?([\w'-]+(?:\s+[\w'-]+)*?)\s+([a-z]+)[?.!\s]*$/i;
8428
8541
  const DOES_HAVE_ASK_RE = /^(?:does|do)\s+(?:an?\s+|the\s+)?(.+?)\s+have\s+(?:an?\s+|the\s+)?(.+?)[?.!\s]*$/i;
8542
+ /** The class-level existential sibling of DOES_HAVE_ASK_RE for a verb OTHER
8543
+ * than "have" — "does a heart contain a hinge". A someValuesFrom
8544
+ * restriction (taught, or EL-entailed by /classify) never cares which
8545
+ * English near-synonym for "has" named it, and the store carries no
8546
+ * per-verb sense distinction for this shape yet, so restrictionExistentialHit
8547
+ * answers on the (subject, filler) SHAPE alone, tried only once
8548
+ * DOES_HAVE_ASK_RE's own literal-"have" reader has already declined. */
8549
+ const DOES_EXISTENTIAL_ASK_RE = /^(?:does|do)\s+(?:an?\s+|the\s+)?(.+?)\s+([a-z]+)\s+(?:an?\s+|the\s+)?(.+?)[?.!\s]*$/i;
8429
8550
  const WHAT_CAN_DO_RE = /^what\s+can\s+(?:an?\s+)?(.+?)\s+do[?.!\s]*$/i;
8430
8551
  const WHAT_HAS_RE = /^what\s+has\s+(?:an?\s+)?(.+?)[?.!\s]*$/i;
8431
8552
  // "what is used for riding" / "what can be used for riding" / "what is for
@@ -8828,6 +8949,61 @@ function withDeducedGoal(res, envelope, query) {
8828
8949
  return goal ? { ...res, goal } : res;
8829
8950
  }
8830
8951
 
8952
+ /** The class-level existential mirror of a direct hasA/tmct:has fact: a
8953
+ * stored (taught, or EL-entailed by /classify) someValuesFrom restriction
8954
+ * reachable from the subject names the filler. Runs off `factRows` rather
8955
+ * than the reduced `memoryFacts` shape because the citation needs each
8956
+ * hit's own `justification` — an EL-derived restriction cites the taught
8957
+ * premises it composed (e.g. "heart is a kind of some-has-valve; valve is a
8958
+ * kind of flap"), not just its own single entailed row. Falls back to
8959
+ * citing the hit itself when no subClassOf premise is on record (a directly
8960
+ * taught, unchained restriction). Returns the rendered `{text,
8961
+ * replace: true}` yes turn on a hit. On a miss, `subjectWord` (the surface
8962
+ * text the question named the subject with) decides the reply: the subject
8963
+ * has SOME remembered restriction that just doesn't reach this filler, so
8964
+ * the miss names `/classify` — the one command that can compose further
8965
+ * ("/syllogise" is never offered here, since its plain scm-sco chase never
8966
+ * touches a class expression) — or, with no restriction on the subject at
8967
+ * all, plain null so the caller's own miss cascade stands unchanged. */
8968
+ async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fillerVariants, subjectWord = null) {
8969
+ const { ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE } = await import("../domain/syllogise.mjs");
8970
+ const rows = await factRows(memoryDir, cache);
8971
+ const onPropertyOf = new Map();
8972
+ const someValuesFromOf = new Map();
8973
+ for (const r of rows) {
8974
+ if (r.predicate === ON_PROPERTY_PREDICATE) onPropertyOf.set(r.subject, r.object);
8975
+ else if (r.predicate === SOME_VALUES_FROM_PREDICATE) someValuesFromOf.set(r.subject, r.object);
8976
+ }
8977
+ // Restricted to a genuine someValuesFrom restriction — onProperty alone
8978
+ // also marks a cardinality restriction (owl:maxCardinality/minCardinality/
8979
+ // cardinality, no someValuesFrom row of its own), which classifyEl's EL
8980
+ // rules never touch; offering /classify over one would be wrong advice,
8981
+ // and it would also swallow a query the cardinality live chases
8982
+ // (factReadBackReaders' CARD_AT_LEAST_ASK_RE/CARD_EXISTENCE_ASK_RE) are
8983
+ // the ones meant to answer, including a provable "no".
8984
+ const subjectRestrictions = rows.filter((r) => r.predicate === SUBCLASS_PREDICATE && subjectVariants.has(r.subject)
8985
+ && onPropertyOf.has(r.object) && someValuesFromOf.has(r.object));
8986
+ const hit = subjectRestrictions
8987
+ .filter((r) => fillerVariants.has(someValuesFromOf.get(r.object)))
8988
+ .sort((a, b) => a.object.localeCompare(b.object))[0];
8989
+ if (hit) {
8990
+ const byId = new Map(rows.map((r) => [r.id, r]));
8991
+ const premises = (hit.justification || [])
8992
+ .map((id) => byId.get(id))
8993
+ .filter((r) => r && r.predicate === SUBCLASS_PREDICATE);
8994
+ const cited = premises.length ? premises : [hit];
8995
+ return { text: `yes — ${cited.map(renderFactLine).join("; ")}`, replace: true };
8996
+ }
8997
+ if (subjectRestrictions.length && subjectWord) {
8998
+ return {
8999
+ text: `I can't confirm that — nothing I remember composes to it yet. Run "/classify ${subjectWord}", then ask me again.`,
9000
+ replace: true,
9001
+ miss: true,
9002
+ };
9003
+ }
9004
+ return null;
9005
+ }
9006
+
8831
9007
  async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle = {}, cache = null, focusLabel = null) {
8832
9008
  let normFactTerm; let normFactPredicate;
8833
9009
  try { ({ normFactTerm, normFactPredicate } = await import("../adapters/memory/core.mjs")); } catch { return null; }
@@ -9167,7 +9343,7 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9167
9343
  // and mechanics predicates are dropped so "what is the letter" never reads
9168
9344
  // back where it's hidden or that it's the objective (WORLD_INTERNAL_PREDICATES).
9169
9345
  const subjectHits = (await factRows(memoryDir, cache))
9170
- .filter((f) => variants.has(f.subject) && !WORLD_INTERNAL_PREDICATES.has(f.predicate));
9346
+ .filter((f) => variants.has(f.subject) && !WORLD_INTERNAL_PREDICATES.has(f.predicate) && !isTransitivePropertyDeclaration(f));
9171
9347
  // Matched through normFactPredicate, so a fact stored under a minted
9172
9348
  // spelling of the same relation ("mgx:used-for", from the participle
9173
9349
  // teach frame, in a store written before the spellings converged) is
@@ -9452,7 +9628,24 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9452
9628
  if (!nextFrontier.length) break;
9453
9629
  frontier = nextFrontier;
9454
9630
  }
9455
- return null;
9631
+ // No direct or ⊑-lifted possession fact — a bare-existential teach or an
9632
+ // EL classification stores the SAME knowledge as a subClassOf-to-
9633
+ // restriction chain rather than a flat possession triple, so try that
9634
+ // shape before declining.
9635
+ return restrictionExistentialHit(memoryDir, cache, subj, obj, doesHave[1].trim());
9636
+ }
9637
+
9638
+ // (b2b-el) "does a heart contain a hinge" — DOES_HAVE_ASK_RE only ever
9639
+ // matches the literal verb "have"; a class-level existential question can
9640
+ // use any near-synonym, so this sibling reader tries the SAME restriction
9641
+ // chase restrictionExistentialHit runs above, keyed on shape alone, once
9642
+ // (b2b)'s own literal-"have" surface has already declined to match at all.
9643
+ const doesExistential = q.match(DOES_EXISTENTIAL_ASK_RE);
9644
+ if (doesExistential) {
9645
+ const subj = factTermVariants(normFactTerm, doesExistential[1]);
9646
+ const obj = factTermVariants(normFactTerm, doesExistential[3]);
9647
+ const hit = await restrictionExistentialHit(memoryDir, cache, subj, obj, doesExistential[1].trim());
9648
+ if (hit) return hit;
9456
9649
  }
9457
9650
 
9458
9651
  // (b2c) "do birds fly" — the do-support surface of (b2), same capableOf
@@ -9773,7 +9966,7 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9773
9966
  // objective, and those datatype internals render as garbled non-English
9774
9967
  // besides. The adventure's own where/openness readers answer the legitimate
9775
9968
  // in-game questions from the world fold.
9776
- hits = hits.filter((f) => !WORLD_INTERNAL_PREDICATES.has(f.predicate));
9969
+ hits = hits.filter((f) => !WORLD_INTERNAL_PREDICATES.has(f.predicate) && !isTransitivePropertyDeclaration(f));
9777
9970
  // A corpus-weak-only result set (every hit resolved ONLY through
9778
9971
  // ConceptNet's /r/RelatedTo tier) still composes its hedged "possibly"
9779
9972
  // lines below exactly as before — this reader's whole job is showing
@@ -11123,9 +11316,29 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
11123
11316
  );
11124
11317
  if (knownSubjectIsa.length) {
11125
11318
  const shown = knownSubjectIsa.slice(0, 3).map(renderFactLine).join("; ");
11126
- const recovery = deeperChainExists
11127
- ? `The facts to settle it are here, but the chain is longer than I follow while answering. Run "/syllogise ${subjectWord}", then ask me again.`
11128
- : `If it's true, teach me: "${subjectWord} is a kind of ${kindWord}". If it isn't, teach me: "no ${subjectWord} is a ${kindWord}".`;
11319
+ // A someValuesFrom restriction node among the subject's own remembered
11320
+ // isa facts means the gap is a class expression /syllogise's plain
11321
+ // scm-sco chase never reaches — /classify is the offer that can
11322
+ // actually close it, named instead of /syllogise rather than beside
11323
+ // it, so the offer never points at a command that provably can't help.
11324
+ // A CARDINALITY restriction (owl:maxCardinality/minCardinality/
11325
+ // cardinality, also onProperty-bearing but with no someValuesFrom row
11326
+ // of its own) is excluded on purpose: classifyEl's rules don't touch
11327
+ // that shape either.
11328
+ const { ON_PROPERTY_PREDICATE: RESTRICTION_ON_PROPERTY, SOME_VALUES_FROM_PREDICATE: RESTRICTION_SOME_VALUES_FROM } = await import("../domain/syllogise.mjs");
11329
+ const onPropertyNodes = new Set();
11330
+ const someValuesFromNodes = new Set();
11331
+ for (const f of rows) {
11332
+ if (f.predicate === RESTRICTION_ON_PROPERTY) onPropertyNodes.add(f.subject);
11333
+ else if (f.predicate === RESTRICTION_SOME_VALUES_FROM) someValuesFromNodes.add(f.subject);
11334
+ }
11335
+ const restrictionNodes = new Set([...onPropertyNodes].filter((n) => someValuesFromNodes.has(n)));
11336
+ const involvesRestriction = knownSubjectIsa.some((f) => restrictionNodes.has(f.object));
11337
+ const recovery = involvesRestriction
11338
+ ? `The facts to settle it are here, but reaching it means composing a restriction /syllogise doesn't follow. Run "/classify ${subjectWord}", then ask me again.`
11339
+ : deeperChainExists
11340
+ ? `The facts to settle it are here, but the chain is longer than I follow while answering. Run "/syllogise ${subjectWord}", then ask me again.`
11341
+ : `If it's true, teach me: "${subjectWord} is a kind of ${kindWord}". If it isn't, teach me: "no ${subjectWord} is a ${kindWord}".`;
11129
11342
  return {
11130
11343
  text: `I can't confirm that — nothing I remember says ${subjectWord} is a ${kindWord}. I do know: ${shown}. ${recovery}`,
11131
11344
  replace: true,
@@ -12318,26 +12531,107 @@ async function ingestReferenceArticle(memoryDir, key, article, cache, tagFor = r
12318
12531
  // materialisation, not the whole-store maintenance job /syllogise runs.
12319
12532
  const AUTO_SYNTHESIS_BUDGET = 12;
12320
12533
 
12534
+ /** The `[reasoning]` knobs for a classification pass rooted at `memoryDir` —
12535
+ * the repo's own `tmct.toml` when it sets one, the shipped defaults
12536
+ * otherwise. `resolveReasoningConfig` wants the NORMALIZED sparse pass-
12537
+ * through `normalizeConfig` produces (a bare `loadTomlConfig` object has no
12538
+ * `.reasoning` key of its own), the same load-then-normalize sequence the
12539
+ * CLI's own `resolveRuntimeConfig` already runs. Failure-tolerant: a missing
12540
+ * or unreadable `tmct.toml` degrades to the defaults, never a thrown error. */
12541
+ async function resolveReasoningConfigForRepo(memoryDir) {
12542
+ const { resolveReasoningConfig } = await import("../domain/reasoning-config.mjs");
12543
+ try {
12544
+ const { loadTomlConfig, normalizeConfig } = await import("../adapters/toml-config.mjs");
12545
+ const raw = await loadTomlConfig(memoryDir);
12546
+ const normalized = await normalizeConfig(raw, { configDir: memoryDir });
12547
+ return resolveReasoningConfig(normalized);
12548
+ } catch {
12549
+ return resolveReasoningConfig(null);
12550
+ }
12551
+ }
12552
+
12553
+ /** The focus set classifyEl needs to reach a bare-existential or transitive-
12554
+ * role chain rooted at `seedTerms`: each seed's own `rdfs:subClassOf`
12555
+ * descendant walk, folded through every someValuesFrom restriction it
12556
+ * reaches onto that restriction's own filler, walked again from there — so
12557
+ * a taught "heart ⊑ ∃has.valve, valve ⊑ ∃has.hinge" reaches both `valve`
12558
+ * and `hinge` from a focus seeded on `heart` alone. classifyEl's own focus
12559
+ * gate takes its input as given (unlike syllogise's `expandFocus`, it has no
12560
+ * expansion step of its own), so this walk runs here rather than inside the
12561
+ * classifier. Bounded by `hops`. Pure. */
12562
+ function elClassifyFocus(rows, seedTerms, onPropertyPredicate, someValuesFromPredicate, hops = 8) {
12563
+ const subClassOf = new Map();
12564
+ const onPropertyOf = new Map();
12565
+ const someValuesFromOf = new Map();
12566
+ for (const r of rows) {
12567
+ if (r.predicate === SUBCLASS_PREDICATE) {
12568
+ if (!subClassOf.has(r.subject)) subClassOf.set(r.subject, []);
12569
+ subClassOf.get(r.subject).push(r.object);
12570
+ } else if (r.predicate === onPropertyPredicate) {
12571
+ onPropertyOf.set(r.subject, r.object);
12572
+ } else if (r.predicate === someValuesFromPredicate) {
12573
+ someValuesFromOf.set(r.subject, r.object);
12574
+ }
12575
+ }
12576
+ const focus = new Set(seedTerms);
12577
+ let frontier = [...focus];
12578
+ for (let hop = 0; hop < hops && frontier.length; hop += 1) {
12579
+ const next = [];
12580
+ for (const t of frontier) {
12581
+ for (const obj of subClassOf.get(t) || []) {
12582
+ if (!focus.has(obj)) { focus.add(obj); next.push(obj); }
12583
+ const filler = onPropertyOf.has(obj) ? someValuesFromOf.get(obj) : null;
12584
+ if (filler && !focus.has(filler)) { focus.add(filler); next.push(filler); }
12585
+ }
12586
+ }
12587
+ frontier = next;
12588
+ }
12589
+ return focus;
12590
+ }
12591
+
12321
12592
  /** After a learn-on-miss load stored new facts about `term`, run a bounded,
12322
12593
  * focus-scoped forward-chaining pass so the new facts connect to what's
12323
- * already remembered — the auto sibling of the /syllogise command. Derived
12594
+ * already remembered — the auto sibling of the /syllogise command, plus its
12595
+ * EL sibling (the auto sibling of /classify): the same seed focus feeds
12596
+ * both, syllogise expanding it through its own `expandFocus`, classifyEl
12597
+ * through `elClassifyFocus` since it has no such option of its own. Derived
12324
12598
  * facts carry entailed:* provenance at their discounted trust and are
12325
- * retractable. Failure-tolerated: a synthesis miss never disturbs the answer
12326
- * the load already composed. Returns the count derived. */
12599
+ * retractable. Both passes are failure-tolerated and independent of each
12600
+ * other: neither a syllogise miss nor an EL miss disturbs the answer the
12601
+ * load already composed, or the other pass's own result. Returns the total
12602
+ * count derived across both. */
12327
12603
  async function synthesiseAroundTerm(memoryDir, term, cache, budget = AUTO_SYNTHESIS_BUDGET) {
12328
12604
  if (!memoryDir || !term || budget <= 0) return 0;
12605
+ let count = 0;
12329
12606
  try {
12330
12607
  const { syllogise } = await import("../domain/syllogise.mjs");
12331
12608
  const { loadMemory, readFactRows, appendFacts, normFactTerm } = await import("../adapters/memory/core.mjs");
12609
+ const seedFocus = [...factTermVariants(normFactTerm, term)];
12332
12610
  const res = await syllogise(memoryDir, {
12333
- focus: [...factTermVariants(normFactTerm, term)],
12611
+ focus: seedFocus,
12334
12612
  expandFocus: true,
12335
12613
  budget,
12336
12614
  store: { loadMemory, readFactRows, appendFacts },
12337
12615
  });
12338
- if (res?.count && cache) cache.rows = null;
12339
- return res?.count || 0;
12340
- } catch { return 0; }
12616
+ if (res?.count) { count += res.count; if (cache) cache.rows = null; }
12617
+ } catch { /* a syllogise miss never disturbs the answer the load already composed */ }
12618
+ try {
12619
+ const { classifyEl } = await import("../domain/el-classify.mjs");
12620
+ const { ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE } = await import("../domain/syllogise.mjs");
12621
+ const { loadMemory, readFactRows, appendFacts, normFactTerm } = await import("../adapters/memory/core.mjs");
12622
+ const seedFocus = [...factTermVariants(normFactTerm, term)];
12623
+ const rows = readFactRows(await loadMemory(memoryDir));
12624
+ const focus = elClassifyFocus(rows, seedFocus, ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE);
12625
+ const reasoning = await resolveReasoningConfigForRepo(memoryDir);
12626
+ const elRes = await classifyEl(memoryDir, {
12627
+ budget: reasoning.classifyBudget,
12628
+ rounds: reasoning.classifyRounds,
12629
+ focus,
12630
+ store: { loadMemory, readFactRows, appendFacts },
12631
+ });
12632
+ if (elRes?.count) { count += elRes.count; if (cache) cache.rows = null; }
12633
+ } catch { /* an EL pass miss never disturbs the answer the load already composed */ }
12634
+ return count;
12341
12635
  }
12342
12636
 
12343
12637
  /** The term an explicit "ask Wikipedia" phrasing names — "what does wikipedia
@@ -15948,6 +16242,54 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15948
16242
  }
15949
16243
  }
15950
16244
 
16245
+ // /classify <term> — run one bounded EL saturation pass (src/domain/el-
16246
+ // classify.mjs) over what's remembered about a term and WRITE the entailed
16247
+ // facts it closes over. /syllogise's own rule set only chains
16248
+ // rdfs:subClassOf/rdf:type edges; /classify's seven EL completion rules
16249
+ // additionally reach class expressions the graph never declared as a node
16250
+ // (an owl:someValuesFrom restriction), so the two commands cover different
16251
+ // ground rather than one superseding the other. Same posture as
16252
+ // /syllogise: an explicit request, a required term (the whole-store pass
16253
+ // spends its budget on facts nobody asked about), and every written fact
16254
+ // carries entailed:el-* provenance, a justification and a trust discounted
16255
+ // below the premises it rode.
16256
+ if (name === "classify") {
16257
+ note(trace, "goal: classify what's remembered about one term under the EL completion rules, writing what follows");
16258
+ if (!memoryDir) return mk("no memory store here — /classify works inside a repo session.", { miss: true });
16259
+ if (!argText) {
16260
+ return mk('/classify needs a term, e.g. `/classify heart` — it closes over what I remember about that term.', { miss: true });
16261
+ }
16262
+ try {
16263
+ const { classifyEl } = await import("../domain/el-classify.mjs");
16264
+ const { loadMemory, readFactRows, appendFacts, normFactTerm } = await import("../adapters/memory/core.mjs");
16265
+ const { SUBCLASS_PREDICATE, ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE } = await import("../domain/syllogise.mjs");
16266
+ const reasoning = await resolveReasoningConfigForRepo(memoryDir);
16267
+ const rows = readFactRows(await loadMemory(memoryDir));
16268
+ const focus = elClassifyFocus(rows, [...factTermVariants(normFactTerm, argText)], ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE);
16269
+ const res = await classifyEl(memoryDir, {
16270
+ budget: reasoning.classifyBudget,
16271
+ rounds: reasoning.classifyRounds,
16272
+ focus,
16273
+ store: { loadMemory, readFactRows, appendFacts },
16274
+ });
16275
+ note(trace, `result: derived ${res.count} entailed fact(s) (rounds ${res.rounds}, budget ${res.budget})`);
16276
+ if (!res.count) {
16277
+ return mk(`nothing new classifies from what I remember about "${argText}" — no entailed facts derived (rounds ${res.rounds}, budget ${res.budget}).`, { miss: true });
16278
+ }
16279
+ const lines = [`derived ${res.count} entailed fact(s) classifying "${argText}":`];
16280
+ for (const d of res.derived) lines.push(` ${d.subject} ${SUBCLASS_PREDICATE} ${d.object} (${d.rule})`);
16281
+ // Same reasoning as /syllogise's own budget-wall line: a truncated pass
16282
+ // that still can't answer the question is worse than no offer at all.
16283
+ if (res.truncated) {
16284
+ lines.push(`budget of ${res.budget} reached — more may follow; run \`tmct classify --budget <n>\` for a wider pass.`);
16285
+ }
16286
+ lines.push("These are derived, not taught — /memory shows each one's provenance and premises.");
16287
+ return mk(lines.join("\n"));
16288
+ } catch (e) {
16289
+ return mk(String(e?.message || e), { miss: true }); // a broken store reads as its own clean error
16290
+ }
16291
+ }
16292
+
15951
16293
  // /export <path> — write the whole memory store as JSONL, the SAME shape
15952
16294
  // `tmct memory --export` and the tmct_export cold tool already emit
15953
16295
  // (serializeFactsJsonl, export-jsonl.mjs) — so a chat session can take its
@@ -17533,6 +17875,64 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
17533
17875
  }
17534
17876
 
17535
17877
  if (workingLine.startsWith("/")) return withLast(await runCommand(workingLine, ctx), "use a specific tool/command directly");
17878
+ // CLOSED MULTIPLE-CHOICE — "is a whale a fish or a mammal", "A) ... B) ...".
17879
+ // Recognized and answered ENTIRELY here, before the write boundary just
17880
+ // below (assertTurn/bareTaxonomyTeach): a choice question's own object slot
17881
+ // carries "or", and falling through would hand that slot to the teach-offer
17882
+ // cascade, which reads it as a thing to be taught — the same failure mode
17883
+ // TEMPORAL_COMPARISON_RE (runAsk, above) exists to dodge for its own shape.
17884
+ // Placed here rather than beside the temporal lanes in runAsk (the closer
17885
+ // stylistic precedent) because runAsk's own band sits AFTER this boundary —
17886
+ // a choice question routed there would still pass through assertTurn first,
17887
+ // resting the write-boundary guarantee on teachLane's own stand-down gates
17888
+ // rather than on control flow. Every branch below resolves the turn; none
17889
+ // falls through, so the boundary holds structurally.
17890
+ {
17891
+ const parsed = splitChoiceQuestion(workingLine);
17892
+ if (parsed) {
17893
+ const choiceGoal = "pick the option a stated relation grounds, among a closed set of alternatives";
17894
+ const refMiss = (text) => {
17895
+ note(trace, `goal: ${choiceGoal}`);
17896
+ note(trace, `lane: splitChoiceQuestion — "${workingLine}" parsed as a ${parsed.shape} choice question but could not compose an answer`);
17897
+ return withLast(plainTurn(workingLine, text, { via: "miss", miss: true, focus, goal: choiceGoal }), choiceGoal);
17898
+ };
17899
+ if (!parsed.sourceTerm) {
17900
+ return refMiss(`I can't tell what these options are alternatives about — nothing in "${parsed.stem}" reads as a subject term to check them against.`);
17901
+ }
17902
+ const probed = await probeChoiceOptions(parsed, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
17903
+ const grounded = probed.filter((o) => o.grounds);
17904
+ note(trace, `goal: ${choiceGoal}`);
17905
+ if (grounded.length === 0) {
17906
+ note(trace, `lane: splitChoiceQuestion — no stated relation between "${parsed.sourceTerm}" and any of ${probed.length} options; the honest miss, never a guess`);
17907
+ return refMiss(`I don't know how "${parsed.sourceTerm}" relates to any of ${joinOr(probed.map((o) => o.text))}. Nothing I hold connects it to one of them.`);
17908
+ }
17909
+ if (grounded.length > 1) {
17910
+ // A tie is reported, never broken — whatever the grounded options'
17911
+ // own edge weights, this branch fires on COUNT alone.
17912
+ note(trace, `lane: splitChoiceQuestion — ${grounded.length} of ${probed.length} options ground against "${parsed.sourceTerm}"; reported as a tie`);
17913
+ const text = `More than one of those grounds: ${joinOr(grounded.map((o) => o.text))}. I have a stated relation from ${parsed.sourceTerm} to each, so nothing in what I hold picks between them.`;
17914
+ const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
17915
+ turn.lane = "ask-choice";
17916
+ turn.detail = {
17917
+ traversal: `${grounded.length} of ${probed.length} options grounded against "${parsed.sourceTerm}"`,
17918
+ matches: grounded.flatMap((o) => o.facts),
17919
+ };
17920
+ return withLast(turn, choiceGoal);
17921
+ }
17922
+ const winner = grounded[0];
17923
+ const fact = winner.facts.slice().sort((a, b) => b.trust - a.trust)[0];
17924
+ note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding fact`);
17925
+ const text = `${winner.text} — ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)}).`;
17926
+ const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
17927
+ turn.lane = "ask-choice";
17928
+ turn.detail = {
17929
+ traversal: `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`,
17930
+ matches: winner.facts,
17931
+ selectedLabel: winner.label,
17932
+ };
17933
+ return withLast(turn, choiceGoal);
17934
+ }
17935
+ }
17536
17936
  // Declarative ACE sentences ("every module is a artifact") ASSERT into tmct's
17537
17937
  // own memory and confirm — they are statements to remember, not graph queries.
17538
17938
  // Gated on memoryDir: only a session shell provides a write target, so a bare