@polycode-projects/the-mechanical-code-talker 5.0.34 → 5.0.36

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.
@@ -53,7 +53,7 @@ import { setConstructionBanks } from "../domain/interpret/strategies/constructio
53
53
  import { nlpAdapter } from "../adapters/ask-nlp.mjs";
54
54
  import { readConstructionFiles } from "../adapters/corpus/construction-banks.mjs";
55
55
  import { fuzzyMatchInSet, fuzzyBound } from "../domain/interpret/fuzzy.mjs";
56
- import { loadLexicon, lookupNoun, lookupVerb, lookupAdjective, lookupProperName, readsAsIndividualName, CODE_REF_SHAPE } from "../domain/grammar/lexicon.mjs";
56
+ import { loadLexicon, lookupNoun, lookupVerb, lookupAdjective, lookupProperName, readsAsIndividualName, numberOf, CODE_REF_SHAPE } from "../domain/grammar/lexicon.mjs";
57
57
  import { pickPhrase } from "../domain/answer-variants.mjs";
58
58
  import {
59
59
  REFERENCE_PACK_NAME, cleanMissReferenceTerm, renderReferenceAnswer, referenceProvenanceTag,
@@ -70,13 +70,14 @@ 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, routeChoiceRelation, lemmaFoldVariants, headNounOf } from "../domain/choice-question.mjs";
73
+ import { splitChoiceQuestion, routeChoiceRelation, lemmaFoldVariants, headNounOf, stemTopicCandidates, stemConstraintTerms } 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";
77
77
  import { adventureTurn, unclaimedAdventureOpening, foldWorldState } from "./adventure.mjs";
78
78
  import { spiderFlyTurn } from "./spider-fly-turn.mjs";
79
79
  import { mudiiiTurn } from "./mudiii-turn.mjs";
80
+ import { parseAgentTraitAsk, answerAgentTraitAsk } from "./agent-editor.mjs";
80
81
  import { DEFAULT_GAME_CONFIG } from "../domain/game-config.mjs";
81
82
 
82
83
  // Composition: the chat surface supplies the domain parser's default lemma/POS
@@ -3793,6 +3794,133 @@ async function choiceWordnetTags(text) {
3793
3794
  for (const syn of synonyms) for (const v of factTermVariants(normFactTermStatic, syn)) tags.set(v, "wordnet");
3794
3795
  return tags;
3795
3796
  }
