@polycode-projects/the-mechanical-code-talker 5.0.39 → 5.0.40

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.39",
3
+ "version": "5.0.40",
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.",
@@ -29,7 +29,7 @@ import {
29
29
  WORLD_RELATIONS, WORLD_NOUN_TO_RELATION, WORLD_PREDICATES, locativePreposition,
30
30
  stripTrailingScopeFiller, stripTrailingTemporalAdverb, CALLS_VERB_REPORT_NOUNS,
31
31
  } from "./ask-vocab.mjs";
32
- import { expandContractions, normalizeQuery, applyNegationFrames, applyPhrasingFrames, matchNegationSet, STOPWORDS, splitWords, wordsOf, escapeRegex } from "./interpret/normalize.mjs";
32
+ import { expandContractions, normalizeQuery, applyNegationFrames, applyPhrasingFrames, applyConditionalFrames, counterfactualSubjectOf, matchNegationSet, STOPWORDS, splitWords, wordsOf, escapeRegex } from "./interpret/normalize.mjs";
33
33
  import { editDistance, fuzzyBound } from "./interpret/fuzzy.mjs";
34
34
  import { parseAnchored } from "./interpret/strategies/grammar.mjs";
35
35
  import { parseKeywordSpot, findPhrase } from "./interpret/strategies/keywords.mjs";
@@ -2515,7 +2515,28 @@ function evalComposite(graph, ast, opts = {}) {
2515
2515
  // qualifier listing ("which modules are tested") registers the same way, just
2516
2516
  // under its own lane name.
2517
2517
  const referents = setReferentsFor(entityType, matches, ast.node === "qualifier" ? "qualifierListing" : "compositeSet");
2518
- return { compositeKind: "set", matches, entityType, referents };
2518
+ const narrowedFrom = matches.length ? null : qualifierEmptiedSet(graph, ast, opts);
2519
+ return { compositeKind: "set", matches, entityType, referents, ...(narrowedFrom ? { narrowedFrom } : {}) };
2520
+ }
2521
+
2522
+ /** An empty composite tells the reader nothing about WHICH branch emptied it.
2523
+ * Two very different answers read the same: a clause nothing satisfied, and a
2524
+ * clause that held real entities until the qualifier took them away. The
2525
+ * second is the one worth saying out loud, and it is exactly what a
2526
+ * conditional compiles to. The seed is re-evaluated once, on the empty path
2527
+ * only, so a question that answered pays nothing for it. */
2528
+ function qualifierEmptiedSet(graph, ast, opts) {
2529
+ if (ast.node !== "boolean" || ast.atoms?.length !== 2) return null;
2530
+ const [seed, filter] = ast.atoms;
2531
+ if (seed.op !== "seed" || filter.op !== "intersection" || filter.kind !== "qual") return null;
2532
+ const clause = seed.ast?.node === "clause" ? seed.ast.clause : null;
2533
+ if (!clause?.kind || !clause.object || clause.modifier === "transitive") return null;
2534
+ const held = evalSet(graph, seed.ast, opts);
2535
+ if (!held.length) return null;
2536
+ return {
2537
+ count: held.length, entityType: clause.entityType || ast.entityType || null,
2538
+ kind: clause.kind, object: clause.object, filters: filter.filters,
2539
+ };
2519
2540
  }
2520
2541
 
2521
2542
  // ---- compositional render: templated, same "honest miss vs cited hit"
@@ -2794,7 +2815,24 @@ function renderComposite(parsed, result, graph) {
2794
2815
  }
2795
2816
  // set-producing
