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

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.
package/README.md CHANGED
@@ -1452,6 +1452,17 @@ loads a repo's graph into a `{ dispatch, resolve, graph }` context,
1452
1452
  `declaredCapabilityNames()` lists every capability a caller can declare. See
1453
1453
  "Planning across the graph" above.
1454
1454
 
1455
+ ```js
1456
+ import { agentbenchEnvelope } from "@polycode-projects/the-mechanical-code-talker/envelope";
1457
+ ```
1458
+
1459
+ This reads the AGENTBENCH capability envelope
1460
+ (`test-benchmarks/agentbench/envelope.json`, see "Measuring it" below) at
1461
+ runtime instead of a hand-copied snapshot. It carries the measured tool-loop
1462
+ rung reached, `structuredOk`/`toolsOk`, and `maxContextTokens` (`null` until
1463
+ AGENTBENCH measures one). A calibration elsewhere can check itself against
1464
+ these figures instead of drifting from them.
1465
+
1455
1466
  <!-- generated by scripts/generate-tool-docs.mjs from src/tools/definitions.mjs — do not edit by hand -->
1456
1467
 
1457
1468
  ## The tool surface
@@ -1577,9 +1588,10 @@ and transcripts are in the linked write-ups.
1577
1588
  | Determinism | Byte-identical on rerun: a 379-case `--replay` clean across 2 runs, no LLM, no network, $0 per turn | A property of the no-model pipeline. | `archive/BENCHMARK_INFERENCE_2.7.12.md` |
1578
1589
  | Dialogue robustness (persona sweep) | A 6-persona sweep (textbook logician, casual newcomer, new developer, adversarial sceptic, returning user, planning user) fixed 25 of the prior cycle's 29 routed findings (21 clean, 4 with a residual noted); 4 remain broken, 2 in a shape distinct from the original complaint | Free exploration across all six personas surfaced roughly 60 fresh findings beyond the ratchet check. The single highest-signal pattern: tmct's own suggested repair text was itself frequently broken when followed verbatim (since fixed, see `NEXT.md`). | `archive/BENCHMARK_CONVERSATION_2.7.11.md` |
1579
1590
 
