@polycode-projects/the-mechanical-code-talker 5.0.35 → 5.0.37

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,
@@ -77,6 +77,7 @@ 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
@@ -8846,6 +8847,85 @@ function apposedFactTerm(term, rows, normFactTerm) {
8846
8847
  * factReadBack(...)` — never both). */
8847
8848
  const CAN_ASK_RE = /^(?:can|could)\s+(all\s+|every\s+)?(?:an?\s+)?([\w'-]+(?:\s+[\w'-]+)*?)\s+([a-z]+)[?.!\s]*$/i;
8848
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
+ }
8849
8929
  /** The class-level existential sibling of DOES_HAVE_ASK_RE for a verb OTHER
8850
8930
  * than "have" — "does a heart contain a hinge". A someValuesFrom
8851
8931
  * restriction (taught, or EL-entailed by /classify) never cares which
@@ -9271,8 +9351,14 @@ function withDeducedGoal(res, envelope, query) {
9271
9351
  * the miss names `/classify` — the one command that can compose further
9272
9352
  * ("/syllogise" is never offered here, since its plain scm-sco chase never
9273
9353
  * touches a class expression) — or, with no restriction on the subject at
9274
- * all, plain null so the caller's own miss cascade stands unchanged. */
9275
- 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 = []) {
9276
9362
  const { ON_PROPERTY_PREDICATE, SOME_VALUES_FROM_PREDICATE } = await import("../domain/syllogise.mjs");
9277
9363
  const rows = await factRows(memoryDir, cache);
9278
9364
  const onPropertyOf = new Map();
@@ -9299,7 +9385,7 @@ async function restrictionExistentialHit(memoryDir, cache, subjectVariants, fill
9299
9385
  .map((id) => byId.get(id))
9300
9386
  .filter((r) => r && r.predicate === SUBCLASS_PREDICATE);
9301
9387
  const cited = premises.length ? premises : [hit];
9302
- return { text: `yes — ${cited.map(renderFactLine).join("; ")}`, replace: true };
9388
+ return { text: `yes — ${[...chainPremises, ...cited].map(renderFactLine).join("; ")}`, replace: true };
9303
9389
  }
9304
9390
  if (subjectRestrictions.length && subjectWord) {
9305
9391
  return {
@@ -9977,6 +10063,27 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9977
10063
  };
9978
10064
  }
9979
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
+
9980
10087
  // (b0) Derived forward yes/no readers — FORWARD_YESNO_MARKERS, one per
9981
10088
  // renderable relation. Runs BEFORE the isa lane because ISA_ASK_RE's lazy
9982
10089
  // subject otherwise swallows these shapes whole ("is a wheel part of a
@@ -10099,6 +10206,27 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10099
10206
  return capabilityBaseRateReply(can[2], can[3], facts);
10100
10207
  }
10101
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
+
10102
10230
  // (b2b) "does a dog have a tail" — yes iff a remembered possession fact
10103
10231
  // says so: the forward yes/no mirror of WHAT_HAS_RE below, with the same
10104
10232
  // single-hit lookup and "never a guessed no" discipline as CAN_ASK_RE
@@ -10111,7 +10239,6 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10111
10239
  if (doesHave) {
10112
10240
  const subj = factTermVariants(normFactTerm, doesHave[1]);
10113
10241
  const obj = factTermVariants(normFactTerm, doesHave[2]);
10114
- const HAS_PREDICATES = new Set(["mgx:hasA", "tmct:has"]);
10115
10242
  const facts = await memoryFacts(memoryDir);
10116
10243
  const hasHit = (subjectSet) => facts.find(
10117
10244
  (f) => HAS_PREDICATES.has(f.predicate) && subjectSet.has(f.subject) && obj.has(f.object),
@@ -10145,11 +10272,22 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10145
10272
  if (liftSeen.has(step.object)) continue;
10146
10273
  liftSeen.add(step.object);
10147
10274
  const nextChain = [...chain, step];
10148
- const lifted = hasHit(factTermVariants(normFactTerm, step.object));
10275
+ const liftedTerms = factTermVariants(normFactTerm, step.object);
10276
+ const lifted = hasHit(liftedTerms);
10149
10277
  if (lifted) {
10150
10278
  return { text: `yes — ${[...nextChain.map(renderFactLine), renderFactLine(lifted)].join("; ")}`, replace: true };
10151
10279
  }
10152
- 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 });
10153
10291
  }
10154
10292
  }
10155
10293
  if (!nextFrontier.length) break;
@@ -12195,6 +12333,15 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
12195
12333
  replace: true,
12196
12334
  };
12197
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
+ }
12198
12345
  // No property hit — but a bare "is X Y" (no article) is exactly the
12199
12346
  // same claim as "is X a Y" would have been had the user included the
12200
12347
  // article (ISA_ASK_RE's own territory, above): the canonical syllogism
@@ -12915,6 +13062,28 @@ function unknownVocabTermOffer(term) {
12915
13062
  return `I don't know "${term}" yet — teach me directly${example ? `, e.g. ${example}` : ` (e.g. "remember <name> is ${article} <thing>")`}.`;
12916
13063
  }