2796
2817
  if (!result.matches.length) {
2797
- const hint = coverageGrainNote(parsed, result.entityType) || touchesRephraseHint(graph);
2818
+ // A grain the graph records nothing at cannot be reported as a filter that
2819
+ // rejected anything — that note keeps precedence over the narrowing below.
2820
+ const grainNote = coverageGrainNote(parsed, result.entityType);
2821
+ // The qualifier, not the clause, is what emptied this set — so name the
2822
+ // entities the clause did hold and point at that branch on its own,
2823
+ // instead of a blanket "nothing matches" beside an unrelated recovery.
2824
+ const narrowed = grainNote ? null : result.narrowedFrom;
2825
+ if (narrowed) {
2826
+ const kindPlural = nounFor(narrowed.entityType || "Module", 2);
2827
+ const held = narrowed.count === 1
2828
+ ? `1 ${nounFor(narrowed.entityType || "Module", 1)} ${verbFor(narrowed.kind)} ${narrowed.object}, but it is not ${listJoin(narrowed.filters)}`
2829
+ : `${narrowed.count} ${kindPlural} ${bareVerbFor(narrowed.kind)} ${narrowed.object}, but none of them is ${listJoin(narrowed.filters)}`;
2830
+ return {
2831
+ content: `${held}. Try "which ${kindPlural} ${bareVerbFor(narrowed.kind)} ${narrowed.object}" for that branch on its own.`,
2832
+ miss: true, ambiguous: false, matches: [],
2833
+ };
2834
+ }
2835
+ const hint = grainNote || touchesRephraseHint(graph);
2798
2836
  return { content: `nothing in the index matches that${result.entityType ? ` (${nounFor(result.entityType, 2)})` : ""}. ${hint}`, miss: true, ambiguous: false, matches: [] };
2799
2837
  }
2800
2838
  return { content: `${compositeList(result.matches)}.`, miss: false, ambiguous: false, matches: result.matches };
