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

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.34",
3
+ "version": "5.0.35",
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.",
@@ -654,3 +654,94 @@ export function routeChoiceRelation(stem) {
654
654
  }
655
655
  return null;
656
656
  }
657
+
658
+ // ---- stem topic candidates (S1) ----
659
+ //
660
+ // extractStemSourceTerm above reads ONE term off a fixed template shape, and
661
+ // when the shape a stem actually has does not match the shape a template
662
+ // expects, the capture lands in the wrong slot with nothing to catch it
663
+ // (design survey section 2.2). stemTopicCandidates instead reads every phrase
664
+ // in the stem that COULD name its topic, so the caller (chat.mjs's
665
+ // chooseChoiceTopic) can pick among them by how much the graph itself knows
666
+ // about each one, rather than by surface shape alone.
667
+
668
+ /** Words that never name a question's topic: articles, pronouns, auxiliaries,
669
+ * modals, wh-words, and the light verbs a stem uses to frame a question
670
+ * ("find", "put", "get") rather than to name its subject. A closed set, in
671
+ * the house style of every other table in this module. */
672
+ export const STEM_TOPIC_STOPWORDS = new Set([
673
+ ...PRONOUN_TERMS,
674
+ ...PHRASE_BOUNDARY_WORDS,
675
+ "a", "an", "the", "some", "any", "few", "many", "several", "more", "most",
676
+ "my", "your", "his", "its", "our", "their",
677
+ "what", "which", "where", "when", "why", "how",
678
+ "find", "found", "put", "get", "keep", "store", "place", "buy", "locate",
679
+ "hide", "wear", "carry", "use", "take", "open", "cross", "need", "want",
680
+ ]);
681
+
682
+ function stemTopicWords(text) {
683
+ return String(text ?? "").toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
684
+ }
685
+
686
+ /** Every word any option's text carries — an option term is an answer
687
+ * candidate, never the topic, so it is dropped from the stem's own
688
+ * candidate list before the graph is ever asked about it. */
689
+ function optionWordSet(options) {
690
+ const words = new Set();
691
+ for (const option of options ?? []) {
692
+ for (const w of stemTopicWords(option?.text)) words.add(w);
693
+ }
694
+ return words;
695
+ }
696
+
697
+ const isUsableTopicWord = (word, optionWords) =>
698
+ word.length > 2 && !STEM_TOPIC_STOPWORDS.has(word) && !optionWords.has(word);
699
+
700
+ /**
701
+ * Every phrase in `stem` that could name what the question is about, in stem
702
+ * order, longest first at each position. Drops STEM_TOPIC_STOPWORDS members,
703
+ * words of two letters or fewer, and every word that also appears in an
704
+ * option — an option term is an answer candidate, never the topic.
705
+ *
706
+ * @param {string} stem
707
+ * @param {Array<{label: string, text: string}>} options
708
+ * @returns {Array<{ text: string, position: number, words: 1 | 2 }>}
709
+ */
710
+ export function stemTopicCandidates(stem, options) {
711
+ const optionWords = optionWordSet(options);
712
+ const words = stemTopicWords(stem);
713
+ const candidates = [];
714
+ const seen = new Set();
715
+ words.forEach((word, i) => {
716
+ if (!isUsableTopicWord(word, optionWords)) return;
717
+ const next = words[i + 1];
718
+ if (next && isUsableTopicWord(next, optionWords)) {
719
+ const text = `${word} ${next}`;
720
+ if (!seen.has(text)) { seen.add(text); candidates.push({ text, position: i, words: 2 }); }
721
+ }
722
+ if (!seen.has(word)) { seen.add(word); candidates.push({ text: word, position: i, words: 1 }); }
723
+ });
724
+ return candidates;
725
+ }
726
+
727
+ /** The stem's other content terms once `topic` is taken out: the constraints
728
+ * the question states beyond naming its subject. Same filtering as
729
+ * stemTopicCandidates, minus the topic's own words. Phase S2 reads this.
730
+ *
731
+ * @param {string} stem
732
+ * @param {string} topic
733
+ * @param {Array<{label: string, text: string}>} options
734
+ * @returns {string[]}
735
+ */
736
+ export function stemConstraintTerms(stem, topic, options) {
737
+ const optionWords = optionWordSet(options);
738
+ const topicWords = new Set(stemTopicWords(topic));
739
+ const terms = [];
740
+ const seen = new Set();
741
+ for (const word of stemTopicWords(stem)) {
742
+ if (!isUsableTopicWord(word, optionWords) || topicWords.has(word) || seen.has(word)) continue;
743
+ seen.add(word);
744
+ terms.push(word);
745
+ }
746
+ return terms;
747
+ }
@@ -69,6 +69,181 @@ export function newsWindowRows(rows, { now, windowMs }) {
69
69
  });