12917
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
+
12918
13087
  /** The curated SEON definition to PREFER for a "what is a <lexicon term>", or null.
12919
13088
  * Gated: the term parses as a meta question, is a grammar-lexicon noun, has a
12920
13089
  * curated definition, this repo carries the SEON concept seed for it (a corpus:seon
@@ -14844,7 +15013,13 @@ const ARCH_OVERVIEW_PHRASES = [
14844
15013
  new RegExp(`^${ARCH_OVERVIEW_LEAD}(?:(?:an?|the)\\s+)?(?:overview|map|diagram)\\s+${ARCH_OVERVIEW_OF_REPO}(?:\\s+here)?\\??$`, "i"),
14845
15014
  ];
14846
15015
 
14847
- 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);
14848
15023
  const ts = new Date().toISOString();
14849
15024
  // The surface this turn runs on ("cli" default; "browser" from a web entry) —
14850
15025
  // the honest-miss tail below points a browser/adventure miss at the teach
@@ -16380,7 +16555,24 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16380
16555
  // nothing but a loose association still gets the "teach me" offer
16381
16556
  // rather than being silently counted as already known.
16382
16557
  const known = hasNonWeakGrounding(await factRows(memoryDir, cache), variants);
16383
- 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
+ }
16384
16576
  }
16385
16577
  }
16386
16578
  }
@@ -17901,6 +18093,24 @@ function rewriteVocabOpener(line, { adventureLive = false } = {}) {
17901
18093
  return null;
17902
18094
  }
17903
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
+
17904
18114
  /** The ESL missing-"does" yes/no — "dog have tail?": subject + bare
17905
18115
  * have/has + object, question mark REQUIRED (the "?" is the whole signal;
17906
18116
  * without it the line is a declarative and belongs to the teach path).
@@ -18218,7 +18428,8 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18218
18428
  const indirectMatch = line.match(INDIRECT_REQUEST_RE);
18219
18429
  const indirectLine = indirectMatch ? indirectMatch[1].trim() : line;
18220
18430
  const preRewriteLine = rewriteEntryPointQuestion(indirectLine) || rewriteProveThat(indirectLine)
18221
- || rewriteVocabOpener(indirectLine, { adventureLive: Boolean(planState?.adventure) }) || indirectLine;
18431
+ || rewriteVocabOpener(indirectLine, { adventureLive: Boolean(planState?.adventure) })
18432
+ || rewriteInvertedWhatIs(indirectLine) || indirectLine;
18222
18433
  // rewriteUsesAsBaseFrame's discontiguous-frame rewrite: applied here, once,
18223
18434
  // before ANY dispatch lane sees the text. Null (no-op) for every turn that
18224
18435
  // doesn't match one of the four discontiguous shapes.
@@ -18426,6 +18637,37 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18426
18637
  }
18427
18638
  }
18428
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
+
18429
18671
  // A "play X" naming no world EITHER game lane above claimed — last resort,
18430
18672
  // checked only once the adventure lane's own fallthrough and spider-fly's
18431
18673
  // own opener have both passed on the line, so this never outguesses a
@@ -19026,6 +19268,42 @@ export async function hasSeededVocabulary(repo) {
19026
19268
  * that. This clause is threaded through runAsk as `vocabHint` and reused by
19027
19269
  * every dead-end that needs to name an exit, so one split here covers them
19028
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
+
19029
19307
  export function vocabExampleHint(seeded, uiContext = "cli") {
19030
19308
  if (seeded) return 'Try "what is a dog" for general vocabulary.';
19031
19309
  return uiContext === "browser"