@@ -3366,10 +3404,40 @@ function rankEntryPointModules(graph, term) {
3366
3404
  * gets an honest "not supported yet" response, never a silent fallback to
3367
3405
  * direct-only behavior. */
3368
3406
  function modifierIsWired(shape, kind, entityType) {
3369
- return shape === "reverse" && (kind === "imports" || kind === "calls") && (!entityType || entityType === "Module");
3407
+ if (shape !== "reverse") return false;
3408
+ if (kind === "imports" || kind === "calls") return !entityType || entityType === "Module";
3409
+ if (kind === "inherits") return !entityType || entityType === "Class";
3410
+ return false;
3370
3411
  }
3371
3412
  const TRANSITIVE_MAX_DEPTH = 8; // matches renderImpact's own default (codegraph.mjs)
3372
3413
 
3414
+ /** Every class below `ind` in the inherits hierarchy. A subclass edge whose
3415
+ * base sits in another module is recorded against an unresolved `ext:<Name>`
3416
+ * endpoint — the extractor declines to assert identity across modules — so an
3417
+ * id-strict walk reads a real hierarchy as flat. The direct reverse traversal
3418
+ * already falls back to matching those by name, and this closure reads them
3419
+ * the same way, one hop at a time. Cycle-safe, and sorted by label so the
3420
+ * answer is a pure function of the fact set. */
3421
+ function subclassClosure(graph, ind, kind) {
3422
+ const edges = kindsFor(kind).flatMap((k) => edgesOfKind(graph, k));
3423
+ const childrenOf = (parent) => {
3424
+ const extId = `ext:${String(parent.label).toLowerCase()}`;
3425
+ return edges
3426
+ .filter((e) => e.object === parent.id || String(e.object).toLowerCase() === extId)
3427
+ .map((e) => graph.byId.get(e.subject))
3428
+ .filter(Boolean);
3429
+ };
3430
+ const found = new Map();
3431
+ const queue = childrenOf(ind);
3432
+ while (queue.length) {
3433
+ const next = queue.shift();
3434
+ if (found.has(next.id) || next.id === ind.id) continue;
3435
+ found.set(next.id, next);
3436
+ queue.push(...childrenOf(next));
3437
+ }
3438
+ return [...found.values()].sort((a, b) => String(a.label).localeCompare(String(b.label)));
3439
+ }
3440
+
3373
3441
  /** A graph's own vocabulary nodes carry their definition text under one of
3374
3442
  * these properties. A code entity's docstring rides `seon:hasDoc` and shares
3375
3443
  * the plain `doc` key, so this set is what separates the two. */
@@ -3708,7 +3776,17 @@ export function traverse(graph, parsed, { contextId = null, prev = null, pinnedO
3708
3776
  // resolve to the same mixed closure — a deliberate scope decision, stated
3709
3777
  // honestly in the traversal receipt below.
3710
3778
  if (parsed.modifier === "transitive") {
3711
- const levels = impactClosure(graph, objMatch, { maxDepth: TRANSITIVE_MAX_DEPTH });
3779
+ // A subsumption closure is its own walk: nothing imports or calls a class,
3780
+ // so the dependency closure would answer an empty set for a hierarchy
3781
+ // question the graph can answer exactly.
3782
+ if (kind === "inherits") {
3783
+ const descendants = subclassClosure(graph, objMatch, kind);
3784
+ return {
3785
+ matches: descendants, objMatch, candidates, ambiguous, matchedVia,
3786
+ traversal: `subclass closure over inherits edges from ${objMatch.label}`,
3787
+ };
3788
+ }
3789
+ const levels = impactClosure(graph, objMatch, { maxDepth: TRANSITIVE_MAX_DEPTH, includeCycleReturn: true });
3712
3790
  const matches = levels.flat().map((d) => graph.byId.get(d.id)).filter(Boolean);
3713
3791
  return {
3714
3792
  matches, objMatch, candidates, ambiguous, matchedVia,
@@ -4414,8 +4492,11 @@ function renderCore(parsed, result, graph) {
4414
4492
  const object = (result.objMatch && CONTEXT_PRONOUNS.includes(String(parsed.object || "").toLowerCase()))
4415
4493
  ? result.objMatch.label
4416
4494
  : parsed.object;
4495
+ // A closure question searched more than the direct edge, so "directly"
4496
+ // would understate what came back empty.
4497
+ const reach = parsed.modifier === "transitive" ? "transitively" : "directly";
4417
4498
  return {
4418
- content: `No ${entityWord} found whose module directly ${verbFor(parsed.kind)} ${object}. ${touchesRephraseHint(graph)}`,
4499
+ content: `No ${entityWord} found whose module ${reach} ${verbFor(parsed.kind)} ${object}. ${touchesRephraseHint(graph)}`,
4419
4500
  miss: true, ambiguous: false,
4420
4501
  };
4421
4502
  }
@@ -5086,6 +5167,68 @@ const classLanesApply = (graph, parsed, result, rendered) => (rendered.ambiguous
5086
5167
  ? tieNamesAClass(graph, parsed, result)
5087
5168
  : !!rendered.miss);
5088
5169
 
5170
+ /** Is this individual part of the CODE graph — a module/file, or a symbol some
5171
+ * module holds? A taught memory fact can put a Class or a Variable in the same
5172
+ * store, and those carry no containing module. */
5173
+ function livesInCodeGraph(graph, ind) {
5174
+ if (!ind?.class) return false;
5175
+ if (ind.class === "Module" || ind.class === "File") return true;
5176
+ return !!moduleIdOf(graph, ind);
5177
+ }
5178
+
5179
+ /** A counterfactual deletion reads the closure its subject actually has.
5180
+ * interpret/normalize.mjs compiles the question to the reverse dependency
5181
+ * closure, which is the right reading for a module: what breaks is what
5182
+ * imports or calls it. Nothing imports a CLASS, so for a class the question
5183
+ * reads the subclass closure instead — deleting a base class breaks what
5184
+ * inherits from it. Returns the rewritten question, or null when the subject
5185
+ * is no class, resolves to nothing, or ties. */
5186
+ function counterfactualSubclassQuery(graph, query) {
5187
+ const subject = counterfactualSubjectOf(query);
5188
+ if (!subject) return null;
5189
+ const resolved = resolveObject(graph, subject);
5190
+ const ind = resolved?.ambiguous ? null : resolved?.match;
5191
+ if (!ind || ind.class !== "Class") return null;
5192
+ return `which classes transitively inherit from ${ind.label}`;
5193
+ }
5194
+
5195
+ const SPECULATIVE_CONDITIONAL_RE = new RegExp(
5196
+ "^if\\s+(.+?)\\s+(?:were|was|had|has|is|are|becomes?|became|gets?|got|stops?|stopped|starts?|started)\\s+"
5197
+ + "[^,]*,?\\s*(?:would|will|could|might|should)\\b",
5198
+ "i",
5199
+ );
5200
+
5201
+ /** The conditional lane's boundary. The graph records what IS, so the one
5202
+ * hypothetical world it can evaluate is a deletion — the edges that would
5203
+ * break are edges it already holds. A rename, a speed, a test nobody wrote:
5204
+ * nothing in the fact set decides those, and the ordinary grammar answered
5205
+ * them by grabbing the nearest predicate it could see ("if fnAlpha were
5206
+ * renamed, would the tests still pass" compiled to a tests question about a
5207
+ * term called "fnAlpha renamed"). This says which conditionals it can read
5208
+ * instead. Fires only on a subject the CODE graph actually holds, so an
5209
+ * unknown term keeps the ordinary wall and a taught memory subject is never
5210
+ * answered with code-graph advice. */
5211
+ function speculativeConditionalRefusal(graph, query) {
5212
+ const q = expandContractions(String(query || "")).trim();
5213
+ if (counterfactualSubjectOf(q)) return null;
5214
+ if (applyConditionalFrames(q) !== q) return null;
5215
+ const m = q.match(SPECULATIVE_CONDITIONAL_RE);
5216
+ if (!m) return null;
5217
+ const resolved = resolveObject(graph, m[1].trim());
5218
+ const ind = resolved?.ambiguous ? null : resolved?.match;
5219
+ if (!ind || !livesInCodeGraph(graph, ind)) return null;
5220
+ const closure = ind.class === "Class" ? "what inherits from it"
5221
+ : ind.class === "Module" || ind.class === "File" ? "what imports or calls it"
5222
+ : "what calls it";
5223
+ return {
5224
+ content: `I can't answer that — the index records what is, not what would be. What it can read about ${ind.label}: "what would break if ${ind.label} were deleted" (${closure}), or "/describe ${ind.label}" for the facts it holds.`,
5225
+ tmct_ask: {
5226
+ mechanical: true, parsed: null, canonical: null, matches: [], traversal: null,
5227
+ miss: true, ambiguous: false, matchedVia: null, relaxed: null,
5228
+ },
5229
+ };
5230
+ }
5231
+
5089
5232
  export function ask(graph, query, { contextId = null, nlp = undefined, prev = null } = {}) {
5090
5233
  if (isHelpRequest(query)) {
5091
5234
  return {
@@ -5096,6 +5239,9 @@ export function ask(graph, query, { contextId = null, nlp = undefined, prev = nu
5096
5239
  },
5097
5240
  };
5098
5241
  }
5242
+ const speculative = speculativeConditionalRefusal(graph, query);
5243
+ if (speculative) return speculative;
5244
+ query = counterfactualSubclassQuery(graph, query) || query;
5099
5245
  query = substituteLastCommitPhrase(graph, query);
5100
5246
  const directFull = parseQueryFull(query, { nlp });
5101
5247
  const direct = directFull.parsed;
@@ -358,8 +358,16 @@ export function renderCompare(graph, indA, indB) {
358
358
  /** BFS the reverse of imports/calls edges from `ind` — "what would break".
359
359
  * Diamonds collapse to shortest depth; cycles terminate via the visited set.
360
360
  * `callsSymbol` is folded in too, coarsened to module level on read: it has
361
- * no import-backing requirement, so it can reach dependents "calls" alone would miss. */
362
- export function impactClosure(graph, ind, { maxDepth = 8 } = {}) {
361
+ * no import-backing requirement, so it can reach dependents "calls" alone would miss.
362
+ *
363
+ * `includeCycleReturn` decides what an import cycle back to the seed means,
364
+ * and the two callers genuinely want different things. An impact REPORT lists
365
+ * the OTHER work a change reaches, and the module being changed is not other
366
+ * work, so it stays out (the default). A dependency CLOSURE answers which
367
+ * entities are inside it, and a module that reaches itself through a cycle is
368
+ * inside its own — leaving it out makes the closure disagree with the edges it
369
+ * just walked. */
370
+ export function impactClosure(graph, ind, { maxDepth = 8, includeCycleReturn = false } = {}) {
363
371
  const dependents = new Map();
364
372
  const coveredBy = new Map(); // moduleId → [test labels]
365
373
  const addDependent = (objectId, subjectId, subjectLabel, via) => {
@@ -408,6 +416,21 @@ export function impactClosure(graph, ind, { maxDepth = 8 } = {}) {
408
416
  .sort((a, b) => String(a.label).localeCompare(String(b.label)));
409
417
  levels.push(withTests);
410
418
  }
419
+ // bfsLevels seeds `visited` with the start node, so an edge that leads back
420
+ // to the seed is invisible to it. The return is placed one level below the
421
+ // shallowest dependent that carries it, and the edge chosen is the first in
422
+ // via order, so the answer is a pure function of the fact set.
423
+ for (let depth = 0; includeCycleReturn && depth < levels.length; depth += 1) {
424
+ const back = levels[depth]
425
+ .flatMap((dep) => (dependents.get(dep.id) || []).filter((d) => d.id === ind.id))
426
+ .sort((a, b) => String(a.via).localeCompare(String(b.via)));
427
+ if (!back.length) continue;
428
+ const returned = { ...back[0], tests: coveredBy.get(ind.id) || [] };
429
+ if (!levels[depth + 1]) levels[depth + 1] = [];
430
+ levels[depth + 1] = [...levels[depth + 1], returned]
431
+ .sort((a, b) => String(a.label).localeCompare(String(b.label)));
432
+ break;
433
+ }
411
434
  return levels;
412
435
  }
413
436
 
@@ -549,25 +549,57 @@ const CONDITIONAL_KIND_PLURAL = Object.freeze({
549
549
  });
550
550
  const CONDITIONAL_QUALIFIER_SRC =
551
551
  "public|private|protected|static|abstract|constant|re-?exported|exported|tested|covered|untested|uncovered";
552
- /** "if a/the <kind> <relation-verb> <object>, is/are it/that/they/this
553
- * <qualifier>?" -> "<kind plural> <relation-gerund> <object> and <qualifier>".
554
- * Closed to the two small tables above (both ends validated), so an
555
- * unrecognized kind/verb/qualifier simply doesn't match — falls through to
556
- * the ordinary grammar, which honestly misses on the untransformed "if …"
557
- * text rather than risk a wrong composition. */
552
+ /** consequent noun -> the qualifier it states. "has it got tests" and "does it
553
+ * have tests" ask what "is it tested" asks, and the graph answers all three
554
+ * off the same tests edge. Closed on purpose: a noun with no entry leaves the
555
+ * whole conditional unmatched rather than being read as some near qualifier. */
556
+ const CONDITIONAL_HAVE_NOUN_QUALIFIER = Object.freeze({
557
+ tests: "tested", "a test": "tested", "any tests": "tested",
558
+ coverage: "covered", "test coverage": "covered",
559
+ });
560
+ /** "if a/the <kind> <relation-verb> <object>, <consequent>?" ->
561
+ * "<kind plural> <relation-gerund> <object> and <qualifier>". The consequent
562
+ * is one of three closed phrasings: "is/are it <qualifier>", "has/have it got
563
+ * <noun>", "does/do it have <noun>". Closed to the tables above (every end
564
+ * validated), so an unrecognized kind/verb/qualifier/noun simply doesn't
565
+ * match — it falls through to the ordinary grammar, which honestly misses on
566
+ * the untransformed "if …" text rather than risk a wrong composition. */
558
567
  const CONDITIONAL_QUALIFIER_RE = new RegExp(
559
568
  "^if\\s+(?:a|an|the)?\\s*(" + Object.keys(CONDITIONAL_KIND_PLURAL).join("|") + ")\\s+"
560
569
  + "(" + Object.keys(CONDITIONAL_VERB_GERUND).join("|") + ")\\s+"
561
- + "(.+?),\\s*(?:is|are)\\s+(?:it|that|they|this)\\s+"
562
- + "(" + CONDITIONAL_QUALIFIER_SRC + ")\\??$",
570
+ + "(.+?),\\s*(?:"
571
+ + "(?:is|are)\\s+(?:it|that|they|this)\\s+(" + CONDITIONAL_QUALIFIER_SRC + ")"
572
+ + "|(?:has|have)\\s+(?:it|that|they|this)\\s+got\\s+(" + Object.keys(CONDITIONAL_HAVE_NOUN_QUALIFIER).join("|") + ")"
573
+ + "|(?:does|do)\\s+(?:it|that|they|this)\\s+have\\s+(" + Object.keys(CONDITIONAL_HAVE_NOUN_QUALIFIER).join("|") + ")"
574
+ + ")\\??$",
563
575
  "i",
564
576
  );
565
577
 
566
- /** Counterfactual deletion -> "which modules transitively import <X>" (the
567
- * existing reverse-dependency closure). Exported so chat.mjs can recognize
568
- * the same shape and prepend a hypothetical marker to the rendered answer. */
569
- export const COUNTERFACTUAL_RE =
570
- /^if\s+(.+?)\s+(?:were|was)\s+(?:deleted|removed),?\s*what\s+(?:would|might|could)\s+(?:break|fail|be\s+affected)\??$/i;
578
+ const COUNTERFACTUAL_GONE_SRC = "(?:were|was)\\s+(?:deleted|removed)";
579
+ const COUNTERFACTUAL_BREAK_SRC = "what\\s+(?:would|might|could)\\s+(?:break|fail|be\\s+affected)";
580
+ /** Counterfactual deletion, if-clause first. */
581
+ export const COUNTERFACTUAL_RE = new RegExp(
582
+ "^if\\s+(.+?)\\s+" + COUNTERFACTUAL_GONE_SRC + ",?\\s*" + COUNTERFACTUAL_BREAK_SRC + "\\??$",
583
+ "i",
584
+ );
585
+ /** The same counterfactual with its if-clause last — "what would break if X
586
+ * were removed". English puts a conditional either way round and the reading
587
+ * is identical, so both orders resolve to the same subject. */
588
+ export const COUNTERFACTUAL_POSTPOSED_RE = new RegExp(
589
+ "^" + COUNTERFACTUAL_BREAK_SRC + "\\s+if\\s+(.+?)\\s+" + COUNTERFACTUAL_GONE_SRC + "\\??$",
590
+ "i",
591
+ );
592
+
593
+ /** The entity a counterfactual-deletion question asks about, either word
594
+ * order, or null when the question isn't one. Callers that need to mark the
595
+ * answer hypothetical (chat.mjs) and callers that need to pick the closure
596
+ * the subject actually has (ask.mjs) read the subject through here rather
597
+ * than each matching one of the two orders. */
598
+ export function counterfactualSubjectOf(text) {
599
+ const q = String(text || "").trim();
600
+ const m = q.match(COUNTERFACTUAL_RE) || q.match(COUNTERFACTUAL_POSTPOSED_RE);
601
+ return m ? m[1].trim() : null;
602
+ }
571
603
 
572
604
  /** Apply the two conditional frames, qualifier composition first (more specific). */
573
605
  export function applyConditionalFrames(text) {
@@ -576,10 +608,14 @@ export function applyConditionalFrames(text) {
576
608
  if (qual) {
577
609
  const kind = CONDITIONAL_KIND_PLURAL[qual[1].toLowerCase()];
578
610
  const gerund = CONDITIONAL_VERB_GERUND[qual[2].toLowerCase()];
579
- return `${kind} ${gerund} ${qual[3].trim()} and ${qual[4].toLowerCase()}`;
611
+ const haveNoun = qual[5] || qual[6];
612
+ const qualifier = qual[4]
613
+ ? qual[4].toLowerCase()
614
+ : CONDITIONAL_HAVE_NOUN_QUALIFIER[haveNoun.toLowerCase()];
615
+ return `${kind} ${gerund} ${qual[3].trim()} and ${qualifier}`;
580
616
  }
581
- const cf = q.match(COUNTERFACTUAL_RE);
582
- if (cf) return `which modules transitively import ${cf[1].trim()}`;
617
+ const subject = counterfactualSubjectOf(q);
618
+ if (subject) return `which modules transitively import ${subject}`;
583
619
  return q;
584
620
  }
585
621
 
@@ -47,7 +47,7 @@ import {
47
47
  stripTrailingScopeFiller, stripTrailingDiscourseTag, EDGE_NOUN_TO_METRIC, RELATIONS, LIST_TRIGGERS,
48
48
  locativePreposition,
49
49
  } from "../domain/ask-vocab.mjs";
50
- import { COUNTERFACTUAL_RE, correctMisspellings, applyPreambleFrames, expandContractions, normalizeQuery, stripFillerWords, escapeRegex, kindNounAnaphoraHint, datedTeachSuffix, QUESTION_LEAD_RE, fillerClausePrefix, leadsInterrogative } from "../domain/interpret/normalize.mjs";
50
+ import { counterfactualSubjectOf, correctMisspellings, applyPreambleFrames, expandContractions, normalizeQuery, stripFillerWords, escapeRegex, kindNounAnaphoraHint, datedTeachSuffix, QUESTION_LEAD_RE, fillerClausePrefix, leadsInterrogative } from "../domain/interpret/normalize.mjs";
51
51
  import { setDefaultNlpAdapter } from "../domain/interpret/nlp-registry.mjs";
52
52
  import { setConstructionBanks } from "../domain/interpret/strategies/constructions.mjs";
53
53
  import { nlpAdapter } from "../adapters/ask-nlp.mjs";
@@ -16655,19 +16655,20 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16655
16655
  note(trace, "source: local committed corpus slice (licence-cited in the aside itself)");
16656
16656
  }
16657
16657
  }
16658
- // Counterfactual marker: "if X were deleted, what would break" compiles to a REAL traversal
16659
- // (interpret/normalize.mjs's COUNTERFACTUAL_RE rewrite, "which modules
16660
- // transitively import X") — but the consequent is hypothetical, so a plain
16661
- // traversal answer would over-claim it as present-tense fact. normalize.mjs
16662
- // only rewrites the QUESTION; this names the SAME raw query shape here (the
16663
- // one seam that sees both the original text and the final answer) and marks
16664
- // the answer as conditional. Gated to a genuine non-miss composed traversal
16665
- // — a counterfactual that happens to miss keeps its ordinary honest-miss
16666
- // wording, never a fabricated "hypothetically" wrapper around a blank.
16667
- const counterfactualSubject = String(query).trim().match(COUNTERFACTUAL_RE);
16658
+ // Counterfactual marker: "if X were deleted, what would break" (either word
16659
+ // order) compiles to a REAL traversal — the reverse dependency closure for a
16660
+ // module, the subclass closure for a class — but the consequent is
16661
+ // hypothetical, so a plain traversal answer would over-claim it as
16662
+ // present-tense fact. interpret/normalize.mjs only rewrites the QUESTION;
16663
+ // this names the SAME raw query shape here (the one seam that sees both the
16664
+ // original text and the final answer) and marks the answer as conditional.
16665
+ // Gated to a genuine non-miss composed traversal — a counterfactual that
16666
+ // happens to miss keeps its ordinary honest-miss wording, never a fabricated
16667
+ // "hypothetically" wrapper around a blank.
16668
+ const counterfactualSubject = counterfactualSubjectOf(query);
16668
16669
  if (!recordMiss && via === "composed" && counterfactualSubject) {
16669
- answer = `hypothetically, if ${counterfactualSubject[1].trim()} were removed: ${answer}`;
16670
- note(trace, `intermediate: COUNTERFACTUAL_RE matched — compiled to a real traversal, wrapped as hypothetical ("${counterfactualSubject[1].trim()}" removed)`);
16670
+ answer = `hypothetically, if ${counterfactualSubject} were removed: ${answer}`;
16671
+ note(trace, `intermediate: counterfactual conditional matched — compiled to a real traversal, wrapped as hypothetical ("${counterfactualSubject}" removed)`);
16671
16672
  }
16672
16673
  // LIVE SUPPLEMENT (/wiki supplement, and its superset /wiki always): a
16673
16674
  // grounded answer also carries what Wikipedia says about its subject —