70
70
  }
71
71
 
72
+ // ---------------------------------------------------------------------------
73
+ // The newsworthiness gate (PLAN_NEWS_FEED.md section 17). A card reports what
74
+ // a contemporary source said inside the window; everything the graph looked
75
+ // up, inferred or already held is background. classifyNewsRow bands a single
76
+ // row; reportedRows and newsworthyHubs narrow buildNewsItems downstream of
77
+ // newsWindowRows/scoreHubs, which keep their own behaviour unchanged.
78
+ // ---------------------------------------------------------------------------
79
+
80
+ // Identity predicates and their negative twins — what a thing IS, never what
81
+ // happened to it, so a row under any of these bands background whoever wrote
82
+ // it. Distinct from renderNewsParagraph's own narrower IDENTITY_PREDICATES
83
+ // (below), which only needs the two positive forms for its identity sentence.
84
+ const GATE_IDENTITY_PREDICATES = new Set(["rdf:type", "rdfs:subClassOf", "mgxneg:subClassOf", "owl:disjointWith"]);
85
+
86
+ // Every determiner a universal quantifier is ever stored under — today only
87
+ // "every" is written (chat.mjs's own teach lane), "all"/"each" kept here so a
88
+ // future writer of either still bands background rather than heading a card.
89
+ const UNIVERSAL_QUANTIFIERS = new Set(["every", "all", "each"]);
90
+
91
+ // A REPORT is `news:` or `news-fixture:` only — `research:` counts for the
92
+ // window (isNewsProvenance, above) but never for the gate: an enrichment
93
+ // lookup is something the graph asked for, not something a source reported.
94
+ const REPORT_PROVENANCE_RE = /(?:^|:)(?:news|news-fixture):/;
95
+
96
+ // A term the anchoring test (newsworthyHubs, below) must treat as prior
97
+ // knowledge — matched at any segment boundary, including after a " | "
98
+ // union, so a row folded from two assertions counts if either one does.
99
+ const CORPUS_OR_TEACH_SEGMENT_RE = /(?:^|:|\|\s*)(?:corpus|teach):/;
100
+
101
+ const hasNonEmptyArray = (value) => Array.isArray(value) && value.length > 0;
102
+
103
+ // The provenance HEAD is the first whitespace-delimited token — the same cut
104
+ // point trust.mjs's own provenanceTagToSource uses, so "entailed:" is read
105
+ // off the row's OWN assertion even when a union has appended a second tag
106
+ // after it.
107
+ const provenanceHead = (provenance) => String(provenance || "").trim().split(/\s+/)[0] || "";
108
+
109
+ /** "derived" | "background" | "reported" for one row, pure over the row plus
110
+ * `now` (PLAN_NEWS_FEED.md section 17.3, step one). Rules apply in order,
111
+ * first hit wins: a syllogised row is derived; an identity, universal or
112
+ * non-news-provenance row is background; a news/news-fixture row with no
113
+ * readable or in-window stamp is background; everything else is reported. */
114
+ export function classifyNewsRow(row, { now, windowMs }) {
115
+ if (provenanceHead(row.provenance).startsWith("entailed:")
116
+ || hasNonEmptyArray(row.environments) || hasNonEmptyArray(row.justification)) {
117
+ return "derived";
118
+ }
119
+ if (GATE_IDENTITY_PREDICATES.has(row.predicate)) return "background";
120
+ if (UNIVERSAL_QUANTIFIERS.has(String(row.quantifier || "").toLowerCase())) return "background";
121
+ if (!REPORT_PROVENANCE_RE.test(String(row.provenance || ""))) return "background";
122
+ const t = rowObservedMs(row);
123
+ const nowMs = toMs(now);
124
+ if (!Number.isFinite(t) || t < nowMs - windowMs || t > nowMs) return "background";
125
+ return "reported";
126
+ }
127
+
128
+ /** The "reported" subset of `rows` — counting occurrences over this set,
129
+ * rather than the wider news window, is what makes a hub's `changedCount`
130
+ * count reports rather than lookups (newsworthyHubs, below). */
131
+ export function reportedRows(rows, { now, windowMs }) {
132
+ return rows.filter((row) => classifyNewsRow(row, { now, windowMs }) === "reported");
133
+ }
134
+
135
+ /** The class objects of every identity row anywhere in `rows` — what the
136
+ * graph's own `rdf:type`/`rdfs:subClassOf` (and negative twins) rows name as
137
+ * a CLASS, regardless of who reported the identity fact. A hub test, not a
138
+ * row band: a term absent from this set is not a class by the graph's own
139
+ * account. */
140
+ export function conceptTerms(rows) {
141
+ const terms = new Set();
142
+ for (const row of rows) {
143
+ if (!GATE_IDENTITY_PREDICATES.has(row.predicate)) continue;
144
+ const t = normFactTerm(row.object);
145
+ if (t) terms.add(t);
146
+ }
147
+ return terms;
148
+ }
149
+
150
+ const BARE_NUMBER_RE = /^-?[£$€]?\d[\d,]*(?:\.\d+)?%?$/;
151
+ const ISO_DATE_RE = /^\d{4}-\d{2}(-\d{2})?$/;
152
+ const QUARTER_RE = /^q[1-4]\s+\d{4}$/i;
153
+ const LEADING_DIGIT_PHRASE_RE = /^\d[\d,.]*\s+\S/;
154
+ const TRAILING_NUMBER_PHRASE_RE = /\s\d[\d,.]*$/;
155
+
156
+ /** True when the WHOLE term is a number, a date or a quantity phrase ("q3
157
+ * 2026", "7,409 square kilometres", "1,683,115") — never a term a hub may
158
+ * head: a date is when a card happened, and an amount is what it says. */
159
+ export function isQuantityTerm(term) {
160
+ const t = String(term ?? "").trim().toLowerCase();
161
+ if (!t) return false;
162
+ if (BARE_NUMBER_RE.test(t)) return true;
163
+ if (ISO_DATE_RE.test(t)) return true;
164
+ if (QUARTER_RE.test(t)) return true;
165
+ if (LEADING_DIGIT_PHRASE_RE.test(t)) return true;
166
+ if (TRAILING_NUMBER_PHRASE_RE.test(t)) return true;
167
+ return false;
168
+ }
169
+
170
+ /** True when `term` contains a digit run anywhere — the anchor a specific
171
+ * measurement gives a seeded hub, weaker than isQuantityTerm's "the whole
172
+ * term IS a number" test. */
173
+ export function hasQuantityMarker(term) {
174
+ return /\d/.test(String(term ?? ""));
175
+ }
176
+
177
+ /** scoreHubs's gated twin: from `reported` rows only, counts terms (subject
178
+ * and object, STOP_SET removed) as `changed`, then keeps a term only when it
179
+ * passes all three hub tests (PLAN_NEWS_FEED.md section 17.3, step two):
180
+ * reported (it is why the term is a candidate at all), not a class or a bare
181
+ * quantity, and anchored — either the window introduced the term outright,
182
+ * or one of its own reported rows joins it to something window-new or
183
+ * carrying a digit run. `rows` is the WHOLE fact set (conceptTerms and the
184
+ * anchoring test both read prior knowledge from it, not just the window). */
185
+ export function newsworthyHubs(rows, reported, { now, windowMs, limit = 6, adjacency = null } = {}) {
186
+ const adj = adjacency ?? buildTermAdjacency(rows);
187
+ const concepts = conceptTerms(rows);
188
+ const nowMs = toMs(now);
189
+ const startMs = nowMs - windowMs;
190
+
191
+ function isWindowNewTerm(term) {
192
+ const idxs = adj.byTerm.get(term);
193
+ if (!idxs || !idxs.length) return false;
194
+ for (const idx of idxs) {
195
+ const row = rows[idx];
196
+ const t = rowObservedMs(row);
197
+ if (!(Number.isFinite(t) && t >= startMs && t <= nowMs)) return false;
198
+ if (CORPUS_OR_TEACH_SEGMENT_RE.test(String(row.provenance || ""))) return false;
199
+ }
200
+ return true;
201
+ }
202
+
203
+ const counts = new Map();
204
+ const anchors = new Map();
205
+ for (const row of reported) {
206
+ const s = normFactTerm(row.subject);
207
+ const o = normFactTerm(row.object);
208
+ for (const [term, other] of [[s, o], [o, s]]) {
209
+ if (!term || STOP_SET.has(term)) continue;
210
+ counts.set(term, (counts.get(term) || 0) + 1);
211
+ let others = anchors.get(term);
212
+ if (!others) anchors.set(term, (others = new Set()));
213
+ if (other) others.add(other);
214
+ }
215
+ }
216
+
217
+ const hubs = [];
218
+ for (const [term, changed] of counts) {
219
+ if (concepts.has(term) || isQuantityTerm(term)) continue;
220
+ let anchored = isWindowNewTerm(term);
221
+ if (!anchored) {
222
+ for (const other of anchors.get(term) ?? []) {
223
+ if (hasQuantityMarker(other) || isWindowNewTerm(other)) { anchored = true; break; }
224
+ }
225
+ }
226
+ if (!anchored) continue;
227
+ hubs.push({ term, changed });
228
+ }
229
+
230
+ return hubs
231
+ .sort((a, b) => b.changed - a.changed || (a.term < b.term ? -1 : a.term > b.term ? 1 : 0))
232
+ .slice(0, limit);
233
+ }
234
+
235
+ /** A card's two-hop sub-graph, divided by the row-band gate: `reported` rows
236
+ * (what heads the card) and everything else (the collapsed background
237
+ * line). `reportedIds` is the reported-row id set the caller already
238
+ * computed over the whole fact set (reportedRows' output, by id). */
239
+ export function splitCardRows(subgraphRows, reportedIds) {
240
+ const ids = reportedIds instanceof Set ? reportedIds : new Set(reportedIds || []);
241
+ const reported = [];
242
+ const background = [];
243
+ for (const row of subgraphRows) (ids.has(row.id) ? reported : background).push(row);
244
+ return { reported, background };
245
+ }
246
+
72
247
  /** Counts window facts per term (subject and object, normalized, STOP_SET
73
248
  * removed) -> [{ term, changed }] sorted changed desc then term asc, capped
74
249
  * at `limit`. */