1580
- Seven offline benchmark rigs live in a clone (they are not in the npm
1581
- package). Each replays a committed case set through the real product and
1582
- writes graded rows you can diff between runs:
1591
+ Seven offline benchmark rigs live in a clone (the harnesses themselves are
1592
+ not in the npm package; AGENTBENCH's capability envelope is, see "As a
1593
+ library" above). Each replays a committed case set through the real product
1594
+ and writes graded rows you can diff between runs:
1583
1595
 
1584
1596
  - `npm run chatbench:run` measures chat quality against CEFR-graded English
1585
1597
  cases with deterministic tier-1 checks (the full tuning loop is in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.31",
3
+ "version": "5.0.32",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -50,7 +50,8 @@
50
50
  "./memory": "./src/adapters/memory/core.mjs",
51
51
  "./repository-interface": "./src/adapters/repository-interface.mjs",
52
52
  "./conformance": "./src/tools/conformance.mjs",
53
- "./ask-browser": "./src/surfaces/web/graph-ask-browser-entry.mjs"
53
+ "./ask-browser": "./src/surfaces/web/graph-ask-browser-entry.mjs",
54
+ "./envelope": "./test-benchmarks/agentbench/envelope-reader.mjs"
54
55
  },
55
56
  "files": [
56
57
  "bin/",
@@ -71,7 +72,9 @@
71
72
  "!corpus/wordnet/generate.mjs",
72
73
  "!corpus/namenet/generate.mjs",
73
74
  "data/",
74
- "!data/sprites-large/"
75
+ "!data/sprites-large/",
76
+ "test-benchmarks/agentbench/envelope.json",
77
+ "test-benchmarks/agentbench/envelope-reader.mjs"
75
78
  ],
76
79
  "publishConfig": {
77
80
  "access": "public"
@@ -165,6 +168,7 @@
165
168
  "claim:commonsenseqa": "node scripts/claims/claim-commonsenseqa.mjs",
166
169
  "claim:planner": "node scripts/claims/claim-planner.mjs",
167
170
  "claim:syllogist": "node scripts/claims/claim-syllogist.mjs",
171
+ "claim:news": "node scripts/news-rig.mjs",
168
172
  "roll": "node scripts/roll.mjs",
169
173
  "build:ask-bundle": "node scripts/build-ask-bundle.mjs",
170
174
  "build:chat-bundle": "node scripts/build-chat-bundle.mjs",
@@ -1,16 +1,31 @@
1
1
  // uuid.mjs — RFC 9562 UUIDv7 (node:crypto ships v4 only). Lifted verbatim from
2
2
  // chat.mjs so the chat session id, the telemetry invocation id, and the bench
3
3
  // per-run stamp all share ONE time-sortable implementation (no second copy, no dep).
4
+ //
5
+ // Built on globalThis.crypto.getRandomValues (Web Crypto — every real browser,
6
+ // and Node >=19, well under this package's >=24 floor) rather than
7
+ // node:crypto's randomBytes: chat.mjs's runTurn stamps a session id here on
8
+ // every turn, and a browser bundle has no node:crypto to import — the
9
+ // browser build's own stub throws the moment randomBytes is actually called
10
+ // (scripts/lib/browser-bundle.mjs's stubNodeBuiltins), which every strict-
11
+ // tier ingest turn news.html's replay/poll/teach paths run through would
12
+ // hit. Web Crypto needs no environment branch: it is the same call in both.
4
13
 
5
- import { randomBytes } from "node:crypto";
14
+ /** 16 cryptographically random bytes as a plain Uint8Array. */
15
+ function randomBytes16() {
16
+ return globalThis.crypto.getRandomValues(new Uint8Array(16));
17
+ }
18
+
19
+ const toHexByte = (n) => n.toString(16).padStart(2, "0");
6
20
 
7
21
  /** UUID v7 (RFC 9562): 48-bit big-endian unix-ms timestamp, then version/variant
8
22
  * bits over crypto-random tail — time-sortable, unlike crypto.randomUUID()'s v4. */
9
23
  export function uuidv7(now = Date.now()) {
10
- const b = randomBytes(16);
11
- b.writeUIntBE(now, 0, 6); // 48-bit unix-ms timestamp, big-endian
24
+ const b = randomBytes16();
25
+ // 48-bit unix-ms timestamp, big-endian, written by hand (no Buffer here).
26
+ for (let i = 0; i < 6; i += 1) b[5 - i] = (now / 2 ** (8 * i)) & 0xff;
12
27
  b[6] = (b[6] & 0x0f) | 0x70; // version 7
13
28
  b[8] = (b[8] & 0x3f) | 0x80; // variant 10xx
14
- const h = b.toString("hex");
29
+ const h = Array.from(b, toHexByte).join("");
15
30
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
16
31
  }
@@ -18,6 +18,7 @@
18
18
  // that declines whenever a candidate option itself reads as a second,
19
19
  // embedded question ("is it a bird or is it a plane").
20
20
  import { leadsInterrogative, QUESTION_LEAD_RE } from "./interpret/normalize.mjs";
21
+ import { gerundOf, pastOf } from "./inflect.mjs";
21
22
 
22
23
  /** The recognized shapes. Frozen so a caller can switch on the value
23
24
  * without inventing its own string. */
@@ -526,3 +527,130 @@ export function isChoiceQuestion(text) {
526
527
  export function choiceDeclineReason(text) {
527
528
  return coreParse(text).reason;
528
529
  }
530
+
531
+ // ---- relation routing ----
532
+ //
533
+ // The direct-edge probe in chat.mjs's probeChoiceOptions accepts an edge
534
+ // under any predicate, which is close to no evidence when CommonsenseQA's
535
+ // distractors sit on the same relation as the gold answer (section 2.3 of
536
+ // the design survey). Routing narrows the accepted edge set to the relation
537
+ // family the stem itself names, before the graph is even touched — a closed
538
+ // cue table, not a general parser, matching the house style of every other
539
+ // table in this module.
540
+ //
541
+ // Ordered by measured cue yield on the committed fixture (section 10.2):
542
+ // AtLocation cues the most stems by a wide margin, so it is tried first.
543
+ // First cue that matches wins; a stem matching none routes to null, which
544
+ // the caller reads as "no relation named" and falls back to any-predicate
545
+ // matching for that question.
546
+ export const CHOICE_RELATION_ROUTES = Object.freeze([
547
+ {
548
+ family: "AtLocation",
549
+ predicates: Object.freeze(["mgx:atLocation", "mgx:locatedNear"]),
550
+ cue: /\b(where|located|location)\b/i,
551
+ },
552
+ {
553
+ family: "IsA/Synonym/HasProperty",
554
+ predicates: Object.freeze(["rdfs:subClassOf", "mgx:synonym", "mgx:hasProperty"]),
555
+ // Narrower than a bare "what is a ...?" lead on purpose — that shape
556
+ // matches almost any noun question ("what is a dog capable of?",
557
+ // "what is a hammer used for?"), which would shadow every other family.
558
+ cue: /\b(kind of|type of|another word for|same as|synonym)\b/i,
559
+ },
560
+ {
561
+ family: "HasPrerequisite/HasSubevent",
562
+ predicates: Object.freeze(["mgx:hasPrerequisite", "mgx:hasSubevent", "mgx:hasFirstSubevent", "mgx:hasLastSubevent"]),
563
+ cue: /\b(before|after|first|next|then|once you|in order to)\b/i,
564
+ },
565
+ {
566
+ family: "Desires/MotivatedByGoal",
567
+ predicates: Object.freeze(["mgx:desires", "mgx:motivatedByGoal", "mgx:causesDesire"]),
568
+ cue: /\b(want\w*|desire\w*|motivat\w*)\b/i,
569
+ },
570
+ {
571
+ family: "Causes",
572
+ predicates: Object.freeze(["mgx:causes", "mgx:causesDesire"]),
573
+ cue: /\b(cause\w*|result(?:s|ed)? in|leads? to|led to)\b/i,
574
+ },
575
+ {
576
+ family: "PartOf/HasA/MadeOf",
577
+ predicates: Object.freeze(["mgx:partOf", "mgx:hasA", "mgx:madeOf"]),
578
+ cue: /\b(part of|made of|has a|have a)\b/i,
579
+ },
580
+ {
581
+ family: "CapableOf",
582
+ predicates: Object.freeze(["mgx:capableOf", "mgxneg:capableOf"]),
583
+ cue: /\b(capable of|able to)\b/i,
584
+ },
585
+ {
586
+ family: "UsedFor",
587
+ predicates: Object.freeze(["mgx:usedFor"]),
588
+ cue: /\b(used for|used to|use for)\b/i,
589
+ },
590
+ ]);
591
+
592
+ // ---- lemma normalization (rung 4, lever 1) ----
593
+ //
594
+ // An option's surface form and a stored edge's surface form differ in
595
+ // regular inflection ("getting full" against an edge to "get full"). Reverse
596
+ // inflection is ambiguous by nature ("having" could come from "hav" or
597
+ // "have"), so every candidate base is SELF-VERIFIED against inflect.mjs's
598
+ // own forward rules before it counts — a candidate survives only when
599
+ // running it back through gerundOf/pastOf reproduces the exact word it came
600
+ // from. No new inflection rule is invented here; this only reverses the
601
+ // existing regular -ing/-ed ones. Plural -s/-es stays out of scope: chat.mjs's
602
+ // own factTermVariants already folds that at the noun level.
603
+
604
+ function gerundBaseCandidates(word) {
605
+ if (!word.endsWith("ing") || word.length <= 4) return [];
606
+ const stem = word.slice(0, -3);
607
+ const candidates = new Set([stem, stem.slice(0, -1), `${stem}e`]);
608
+ return [...candidates].filter((c) => c.length > 1 && gerundOf(c) === word);
609
+ }
610
+
611
+ function pastBaseCandidates(word) {
612
+ if (!word.endsWith("ed") || word.length <= 3) return [];
613
+ const candidates = new Set([word.slice(0, -1), word.slice(0, -2), word.slice(0, -2).slice(0, -1)]);
614
+ if (word.endsWith("ied")) candidates.add(`${word.slice(0, -3)}y`);
615
+ return [...candidates].filter((c) => c.length > 1 && pastOf(c) === word);
616
+ }
617
+
618
+ /** Every phrase reachable from `text` by lemmatizing exactly one word's
619
+ * regular -ing/-ed inflection back to its base form — "getting full" ->
620
+ * "get full", "she reduced it" untouched (no word survives self-
621
+ * verification as a genuine -ing/-ed inflection). */
622
+ export function lemmaFoldVariants(text) {
623
+ const words = String(text ?? "").toLowerCase().trim().split(/\s+/).filter(Boolean);
624
+ const variants = new Set();
625
+ words.forEach((word, i) => {
626
+ for (const base of [...gerundBaseCandidates(word), ...pastBaseCandidates(word)]) {
627
+ variants.add([...words.slice(0, i), base, ...words.slice(i + 1)].join(" "));
628
+ }
629
+ });
630
+ return variants;
631
+ }
632
+
633
+ // ---- head-noun backoff (rung 4, lever 2) ----
634
+
635
+ /** The head noun of a multi-word phrase — its LAST word, the house style's
636
+ * own head-final assumption ("fast food restaurant" -> "restaurant", "train
637
+ * station" -> "station"). Returns "" for a single-word phrase: there is
638
+ * nothing to back off to when the phrase already IS its own head. Bounded
639
+ * and closed on purpose — the head only, never every sub-phrase — so the
640
+ * caller stays a single, cheap fallback pass rather than a fuzzy search. */
641
+ export function headNounOf(text) {
642
+ const words = String(text ?? "").toLowerCase().trim().split(/\s+/).filter(Boolean);
643
+ return words.length > 1 ? words[words.length - 1] : "";
644
+ }
645
+
646
+ /** Reads the relation family a stem's own wording names, first cue wins.
647
+ * Returns null when no route's cue matches, which the caller reads as "no
648
+ * relation named" — the probe then falls back to any-predicate matching.
649
+ * @returns {null | { family: string, predicates: string[] }} */
650
+ export function routeChoiceRelation(stem) {
651
+ const text = String(stem ?? "");
652
+ for (const route of CHOICE_RELATION_ROUTES) {
653
+ if (route.cue.test(text)) return { family: route.family, predicates: [...route.predicates] };
654
+ }
655
+ return null;
656
+ }
@@ -26,18 +26,36 @@ function toMs(value) {
26
26
  return Number.isFinite(t) ? t : NaN;
27
27
  }
28
28
 
29
- const NEWS_WINDOW_PROVENANCE_RE = /^(news:|news-fixture:|research:)/;
29
+ // The ingest seam wraps a caller's tag in its own audit prefix
30
+ // (extracted:news-fixture:…, optimistic-extract:news:…), so the news tag is
31
+ // matched at any segment boundary, never only at the front.
32
+ const NEWS_WINDOW_PROVENANCE_RE = /(?:^|:)(?:news|news-fixture|research):/;
30
33
 
31
34
  /** Rows whose provenance carries a `news:`, `news-fixture:` or `research:`
32
35
  * tag and whose observedAt (else createdAt) falls inside [now - windowMs,
33
36
  * now]. Pure filter — `now` is the caller's clock reading, nothing here
34
37
  * reads a live one. */
38
+ /** A row's own observation moment: the top-level stamp when a caller set
39
+ * one, else the latest per-assertion stamp the fold surfaces — readFactRows
40
+ * keeps observedAt/createdAt on each assertion record, not on the row. */
41
+ function rowObservedMs(row) {
42
+ const own = toMs(row.observedAt || "");
43
+ if (Number.isFinite(own)) return own;
44
+ let latest = NaN;
45
+ for (const a of row.assertions || []) {
46
+ const t = toMs(a.observedAt || a.createdAt || "");
47
+ if (Number.isFinite(t) && !(latest >= t)) latest = t;
48
+ }
49
+ if (Number.isFinite(latest)) return latest;
50
+ return toMs(row.createdAt || "");
51
+ }
52
+
35
53
  export function newsWindowRows(rows, { now, windowMs }) {
36
54
  const nowMs = toMs(now);
37
55
  const startMs = nowMs - windowMs;
38
56
  return rows.filter((row) => {
39
57
  if (!NEWS_WINDOW_PROVENANCE_RE.test(String(row.provenance || ""))) return false;
40
- const t = toMs(row.observedAt || row.createdAt || "");
58
+ const t = rowObservedMs(row);
41
59
  return Number.isFinite(t) && t >= startMs && t <= nowMs;
42
60
  });
43
61
  }
@@ -59,7 +59,7 @@ const byRank = (a, b) => b.count - a.count || (a.term < b.term ? -1 : a.term > b
59
59
  * "pending" here — the negative-cache expiry, computed fresh on every call
60
60
  * from the arguments alone. The ledger itself is never mutated by this. */
61
61
  function effectiveStatus(entry, now, ttlMs) {
62
- if (entry.status !== "missed" || now == null || !ttlMs) return entry.status;
62
+ if (entry.status !== "missed" || now == null || ttlMs == null) return entry.status;
63
63
  const missedAtMs = Date.parse(entry.missedAt);
64
64
  if (!Number.isFinite(missedAtMs)) return entry.status;
65
65
  const nowMs = typeof now === "number" ? now : Date.parse(now);
@@ -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
@@ -13493,16 +13626,35 @@ async function entityOfKindInText(graph, expectedClass, answerText) {
13493
13626
  return null;
13494
13627
  }
13495
13628
 
13629
+ // The one taught action this lane derives a constraint for without being
13630
+ // asked: the river-crossing world pack and data/games/river.txt's own
13631
+ // taught lesson both name their crossing action "ferry onto", so a
13632
+ // mgx:consumes/mgx:guards pair only ever widens or narrows THAT action's
13633
+ // legal moves, never a different taught world's. A world that never teaches
13634
+ // "ferry onto" gets no constraint rows at all — constraintsFromDrives runs
13635
+ // over every fact row, but compileDomain groups action-constraint rows by
13636
+ // name, so the derived rows simply have nowhere to attach.
13637
+ const DRIVE_DERIVED_CONSTRAINT_ACTION = "ferry onto";
13638
+
13496
13639
  /** 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. */
13640
+ * through src/domain.mjs, with the fox may not be with the goat family of
13641
+ * constraints added wherever the rows state a consumes/guards pair
13642
+ * (agent-traits.mjs's constraintsFromDrives) — the same bridge
13643
+ * mudiii-turn.mjs's own puzzle plan runs, so a world taught here and a
13644
+ * world played on the square solve the same puzzle the same way. A world
13645
+ * with no such pair compiles exactly as it did before this ran. Fresh-loads
13646
+ * memory (never the turn cache) because the caller may have just written
13647
+ * snapshot rows this same turn. */
13499
13648
  async function loadPlanContext(memoryDir) {
13500
13649
  const { loadMemory, readFactRows, readRuleRows } = await import("../adapters/memory/core.mjs");
13501
13650
  const { compileDomain, stateFromFacts } = await import("../domain/domain.mjs");
13651
+ const { constraintsFromDrives } = await import("../domain/agent-traits.mjs");
13502
13652
  const payload = await loadMemory(memoryDir);
13503
13653
  const factRows = readFactRows(payload);
13504
13654
  const ruleRows = readRuleRows(payload);
13505
- const domain = compileDomain(factRows, ruleRows);
13655
+ const derivedConstraints = constraintsFromDrives(factRows)
13656
+ .map((slots) => ({ name: DRIVE_DERIVED_CONSTRAINT_ACTION, kind: "action-constraint", slots }));
13657
+ const domain = compileDomain(factRows, [...ruleRows, ...derivedConstraints]);
13506
13658
  const state = stateFromFacts(factRows, domain);
13507
13659
  return { factRows, ruleRows, domain, state };
13508
13660
  }
@@ -18311,20 +18463,36 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18311
18463
  turn.lane = "ask-choice";
18312
18464
  turn.detail = {
18313
18465
  traversal: `${grounded.length} of ${probed.length} options grounded against "${parsed.sourceTerm}"`,
18314
- matches: grounded.flatMap((o) => o.facts),
18466
+ matches: grounded.flatMap((o) => (o.facts.length ? o.facts : o.chain || [])),
18315
18467
  };
18316
18468
  return withLast(turn, choiceGoal);
18317
18469
  }
18318
18470
  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)}).`;
18471
+ // Direct edge first; a chain (rung 3) only ever fires when NO direct
18472
+ // edge exists for the winning option — probeChoiceOptions' own guard.
18473
+ let text; let matches; let hop; let traversalNote; let matchedBy;
18474
+ if (winner.facts.length > 0) {
18475
+ const fact = winner.facts.slice().sort((a, b) => b.trust - a.trust)[0];
18476
+ text = `${winner.text} — ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)}).`;
18477
+ matches = winner.facts;
18478
+ hop = 1;
18479
+ matchedBy = fact.matchedBy;
18480
+ traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`;
18481
+ } else {
18482
+ text = `${winner.text} — ${renderIsaChain(winner.chain)}.`;
18483
+ matches = winner.chain;
18484
+ hop = winner.chain.length;
18485
+ traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via a ${winner.chain.length}-hop isa chain`;
18486
+ }
18487
+ note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18322
18488
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18323
18489
  turn.lane = "ask-choice";
18324
18490
  turn.detail = {
18325
- traversal: `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`,
18326
- matches: winner.facts,
18491
+ traversal: traversalNote,
18492
+ matches,
18327
18493
  selectedLabel: winner.label,
18494
+ hop,
18495
+ ...(matchedBy ? { matchedBy } : {}),
18328
18496
  };
18329
18497
  return withLast(turn, choiceGoal);
18330
18498
  }
@@ -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
  }