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

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.
@@ -70,7 +70,7 @@ import { newsTurn, resolveNewsConfig, NEWS_DEFAULTS, createNewsState } from "./n
70
70
  import { CHILD_PACK_NAME, childProvenanceTag } from "../domain/child-pack.mjs";
71
71
  import { getChildPackProvider } from "../adapters/corpus/child-pack.mjs";
72
72
  import { dialogueActForLane } from "../domain/dialogue-acts.mjs";
73
- import { splitChoiceQuestion } from "../domain/choice-question.mjs";
73
+ import { splitChoiceQuestion, routeChoiceRelation, lemmaFoldVariants, headNounOf } from "../domain/choice-question.mjs";
74
74
  import { subClassParents, subClassChildren, descendantSet, ancestryChain, clusterSenses } from "../domain/sense-split.mjs";
75
75
  import { ANSWER_STOP_SET } from "../domain/hub-terms.mjs";
76
76
  import { relatedForTerm } from "../domain/skos-view.mjs";
@@ -3703,9 +3703,96 @@ export { isAnchorableTerm };
3703
3703
  * graph from the question's own distractors would ground every option for
3704
3704
  * free, which is a slow way to guess rather than an honest probe.
3705
3705
  *
3706
- * `chain` stays null on every entry here — a direct-edge probe only. A
3707
- * bounded findIsaChain chase for an option with no direct edge is later work
3708
- * (rung 3), which is why `graph` already rides this signature unused. */
3706
+ * ROUTING (rung 2): `routeChoiceRelation` (choice-question.mjs) reads the
3707
+ * relation family the STEM itself names — "where" cues AtLocation, "part of"
3708
+ * cues PartOf/HasA/MadeOf, and so on, a closed cue table ordered by measured
3709
+ * yield on the committed fixture. When a route fires, an edge only grounds
3710
+ * an option if its predicate is IN that family — an edge under some other
3711
+ * predicate is no longer "a stated relation", it is the WRONG stated
3712
+ * relation, and the whole point of routing is to stop counting that as
3713
+ * evidence. A stem naming no relation at all (routeChoiceRelation returns
3714
+ * null) falls back to the unrouted any-predicate probe, unchanged.
3715
+ *
3716
+ * CHAIN FALLBACK (rung 3): an option with no direct edge gets one more
3717
+ * chance — findIsaChain (syllogise.mjs), the SAME bounded rooted proof
3718
+ * search the isa lanes already cite, chases from every spelling of
3719
+ * sourceTerm toward the option over the store's own rdf:type/rdfs:subClassOf
3720
+ * edges, maxHops:2 (its usual live-chase bound). `chain`, when non-null, is
3721
+ * the ORDERED ARRAY OF FACT ROWS the chase proved, every one of them a real
3722
+ * stored row so the citation never names a step nothing backs — the same
3723
+ * `premises.every(Boolean)` discipline the isa lanes use before returning a
3724
+ * chain answer. The routing filter above does not apply to the chain: a
3725
+ * relation family cues a DIRECT edge's predicate, and findIsaChain only ever
3726
+ * walks the isa family, a different axis entirely.
3727
+ *
3728
+ * WORDING (rung 4): an option's variant set is TAGGED, not just widened —
3729
+ * `choiceTermTags` maps every spelling the option could be read as back to
3730
+ * the mechanism that produced it ("exact" for factTermVariants' own plural
3731
+ * fold, "lemma" for lemmaFoldVariants' regular -ing/-ed reversal), so a
3732
+ * grounded fact's `matchedBy` says HOW it matched, not just THAT it did.
3733
+ * HEAD-NOUN BACKOFF is a second, separate pass: only when the full phrase
3734
+ * (exact + lemma) finds NOTHING does a multi-word option retry under its
3735
+ * head noun alone (`headNounOf`, choice-question.mjs) — "fast food
3736
+ * restaurant" retries as "restaurant". Bounded to the head only, never
3737
+ * every sub-phrase, and never tried when the full phrase already grounded.
3738
+ * WORDNET EXPANSION is the third and widest pass, tried only when the first
3739
+ * two find nothing: a fixed-depth (one hop) lookup into
3740
+ * corpus/wordnet/wordnet-full.jsonl's own `/r/Synonym` edges, the same
3741
+ * ConceptNet-shape corpus the `wordnet-xl` band already ships from, loaded
3742
+ * and indexed once per process and cached (loadWordnetSynonymIndex, below)
3743
+ * — a 28 MB file is not re-parsed per turn. */
3744
+ function choiceTermTags(text) {
3745
+ const tags = new Map();
3746
+ const addAll = (values, tag) => { for (const v of values) if (!tags.has(v)) tags.set(v, tag); };
3747
+ addAll(factTermVariants(normFactTermStatic, text), "exact");
3748
+ for (const folded of lemmaFoldVariants(text)) addAll(factTermVariants(normFactTermStatic, folded), "lemma");
3749
+ return tags;
3750
+ }
3751
+ function choiceHeadNounTags(text) {
3752
+ const head = headNounOf(text);
3753
+ if (!head) return new Map();
3754
+ const tags = new Map();
3755
+ for (const v of factTermVariants(normFactTermStatic, head)) tags.set(v, "head-noun");
3756
+ return tags;
3757
+ }
3758
+
3759
+ /** subject|object -> Set(synonym) built once from wordnet-full.jsonl's own
3760
+ * `/r/Synonym` rows, both directions (a chained synonym pair is stored one
3761
+ * way in the source file, and a lookup needs to reach it from either
3762
+ * member). Cached at module scope: the file is 28 MB / ~206,000 rows, and a
3763
+ * choice question that never needs this pass never pays to load it — the
3764
+ * cache only fills on the first ungrounded option that reaches it. */
3765
+ let choiceWordnetSynonymIndex = null;
3766
+ async function loadChoiceWordnetSynonymIndex() {
3767
+ if (choiceWordnetSynonymIndex) return choiceWordnetSynonymIndex;
3768
+ const index = new Map();
3769
+ try {
3770
+ const { loadSlice, termText, WORDNET_DIR } = await import("../adapters/corpus/conceptnet.mjs");
3771
+ const assertions = await loadSlice(join(WORDNET_DIR, "wordnet-full.jsonl"));
3772
+ const add = (a, b) => {
3773
+ if (!a || !b || a === b) return;
3774
+ if (!index.has(a)) index.set(a, new Set());
3775
+ index.get(a).add(b);
3776
+ };
3777
+ for (const row of assertions) {
3778
+ if (row.rel !== "/r/Synonym") continue;
3779
+ const a = termText(row.start);
3780
+ const b = termText(row.end);
3781
+ add(a, b);
3782
+ add(b, a);
3783
+ }
3784
+ } catch { /* the corpus is optional; an empty index just skips this pass */ }
3785
+ choiceWordnetSynonymIndex = index;
3786
+ return choiceWordnetSynonymIndex;
3787
+ }
3788
+ async function choiceWordnetTags(text) {
3789
+ const index = await loadChoiceWordnetSynonymIndex();
3790
+ const synonyms = index.get(String(text ?? "").toLowerCase().trim());
3791
+ if (!synonyms) return new Map();
3792
+ const tags = new Map();
3793
+ for (const syn of synonyms) for (const v of factTermVariants(normFactTermStatic, syn)) tags.set(v, "wordnet");
3794
+ return tags;
3795
+ }
3709
3796
  async function probeChoiceOptions(parsed, { memoryDir, env, cache, graph, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3710
3797
  const sourceVariants = factTermVariants(normFactTermStatic, parsed.sourceTerm);
3711
3798
  let rows = await factRows(memoryDir, cache);
@@ -3714,12 +3801,58 @@ async function probeChoiceOptions(parsed, { memoryDir, env, cache, graph, synthe
3714
3801
  const learned = await childPackFactsForKey(parsed.sourceTerm, { memoryDir, env, cache, synthesisBudget });
3715
3802
  if (learned) rows = await factRows(memoryDir, cache);
3716
3803
  }
3717
- return parsed.options.map((option) => {
3718
- const optionVariants = factTermVariants(normFactTermStatic, option.text);
3719
- const facts = rows.filter((f) => (sourceVariants.has(f.subject) && optionVariants.has(f.object))
3720
- || (sourceVariants.has(f.object) && optionVariants.has(f.subject)));
3721
- return { label: option.label, text: option.text, grounds: facts.length > 0, facts, chain: null };
3722
- });
3804
+ const route = routeChoiceRelation(parsed.stem);
3805
+ const {
3806
+ findIsaChain: chaseChoiceIsa, buildSubClassSuccessors: buildChoiceSubClassSucc,
3807
+ TYPE_PREDICATE: CHOICE_TYPE_PREDICATE, SUBCLASS_PREDICATE: CHOICE_SUBCLASS_PREDICATE,
3808
+ } = await import("../domain/syllogise.mjs");
3809
+ const choiceTypeRows = rows.filter((f) => f.predicate === CHOICE_TYPE_PREDICATE);
3810
+ const choiceSubClassRows = rows.filter((f) => f.predicate === CHOICE_SUBCLASS_PREDICATE);
3811
+ const choiceTypeEdges = choiceTypeRows.map((f) => [f.subject, f.object]);
3812
+ const choiceSubClassSucc = buildChoiceSubClassSucc(choiceSubClassRows.map((f) => [f.subject, f.object]));
3813
+ const factForChoiceChainStep = (step) => (step.predicate === CHOICE_SUBCLASS_PREDICATE ? choiceSubClassRows : choiceTypeRows)
3814
+ .find((f) => f.subject === step.subject && f.object === step.object);
3815
+ const matchFacts = (variantsSet) => {
3816
+ let matched = rows.filter((f) => (sourceVariants.has(f.subject) && variantsSet.has(f.object))
3817
+ || (sourceVariants.has(f.object) && variantsSet.has(f.subject)));
3818
+ if (route) matched = matched.filter((f) => route.predicates.includes(f.predicate));
3819
+ return matched;
3820
+ };
3821
+
3822
+ return Promise.all(parsed.options.map(async (option) => {
3823
+ const primaryTags = choiceTermTags(option.text);
3824
+ const primaryVariants = new Set(primaryTags.keys());
3825
+ let facts = matchFacts(primaryVariants);
3826
+ let activeTags = primaryTags;
3827
+ if (facts.length === 0) {
3828
+ const headTags = choiceHeadNounTags(option.text);
3829
+ if (headTags.size) {
3830
+ const headFacts = matchFacts(new Set(headTags.keys()));
3831
+ if (headFacts.length) { facts = headFacts; activeTags = headTags; }
3832
+ }
3833
+ }
3834
+ if (facts.length === 0) {
3835
+ const wordnetTags = await choiceWordnetTags(option.text);
3836
+ if (wordnetTags.size) {
3837
+ const wordnetFacts = matchFacts(new Set(wordnetTags.keys()));
3838
+ if (wordnetFacts.length) { facts = wordnetFacts; activeTags = wordnetTags; }
3839
+ }
3840
+ }
3841
+ facts = facts.map((f) => {
3842
+ const optionSideTerm = sourceVariants.has(f.subject) ? f.object : f.subject;
3843
+ return { ...f, matchedBy: activeTags.get(optionSideTerm) ?? "exact" };
3844
+ });
3845
+ let chain = null;
3846
+ if (facts.length === 0) {
3847
+ for (const subj of sourceVariants) {
3848
+ const path = chaseChoiceIsa(subj, primaryVariants, choiceTypeEdges, choiceSubClassSucc, { maxHops: 2 });
3849
+ if (!path) continue;
3850
+ const premises = path.map(factForChoiceChainStep);
3851
+ if (premises.every(Boolean)) { chain = premises; break; }
3852
+ }
3853
+ }
3854
+ return { label: option.label, text: option.text, grounds: facts.length > 0 || chain !== null, facts, chain };
3855
+ }));
3723
3856
  }
3724
3857
 
3725
3858
  /** The "both sides ungrounded" grounding NUDGE: reuses teachSuggestion's own
@@ -4118,11 +4251,23 @@ async function unknownAdjectiveFallback(payload, { memoryDir, sessionId, lexicon
4118
4251
  // "every p is a glyph" teach while "every p is venomous" refuses, an
4119
4252
  // unpredictable asymmetry between two universally-quantified sentences
4120
4253
  // over the same corpus-anchored subject.
4121
- const universalQuantifier = /^(?:every|each|all|any)$/i.test((det || "").trim());
4254
+ // A bare GENERIC PLURAL subject with no determiner at all ("animals are
4255
+ // alive") carries the same implicit-universal reading matchBareHabitualTeach
4256
+ // already gives a bare plural verb subject ("dogs bark" mints the same
4257
+ // capability "every dog can bark" reaches for) — an English plural with no
4258
+ // article generalizes over the whole class. Gated on the LEXICON's own
4259
+ // plural fold, never the naive suffix strip alone, so only a genuinely
4260
+ // plural noun qualifies: "redis" ends in "s" but has no lexicon singular,
4261
+ // so it stays outside this reading and falls through to the ordinary bare
4262
+ // (single-entity) property gate below, unaffected.
4263
+ const lexiconSingular = /^are$/i.test(verb) ? lookupNoun(lex, subjectRaw)?.lemma : null;
4264
+ const bareGenericPlural = !String(det || "").trim() && !!lexiconSingular
4265
+ && lexiconSingular.toLowerCase() !== String(subjectRaw).toLowerCase();
4266
+ const universalQuantifier = /^(?:every|each|all|any)$/i.test((det || "").trim()) || bareGenericPlural;
4122
4267
  if (universalQuantifier && (await isAnchorableTerm(subjectRaw, lex, memoryDir, cache, graph))
4123
4268
  && (lookupAdjective(lex, objectRaw) || (await objectReadsAsNonNoun(objectRaw)))) {
4124
4269
  const classSubject = /^are$/i.test(verb)
4125
- ? (lookupNoun(lex, subjectRaw)?.lemma || singularizeSurface(subjectRaw))
4270
+ ? (lexiconSingular || singularizeSurface(subjectRaw))
4126
4271
  : subjectRaw;
4127
4272
  return teachFact(memoryDir, sessionId, {
4128
4273
  subject: classSubject, predicate: HAS_PROPERTY_PREDICATE, object: objectRaw, quantifier: "every", observedAt, dateText,
@@ -4366,6 +4511,17 @@ const quantifiedHasObject = (m) => (/^all$/i.test(m[1])
4366
4511
  * the single noun between the determiner and the verb; a two-token subject stays
4367
4512
  * declined, like the preposition-pinned frame, because nothing names its head. */
4368
4513
  const DETERMINER_HAS_TEACH_RE = /^(?:the|an?|my|your|our|their|his|her|its)\s+([\w'-]+)\s+(?:has|have|had)\s+(.+?)[.!?]*$/i;
4514
+ /** The determiner-led CAPABILITY teach ("a pig can be alive", "the wolf can
4515
+ * swim") — DETERMINER_HAS_TEACH_RE's own sibling for the "can" verb family.
4516
+ * The closed modal pins the split the same way "has"/"have" pins
4517
+ * DETERMINER_HAS_TEACH_RE's, so a leading article needs no verb-position
4518
+ * guessing. Its own object slot is unbounded ("can VERB", "can be
4519
+ * ADJECTIVE" — matchBareCanTeach/parseCapability already own the
4520
+ * single-word-verb case; this is the multi-word remainder both decline on),
4521
+ * so a plural bare subject ("animals can be alive") and its singular
4522
+ * articled twin ("a pig can be alive") land through the same generalVerbTeach
4523
+ * mint instead of one of the two silently declining. */
4524
+ const DETERMINER_CAN_TEACH_RE = /^(?:the|an?|every|each|all|my|your|our|their|his|her|its)\s+([\w'-]+)\s+can\s+(.+?)[.!?]*$/i;
4369
4525
  /** The quantified LOCATIVE teach ("every disk rests on peg-a", "each disk
4370
4526
  * rests on peg-a", "all disks rest on peg-a") — QUANTIFIED_HAS_TEACH_RE's own
4371
4527
  * sibling for the board-fact verb family. The has/have frame can pin the
@@ -4588,6 +4744,7 @@ async function generalVerbTeach(payload) {
4588
4744
  if (GENERAL_VERB_DETERMINER_RE.test(subjectRaw) || quantLoc || countLoc) {
4589
4745
  const quantHas = (!quantLoc && !countLoc) ? p.match(QUANTIFIED_HAS_TEACH_RE) : null;
4590
4746
  const detHas = (!quantHas && !quantLoc && !countLoc) ? p.match(DETERMINER_HAS_TEACH_RE) : null;
4747
+ const detCan = (!quantHas && !detHas && !quantLoc && !countLoc) ? p.match(DETERMINER_CAN_TEACH_RE) : null;
4591
4748
  if (quantHas) {
4592
4749
  subjectRaw = quantifiedHasSubject(quantHas);
4593
4750
  verbRaw = "has";
@@ -4596,6 +4753,10 @@ async function generalVerbTeach(payload) {
4596
4753
  subjectRaw = detHas[1];
4597
4754
  verbRaw = "has";
4598
4755
  objectRaw = detHas[2];
4756
+ } else if (detCan) {
4757
+ subjectRaw = detCan[1];
4758
+ verbRaw = "can";
4759
+ objectRaw = detCan[2];
4599
4760
  } else if (quantLoc) {
4600
4761
  // Universal locative ("every disk rests on peg-a") — the same
4601
4762
  // "every"-only quantifier-field convention unknownSubjectFallback's
@@ -6497,20 +6658,35 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6497
6658
  // every other sentence reading its first word exactly as before.
6498
6659
  const detLed = raw.match(GENERAL_VERB_DETERMINER_TEACH_RE);
6499
6660
  const detHasLed = detLed ? null : raw.match(DETERMINER_HAS_TEACH_RE);
6500
- const quantHasLed = (detLed || detHasLed) ? null : raw.match(QUANTIFIED_HAS_TEACH_RE);
6661
+ // A determiner-led CAPABILITY lead ("a pig can be alive") needs the same
6662
+ // override as detHasLed: its own first word ("a") never POS-tags as a
6663
+ // NOUN/PROPN, and matchBareCanTeach/parseCapability both decline on a
6664
+ // multi-word verb ("be alive"), so without this the sentence never even
6665
+ // reaches generalVerbTeach — exactly the gap that let the bare-plural
6666
+ // twin ("animals can be alive") teach while its singular-articled form
6667
+ // silently declined. Read through splitTeachNegation first (its own
6668
+ // idempotent rebuild — generalVerbTeach re-derives the identical
6669
+ // positive form later) so a negated lead ("a rock cannot be alive")
6670
+ // is recognized here too: the bare-plural twin ("rocks cannot be
6671
+ // alive") never needed this, since its own no-article subject already
6672
+ // passes the POS gate below without going through any det-led shape at
6673
+ // all, which is exactly the asymmetry this lead exists to close.
6674
+ const detCanLed = (detLed || detHasLed) ? null : splitTeachNegation(raw).payload.match(DETERMINER_CAN_TEACH_RE);
6675
+ const quantHasLed = (detLed || detHasLed || detCanLed) ? null : raw.match(QUANTIFIED_HAS_TEACH_RE);
6501
6676
  // The two locative quantifier leads ("every disk rests…", "one more disk
6502
6677
  // rests…") need the same override as quantHasLed/detHasLed just below:
6503
6678
  // their own first word ("every"/"one"/"another") never POS-tags as a
6504
6679
  // NOUN/PROPN, so without this the bare-sentence POS gate silently drops
6505
6680
  // them exactly the way it used to drop "every overbid has a gouger".
6506
- const quantLocLed = (detLed || detHasLed || quantHasLed) ? null : raw.match(QUANTIFIED_LOCATIVE_TEACH_RE);
6507
- const countLocLed = (detLed || detHasLed || quantHasLed || quantLocLed)
6681
+ const quantLocLed = (detLed || detHasLed || detCanLed || quantHasLed) ? null : raw.match(QUANTIFIED_LOCATIVE_TEACH_RE);
6682
+ const countLocLed = (detLed || detHasLed || detCanLed || quantHasLed || quantLocLed)
6508
6683
  ? null : raw.match(LOCATIVE_COUNTING_TEACH_RE);
6509
6684
  const subjectWord = detLed ? detLed[1].split(/\s+/).pop()
6510
6685
  : (detHasLed ? detHasLed[1]
6511
- : (quantHasLed ? quantifiedHasSubject(quantHasLed)
6512
- : (quantLocLed ? quantifiedLocativeSubject(quantLocLed)
6513
- : (countLocLed ? countLocLed[1] : raw.match(/^([\w'-]+)/)?.[1]))));
6686
+ : (detCanLed ? detCanLed[1]
6687
+ : (quantHasLed ? quantifiedHasSubject(quantHasLed)
6688
+ : (quantLocLed ? quantifiedLocativeSubject(quantLocLed)
6689
+ : (countLocLed ? countLocLed[1] : raw.match(/^([\w'-]+)/)?.[1])))));
6514
6690
  // The quantifier lead ("every … has …") is itself a strong declarative
6515
6691
  // signal, so it overrides the single-token POS gate: a noun that doubles
6516
6692
  // as a verb ("every overbid has a gouger" — wink tags "overbid" VERB)
@@ -6519,7 +6695,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6519
6695
  // NON_DECLARATIVE_OPENER_RE runs even for these leads — "every umm has a
6520
6696
  // thing" isn't a real quantified sentence, just filler that fits the shape.
6521
6697
  if (subjectWord && !NON_DECLARATIVE_OPENER_RE.test(subjectWord)
6522
- && (quantHasLed || detHasLed || quantLocLed || countLocLed || (await subjectIsNounOrPropn(subjectWord)))) {
6698
+ && (quantHasLed || detHasLed || detCanLed || quantLocLed || countLocLed || (await subjectIsNounOrPropn(subjectWord)))) {
6523
6699
  // A PLURAL explicit-capability surface ("wrens can hum") whose
6524
6700
  // SINGULAR is a grounded term stores under the singular first — the
6525
6701
  // spelling the grounding fact and every query-side variant fold use —
@@ -10405,9 +10581,17 @@ async function synonymFactAnswer(memoryDir, query, envelope) {
10405
10581
  * factAnswer's "what do you know about X" KNOW_ABOUT form): everything remembered
10406
10582
  * that mentions X on either side. */
10407
10583
  const TOLD_ABOUT_RE = /^what\s+(?:did|have)\s+(?:i|we|you)\s+(?:told|tell|said|say)\s+(?:you|me|us)?\s*about\s+(.+?)[?.!\s]*$/i;
10408
- /** "what kind of thing is an X" — the subject-side membership phrasing the grammar
10409
- * doesn't parse: reports X's OWN remembered type (falling back to X's members). */
10410
- const KIND_OF_RE = /^what\s+kind\s+of\s+(?:thing|class|type|category|entity)?\s*(?:is|are)\s+(?:an?\s+)?(.+?)[?.!\s]*$/i;
10584
+ /** "what kind of thing is an X" / "what type of creature is X" — the
10585
+ * subject-side membership phrasing the grammar doesn't parse: reports X's
10586
+ * OWN remembered type (falling back to X's members). "kind" and "type" both
10587
+ * lead (English uses them interchangeably here); the qualifier noun between
10588
+ * "kind/type of" and "is/are" is OPTIONAL and, when present, captured
10589
+ * separately (group 1) rather than restricted to a closed generic set — "a
10590
+ * creature"/"an animal" reads exactly like the bare "thing"/"class" the
10591
+ * original five-word set already covered, since the qualifier only narrows
10592
+ * how the question reads (see this function's own qualifier-confirmation
10593
+ * block below), never which shapes the regex accepts. */
10594
+ const KIND_OF_RE = /^what\s+(?:kind|type)\s+of\s+(?:an?\s+)?([\w-]+(?:\s+[\w-]+)?)?\s*(?:is|are)\s+(?:an?\s+)?(.+?)[?.!\s]*$/i;
10411
10595
  /** "does every <N1> have at least <m> <N2>" — cardinality monotonicity: a
10412
10596
  * class's OWN declared exactly/min cardinality restriction proves "at least
10413
10597
  * m" for any queried m <= n (src/domain/syllogise.mjs's proveCardinalityAtLeast). */
@@ -12104,8 +12288,9 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
12104
12288
  // article) does, for every term alike.
12105
12289
  let term = envelope?.parsed?.shape === "meta" ? envelope.parsed.object : null;
12106
12290
  let kindOf = false;
12291
+ let qualifier = null;
12107
12292
  const mk = q.match(KIND_OF_RE);
12108
- if (mk) { term = mk[1]; kindOf = true; }
12293
+ if (mk) { qualifier = mk[1] ? mk[1].trim() : null; term = mk[2]; kindOf = true; }
12109
12294
  else if (!term && !envelope?.parsed) {
12110
12295
  const m = q.match(/^what\s+(?:is|are)\s+(?:an?\s+)?(.+?)[?.!\s]*$/i);
12111
12296
  if (m) term = m[1];
@@ -12118,6 +12303,23 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
12118
12303
  ? (subjectHits.length ? subjectHits : objectHits)
12119
12304
  : (objectHits.length ? objectHits : subjectHits);
12120
12305
  if (!hits.length) return null;
12306
+ // The qualifier noun ("creature" in "what type of creature is john") never
12307
+ // gates the answer — it narrows how the question reads, the same way
12308
+ // grammar.resolve.type-word-describes-subject's "the Store class" narrows
12309
+ // presentation without excluding an answer. When the answered type is
12310
+ // ALSO directly taught as a kind of the qualifier ("pig rdfs:subClassOf
12311
+ // creature"), that confirming fact rides along with the answer; when no
12312
+ // such fact is known, the plain type answer stands on its own — never a
12313
+ // fabricated confirmation, and never a refusal over a qualifier word the
12314
+ // store simply hasn't linked yet.
12315
+ if (qualifier && hits === subjectHits) {
12316
+ const qualifierVariants = factTermVariants(normFactTerm, qualifier);
12317
+ const bridgeFor = (hit) => isa.find((g) => g.subject === hit.object && qualifierVariants.has(g.object));
12318
+ const confirmed = hits.map((hit) => ({ hit, bridge: bridgeFor(hit) })).find(({ bridge }) => bridge);
12319
+ if (confirmed) {
12320
+ return { text: `${renderFactLine(confirmed.hit)} — ${renderFactLine(confirmed.bridge)}`, replace: true };
12321
+ }
12322
+ }
12121
12323
  return renderMany(hits);
12122
12324
  }
12123
12325
 
@@ -13493,16 +13695,35 @@ async function entityOfKindInText(graph, expectedClass, answerText) {
13493
13695
  return null;
13494
13696
  }
13495
13697
 
13698
+ // The one taught action this lane derives a constraint for without being
13699
+ // asked: the river-crossing world pack and data/games/river.txt's own
13700
+ // taught lesson both name their crossing action "ferry onto", so a
13701
+ // mgx:consumes/mgx:guards pair only ever widens or narrows THAT action's
13702
+ // legal moves, never a different taught world's. A world that never teaches
13703
+ // "ferry onto" gets no constraint rows at all — constraintsFromDrives runs
13704
+ // over every fact row, but compileDomain groups action-constraint rows by
13705
+ // name, so the derived rows simply have nowhere to attach.
13706
+ const DRIVE_DERIVED_CONSTRAINT_ACTION = "ferry onto";
13707
+
13496
13708
  /** Load the taught domain for the plan lane: fact rows + rule rows compiled
13497
- * through src/domain.mjs. Fresh-loads memory (never the turn cache) because
13498
- * the caller may have just written snapshot rows this same turn. */
13709
+ * through src/domain.mjs, with the fox may not be with the goat family of
13710
+ * constraints added wherever the rows state a consumes/guards pair
13711
+ * (agent-traits.mjs's constraintsFromDrives) — the same bridge
13712
+ * mudiii-turn.mjs's own puzzle plan runs, so a world taught here and a
13713
+ * world played on the square solve the same puzzle the same way. A world
13714
+ * with no such pair compiles exactly as it did before this ran. Fresh-loads
13715
+ * memory (never the turn cache) because the caller may have just written
13716
+ * snapshot rows this same turn. */
13499
13717
  async function loadPlanContext(memoryDir) {
13500
13718
  const { loadMemory, readFactRows, readRuleRows } = await import("../adapters/memory/core.mjs");
13501
13719
  const { compileDomain, stateFromFacts } = await import("../domain/domain.mjs");
13720
+ const { constraintsFromDrives } = await import("../domain/agent-traits.mjs");
13502
13721
  const payload = await loadMemory(memoryDir);
13503
13722
  const factRows = readFactRows(payload);
13504
13723
  const ruleRows = readRuleRows(payload);
13505
- const domain = compileDomain(factRows, ruleRows);
13724
+ const derivedConstraints = constraintsFromDrives(factRows)
13725
+ .map((slots) => ({ name: DRIVE_DERIVED_CONSTRAINT_ACTION, kind: "action-constraint", slots }));
13726
+ const domain = compileDomain(factRows, [...ruleRows, ...derivedConstraints]);
13506
13727
  const state = stateFromFacts(factRows, domain);
13507
13728
  return { factRows, ruleRows, domain, state };
13508
13729
  }
@@ -15160,6 +15381,15 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15160
15381
  // sides singularizing to KNOWN lexicon nouns, so real chatter ("these are
15161
15382
  // yours") stays with the orientation card.
15162
15383
  let isPluralMembershipTeach = false;
15384
+ // The property-teach sibling: "animals are alive" — the SAME 3-word
15385
+ // deferral, but the OBJECT is an ADJECTIVE, not a noun class, so it needs
15386
+ // its own noun-vs-adjective read below rather than isPluralMembershipTeach's
15387
+ // noun-noun gate. Matches unknownAdjectiveFallback's own bare-generic-plural
15388
+ // mint gate (chat.mjs's teach-side write) exactly, so the two lanes can
15389
+ // never disagree about which "X are Y" sentences are teachable — without
15390
+ // this, the sentence never reaches teachLane at all, and the mint gate's
15391
+ // own widening below has nothing to widen.
15392
+ let isPluralPropertyTeach = false;
15163
15393
  // A bare habitual naming a subject grounded NOWHERE ("penguins swim", no
15164
15394
  // prior grounding) gets an honest grounding hint instead of the
15165
15395
  // orientation card — computed here, rendered inside the conversational
@@ -15179,12 +15409,19 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15179
15409
  ? null : (matchBareHabitualTeach(bareLine) || matchBareCanTeach(bareLine));
15180
15410
  if (pm || habitual) {
15181
15411
  try {
15182
- const { loadLexicon, lookupNoun } = await import("../domain/grammar/lexicon.mjs");
15412
+ const { loadLexicon, lookupNoun, lookupAdjective } = await import("../domain/grammar/lexicon.mjs");
15183
15413
  const lex = loadLexicon();
15184
15414
  if (pm) {
15185
15415
  const s = singularizeSurface(pm[1].toLowerCase());
15186
15416
  const o = singularizeSurface(pm[2].toLowerCase());
15187
15417
  isPluralMembershipTeach = s !== pm[1].toLowerCase() && !!lookupNoun(lex, s) && !!lookupNoun(lex, o);
15418
+ if (!isPluralMembershipTeach) {
15419
+ const subjSingular = lookupNoun(lex, pm[1])?.lemma;
15420
+ if (subjSingular && subjSingular.toLowerCase() !== pm[1].toLowerCase()
15421
+ && (lookupAdjective(lex, pm[2]) || (await objectReadsAsNonNoun(pm[2])))) {
15422
+ isPluralPropertyTeach = true;
15423
+ }
15424
+ }
15188
15425
  } else {
15189
15426
  // The bare habitual/capability siblings ("dogs bark", "a dog
15190
15427
  // barks", "wrens can sing") — same deferral, same known-subject
@@ -15242,7 +15479,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15242
15479
  } catch { /* leave false — the ordinary path decides */ }
15243
15480
  }
15244
15481
  }
15245
- const conversationalCandidateBaseGate = !handled && miss && !envelope?.parsed && !isWhatAboutContinuation && !isVagueTouchResolvable && !isDescribePronounContinuation && !isExplainTouch && !isStaccatoNegation && !isVagueRelationTouch && !isStaccatoComparative && !isStaccatoPronounNoFocus && !isPluralMembershipTeach && !isBareRelationalVerbTeach;
15482
+ const conversationalCandidateBaseGate = !handled && miss && !envelope?.parsed && !isWhatAboutContinuation && !isVagueTouchResolvable && !isDescribePronounContinuation && !isExplainTouch && !isStaccatoNegation && !isVagueRelationTouch && !isStaccatoComparative && !isStaccatoPronounNoFocus && !isPluralMembershipTeach && !isPluralPropertyTeach && !isBareRelationalVerbTeach;
15246
15483
  // A turn whose pronoun was bound to a vocabulary antecedent is PROVABLY a
15247
15484
  // fact question ("can it bark" → "can dog bark") — never conversational,
15248
15485
  // however short. Without this, the substituted 3-worder still trips
@@ -18311,20 +18548,36 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18311
18548
  turn.lane = "ask-choice";
18312
18549
  turn.detail = {
18313
18550
  traversal: `${grounded.length} of ${probed.length} options grounded against "${parsed.sourceTerm}"`,
18314
- matches: grounded.flatMap((o) => o.facts),
18551
+ matches: grounded.flatMap((o) => (o.facts.length ? o.facts : o.chain || [])),
18315
18552
  };
18316
18553
  return withLast(turn, choiceGoal);
18317
18554
  }
18318
18555
  const winner = grounded[0];
18319
- const fact = winner.facts.slice().sort((a, b) => b.trust - a.trust)[0];
18320
- note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding fact`);
18321
- const text = `${winner.text} — ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)}).`;
18556
+ // Direct edge first; a chain (rung 3) only ever fires when NO direct
18557
+ // edge exists for the winning option — probeChoiceOptions' own guard.
18558
+ let text; let matches; let hop; let traversalNote; let matchedBy;
18559
+ if (winner.facts.length > 0) {
18560
+ const fact = winner.facts.slice().sort((a, b) => b.trust - a.trust)[0];
18561
+ text = `${winner.text} — ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)}).`;
18562
+ matches = winner.facts;
18563
+ hop = 1;
18564
+ matchedBy = fact.matchedBy;
18565
+ traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`;
18566
+ } else {
18567
+ text = `${winner.text} — ${renderIsaChain(winner.chain)}.`;
18568
+ matches = winner.chain;
18569
+ hop = winner.chain.length;
18570
+ traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via a ${winner.chain.length}-hop isa chain`;
18571
+ }
18572
+ note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18322
18573
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18323
18574
  turn.lane = "ask-choice";
18324
18575
  turn.detail = {
18325
- traversal: `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`,
18326
- matches: winner.facts,
18576
+ traversal: traversalNote,
18577
+ matches,
18327
18578
  selectedLabel: winner.label,
18579
+ hop,
18580
+ ...(matchedBy ? { matchedBy } : {}),
18328
18581
  };
18329
18582
  return withLast(turn, choiceGoal);
18330
18583
  }
@@ -90,9 +90,9 @@ export function parseArgs(argv) {
90
90
  * — `recognized` true iff runTurn's own record called this a stored assertion,
91
91
  * `rows` the Fact rows it touched (possibly empty for a Rule-only write).
92
92
  */
93
- async function runSentence(sentence, { config, memoryDir }) {
93
+ async function runSentence(sentence, { config, memoryDir, env }) {
94
94
  const before = readFactRows(await loadMemory(memoryDir));
95
- const { record, answer } = await runTurn(sentence, { config, memoryDir, sessionId: uuidv7() });
95
+ const { record, answer } = await runTurn(sentence, { config, memoryDir, sessionId: uuidv7(), env });
96
96
  if (record?.via !== "assert" || record?.miss) return { recognized: false, rows: [], decline: String(answer || "") };
97
97
  const after = readFactRows(await loadMemory(memoryDir));
98
98
  return { recognized: true, rows: touchedFactRows(before, after) };
@@ -619,7 +619,7 @@ function canonicalLines(facts, storeRows) {
619
619
  */
620
620
  export async function ingestText(text, {
621
621
  memoryDir = null, sourceTag = "text", optimistic = false,
622
- canonical = false, config = null, lexicon = null,
622
+ canonical = false, config = null, lexicon = null, observedAt = "",
623
623
  } = {}) {
624
624
  // Paragraphs first (blank-line separated), so the pronoun carry never bridges
625
625
  // a topic break: a fresh paragraph clears the last-subject it would resolve
@@ -628,10 +628,19 @@ export async function ingestText(text, {
628
628
  const paragraphs = String(text ?? "").split(/\n[ \t]*\n/);
629
629
  const ephemeral = !memoryDir;
630
630
  const dir = memoryDir || await mkdtemp(join(tmpdir(), "tmct-ingest-"));
631
- // `dir` may be a backend handle (a sqlite store), not a path — only a real
632
- // directory string can seed loadConfig's cwd; a handle-holding caller passes
633
- // its own config.
634
- const cfg = config || loadConfig(process.env, typeof dir === "string" ? dir : process.cwd());
631
+ // `dir` may be a backend handle (a sqlite store, or a browser's in-memory
632
+ // store), not a path — only a real directory string can seed loadConfig's
633
+ // cwd, and `process` itself doesn't exist in a browser. A handle-holding
634
+ // caller passes its own config; absent that, `graphFile` is moot for a
635
+ // handle anyway (there is no on-disk repo to resolve it against), so a
636
+ // bare default stands in rather than reaching for `loadConfig`/`process`.
637
+ const cfg = config || (typeof dir === "string" ? loadConfig(process.env, dir) : { graphFile: "" });
638
+ // dispatchTurn's own `env = process.env` default parameter is evaluated
639
+ // eagerly, so it throws in a browser the moment runSentence (below) omits
640
+ // `env` — passing it explicitly here (real env in Node, `{}` in a browser)
641
+ // is the same shape `env` already has to take everywhere else this module
642
+ // runs client-side.
643
+ const runEnv = typeof process !== "undefined" && process.env ? process.env : {};
635
644
  const lex = lexicon || loadLexicon();
636
645
  const nlp = optimistic ? winkInstance() : null;
637
646
  // The fact-degree scan below runs whether or not --optimistic is on, so it
@@ -658,7 +667,7 @@ export async function ingestText(text, {
658
667
  // grounds nothing, else the Fact rows it touched.
659
668
  let lastDecline = "";
660
669
  const strictRows = async (form) => {
661
- const { recognized, rows, decline } = await runSentence(form, { config: cfg, memoryDir: dir });
670
+ const { recognized, rows, decline } = await runSentence(form, { config: cfg, memoryDir: dir, env: runEnv });
662
671
  if (!recognized) lastDecline = decline || lastDecline;
663
672
  return recognized && rows.length ? rows : null;
664
673
  };
@@ -699,7 +708,7 @@ export async function ingestText(text, {
699
708
  for (const row of rows) {
700
709
  await appendFact(dir, {
701
710
  subject: row.subject, predicate: row.predicate, object: row.object,
702
- provenance: tag, quantifier: row.quantifier || "",
711
+ provenance: tag, quantifier: row.quantifier || "", observedAt,
703
712
  });
704
713
  extracted.push({
705
714
  subject: row.subject, predicate: row.predicate, object: row.object,
@@ -717,7 +726,7 @@ export async function ingestText(text, {
717
726
  const tag = `optimistic-extract:${sourceTag}`;
718
727
  for (const t of candidates) {
719
728
  await appendFact(dir, {
720
- subject: t.subject, predicate: t.predicate, object: t.object, provenance: tag,
729
+ subject: t.subject, predicate: t.predicate, object: t.object, provenance: tag, observedAt,
721
730
  });
722
731
  optimisticFacts.push({ ...t, provenance: tag, sentence });
723
732
  }
@@ -68,11 +68,13 @@ export { generateCompletion, createCompletionsGraphAdapter } from "./completions
68
68
  // The news capability: scheduled multi-source ingestion, occurrence-ranked
69
69
  // grounding gaps, KB enrichment and the fact-churn feed builder — one
70
70
  // library contract every surface (news.html, chat's `/news`, the CLI verb,
71
- // a JS import) consumes the same way.
71
+ // a JS import) consumes the same way. The `./news` subpath (news-exports.mjs)
72
+ // carries this same contract plus the built-in fetchers and courtesy gate,
73
+ // reachable without the chat/grammar engine this "." entry also pulls in.
72
74
  export {
73
75
  resolveNewsConfig, parseNewsRequest, pollNewsSources, ingestNewsSnapshot,
74
76
  enrichTopTerms, reprocessAfterGrounding, isVocabGroundedTerm, isFactGroundedTerm,
75
- ingestUploadedFactRows, buildFeed, newsTurn,
77
+ ingestUploadedFactRows, buildFeed, newsTurn, cycleMetrics, createNewsState,
76
78
  } from "./news.mjs";
77
79
  export { buildNewsItems } from "../domain/news-feed.mjs";
78
80
  export { rankedTerms } from "../domain/term-ledger.mjs";
@@ -536,6 +536,17 @@ async function mudiiiBeliefAnswer(match, { memoryDir, gameConfig = DEFAULT_GAME_
536
536
  const RIVER_CROSSING_ACTION = "ferry onto";
537
537
  const RIVER_CROSSING_GOAL = [{ universal: true, term: "passenger", predicate: "currently-in", object: "bank-west" }];
538
538
 
539
+ /** Who stands where, in one plain `{ individual: place }` map, read off a
540
+ * planner state's own rows. The state carries one row per individual under
541
+ * the domain's dynamic predicates, so this is a straight transcription — no
542
+ * predicate is privileged, and a puzzle with a different position predicate
543
+ * reads the same way. Pure. */
544
+ function placesInState(state) {
545
+ const places = {};
546
+ for (const row of state || []) places[row.subject] = row.object;
547
+ return places;
548
+ }
549
+
539
550
  /** The river-crossing puzzle's own plan, recomputed from `rows`/`ruleRows` as
540
551
  * they stand right now: the world's own action rules plus whatever
541
552
  * action-constraint rows the drive facts themselves imply
@@ -543,11 +554,18 @@ const RIVER_CROSSING_GOAL = [{ universal: true, term: "passenger", predicate: "c
543
554
  * data/games/river.txt. Null on a world whose rule rows carry no "ferry
544
555
  * onto" action-signature, or whose action domain does not carry a
545
556
  * "passenger" class the goal can quantify over. Returns `{ moves, plan,
546
- * miss }`: `moves` is every legal move from the CURRENT position (the empty
547
- * list when nothing may move), `plan` is the found action sequence or null,
548
- * `miss` is null when a plan was found and the stated reason otherwise — a
549
- * budget decline as well as an exhausted search, never a shortened plan
550
- * either way. Pure. */
557
+ * places, goalPlace, miss }`: `moves` is every legal move from the CURRENT
558
+ * position (the empty list when nothing may move), `plan` is the found action
559
+ * sequence or null, `miss` is null when a plan was found and the stated reason
560
+ * otherwise — a budget decline as well as an exhausted search, never a
561
+ * shortened plan either way.
562
+ *
563
+ * `places` is what a player watches the plan through: one `{ individual:
564
+ * place }` map per position the plan passes through, opening arrangement
565
+ * first, so `places[k]` is where everyone stands after `k` moves and
566
+ * `places.length` is `plan.length + 1`. A miss still carries the opening
567
+ * arrangement alone, so a board can be drawn for a puzzle with no crossing.
568
+ * `goalPlace` names where the goal wants the passengers. Pure. */
551
569
  function riverPuzzleOutlook(rows, ruleRows) {
552
570
  const hasFerryAction = (ruleRows || []).some((r) => r.kind === "action-signature" && r.name === RIVER_CROSSING_ACTION);
553
571
  if (!hasFerryAction) return null;
@@ -561,13 +579,27 @@ function riverPuzzleOutlook(rows, ruleRows) {
561
579
  }
562
580
  const start = stateFromFacts(rows, domain);
563
581
  const moves = movesFromRules(start, domain).map((m) => m.action.label);
582
+ const opening = [placesInState(start)];
583
+ const goalPlace = RIVER_CROSSING_GOAL[0].object;
564
584
  const maxDepth = DEFAULT_GAME_CONFIG.planning.maxDepth;
565
585
  try {
566
586
  const found = findActionPath(start, isGoal, (s) => movesFromRules(s, domain), { maxDepth, stateKey: stateKeyFor });
567
- return { moves, plan: found ? found.actions : null, miss: found ? null : `no plan found within ${maxDepth} moves` };
587
+ return {
588
+ moves,
589
+ plan: found ? found.actions : null,
590
+ places: found ? found.states.map(placesInState) : opening,
591
+ goalPlace,
592
+ miss: found ? null : `no plan found within ${maxDepth} moves`,
593
+ };
568
594
  } catch (err) {
569
595
  if (!(err instanceof PlanBudgetError)) throw err;
570
- return { moves, plan: null, miss: `action grounding count ${err.groundings} exceeds the budget of ${err.budget}` };
596
+ return {
597
+ moves,
598
+ plan: null,
599
+ places: opening,
600
+ goalPlace,
601
+ miss: `action grounding count ${err.groundings} exceeds the budget of ${err.budget}`,
602
+ };
571
603
  }
572
604
  }
573
605