@@ -178,12 +353,23 @@ const SENTENCE_CAP = 5;
178
353
  * 8.3): identity first, then the hub's own relations grouped by predicate in
179
354
  * FACT_PREDICATE_PHRASES table order, then one closing sentence naming up to
180
355
  * three second-hop facts. Every sentence shown is a grounded fact, never a
181
- * paraphrase of prose the grammar could not read. */
182
- export function renderNewsParagraph(hub, subgraphRows) {
356
+ * paraphrase of prose the grammar could not read.
357
+ *
358
+ * `reportedIds` (PLAN_NEWS_FEED.md section 17.4), when given, restricts the
359
+ * relation sentences and the closing "Around it" sentence to rows in that
360
+ * set — the identity sentence keeps drawing from every row it's handed,
361
+ * since "what is this thing" is the first question a reader has regardless
362
+ * of who reported it. Defaults to null, meaning every row renders, so every
363
+ * existing caller and pin is unaffected. */
364
+ export function renderNewsParagraph(hub, subgraphRows, { reportedIds = null } = {}) {
183
365
  const hubTerm = normFactTerm(hub);
366
+ const isReported = reportedIds === null
367
+ ? () => true
368
+ : (id) => (reportedIds instanceof Set ? reportedIds.has(id) : reportedIds.includes(id));
184
369
  const hubRows = subgraphRows.filter((r) => normFactTerm(r.subject) === hubTerm);
370
+ const reportedHubRows = hubRows.filter((r) => isReported(r.id));
185
371
  const secondHopRows = subgraphRows.filter(
186
- (r) => normFactTerm(r.subject) !== hubTerm && normFactTerm(r.object) !== hubTerm,
372
+ (r) => normFactTerm(r.subject) !== hubTerm && normFactTerm(r.object) !== hubTerm && isReported(r.id),
187
373
  );
188
374
 
189
375
  const sentences = [];
@@ -196,7 +382,7 @@ export function renderNewsParagraph(hub, subgraphRows) {
196
382
 
197
383
  for (const predicate of Object.keys(FACT_PREDICATE_PHRASES)) {
198
384
  if (IDENTITY_PREDICATES.has(predicate) || sentences.length >= SENTENCE_CAP) continue;
199
- const objects = hubRows
385
+ const objects = reportedHubRows
200
386
  .filter((r) => r.predicate === predicate)
201
387
  .map((r) => r.object)
202
388
  .sort();
@@ -218,25 +404,35 @@ export function renderNewsParagraph(hub, subgraphRows) {
218
404
  return capped.length ? `${capped.join(". ")}.` : "";
219
405
  }
220
406
 
221
- /** scoreHubs -> one item per hub (PLAN_NEWS_FEED.md section 6.6), paragraph
222
- * included, sorted builtAt desc then id asc. `sourcesByFactId` maps fact ids
223
- * to snapshot source links ({ title, url, name }). */
407
+ /** newsworthyHubs -> one item per hub (PLAN_NEWS_FEED.md section 6.6),
408
+ * paragraph included, sorted builtAt desc then id asc. `sourcesByFactId`
409
+ * maps fact ids to snapshot source links ({ title, url, name }). The gate
410
+ * (PLAN_NEWS_FEED.md section 17): `reportedRows` replaces `newsWindowRows`
411
+ * and `newsworthyHubs` replaces `scoreHubs` as this function's own inputs —
412
+ * both keep their prior behaviour for every other caller. Each item's
413
+ * two-hop sub-graph then splits into its own `reported`/`background` rows,
414
+ * so a card's paragraph draws from what was reported and its collapsed
415
+ * `backgroundParagraph` draws from what the graph already knew. */
224
416
  export function buildNewsItems(rows, { now, windowMs, limit = 6, sourcesByFactId = new Map() } = {}) {
225
- const windowRows = newsWindowRows(rows, { now, windowMs });
226
- const hubs = scoreHubs(rows, windowRows, { limit });
417
+ const reported = reportedRows(rows, { now, windowMs });
418
+ const reportedIds = new Set(reported.map((r) => r.id));
227
419
  const adjacency = buildTermAdjacency(rows);
420
+ const hubs = newsworthyHubs(rows, reported, { now, windowMs, limit, adjacency });
228
421
  const items = hubs.map(({ term, changed }) => {
229
422
  const subgraphRows = subgraphAround(rows, term, { adjacency });
230
423
  const factIds = subgraphRows.map((r) => r.id).sort();
424
+ const { background } = splitCardRows(subgraphRows, reportedIds);
231
425
  return {
232
426
  id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
233
427
  hub: term,
234
428
  factIds,
235
429
  changedCount: changed,
236
430
  builtAt: now,
237
- paragraph: renderNewsParagraph(term, subgraphRows),
431
+ paragraph: renderNewsParagraph(term, subgraphRows, { reportedIds }),
238
432
  tier: tierOf(subgraphRows),
239
433
  sources: collectSources(subgraphRows, sourcesByFactId),
434
+ background: background.map((r) => r.id).sort(),
435
+ backgroundParagraph: renderNewsParagraph(term, background),
240
436
  };
241
437
  });
242
438
  return items.sort((a, b) => (toMs(b.builtAt) - toMs(a.builtAt)) || byId(a, b));
@@ -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, 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";
@@ -3793,6 +3793,133 @@ async function choiceWordnetTags(text) {
3793
3793
  for (const syn of synonyms) for (const v of factTermVariants(normFactTermStatic, syn)) tags.set(v, "wordnet");
3794
3794
  return tags;
3795
3795
  }
3796
+ /**
3797
+ * Picks the one candidate the question is about: the candidate the graph
3798
+ * holds the most facts about, counting rows where the term is the subject or
3799
+ * the object under any predicate. Ties in that count go to the phrase
3800
+ * extractStemSourceTerm captured (a structural read beats a graph count when
3801
+ * the graph cannot separate), then to the longer phrase, then to the leftmost.
3802
+ * Returns "" when no candidate is named in the store at all, which the lane
3803
+ * reports as the no-topic miss it already has.
3804
+ *
3805
+ * Pure in the fact set: the same rows in any order give the same topic, the
3806
+ * discipline sortFactIndividualsById already holds the store to.
3807
+ *
3808
+ * @returns {Promise<{ topic: string, salience: number, runnerUp: string }>}
3809
+ */
3810
+ async function chooseChoiceTopic(candidates, { memoryDir, cache, templateCapture }) {
3811
+ if (!candidates.length) return { topic: "", salience: 0, runnerUp: "" };
3812
+ const rows = await factRows(memoryDir, cache);
3813
+ const salienceOf = (text) => {
3814
+ const variants = factTermVariants(normFactTermStatic, text);
3815
+ let count = 0;
3816
+ for (const f of rows) { if (variants.has(f.subject) || variants.has(f.object)) count += 1; }
3817
+ return count;
3818
+ };
3819
+ const scored = candidates
3820
+ .map((c) => ({ ...c, salience: salienceOf(c.text) }))
3821
+ .sort((a, b) => {
3822
+ if (b.salience !== a.salience) return b.salience - a.salience;
3823
+ const aIsCapture = a.text === templateCapture;
3824
+ const bIsCapture = b.text === templateCapture;
3825
+ if (aIsCapture !== bIsCapture) return aIsCapture ? -1 : 1;
3826
+ if (b.words !== a.words) return b.words - a.words;
3827
+ return a.position - b.position;
3828
+ });
3829
+ const best = scored[0];
3830
+ if (best.salience === 0) return { topic: "", salience: 0, runnerUp: "" };
3831
+ const runnerUp = scored.find((c) => c.text !== best.text)?.text ?? "";
3832
+ return { topic: best.text, salience: best.salience, runnerUp };
3833
+ }
3834
+
3835
+ /**
3836
+ * Pulls the child pack once per constraint term, so the constraint check in
3837
+ * the tie branch has rows to read. Bounded three ways: at most
3838
+ * CHOICE_CONSTRAINT_PULL_BUDGET terms per turn, in stemConstraintTerms order;
3839
+ * nothing pulled for a term memory already holds a fact for; nothing pulled
3840
+ * for any option term, ever — terms reaching here already went through
3841
+ * stemConstraintTerms' own option-word filter, the same discipline
3842
+ * probeChoiceOptions' own docblock states for the topic pull.
3843
+ *
3844
+ * @returns {Promise<string[]>} the terms actually pulled, for the trace note
3845
+ */
3846
+ async function pullChoiceConstraintFacts(terms, { memoryDir, env, cache, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3847
+ const pulled = [];
3848
+ if (!memoryDir) return pulled;
3849
+ for (const term of terms.slice(0, CHOICE_CONSTRAINT_PULL_BUDGET)) {
3850
+ const rows = await factRows(memoryDir, cache);
3851
+ const variants = factTermVariants(normFactTermStatic, term);
3852
+ const hasFact = rows.some((f) => variants.has(f.subject) || variants.has(f.object));
3853
+ if (hasFact) continue;
3854
+ const learned = await childPackFactsForKey(term, { memoryDir, env, cache, synthesisBudget });
3855
+ if (learned) pulled.push(term);
3856
+ }
3857
+ return pulled;
3858
+ }
3859
+
3860
+ /** Every constraint term the graph links `option`'s own term to, each with
3861
+ * the ONE fact row that proves it (first match in `rows`' own order, which
3862
+ * is already canonical — the store sorts fact individuals by content-
3863
+ * addressed id, so this reads the same regardless of insertion order).
3864
+ * Unrouted, either direction: this is not the topic probe's grounding
3865
+ * check, it is "does the graph also connect this option to something else
3866
+ * the question said", and section 2.6 of the design survey found that rule
3867
+ * only under any predicate. */
3868
+ function choiceOptionSatisfiedConstraints(option, constraintTerms, rows) {
3869
+ const optionVariants = factTermVariants(normFactTermStatic, option.text);
3870
+ const satisfied = [];
3871
+ for (const term of constraintTerms) {
3872
+ const termVariants = factTermVariants(normFactTermStatic, term);
3873
+ const fact = rows.find((f) => (optionVariants.has(f.subject) && termVariants.has(f.object))
3874
+ || (optionVariants.has(f.object) && termVariants.has(f.subject)));
3875
+ if (fact) satisfied.push({ term, fact });
3876
+ }
3877
+ return satisfied;
3878
+ }
3879
+
3880
+ /**
3881
+ * Splits a tie by how much of the question each grounded option answers.
3882
+ * `satisfied` is the constraint terms the graph links that option to, each
3883
+ * with the fact row that proves it, so the answer can cite them. Returns
3884
+ * null when no option is strictly ahead, or when the leader satisfies
3885
+ * nothing — both of which stay refusals. The ties-never-broken rule this
3886
+ * answers to: a pick is made only against MORE satisfied constraints, never
3887
+ * a strength ordering over any single piece of evidence.
3888
+ *
3889
+ * @returns {null | {
3890
+ * winner: { label, text, facts, chain, satisfied: Array<{ term, fact }> },
3891
+ * runnerUp: { label, text, satisfied: Array<{ term, fact }> },
3892
+ * missedByRunnerUp: string[],
3893
+ * }}
3894
+ */
3895
+ function separateChoiceTie(grounded, constraintTerms, rows) {
3896
+ if (!constraintTerms.length) return null;
3897
+ const scored = grounded.map((option) => ({
3898
+ option,
3899
+ satisfied: choiceOptionSatisfiedConstraints(option, constraintTerms, rows),
3900
+ }));
3901
+ const bestCount = Math.max(...scored.map((s) => s.satisfied.length));
3902
+ if (bestCount === 0) return null;
3903
+ const leaders = scored.filter((s) => s.satisfied.length === bestCount);
3904
+ if (leaders.length > 1) return null;
3905
+ const winner = leaders[0];
3906
+ const runnerUp = scored
3907
+ .filter((s) => s.option.label !== winner.option.label)
3908
+ .reduce((best, cur) => {
3909
+ if (!best) return cur;
3910
+ if (cur.satisfied.length > best.satisfied.length) return cur;
3911
+ if (cur.satisfied.length === best.satisfied.length && cur.option.label < best.option.label) return cur;
3912
+ return best;
3913
+ }, null);
3914
+ const runnerUpTerms = new Set(runnerUp.satisfied.map((s) => s.term));
3915
+ const missedByRunnerUp = winner.satisfied.map((s) => s.term).filter((term) => !runnerUpTerms.has(term));
3916
+ return {
3917
+ winner: { label: winner.option.label, text: winner.option.text, facts: winner.option.facts, chain: winner.option.chain, satisfied: winner.satisfied },
3918
+ runnerUp: { label: runnerUp.option.label, text: runnerUp.option.text, satisfied: runnerUp.satisfied },
3919
+ missedByRunnerUp,
3920
+ };
3921
+ }
3922
+
3796
3923
  async function probeChoiceOptions(parsed, { memoryDir, env, cache, graph, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3797
3924
  const sourceVariants = factTermVariants(normFactTermStatic, parsed.sourceTerm);
3798
3925
  let rows = await factRows(memoryDir, cache);
@@ -12982,6 +13109,14 @@ async function ingestReferenceArticle(memoryDir, key, article, cache, tagFor = r
12982
13109
  // materialisation, not the whole-store maintenance job /syllogise runs.
12983
13110
  const AUTO_SYNTHESIS_BUDGET = 12;
12984
13111
 
13112
+ // Caps how many child-pack pulls one tied choice-question turn may spend on
13113
+ // the stem's own constraint terms (pullChoiceConstraintFacts, above). Five
13114
+ // covers every constraint term a CommonsenseQA stem carries after stopword
13115
+ // filtering; the cap is what stops a long stem from turning one turn into a
13116
+ // bulk import. A constant rather than config: it bounds work per turn, which
13117
+ // is a design decision, not a preference.
13118
+ const CHOICE_CONSTRAINT_PULL_BUDGET = 5;
13119
+
12985
13120
  /** The `[reasoning]` knobs for a classification pass rooted at `memoryDir` —
12986
13121
  * the repo's own `tmct.toml` when it sets one, the shipped defaults
12987
13122
  * otherwise. `resolveReasoningConfig` wants the NORMALIZED sparse pass-
@@ -17421,6 +17556,11 @@ const joinList = (a) => (a.length > 1 ? `${a.slice(0, -1).join(", ")} and ${a[a.
17421
17556
  // deliberately not the resolver's longer numbered ambiguity format.
17422
17557
  const joinOr = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, or ${a[a.length - 1]}`
17423
17558
  : a.length === 2 ? `${a[0]} or ${a[1]}` : (a[0] ?? ""));
17559
+ // Same Oxford-comma join as joinOr, "and" for a list every member of which
17560
+ // holds at once (the constraint terms a runner-up failed to satisfy), not a
17561
+ // set of alternatives.
17562
+ const joinAnd = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, and ${a[a.length - 1]}`
17563
+ : a.length === 2 ? `${a[0]} and ${a[1]}` : (a[0] ?? ""));
17424
17564
 
17425
17565
  /** Render the next page of a held remainder (pending: {items:[str], noun}). Returns a
17426
17566
  * plain turn whose `detail.pending` carries what's still unseen (null when the batch
@@ -18524,31 +18664,84 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18524
18664
  const parsed = splitChoiceQuestion(workingLine);
18525
18665
  if (parsed) {
18526
18666
  const choiceGoal = "pick the option a stated relation grounds, among a closed set of alternatives";
18527
- const refMiss = (text) => {
18667
+ const refMiss = (text, extraDetail = null) => {
18528
18668
  note(trace, `goal: ${choiceGoal}`);
18529
18669
  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);
18670
+ const turn = plainTurn(workingLine, text, { via: "miss", miss: true, focus, goal: choiceGoal });
18671
+ if (extraDetail) turn.detail = { ...turn.detail, ...extraDetail };
18672
+ return withLast(turn, choiceGoal);
18531
18673
  };
18532
- if (!parsed.sourceTerm) {
18674
+ // The topic is read off a CANDIDATE LIST (stemTopicCandidates), not off
18675
+ // a single fixed-shape template capture: extractStemSourceTerm's own
18676
+ // capture (parsed.sourceTerm) survives only as chooseChoiceTopic's tie-
18677
+ // break, because a template is right about a fronted "where would you
18678
+ // find X" stem, exactly the stems where several candidates tie on
18679
+ // salience. A stem naming no usable candidate, or naming several that
18680
+ // the graph holds nothing about, both come back as "" here — the same
18681
+ // no-topic miss either way.
18682
+ const candidates = stemTopicCandidates(parsed.stem, parsed.options);
18683
+ const { topic } = await chooseChoiceTopic(candidates, {
18684
+ memoryDir, cache: factRowsCache, templateCapture: parsed.sourceTerm,
18685
+ });
18686
+ if (!topic) {
18533
18687
  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
18688
  }
18535
- const probed = await probeChoiceOptions(parsed, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
18689
+ const probed = await probeChoiceOptions({ ...parsed, sourceTerm: topic }, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
18536
18690
  const grounded = probed.filter((o) => o.grounds);
18537
18691
  note(trace, `goal: ${choiceGoal}`);
18538
18692
  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.`);
18693
+ note(trace, `lane: splitChoiceQuestion — no stated relation between "${topic}" and any of ${probed.length} options; the honest miss, never a guess`);
18694
+ 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
18695
  }
18542
18696
  if (grounded.length > 1) {
18697
+ // The stem's OTHER content terms are constraints the question stated
18698
+ // beyond naming its topic — pulled here, not at the topic probe
18699
+ // above, because they only matter once a tie needs something to
18700
+ // separate on. Never pulled for an option term (stemConstraintTerms'
18701
+ // own filter already excludes those).
18702
+ const constraintTerms = stemConstraintTerms(parsed.stem, topic, parsed.options);
18703
+ await pullChoiceConstraintFacts(constraintTerms, { memoryDir, env, cache: factRowsCache, synthesisBudget });
18704
+ const rowsAfterPull = await factRows(memoryDir, factRowsCache);
18705
+ // Separate on constraints, never on strength: separateChoiceTie only
18706
+ // picks when exactly one option satisfies STRICTLY MORE of the
18707
+ // stem's other content terms than every rival — a level count, a
18708
+ // zero count, or more than one option level all stay a refusal.
18709
+ const separated = separateChoiceTie(grounded, constraintTerms, rowsAfterPull);
18710
+ if (separated) {
18711
+ const { winner, runnerUp, missedByRunnerUp } = separated;
18712
+ const groundingFact = winner.facts.length > 0 ? winner.facts.slice().sort((a, b) => b.trust - a.trust)[0] : null;
18713
+ const groundingClause = groundingFact
18714
+ ? `${factPhrase(groundingFact)} (source: ${citationProvenance(groundingFact.provenance)})`
18715
+ : renderIsaChain(winner.chain);
18716
+ const constraintClause = winner.satisfied
18717
+ .map(({ term, fact }) => `the question also says ${term}, which ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)})`)
18718
+ .join("; ");
18719
+ const text = `${winner.text} — ${groundingClause}, and ${constraintClause}. The other option that `
18720
+ + `grounds is ${runnerUp.text}, and I hold nothing linking it to ${joinAnd(missedByRunnerUp)}.`;
18721
+ 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`);
18722
+ const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18723
+ turn.lane = "ask-choice";
18724
+ turn.detail = {
18725
+ traversal: `option "${winner.label}" separated from a ${grounded.length}-way tie against "${topic}" by ${winner.satisfied.length} constraint term(s)`,
18726
+ matches: [...(groundingFact ? [groundingFact] : winner.chain), ...winner.satisfied.map((s) => s.fact)],
18727
+ selectedLabel: winner.label,
18728
+ topic,
18729
+ separatedBy: winner.satisfied.map((s) => s.term),
18730
+ runnerUpLabel: runnerUp.label,
18731
+ };
18732
+ return withLast(turn, choiceGoal);
18733
+ }
18543
18734
  // 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.`;
18735
+ // own edge weights, this branch fires on COUNT alone (or on a level
18736
+ // constraint count above, which is the same rule at a finer grain).
18737
+ note(trace, `lane: splitChoiceQuestion — ${grounded.length} of ${probed.length} options ground against "${topic}"; reported as a tie`);
18738
+ 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
18739
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18548
18740
  turn.lane = "ask-choice";
18549
18741
  turn.detail = {
18550
- traversal: `${grounded.length} of ${probed.length} options grounded against "${parsed.sourceTerm}"`,
18742
+ traversal: `${grounded.length} of ${probed.length} options grounded against "${topic}"`,
18551
18743
  matches: grounded.flatMap((o) => (o.facts.length ? o.facts : o.chain || [])),
18744
+ topic,
18552
18745
  };
18553
18746
  return withLast(turn, choiceGoal);
18554
18747
  }
@@ -18562,14 +18755,14 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18562
18755
  matches = winner.facts;
18563
18756
  hop = 1;
18564
18757
  matchedBy = fact.matchedBy;
18565
- traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`;
18758
+ traversalNote = `option "${winner.label}" grounded against "${topic}" via ${fact.predicate}`;
18566
18759
  } else {
18567
18760
  text = `${winner.text} — ${renderIsaChain(winner.chain)}.`;
18568
18761
  matches = winner.chain;
18569
18762
  hop = winner.chain.length;
18570
- traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via a ${winner.chain.length}-hop isa chain`;
18763
+ traversalNote = `option "${winner.label}" grounded against "${topic}" via a ${winner.chain.length}-hop isa chain`;
18571
18764
  }
18572
- note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18765
+ note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${topic}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18573
18766
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18574
18767
  turn.lane = "ask-choice";
18575
18768
  turn.detail = {
@@ -18577,6 +18770,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18577
18770
  matches,
18578
18771
  selectedLabel: winner.label,
18579
18772
  hop,
18773
+ topic,
18580
18774
  ...(matchedBy ? { matchedBy } : {}),
18581
18775
  };
18582
18776
  return withLast(turn, choiceGoal);