3797
+ /**
3798
+ * Picks the one candidate the question is about: the candidate the graph
3799
+ * holds the most facts about, counting rows where the term is the subject or
3800
+ * the object under any predicate. Ties in that count go to the phrase
3801
+ * extractStemSourceTerm captured (a structural read beats a graph count when
3802
+ * the graph cannot separate), then to the longer phrase, then to the leftmost.
3803
+ * Returns "" when no candidate is named in the store at all, which the lane
3804
+ * reports as the no-topic miss it already has.
3805
+ *
3806
+ * Pure in the fact set: the same rows in any order give the same topic, the
3807
+ * discipline sortFactIndividualsById already holds the store to.
3808
+ *
3809
+ * @returns {Promise<{ topic: string, salience: number, runnerUp: string }>}
3810
+ */
3811
+ async function chooseChoiceTopic(candidates, { memoryDir, cache, templateCapture }) {
3812
+ if (!candidates.length) return { topic: "", salience: 0, runnerUp: "" };
3813
+ const rows = await factRows(memoryDir, cache);
3814
+ const salienceOf = (text) => {
3815
+ const variants = factTermVariants(normFactTermStatic, text);
3816
+ let count = 0;
3817
+ for (const f of rows) { if (variants.has(f.subject) || variants.has(f.object)) count += 1; }
3818
+ return count;
3819
+ };
3820
+ const scored = candidates
3821
+ .map((c) => ({ ...c, salience: salienceOf(c.text) }))
3822
+ .sort((a, b) => {
3823
+ if (b.salience !== a.salience) return b.salience - a.salience;
3824
+ const aIsCapture = a.text === templateCapture;
3825
+ const bIsCapture = b.text === templateCapture;
3826
+ if (aIsCapture !== bIsCapture) return aIsCapture ? -1 : 1;
3827
+ if (b.words !== a.words) return b.words - a.words;
3828
+ return a.position - b.position;
3829
+ });
3830
+ const best = scored[0];
3831
+ if (best.salience === 0) return { topic: "", salience: 0, runnerUp: "" };
3832
+ const runnerUp = scored.find((c) => c.text !== best.text)?.text ?? "";
3833
+ return { topic: best.text, salience: best.salience, runnerUp };
3834
+ }
3835
+
3836
+ /**
3837
+ * Pulls the child pack once per constraint term, so the constraint check in
3838
+ * the tie branch has rows to read. Bounded three ways: at most
3839
+ * CHOICE_CONSTRAINT_PULL_BUDGET terms per turn, in stemConstraintTerms order;
3840
+ * nothing pulled for a term memory already holds a fact for; nothing pulled
3841
+ * for any option term, ever — terms reaching here already went through
3842
+ * stemConstraintTerms' own option-word filter, the same discipline
3843
+ * probeChoiceOptions' own docblock states for the topic pull.
3844
+ *
3845
+ * @returns {Promise<string[]>} the terms actually pulled, for the trace note
3846
+ */
3847
+ async function pullChoiceConstraintFacts(terms, { memoryDir, env, cache, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3848
+ const pulled = [];
3849
+ if (!memoryDir) return pulled;
3850
+ for (const term of terms.slice(0, CHOICE_CONSTRAINT_PULL_BUDGET)) {
3851
+ const rows = await factRows(memoryDir, cache);
3852
+ const variants = factTermVariants(normFactTermStatic, term);
3853
+ const hasFact = rows.some((f) => variants.has(f.subject) || variants.has(f.object));
3854
+ if (hasFact) continue;
3855
+ const learned = await childPackFactsForKey(term, { memoryDir, env, cache, synthesisBudget });
3856
+ if (learned) pulled.push(term);
3857
+ }
3858
+ return pulled;
3859
+ }
3860
+
3861
+ /** Every constraint term the graph links `option`'s own term to, each with
3862
+ * the ONE fact row that proves it (first match in `rows`' own order, which
3863
+ * is already canonical — the store sorts fact individuals by content-
3864
+ * addressed id, so this reads the same regardless of insertion order).
3865
+ * Unrouted, either direction: this is not the topic probe's grounding
3866
+ * check, it is "does the graph also connect this option to something else
3867
+ * the question said", and section 2.6 of the design survey found that rule
3868
+ * only under any predicate. */
3869
+ function choiceOptionSatisfiedConstraints(option, constraintTerms, rows) {
3870
+ const optionVariants = factTermVariants(normFactTermStatic, option.text);
3871
+ const satisfied = [];
3872
+ for (const term of constraintTerms) {
3873
+ const termVariants = factTermVariants(normFactTermStatic, term);
3874
+ const fact = rows.find((f) => (optionVariants.has(f.subject) && termVariants.has(f.object))
3875
+ || (optionVariants.has(f.object) && termVariants.has(f.subject)));
3876
+ if (fact) satisfied.push({ term, fact });
3877
+ }
3878
+ return satisfied;
3879
+ }
3880
+
3881
+ /**
3882
+ * Splits a tie by how much of the question each grounded option answers.
3883
+ * `satisfied` is the constraint terms the graph links that option to, each
3884
+ * with the fact row that proves it, so the answer can cite them. Returns
3885
+ * null when no option is strictly ahead, or when the leader satisfies
3886
+ * nothing — both of which stay refusals. The ties-never-broken rule this
3887
+ * answers to: a pick is made only against MORE satisfied constraints, never
3888
+ * a strength ordering over any single piece of evidence.
3889
+ *
3890
+ * @returns {null | {
3891
+ * winner: { label, text, facts, chain, satisfied: Array<{ term, fact }> },
3892
+ * runnerUp: { label, text, satisfied: Array<{ term, fact }> },
3893
+ * missedByRunnerUp: string[],
3894
+ * }}
3895
+ */
3896
+ function separateChoiceTie(grounded, constraintTerms, rows) {
3897
+ if (!constraintTerms.length) return null;
3898
+ const scored = grounded.map((option) => ({
3899
+ option,
3900
+ satisfied: choiceOptionSatisfiedConstraints(option, constraintTerms, rows),
3901
+ }));
3902
+ const bestCount = Math.max(...scored.map((s) => s.satisfied.length));
3903
+ if (bestCount === 0) return null;
3904
+ const leaders = scored.filter((s) => s.satisfied.length === bestCount);
3905
+ if (leaders.length > 1) return null;
3906
+ const winner = leaders[0];
3907
+ const runnerUp = scored
3908
+ .filter((s) => s.option.label !== winner.option.label)
3909
+ .reduce((best, cur) => {
3910
+ if (!best) return cur;
3911
+ if (cur.satisfied.length > best.satisfied.length) return cur;
3912
+ if (cur.satisfied.length === best.satisfied.length && cur.option.label < best.option.label) return cur;
3913
+ return best;
3914
+ }, null);
3915
+ const runnerUpTerms = new Set(runnerUp.satisfied.map((s) => s.term));
3916
+ const missedByRunnerUp = winner.satisfied.map((s) => s.term).filter((term) => !runnerUpTerms.has(term));
3917
+ return {
3918
+ winner: { label: winner.option.label, text: winner.option.text, facts: winner.option.facts, chain: winner.option.chain, satisfied: winner.satisfied },
3919
+ runnerUp: { label: runnerUp.option.label, text: runnerUp.option.text, satisfied: runnerUp.satisfied },
3920
+ missedByRunnerUp,
3921
+ };
3922
+ }
3923
+
3796
3924
  async function probeChoiceOptions(parsed, { memoryDir, env, cache, graph, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3797
3925
  const sourceVariants = factTermVariants(normFactTermStatic, parsed.sourceTerm);
3798
3926
  let rows = await factRows(memoryDir, cache);
@@ -8719,6 +8847,85 @@ function apposedFactTerm(term, rows, normFactTerm) {
8719
8847
  * factReadBack(...)` — never both). */
8720
8848
  const CAN_ASK_RE = /^(?:can|could)\s+(all\s+|every\s+)?(?:an?\s+)?([\w'-]+(?:\s+[\w'-]+)*?)\s+([a-z]+)[?.!\s]*$/i;
8721
8849
  const DOES_HAVE_ASK_RE = /^(?:does|do)\s+(?:an?\s+|the\s+)?(.+?)\s+have\s+(?:an?\s+|the\s+)?(.+?)[?.!\s]*$/i;
8850
+ /** "how many legs does a dog have" and its plural sibling "how many legs do
8851
+ * dogs have" — the COUNT surface of the same possession facts DOES_HAVE_ASK_RE
8852
+ * reads back. Both auxiliaries in one shape: the singular/plural fold happens
8853
+ * on the terms (factTermVariants), so the auxiliary carries no meaning here. */
8854
+ const HOW_MANY_HAVE_ASK_RE = /^how\s+many\s+(.+?)\s+(?:does|do)\s+(?:an?\s+|the\s+)?(.+?)\s+have[?.!\s]*$/i;
8855
+ /** The two spellings a possession fact lands under: the corpus mints mgx:hasA,
8856
+ * the teach lane tmct:has. Every possession reader searches both. */
8857
+ const HAS_PREDICATES = new Set(["mgx:hasA", "tmct:has"]);
8858
+
8859
+ /** "can a pig be alive" / "could animals be alive" — the modal surface of the
8860
+ * plain "are pigs alive" property question. CAN_ASK_RE's own single-word verb
8861
+ * slot cannot read this shape (it binds "pig be" as the subject and "alive" as
8862
+ * the verb), so the modal-plus-copula spelling gets its own closed template
8863
+ * and reaches the property facts the plain question already answers from,
8864
+ * plus the taught capability spelling ("animals can be alive", stored as
8865
+ * mgx:capableOf "be alive"). */
8866
+ const CAN_BE_PROPERTY_ASK_RE = /^(?:can|could)\s+(?:all\s+|every\s+)?(?:an?\s+|the\s+)?(.+?)\s+be\s+([a-z][\w-]*)[?.!\s]*$/i;
8867
+
8868
+ /** Whether a STORED term names the same thing as one of a query term's
8869
+ * variants. factTermVariants only ever folds toward the singular, so a fact
8870
+ * taught in the plural ("animals can be alive" stores the subject "animals")
8871
+ * is invisible to a singular query unless the stored side folds too. Both
8872
+ * sides fold here. */
8873
+ function termInVariants(normFactTerm, variants, term) {
8874
+ if (variants.has(term)) return true;
8875
+ for (const v of factTermVariants(normFactTerm, term)) if (variants.has(v)) return true;
8876
+ return false;
8877
+ }
8878
+
8879
+ /** The facts backing a property claim about a subject: the subject's own
8880
+ * property fact, or ONE stored subclass/type hop to a parent that carries it.
8881
+ * Returns the facts to cite in reading order (the membership first, then the
8882
+ * property), or null when nothing stored says it. One hop, so a two-step
8883
+ * taxonomy stays a miss rather than a guess — every fact in the answer is one
8884
+ * the store really holds, and the caller cites all of them. */
8885
+ function propertyPremises(rows, subjectVariants, adjective, normFactTerm) {
8886
+ const carriesProperty = (f) => (f.predicate === HAS_PROPERTY_PREDICATE && normFactTerm(f.object) === adjective)
8887
+ || (f.predicate === `tmct:${adjective}` && f.object === "true");
8888
+ const isSubject = (variants, f) => termInVariants(normFactTerm, variants, f.subject);
8889
+ const direct = rows.find((f) => isSubject(subjectVariants, f) && carriesProperty(f));
8890
+ if (direct) return [direct];
8891
+ for (const step of rows.filter((f) => ISA_PREDICATES.has(f.predicate) && isSubject(subjectVariants, f))) {
8892
+ const parentVariants = factTermVariants(normFactTerm, step.object);
8893
+ const inherited = rows.find((f) => isSubject(parentVariants, f) && carriesProperty(f));
8894
+ if (inherited) return [step, inherited];
8895
+ }
8896
+ return null;
8897
+ }
8898
+
8899
+ /** The capability twin of propertyPremises, over the same one stored hop: a
8900
+ * taught "animals can be alive" plus "a pig is an animal" answers "can a pig
8901
+ * be alive", citing both. The stored object keeps the bare infinitive it was
8902
+ * taught with ("be alive"), so the caller passes the variants it wants
8903
+ * matched rather than a single spelling. */
8904
+ function capabilityPremises(rows, subjectVariants, objectVariants, normFactTerm) {
8905
+ const carriesCapability = (f) => f.predicate === "mgx:capableOf" && objectVariants.has(normFactTerm(f.object));
8906
+ const isSubject = (variants, f) => termInVariants(normFactTerm, variants, f.subject);
8907
+ const direct = rows.find((f) => isSubject(subjectVariants, f) && carriesCapability(f));
8908
+ if (direct) return [direct];
8909
+ for (const step of rows.filter((f) => ISA_PREDICATES.has(f.predicate) && isSubject(subjectVariants, f))) {
8910
+ const parentVariants = factTermVariants(normFactTerm, step.object);
8911
+ const inherited = rows.find((f) => isSubject(parentVariants, f) && carriesCapability(f));
8912
+ if (inherited) return [step, inherited];
8913
+ }
8914
+ return null;
8915
+ }
8916
+ /** The teach lane stores "a dog has 4 legs" as ONE object string — "4 legs",
8917
+ * quantity and part together — so a count question has to split the quantity
8918
+ * back off the front to answer it. `numberOf` (the grammar lexicon's own
8919
+ * closed table) decides what reads as a quantity, which is why "4 legs" and
8920
+ * "two eyes" answer the same way. An object with no leading quantity ("a
8921
+ * tail") returns null and the count reader declines, leaving the plain
8922
+ * possession readers to answer it. */
8923
+ function quantifiedPossession(object) {
8924
+ const m = String(object ?? "").trim().match(/^([\w-]+)\s+(\S.*)$/);
8925
+ if (!m) return null;
8926
+ const count = numberOf(m[1]);
8927
+ return count === null ? null : { count, part: m[2] };
8928
+ }
8722
8929
  /** The class-level existential sibling of DOES_HAVE_ASK_RE for a verb OTHER
8723
8930
  * than "have" — "does a heart contain a hinge". A someValuesFrom
8724
8931
  * restriction (taught, or EL-entailed by /classify) never cares which
@@ -9144,8 +9351,14 @@ function withDeducedGoal(res, envelope, query) {
9144
9351
  * the miss names `/classify` — the one command that can compose further
9145
9352
  * ("/syllogise" is never offered here, since its plain scm-sco chase never
9146
9353
  * touches a class expression) — or, with no restriction on the subject at
9147
- * all, plain null so the caller's own miss cascade stands unchanged. */
9148
- async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fillerVariants, subjectWord = null) {
9354
+ * all, plain null so the caller's own miss cascade stands unchanged.
9355
+ *
9356
+ * `chainPremises` are the isa-family facts a caller already walked to reach
9357
+ * these subject variants — an individual's type assertion, and any further
9358
+ * subclass steps above it. They are cited ahead of the restriction's own
9359
+ * premises so the answer shows the whole route it took, not just the last
9360
+ * step of it. */
9361
+ async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fillerVariants, subjectWord = null, chainPremises = []) {
9149
9362
  const { ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE } = await import("../domain/syllogise.mjs");
9150
9363
  const rows = await factRows(memoryDir, cache);
9151
9364
  const onPropertyOf = new Map();
@@ -9172,7 +9385,7 @@ async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fill
9172
9385
  .map((id) => byId.get(id))
9173
9386
  .filter((r) => r && r.predicate === SUBCLASS_PREDICATE);
9174
9387
  const cited = premises.length ? premises : [hit];
9175
- return { text: `yes — ${cited.map(renderFactLine).join("; ")}`, replace: true };
9388
+ return { text: `yes — ${[...chainPremises, ...cited].map(renderFactLine).join("; ")}`, replace: true };
9176
9389
  }
9177
9390
  if (subjectRestrictions.length && subjectWord) {
9178
9391
  return {
@@ -9850,6 +10063,27 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9850
10063
  };
9851
10064
  }
9852
10065
 
10066
+ // (b-pre) "can a pig be alive" — the modal surface of the plain "are pigs
10067
+ // alive" property question. It runs ahead of every reader below because two
10068
+ // of them claim the shape and answer the wrong question with it: (b0)'s
10069
+ // derived "can be" marker looks for a capability fact whose object is the
10070
+ // bare property (the teach lane stores the infinitive, "be alive"), and
10071
+ // CAN_ASK_RE's single-word verb slot binds "pig be" as the subject. Both
10072
+ // stored spellings of the claim are searched here — the property fact the
10073
+ // plain question reads, and the taught capability fact — and each search
10074
+ // lifts one stored subclass/type hop, so a pig inherits what animals carry,
10075
+ // with the membership cited beside the property. Nothing stored either way
10076
+ // declines and the readers below get their ordinary turn.
10077
+ const canBe = positiveQuestionSurface(q).match(CAN_BE_PROPERTY_ASK_RE);
10078
+ if (canBe) {
10079
+ const canBeSubject = factTermVariants(normFactTerm, canBe[1]);
10080
+ const property = canBe[2].toLowerCase();
10081
+ const canBeRows = await factRows(memoryDir, cache);
10082
+ const canBePremises = propertyPremises(canBeRows, canBeSubject, property, normFactTerm)
10083
+ ?? capabilityPremises(canBeRows, canBeSubject, new Set([`be ${property}`, property]), normFactTerm);
10084
+ if (canBePremises) return { text: `yes — ${canBePremises.map(renderFactLine).join("; ")}`, replace: true };
10085
+ }
10086
+
9853
10087
  // (b0) Derived forward yes/no readers — FORWARD_YESNO_MARKERS, one per
9854
10088
  // renderable relation. Runs BEFORE the isa lane because ISA_ASK_RE's lazy
9855
10089
  // subject otherwise swallows these shapes whole ("is a wheel part of a
@@ -9972,6 +10206,27 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9972
10206
  return capabilityBaseRateReply(can[2], can[3], facts);
9973
10207
  }
9974
10208
 
10209
+ // (b2a-count) "how many legs does a dog have" — the count surface of the
10210
+ // possession facts (b2b) reads back, over the SAME predicates and the same
10211
+ // singular/plural fold. The stored object carries the quantity inside it
10212
+ // ("dog has 4 legs"), so the reader splits it off with quantifiedPossession
10213
+ // and matches only the part tail against what was asked. The answer leads
10214
+ // with the count and cites the fact it came from; a possession fact with no
10215
+ // quantity in it, or no possession fact at all, declines here so the honest
10216
+ // miss stands.
10217
+ const howManyHave = q.match(HOW_MANY_HAVE_ASK_RE);
10218
+ if (howManyHave) {
10219
+ const partVariants = factTermVariants(normFactTerm, howManyHave[1]);
10220
+ const countSubj = factTermVariants(normFactTerm, howManyHave[2]);
10221
+ const countFacts = await memoryFacts(memoryDir);
10222
+ const quantifiedHit = countFacts
10223
+ .map((f) => ({ fact: f, quantified: HAS_PREDICATES.has(f.predicate) && countSubj.has(f.subject) ? quantifiedPossession(f.object) : null }))
10224
+ .find(({ quantified }) => quantified && [...factTermVariants(normFactTerm, quantified.part)].some((v) => partVariants.has(v)));
10225
+ if (quantifiedHit) {
10226
+ return { text: `${quantifiedHit.quantified.count} — ${renderFactLine(quantifiedHit.fact)}`, replace: true };
10227
+ }
10228
+ }
10229
+
9975
10230
  // (b2b) "does a dog have a tail" — yes iff a remembered possession fact
9976
10231
  // says so: the forward yes/no mirror of WHAT_HAS_RE below, with the same
9977
10232
  // single-hit lookup and "never a guessed no" discipline as CAN_ASK_RE
@@ -9984,7 +10239,6 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9984
10239
  if (doesHave) {
9985
10240
  const subj = factTermVariants(normFactTerm, doesHave[1]);
9986
10241
  const obj = factTermVariants(normFactTerm, doesHave[2]);
9987
- const HAS_PREDICATES = new Set(["mgx:hasA", "tmct:has"]);
9988
10242
  const facts = await memoryFacts(memoryDir);
9989
10243
  const hasHit = (subjectSet) => facts.find(
9990
10244
  (f) => HAS_PREDICATES.has(f.predicate) && subjectSet.has(f.subject) && obj.has(f.object),
@@ -10018,11 +10272,22 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10018
10272
  if (liftSeen.has(step.object)) continue;
10019
10273
  liftSeen.add(step.object);
10020
10274
  const nextChain = [...chain, step];
10021
- const lifted = hasHit(factTermVariants(normFactTerm, step.object));
10275
+ const liftedTerms = factTermVariants(normFactTerm, step.object);
10276
+ const lifted = hasHit(liftedTerms);
10022
10277
  if (lifted) {
10023
10278
  return { text: `yes — ${[...nextChain.map(renderFactLine), renderFactLine(lifted)].join("; ")}`, replace: true };
10024
10279
  }
10025
- nextFrontier.push({ terms: factTermVariants(normFactTerm, step.object), chain: nextChain });
10280
+ // A class-level "every argyle has a receptacle" is stored as a
10281
+ // someValuesFrom restriction, not a flat possession triple, so the
10282
+ // same walk has to look for that shape at every step it reaches —
10283
+ // otherwise an individual placed in the class ("e150.mjs is a
10284
+ // argyle") inherits nothing. The walked isa steps are cited beside
10285
+ // the restriction's own premises. `subjectWord` stays null here so
10286
+ // the mid-walk "/classify" nudge never fires: the walk is still
10287
+ // going, and the direct call below owns that miss.
10288
+ const liftedRestriction = await restrictionExistentialHit(memoryDir, cache, liftedTerms, obj, null, nextChain);
10289
+ if (liftedRestriction) return liftedRestriction;
10290
+ nextFrontier.push({ terms: liftedTerms, chain: nextChain });
10026
10291
  }
10027
10292
  }
10028
10293
  if (!nextFrontier.length) break;
@@ -12068,6 +12333,15 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
12068
12333
  replace: true,
12069
12334
  };
12070
12335
  }
12336
+ // A property the subject doesn't carry itself can still be carried by a
12337
+ // class it belongs to: "a pig is an animal" plus "animals are alive"
12338
+ // answers "are pigs alive". One stored hop, and BOTH facts go on the
12339
+ // line — the membership and the property — so the answer asserts nothing
12340
+ // the store doesn't already hold. A two-step taxonomy stays a miss here.
12341
+ const inheritedProperty = propertyPremises(rows, subjVariants, adjective, normFactTerm);
12342
+ if (inheritedProperty) {
12343
+ return { text: `yes — ${inheritedProperty.map(renderFactLine).join("; ")}`, replace: true };
12344
+ }
12071
12345
  // No property hit — but a bare "is X Y" (no article) is exactly the
12072
12346
  // same claim as "is X a Y" would have been had the user included the
12073
12347
  // article (ISA_ASK_RE's own territory, above): the canonical syllogism
@@ -12788,6 +13062,28 @@ function unknownVocabTermOffer(term) {
12788
13062
  return `I don't know "${term}" yet — teach me directly${example ? `, e.g. ${example}` : ` (e.g. "remember <name> is ${article} <thing>")`}.`;
12789
13063
  }
12790
13064
 
13065
+ /** The head noun's answer for an adjective-qualified phrase the store holds
13066
+ * nothing under — "female dog" answers for "dog", with the phrase named as
13067
+ * unheld so the adjective is never silently dropped. Closed to exactly the
13068
+ * two-word shape whose first word the lexicon calls an adjective and whose
13069
+ * second it calls a noun, and it only ever returns text when the head noun
13070
+ * really resolves; anything else is null and the caller's own dead-end
13071
+ * stands. The envelope is deliberately NOT passed on: it was parsed from the
13072
+ * question about the full phrase, and metaTermOf would read the phrase back
13073
+ * out of it and re-ask the question that just missed. */
13074
+ async function adjectiveQualifiedHeadAnswer(term, { memoryDir, biasByBundle = {}, cache = null, graph = null, lexicon = null }) {
13075
+ const words = String(term ?? "").trim().toLowerCase().split(/\s+/);
13076
+ if (words.length !== 2) return null;
13077
+ const [modifier, head] = words;
13078
+ const lex = lexicon || loadLexicon();
13079
+ if (!lookupAdjective(lex, modifier) || !lookupNoun(lex, head)) return null;
13080
+ const headQuery = `what is ${indefiniteArticleFor(head)} ${head}`;
13081
+ const hit = (await factAnswer(memoryDir, headQuery, null, true, biasByBundle, cache))
13082
+ ?? (await factReadBack(memoryDir, headQuery, null, true, graph, null, biasByBundle, cache));
13083
+ if (!hit || hit.miss || !hit.text) return null;
13084
+ return `I have nothing under "${term}". Here's what I know about ${indefiniteArticleFor(head)} ${head}:\n${hit.text}`;
13085
+ }
13086
+
12791
13087
  /** The curated SEON definition to PREFER for a "what is a <lexicon term>", or null.
12792
13088
  * Gated: the term parses as a meta question, is a grammar-lexicon noun, has a
12793
13089
  * curated definition, this repo carries the SEON concept seed for it (a corpus:seon
@@ -12982,6 +13278,14 @@ async function ingestReferenceArticle(memoryDir, key, article, cache, tagFor = r
12982
13278
  // materialisation, not the whole-store maintenance job /syllogise runs.
12983
13279
  const AUTO_SYNTHESIS_BUDGET = 12;
12984
13280
 
13281
+ // Caps how many child-pack pulls one tied choice-question turn may spend on
13282
+ // the stem's own constraint terms (pullChoiceConstraintFacts, above). Five
13283
+ // covers every constraint term a CommonsenseQA stem carries after stopword
13284
+ // filtering; the cap is what stops a long stem from turning one turn into a
13285
+ // bulk import. A constant rather than config: it bounds work per turn, which
13286
+ // is a design decision, not a preference.
13287
+ const CHOICE_CONSTRAINT_PULL_BUDGET = 5;
13288
+
12985
13289
  /** The `[reasoning]` knobs for a classification pass rooted at `memoryDir` —
12986
13290
  * the repo's own `tmct.toml` when it sets one, the shipped defaults
12987
13291
  * otherwise. `resolveReasoningConfig` wants the NORMALIZED sparse pass-
@@ -14709,7 +15013,13 @@ const ARCH_OVERVIEW_PHRASES = [
14709
15013
  new RegExp(`^${ARCH_OVERVIEW_LEAD}(?:(?:an?|the)\\s+)?(?:overview|map|diagram)\\s+${ARCH_OVERVIEW_OF_REPO}(?:\\s+here)?\\??$`, "i"),
14710
15014
  ];
14711
15015
 
14712
- async function runAsk(query, { config, source, graph, focus, last, templates, memoryDir, sessionId = "", lexicon = null, env, trace, vocabHint = null, tel = null, biasByBundle = {}, cache = null, vocabAntecedent = null, planHolder = null, discourseHolder = null, gameConfig = DEFAULT_GAME_CONFIG, liveReference = false, onLiveLookup = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, codeDomainActive = false }) {
15016
+ async function runAsk(query, { config, source, graph, focus, last, templates, memoryDir, sessionId = "", lexicon = null, env, trace, vocabHint: sessionVocabHint = null, tel = null, biasByBundle = {}, cache = null, vocabAntecedent = null, planHolder = null, discourseHolder = null, gameConfig = DEFAULT_GAME_CONFIG, liveReference = false, onLiveLookup = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, codeDomainActive = false }) {
15017
+ // The session-wide hint names a term this session can PROVE resolves; when
15018
+ // the question itself named a subject the lexicon knows, the hint names that
15019
+ // instead, so a miss on "how many eyes does a human have" points at "human"
15020
+ // rather than at the stock example. Computed once per turn, and every
15021
+ // dead-end below reads it through this one binding.
15022
+ const vocabHint = namedSubjectVocabHint(query, sessionVocabHint, lexicon);
14713
15023
  const ts = new Date().toISOString();
14714
15024
  // The surface this turn runs on ("cli" default; "browser" from a web entry) —
14715
15025
  // the honest-miss tail below points a browser/adventure miss at the teach
@@ -16245,7 +16555,24 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16245
16555
  // nothing but a loose association still gets the "teach me" offer
16246
16556
  // rather than being silently counted as already known.
16247
16557
  const known = hasNonWeakGrounding(await factRows(memoryDir, cache), variants);
16248
- if (!known) teachOffer = unknownVocabTermOffer(cleanTerm);
16558
+ if (!known) {
16559
+ // An adjective-qualified phrase the store has never heard of still
16560
+ // has a head noun it may know all about: "what is a female dog"
16561
+ // (and its inverted twin "a female dog is what") answers for "dog"
16562
+ // and says the graph holds nothing under "female dog", so the
16563
+ // adjective is never silently dropped. Only on a REAL hit for the
16564
+ // head noun; with nothing there either, the ordinary teach-offer
16565
+ // stands.
16566
+ const headFallback = await adjectiveQualifiedHeadAnswer(cleanTerm, { memoryDir, biasByBundle, cache, graph, lexicon });
16567
+ if (headFallback) {
16568
+ answer = headFallback;
16569
+ via = "fact";
16570
+ recordMiss = false;
16571
+ note(trace, "lane: (4x) ADJECTIVE-QUALIFIED HEAD NOUN — the full phrase grounded nothing, so the answer is the head noun's, with the phrase named as unheld");
16572
+ } else {
16573
+ teachOffer = unknownVocabTermOffer(cleanTerm);
16574
+ }
16575
+ }
16249
16576
  }
16250
16577
  }
16251
16578
  }
@@ -17421,6 +17748,11 @@ const joinList = (a) => (a.length > 1 ? `${a.slice(0, -1).join(", ")} and ${a[a.
17421
17748
  // deliberately not the resolver's longer numbered ambiguity format.
17422
17749
  const joinOr = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, or ${a[a.length - 1]}`
17423
17750
  : a.length === 2 ? `${a[0]} or ${a[1]}` : (a[0] ?? ""));
17751
+ // Same Oxford-comma join as joinOr, "and" for a list every member of which
17752
+ // holds at once (the constraint terms a runner-up failed to satisfy), not a
17753
+ // set of alternatives.
17754
+ const joinAnd = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, and ${a[a.length - 1]}`
17755
+ : a.length === 2 ? `${a[0]} and ${a[1]}` : (a[0] ?? ""));
17424
17756
 
17425
17757
  /** Render the next page of a held remainder (pending: {items:[str], noun}). Returns a
17426
17758
  * plain turn whose `detail.pending` carries what's still unseen (null when the batch
@@ -17761,6 +18093,24 @@ function rewriteVocabOpener(line, { adventureLive = false } = {}) {
17761
18093
  return null;
17762
18094
  }
17763
18095
 
18096
+ /** The INVERTED vocabulary question — "a dog is what?", "dogs are what". It
18097
+ * asks exactly what "what is a dog" asks, with the wh-word left where the
18098
+ * answer would go, so it rewrites to the canonical form here, once, before
18099
+ * any dispatch lane sees the text. The determiner is carried through as
18100
+ * typed, since the vocabulary lane already reads the term with or without one.
18101
+ * A pronoun or demonstrative subject is excluded: "that is what" is a
18102
+ * conversational fragment, not a question about a term. Question mark
18103
+ * optional — the word order is the whole signal. */
18104
+ const INVERTED_WHATIS_RE = /^(an?|the)?\s*([a-z][\w'-]*(?:\s+[a-z][\w'-]*)*)\s+(?:is|are)\s+what\s*[?.!]*$/i;
18105
+ const INVERTED_WHATIS_PRONOUN_SUBJECT_RE = /^(?:it|this|that|these|those|they|them|he|she|we|you|i|there|here|so|then|and|but|which|who|what|where|when|why|how)$/i;
18106
+ function rewriteInvertedWhatIs(line) {
18107
+ const m = String(line || "").trim().match(INVERTED_WHATIS_RE);
18108
+ if (!m) return null;
18109
+ const phrase = m[2].trim();
18110
+ if (INVERTED_WHATIS_PRONOUN_SUBJECT_RE.test(phrase.split(/\s+/)[0])) return null;
18111
+ return `what is ${m[1] ? `${m[1].toLowerCase()} ` : ""}${phrase}`;
18112
+ }
18113
+
17764
18114
  /** The ESL missing-"does" yes/no — "dog have tail?": subject + bare
17765
18115
  * have/has + object, question mark REQUIRED (the "?" is the whole signal;
17766
18116
  * without it the line is a declarative and belongs to the teach path).
@@ -18078,7 +18428,8 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18078
18428
  const indirectMatch = line.match(INDIRECT_REQUEST_RE);
18079
18429
  const indirectLine = indirectMatch ? indirectMatch[1].trim() : line;
18080
18430
  const preRewriteLine = rewriteEntryPointQuestion(indirectLine) || rewriteProveThat(indirectLine)
18081
- || rewriteVocabOpener(indirectLine, { adventureLive: Boolean(planState?.adventure) }) || indirectLine;
18431
+ || rewriteVocabOpener(indirectLine, { adventureLive: Boolean(planState?.adventure) })
18432
+ || rewriteInvertedWhatIs(indirectLine) || indirectLine;
18082
18433
  // rewriteUsesAsBaseFrame's discontiguous-frame rewrite: applied here, once,
18083
18434
  // before ANY dispatch lane sees the text. Null (no-op) for every turn that
18084
18435
  // doesn't match one of the four discontiguous shapes.
@@ -18286,6 +18637,37 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18286
18637
  }
18287
18638
  }
18288
18639
 
18640
+ // AGENT DRIVE TRAITS — "who does the cabbage evade", "what does the fox
18641
+ // eat", "who guards the goat": the ask side of the actor card's own closed
18642
+ // sentence table (agent-editor.mjs), reading the SAME `mgx:` trait rows
18643
+ // that card renders and writes. It sits after the game lanes so a live
18644
+ // game's own grammar always wins the line, and it claims a question only
18645
+ // when the store states a trait about the named term at all — with none,
18646
+ // agent-editor answers null and the question falls through to whatever
18647
+ // lane owned it before.
18648
+ {
18649
+ const traitAsk = parseAgentTraitAsk(workingLine);
18650
+ if (traitAsk) {
18651
+ const rows = await factRows(memoryDir, factRowsCache);
18652
+ const answered = answerAgentTraitAsk(rows, traitAsk, {
18653
+ cite: (r) => (r.provenance ? ` (source: ${citationProvenance(r.provenance)})` : ""),
18654
+ });
18655
+ if (answered) {
18656
+ const goal = "look up a stated agent trait";
18657
+ note(trace, `lane: agent-trait ask — ${traitAsk.direction} ${traitAsk.predicate} on "${traitAsk.term}", ${answered.matches.length} stated row(s)`);
18658
+ const turn = plainTurn(workingLine, answered.text, { via: "composed", miss: answered.miss, focus, goal });
18659
+ turn.lane = "ask-agent-trait";
18660
+ turn.detail = {
18661
+ traversal: `${traitAsk.direction} read of ${traitAsk.predicate} over "${traitAsk.term}"`,
18662
+ matches: answered.matches,
18663
+ };
18664
+ const rec = withLast(turn, goal);
18665
+ rec.planState = planHolder.state;
18666
+ return rec;
18667
+ }
18668
+ }
18669
+ }
18670
+
18289
18671
  // A "play X" naming no world EITHER game lane above claimed — last resort,
18290
18672
  // checked only once the adventure lane's own fallthrough and spider-fly's
18291
18673
  // own opener have both passed on the line, so this never outguesses a
@@ -18524,31 +18906,84 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18524
18906
  const parsed = splitChoiceQuestion(workingLine);
18525
18907
  if (parsed) {
18526
18908
  const choiceGoal = "pick the option a stated relation grounds, among a closed set of alternatives";
18527
- const refMiss = (text) => {
18909
+ const refMiss = (text, extraDetail = null) => {
18528
18910
  note(trace, `goal: ${choiceGoal}`);
18529
18911
  note(trace, `lane: splitChoiceQuestion — "${workingLine}" parsed as a ${parsed.shape} choice question but could not compose an answer`);
18530
- return withLast(plainTurn(workingLine, text, { via: "miss", miss: true, focus, goal: choiceGoal }), choiceGoal);
18912
+ const turn = plainTurn(workingLine, text, { via: "miss", miss: true, focus, goal: choiceGoal });
18913
+ if (extraDetail) turn.detail = { ...turn.detail, ...extraDetail };
18914
+ return withLast(turn, choiceGoal);
18531
18915
  };
18532
- if (!parsed.sourceTerm) {
18916
+ // The topic is read off a CANDIDATE LIST (stemTopicCandidates), not off
18917
+ // a single fixed-shape template capture: extractStemSourceTerm's own
18918
+ // capture (parsed.sourceTerm) survives only as chooseChoiceTopic's tie-
18919
+ // break, because a template is right about a fronted "where would you
18920
+ // find X" stem, exactly the stems where several candidates tie on
18921
+ // salience. A stem naming no usable candidate, or naming several that
18922
+ // the graph holds nothing about, both come back as "" here — the same
18923
+ // no-topic miss either way.
18924
+ const candidates = stemTopicCandidates(parsed.stem, parsed.options);
18925
+ const { topic } = await chooseChoiceTopic(candidates, {
18926
+ memoryDir, cache: factRowsCache, templateCapture: parsed.sourceTerm,
18927
+ });
18928
+ if (!topic) {
18533
18929
  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.`);
18534
18930
  }
18535
- const probed = await probeChoiceOptions(parsed, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
18931
+ const probed = await probeChoiceOptions({ ...parsed, sourceTerm: topic }, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
18536
18932
  const grounded = probed.filter((o) => o.grounds);
18537
18933
  note(trace, `goal: ${choiceGoal}`);
18538
18934
  if (grounded.length === 0) {
18539
- note(trace, `lane: splitChoiceQuestion — no stated relation between "${parsed.sourceTerm}" and any of ${probed.length} options; the honest miss, never a guess`);
18540
- 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.`);
18935
+ note(trace, `lane: splitChoiceQuestion — no stated relation between "${topic}" and any of ${probed.length} options; the honest miss, never a guess`);
18936
+ return refMiss(`I don't know how "${topic}" relates to any of ${joinOr(probed.map((o) => o.text))}. Nothing I hold connects it to one of them.`, { topic });
18541
18937
  }
18542
18938
  if (grounded.length > 1) {
18939
+ // The stem's OTHER content terms are constraints the question stated
18940
+ // beyond naming its topic — pulled here, not at the topic probe
18941
+ // above, because they only matter once a tie needs something to
18942
+ // separate on. Never pulled for an option term (stemConstraintTerms'
18943
+ // own filter already excludes those).
18944
+ const constraintTerms = stemConstraintTerms(parsed.stem, topic, parsed.options);
18945
+ await pullChoiceConstraintFacts(constraintTerms, { memoryDir, env, cache: factRowsCache, synthesisBudget });
18946
+ const rowsAfterPull = await factRows(memoryDir, factRowsCache);
18947
+ // Separate on constraints, never on strength: separateChoiceTie only
18948
+ // picks when exactly one option satisfies STRICTLY MORE of the
18949
+ // stem's other content terms than every rival — a level count, a
18950
+ // zero count, or more than one option level all stay a refusal.
18951
+ const separated = separateChoiceTie(grounded, constraintTerms, rowsAfterPull);
18952
+ if (separated) {
18953
+ const { winner, runnerUp, missedByRunnerUp } = separated;
18954
+ const groundingFact = winner.facts.length > 0 ? winner.facts.slice().sort((a, b) => b.trust - a.trust)[0] : null;
18955
+ const groundingClause = groundingFact
18956
+ ? `${factPhrase(groundingFact)} (source: ${citationProvenance(groundingFact.provenance)})`
18957
+ : renderIsaChain(winner.chain);
18958
+ const constraintClause = winner.satisfied
18959
+ .map(({ term, fact }) => `the question also says ${term}, which ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)})`)
18960
+ .join("; ");
18961
+ const text = `${winner.text} — ${groundingClause}, and ${constraintClause}. The other option that `
18962
+ + `grounds is ${runnerUp.text}, and I hold nothing linking it to ${joinAnd(missedByRunnerUp)}.`;
18963
+ note(trace, `lane: splitChoiceQuestion — "${winner.label}" satisfies ${winner.satisfied.length} constraint term(s) the runner-up "${runnerUp.label}" does not; separated, not a broken tie`);
18964
+ const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18965
+ turn.lane = "ask-choice";
18966
+ turn.detail = {
18967
+ traversal: `option "${winner.label}" separated from a ${grounded.length}-way tie against "${topic}" by ${winner.satisfied.length} constraint term(s)`,
18968
+ matches: [...(groundingFact ? [groundingFact] : winner.chain), ...winner.satisfied.map((s) => s.fact)],
18969
+ selectedLabel: winner.label,
18970
+ topic,
18971
+ separatedBy: winner.satisfied.map((s) => s.term),
18972
+ runnerUpLabel: runnerUp.label,
18973
+ };
18974
+ return withLast(turn, choiceGoal);
18975
+ }
18543
18976
  // A tie is reported, never broken — whatever the grounded options'
18544
- // own edge weights, this branch fires on COUNT alone.
18545
- note(trace, `lane: splitChoiceQuestion — ${grounded.length} of ${probed.length} options ground against "${parsed.sourceTerm}"; reported as a tie`);
18546
- 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.`;
18977
+ // own edge weights, this branch fires on COUNT alone (or on a level
18978
+ // constraint count above, which is the same rule at a finer grain).
18979
+ note(trace, `lane: splitChoiceQuestion — ${grounded.length} of ${probed.length} options ground against "${topic}"; reported as a tie`);
18980
+ const text = `More than one of those grounds: ${joinOr(grounded.map((o) => o.text))}. I have a stated relation from ${topic} to each, so nothing in what I hold picks between them.`;
18547
18981
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18548
18982
  turn.lane = "ask-choice";
18549
18983
  turn.detail = {
18550
- traversal: `${grounded.length} of ${probed.length} options grounded against "${parsed.sourceTerm}"`,
18984
+ traversal: `${grounded.length} of ${probed.length} options grounded against "${topic}"`,
18551
18985
  matches: grounded.flatMap((o) => (o.facts.length ? o.facts : o.chain || [])),
18986
+ topic,
18552
18987
  };
18553
18988
  return withLast(turn, choiceGoal);
18554
18989
  }
@@ -18562,14 +18997,14 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18562
18997
  matches = winner.facts;
18563
18998
  hop = 1;
18564
18999
  matchedBy = fact.matchedBy;
18565
- traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`;
19000
+ traversalNote = `option "${winner.label}" grounded against "${topic}" via ${fact.predicate}`;
18566
19001
  } else {
18567
19002
  text = `${winner.text} — ${renderIsaChain(winner.chain)}.`;
18568
19003
  matches = winner.chain;
18569
19004
  hop = winner.chain.length;
18570
- traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via a ${winner.chain.length}-hop isa chain`;
19005
+ traversalNote = `option "${winner.label}" grounded against "${topic}" via a ${winner.chain.length}-hop isa chain`;
18571
19006
  }
18572
- note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
19007
+ note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${topic}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18573
19008
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18574
19009
  turn.lane = "ask-choice";
18575
19010
  turn.detail = {
@@ -18577,6 +19012,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18577
19012
  matches,
18578
19013
  selectedLabel: winner.label,
18579
19014
  hop,
19015
+ topic,
18580
19016
  ...(matchedBy ? { matchedBy } : {}),
18581
19017
  };
18582
19018
  return withLast(turn, choiceGoal);
@@ -18832,6 +19268,42 @@ export async function hasSeededVocabulary(repo) {
18832
19268
  * that. This clause is threaded through runAsk as `vocabHint` and reused by
18833
19269
  * every dead-end that needs to name an exit, so one split here covers them
18834
19270
  * all rather than each miss carrying its own copy. */
19271
+ /** The stock vocabulary example, rewritten to name the subject THIS question
19272
+ * asked about. A miss on "how many eyes does a human have" that recommends
19273
+ * "what is a dog" answers a question nobody asked; naming "human" points at
19274
+ * the term the user already has in mind, and the next turn is one they meant
19275
+ * to type. The subject comes from a CLOSED list of question shapes — the same
19276
+ * regexes the readers themselves match on, read at call time so each is
19277
+ * already initialised — and only counts when the lexicon knows the head word,
19278
+ * so a garbled parse can never put nonsense inside the offered example. With
19279
+ * no readable subject, or a subject that IS the stock term, the hint comes
19280
+ * back exactly as the session computed it. */
19281
+ function namedSubjectVocabHint(query, hint, lexicon = null) {
19282
+ const STOCK = '"what is a dog"';
19283
+ if (!hint || !hint.includes(STOCK)) return hint;
19284
+ const q = normalizeQuery(String(query ?? "")).trim();
19285
+ const readers = [
19286
+ { re: HOW_MANY_HAVE_ASK_RE, group: 2 },
19287
+ { re: DOES_HAVE_ASK_RE, group: 1 },
19288
+ { re: CAN_BE_PROPERTY_ASK_RE, group: 1 },
19289
+ { re: CAN_ASK_RE, group: 2 },
19290
+ { re: DO_VERB_ASK_RE, group: 2 },
19291
+ { re: IS_ADJECTIVE_YESNO_RE, group: 1 },
19292
+ { re: BARE_WHATIS_RE, group: 1 },
19293
+ ];
19294
+ let lex = lexicon;
19295
+ for (const { re, group } of readers) {
19296
+ const raw = q.match(re)?.[group]?.trim();
19297
+ if (!raw) continue;
19298
+ const word = singularizeSurface(raw.toLowerCase().split(/\s+/).pop());
19299
+ if (!word || word === "dog") continue;
19300
+ if (!lex) lex = loadLexicon();
19301
+ if (!lookupNoun(lex, word)) continue;
19302
+ return hint.replace(STOCK, `"what is ${indefiniteArticleFor(word)} ${word}"`);
19303
+ }
19304
+ return hint;
19305
+ }
19306
+
18835
19307
  export function vocabExampleHint(seeded, uiContext = "cli") {
18836
19308
  if (seeded) return 'Try "what is a dog" for general vocabulary.';
18837
19309
  return uiContext === "browser"