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

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.41",
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";
@@ -545,6 +545,49 @@ function parseSetPhrase(text, nlp, depth) {
545
545
  * the gerund form, "who touched the module importing X" falls through to the legacy
546
546
  * strategy pipeline, which misreads the leading verb "touched" as the flat ASK shape's
547
547
  * subject term instead of resolving to a real entity. */
548
+ /** Split a relative clause's words at a trailing branch of bare qualifier
549
+ * adjectives, which restricts the MATRIX head rather than the embedded one.
550
+ *
551
+ * "modules importing the module that defines fnAlpha but not tested" excludes
552
+ * the tested IMPORTERS, not a tested definer — the same sentence with the
553
+ * adjective fronted ("untested modules that import the module that defines
554
+ * fnAlpha") is the reading it pairs with, and the explicit-pronoun order
555
+ * ("modules that import … and tested") already splits its branches at the
556
+ * matrix head before this production is reached. Left inside the relative
557
+ * clause, the filter narrowed the definer instead, which is a set of one that
558
+ * usually survives it, so the exclusion silently did nothing.
559
+ *
560
+ * Only adjectives lift. A trailing branch with a verb of its own is a second
561
+ * predicate on the embedded head and stays where it was written. Returns
562
+ * {rest, lifted} with `lifted` as ready-made boolean atoms, or null when the
563
+ * clause carries no such branch. */
564
+ function liftTrailingQualifierBranches(words) {
565
+ const lc = words.map((x) => x.toLowerCase());
566
+ const conns = Object.keys(BOOLEAN_CONNECTIVES).sort((a, z) => z.split(" ").length - a.split(" ").length);
567
+ const lifted = [];
568
+ let end = words.length;
569
+ for (;;) {
570
+ let found = null;
571
+ for (let i = end - 1; i >= 1 && !found; i -= 1) {
572
+ for (const c of conns) {
573
+ const cw = c.split(" ");
574
+ if (i + cw.length <= end && lc.slice(i, i + cw.length).join(" ") === c) {
575
+ found = { at: i, len: cw.length, op: BOOLEAN_CONNECTIVES[c] };
576
+ break;
577
+ }
578
+ }
579
+ }
580
+ if (!found) break;
581
+ const tail = words.slice(found.at + found.len, end);
582
+ const { blc } = dropLeadCopula(tail, tail.map((x) => x.toLowerCase()));
583
+ if (!blc.length || !blc.every((x) => QUALIFIERS[x])) break;
584
+ lifted.unshift({ op: found.op, kind: "qual", filters: blc });
585
+ end = found.at;
586
+ }
587
+ if (!lifted.length || !end) return null;
588
+ return { rest: words.slice(0, end), lifted };
589
+ }
590
+
548
591
  function parseNested(w, lc, nlp, depth) {
549
592
  for (let r = 1; r < lc.length; r += 1) {
550
593
  const isPronoun = RELATIVE_PRONOUNS.includes(lc[r]);
@@ -568,10 +611,18 @@ function parseNested(w, lc, nlp, depth) {
568
611
  // so the inner may itself be nested/boolean/qualified (depth ≥2). An explicit
569
612
  // relative pronoun is consumed (skip past it, start at r+1); a gerund marker IS
570
613
  // the predicate's own verb, so it stays in the inner text (start AT r).
571
- const innerText = `which ${lc[r - 1]} ${w.slice(isPronoun ? r + 1 : r).join(" ")}`;
614
+ const innerWords = w.slice(isPronoun ? r + 1 : r);
615
+ const highAttached = liftTrailingQualifierBranches(innerWords);
616
+ const innerText = `which ${lc[r - 1]} ${(highAttached ? highAttached.rest : innerWords).join(" ")}`;
572
617
  const inner = parseSetPhrase(innerText, nlp, depth + 1);
573
618
  if (!inner || inner.node === "miss") return inner ? { node: "miss", reason: inner.reason || "inner clause didn't parse" } : { node: "miss", reason: "inner clause didn't parse" };
574
- return { node: outer.shape === "reverse" ? "reverseSet" : "forwardSet", kind: outer.kind, entityType: outer.entityType, inner };
619
+ const set = { node: outer.shape === "reverse" ? "reverseSet" : "forwardSet", kind: outer.kind, entityType: outer.entityType, inner };
620
+ if (!highAttached) return set;
621
+ return {
622
+ node: "boolean",
623
+ entityType: outer.entityType,
624
+ atoms: [{ op: "seed", kind: "set", ast: set }, ...highAttached.lifted],
625
+ };
575
626
  }
576
627
  return null;
577
628
  }
@@ -1238,6 +1289,24 @@ function parseFindPredicateHead(w, lc) {
1238
1289
  return { entityType: noun.entityType, term, relIdx: r };
1239
1290
  }
1240
1291
 
1292
+ // An identity filter inside a boolean predicate: "…covered by X AND NAMED Y"
1293
+ // keeps the members of the branch's own set whose name is Y. Without it the
1294
+ // branch has no verb of its own, so it inherits the previous branch's verb and
1295
+ // reads the name as that verb's object — which either fails to parse or answers
1296
+ // about the wrong entity. Exact names only; the {node:"named"} leaf it builds
1297
+ // runs no fuzzy tier, and a name the index has no entity for refuses.
1298
+ // "called" also spells the passive of the `calls` verb, so it reads as a name
1299
+ // only where a copula has already declared a predicate adjective ("and IS
1300
+ // called X"); "named" carries no such second reading and needs no copula.
1301
+ function nameFilterAtom(entityType, bw, blc, afterCopula) {
1302
+ if (!blc.length) return null;
1303
+ if (blc[0] !== "named" && !(blc[0] === "called" && afterCopula)) return null;
1304
+ if (blc[1] === "by") return null;
1305
+ const term = bw.slice(1).join(" ").trim();
1306
+ if (!term) return null;
1307
+ return { node: "named", entityType: entityType || null, term };
1308
+ }
1309
+
1241
1310
  /** Build boolean/qualifier atoms for a predicate whose first (seed) atom the
1242
1311
  * caller already determined externally. Every atom's op defaults to
1243
1312
  * "intersection" except where an explicit and/or/but-not connective says
@@ -1252,6 +1321,8 @@ function buildPredicateAtoms(entityType, subjPrefix, predLc, predWords, nlp, dep
1252
1321
  const op = b === 0 ? "intersection" : ops[b - 1];
1253
1322
  const qc = dropLeadCopula(bw, blc);
1254
1323
  if (qc.blc.length && qc.blc.every((x) => QUALIFIERS[x])) { atoms.push({ op, kind: "qual", filters: qc.blc }); continue; }
1324
+ const namedAtom = nameFilterAtom(entityType, qc.bw, qc.blc, qc.blc.length !== blc.length);
1325
+ if (namedAtom) { atoms.push({ op, kind: "set", ast: namedAtom }); continue; }
1255
1326
  if (blc[0] === "of" || blc[0] === "in") {
1256
1327
  const owned = membershipAtom(entityType, bw.slice(1), nlp, depth);
1257
1328
  if (owned.node === "miss") return { miss: owned.reason };
@@ -1393,6 +1464,8 @@ function parseRelationalOrQualified(w, lc, nlp, depth) {
1393
1464
  const op = b === 0 ? "seed" : ops[b - 1];
1394
1465
  const qc = dropLeadCopula(bw, blc);
1395
1466
  if (qc.blc.length && qc.blc.every((x) => QUALIFIERS[x])) { atoms.push({ op, kind: "qual", filters: qc.blc }); continue; }
1467
+ const namedAtom = nameFilterAtom(entityType, qc.bw, qc.blc, qc.blc.length !== blc.length);
1468
+ if (namedAtom) { atoms.push({ op, kind: "set", ast: namedAtom }); continue; }
1396
1469
  if (blc[0] === "of" || blc[0] === "in") {
1397
1470
  const owned = membershipAtom(entityType, bw.slice(1), nlp, depth + 1);
1398
1471
  if (owned.node === "miss") return owned;
@@ -1687,6 +1760,24 @@ function moduleIdOf(graph, ind) {
1687
1760
  return qualSets(graph).moduleOfSymbol.get(ind.id) || null;
1688
1761
  }
1689
1762
 
1763
+ /** The module a coverage question is really about for this individual.
1764
+ *
1765
+ * `tests` edges run module to module, so a symbol is covered exactly when the
1766
+ * module it lives in is. Which module that is comes from the defines edge
1767
+ * first and the recorded source site second — a method belongs to its class,
1768
+ * not to the module's top-level scope, so it carries a site and no defines
1769
+ * edge of its own, and reading only the edge left every method outside the
1770
+ * tested set and therefore inside every complement.
1771
+ *
1772
+ * Null means the index places this individual in no module at all, which is a
1773
+ * different thing from "not tested" — see qualHolds. */
1774
+ function coveragePivotModuleId(graph, ind) {
1775
+ const direct = moduleIdOf(graph, ind);
1776
+ if (direct) return direct;
1777
+ const path = moduleLabelOf(ind);
1778
+ return path ? modulesByPath(graph).get(normPath(path))?.id || null : null;
1779
+ }
1780
+
1690
1781
  /** Meta fallback to real entities: after a SchemaClass/SchemaPredicate miss,
1691
1782
  * an exact case-insensitive unique label match against real code-entity
1692
1783
  * classes, so "what is a Record" answers even though Record isn't a graph
@@ -1790,7 +1881,7 @@ function qualHolds(graph, ind, spec) {
1790
1881
  return ex.has(String(ind.label).toLowerCase()) || ex.has(String(ind.id).toLowerCase());
1791
1882
  }
1792
1883
  case "tested": {
1793
- const mid = moduleIdOf(graph, ind);
1884
+ const mid = coveragePivotModuleId(graph, ind);
1794
1885
  const sets = qualSets(graph);
1795
1886
  // A TEST module is neither tested nor untested. Coverage is a claim about
1796
1887
  // SOURCE modules, so asking whether a test covers itself is a category
@@ -1800,10 +1891,13 @@ function qualHolds(graph, ind, spec) {
1800
1891
  // path shape (a test-named module that happens to test nothing).
1801
1892
  const mind = mid ? graph.byId?.get?.(mid) : null;
1802
1893
  if (mid && (sets.testModules.has(mid) || (mind && isTestPath(String(mind.label).toLowerCase())))) return false;
1803
- // An entity whose defining module can't be resolved (a class with no
1804
- // defines edge) is not a test module — it reads as "not tested", so it
1805
- // stays in the untested set instead of dropping out of both polarities.
1806
- return (!!mid && sets.testedModules.has(mid)) === spec.value;
1894
+ // Nothing this index can place in a module is outside the coverage
1895
+ // question altogether, at BOTH polarities — a Commit is neither tested
1896
+ // nor untested. Reading a missing pivot as "not tested" put every such
1897
+ // individual in the complement, which is how the negation's universe
1898
+ // grew past the set the question was about.
1899
+ if (!mid) return false;
1900
+ return sets.testedModules.has(mid) === spec.value;
1807
1901
  }
1808
1902
  default: return false;
1809
1903
  }
@@ -1955,9 +2049,48 @@ function packageIndividuals(graph) {
1955
2049
  .map(([dir]) => ({ id: `pkg:${dir}`, label: dir, class: "Package" }));
1956
2050
  }
1957
2051
 
2052
+ /** Individuals whose own name IS `term`: an exact label or id, or — for a module
2053
+ * — the same path once normalized. No substring, prose or fuzzy tier: a name
2054
+ * filter that near-matched would hand back a confident answer about a
2055
+ * neighbouring entity, which is the shape the miss-over-guess contract forbids.
2056
+ * `entityType` null means any kind. */
2057
+ function individualsNamed(graph, term, entityType) {
2058
+ const t = String(term || "").trim().toLowerCase();
2059
+ if (!t) return [];
2060
+ const asPath = normPath(t);
2061
+ return graph.individuals.filter((ind) => {
2062
+ if (entityType && ind.class !== entityType) return false;
2063
+ const label = String(ind.label || "").toLowerCase();
2064
+ if (label === t || String(ind.id || "").toLowerCase() === t) return true;
2065
+ return ind.class === "Module" && normPath(label) === asPath;
2066
+ });
2067
+ }
2068
+
2069
+ /** The first `named <X>` filter anywhere in a compiled AST whose name the graph
2070
+ * holds no entity for, with whatever else does carry that name. A name the
2071
+ * index cannot place is a refusal, not an empty intersection: the surrounding
2072
+ * question would otherwise answer "no classes" about a module that does not
2073
+ * exist. Walks the whole AST, so the filter refuses at any nesting depth.
2074
+ * Deterministic — individuals are scanned in graph order. */
2075
+ function unknownNameFilter(graph, node) {
2076
+ if (!node || typeof node !== "object") return null;
2077
+ if (Array.isArray(node)) {
2078
+ for (const child of node) { const hit = unknownNameFilter(graph, child); if (hit) return hit; }
2079
+ return null;
2080
+ }
2081
+ if (node.node === "named") {
2082
+ if (individualsNamed(graph, node.term, node.entityType).length) return null;
2083
+ return { term: node.term, entityType: node.entityType || null, elsewhere: individualsNamed(graph, node.term, null)[0] || null };
2084
+ }
2085
+ for (const value of Object.values(node)) { const hit = unknownNameFilter(graph, value); if (hit) return hit; }
2086
+ return null;
2087
+ }
2088
+
1958
2089
  /** Compile a set-producing AST into an array of individuals. */
1959
2090
  function evalSet(graph, ast, opts) {
1960
2091
  switch (ast.node) {
2092
+ // Identity filter: the entity a boolean branch's "named <X>" picks out.
2093
+ case "named": return individualsNamed(graph, ast.term, ast.entityType);
1961
2094
  case "clause": return traverse(graph, ast.clause, opts).matches || [];
1962
2095
  case "allOfClass":
1963
2096
  if (ast.entityType === "Package") return packageIndividuals(graph);
@@ -2079,6 +2212,17 @@ function evalSet(graph, ast, opts) {
2079
2212
  * for them: "not exported" really is everything that is not exported. */
2080
2213
  const oppositeQualifierSpec = (spec) => (spec && typeof spec.value === "boolean" ? { ...spec, value: !spec.value } : null);
2081
2214
 
2215
+ /** The adjective for a qualifier's opposite, where the vocabulary carries one
2216
+ * ("untested" -> "tested"). A receipt that has to state the negation reads
2217
+ * "but it is tested" from this, instead of stacking a bare "not" onto an
2218
+ * already-negative adjective. Null where the qualifier has no opposite word. */
2219
+ function oppositeQualifierWord(word) {
2220
+ const spec = QUALIFIERS[word];
2221
+ const opposite = oppositeQualifierSpec(spec);
2222
+ if (!opposite) return null;
2223
+ return Object.keys(QUALIFIERS).find((k) => QUALIFIERS[k].via === opposite.via && QUALIFIERS[k].value === opposite.value) || null;
2224
+ }
2225
+
2082
2226
  function evalBoolean(graph, ast, opts) {
2083
2227
  let acc = [];
2084
2228
  for (const atom of ast.atoms) {
@@ -2460,6 +2604,8 @@ function commitTouchObjectIds(graph, base, opts) {
2460
2604
  * simple path — {matches, …} plus compositeKind/compositeMiss flags render() reads. */
2461
2605
  function evalComposite(graph, ast, opts = {}) {
2462
2606
  if (ast.node === "miss") return { compositeMiss: true, reason: ast.reason || null, matches: [] };
2607
+ const unknownName = unknownNameFilter(graph, ast);
2608
+ if (unknownName) return { compositeMiss: true, unknownName, matches: [] };
2463
2609
  if (ast.node === "exists") return evalExists(graph, ast);
2464
2610
  if (ast.node === "qualCheck") return evalQualCheck(graph, ast, opts);
2465
2611
  if (ast.node === "universal") return evalUniversal(graph, ast, opts);
@@ -2515,7 +2661,46 @@ function evalComposite(graph, ast, opts = {}) {
2515
2661
  // qualifier listing ("which modules are tested") registers the same way, just
2516
2662
  // under its own lane name.
2517
2663
  const referents = setReferentsFor(entityType, matches, ast.node === "qualifier" ? "qualifierListing" : "compositeSet");
2518
- return { compositeKind: "set", matches, entityType, referents };
2664
+ const narrowedFrom = matches.length ? null : qualifierEmptiedSet(graph, ast, opts);
2665
+ return { compositeKind: "set", matches, entityType, referents, ...(narrowedFrom ? { narrowedFrom } : {}) };
2666
+ }
2667
+
2668
+ /** An empty composite tells the reader nothing about WHICH branch emptied it.
2669
+ * Two very different answers read the same: a clause nothing satisfied, and a
2670
+ * clause that held real entities until the qualifier took them away. The
2671
+ * second is the one worth saying out loud, and it is exactly what a
2672
+ * conditional compiles to. The seed is re-evaluated once, on the empty path
2673
+ * only, so a question that answered pays nothing for it. */
2674
+ function qualifierEmptiedSet(graph, ast, opts) {
2675
+ if (ast.node !== "boolean" || ast.atoms?.length !== 2) return null;
2676
+ const [seed, filter] = ast.atoms;
2677
+ if (seed.op !== "seed" || filter.kind !== "qual") return null;
2678
+ const excluded = filter.op === "difference";
2679
+ if (!excluded && filter.op !== "intersection") return null;
2680
+ const clause = seed.ast?.node === "clause" ? seed.ast.clause : null;
2681
+ if (!clause?.kind || !clause.object || clause.modifier === "transitive") return null;
2682
+ const held = evalSet(graph, seed.ast, opts);
2683
+ if (!held.length) return null;
2684
+ const allHold = (words) => held.every((ind) => words.every((f) => qualHolds(graph, ind, QUALIFIERS[f])));
2685
+ // A difference reports what the exclusion took away, so it may only name the
2686
+ // qualifier where the clause's members really do satisfy it. A member the
2687
+ // qualifier does not apply to at either polarity leaves by the same door, and
2688
+ // saying it was tested would be a guess about a coverage fact nothing records.
2689
+ if (excluded && !allHold(filter.filters)) return null;
2690
+ // An intersection's members failed the filter, which is all that is proven,
2691
+ // so the receipt negates it. A filter that is already a negative adjective
2692
+ // would stack into "but it is not untested", so where the vocabulary carries
2693
+ // the positive word AND every member satisfies it, the receipt says that
2694
+ // instead.
2695
+ const opposites = excluded || !filter.filters.every((f) => QUALIFIERS[f].value === false)
2696
+ ? [] : filter.filters.map(oppositeQualifierWord);
2697
+ const statable = opposites.length > 0 && opposites.every(Boolean) && allHold(opposites);
2698
+ return {
2699
+ count: held.length, entityType: clause.entityType || ast.entityType || null,
2700
+ kind: clause.kind, object: clause.object,
2701
+ filters: statable ? opposites : filter.filters,
2702
+ negated: !excluded && !statable,
2703
+ };
2519
2704
  }
2520
2705
 
2521
2706
  // ---- compositional render: templated, same "honest miss vs cited hit"
@@ -2550,14 +2735,15 @@ function filtersOnCoverage(node) {
2550
2735
  return Object.values(node).some(filtersOnCoverage);
2551
2736
  }
2552
2737
 
2553
- /** An empty coverage-filtered set over symbols is a grain mismatch, not an
2554
- * absent answer: `tests` edges are recorded module to module, so no
2555
- * function-grain coverage exists to filter on. Say that instead of the
2738
+ /** An empty coverage-filtered set over symbols has a grain behind it worth
2739
+ * saying: `tests` edges are recorded module to module, so a symbol counts as
2740
+ * covered exactly when the module it lives in does. Say that instead of the
2556
2741
  * generic rephrase nudge, which would send the reader somewhere unrelated. */
2557
2742
  function coverageGrainNote(parsed, entityType) {
2558
2743
  if (!["Function", "Method"].includes(entityType)) return null;
2559
2744
  if (!filtersOnCoverage(parsed)) return null;
2560
- return "This index records tests edges module to module, so it holds no function-grain coverage to filter on — ask whether the module a function lives in is tested instead.";
2745
+ const noun = nounFor(entityType, 1);
2746
+ return `This index records tests edges module to module, so a ${noun} counts as covered exactly when the module it lives in is tested — ask about that module to see the coverage itself.`;
2561
2747
  }
2562
2748
 
2563
2749
  function renderComposite(parsed, result, graph) {
@@ -2565,6 +2751,14 @@ function renderComposite(parsed, result, graph) {
2565
2751
  if (result.reason === "no-prev") {
2566
2752
  return { content: `"those"/"them" needs a previous answer to refer to — ask a listing question first, then follow up.`, miss: true, ambiguous: false };
2567
2753
  }
2754
+ if (result.unknownName) {
2755
+ const { term, entityType, elsewhere } = result.unknownName;
2756
+ const wanted = entityType ? nounFor(entityType, 1) : "entity";
2757
+ const clash = elsewhere
2758
+ ? ` "${term}" names ${articleFor(nounFor(elsewhere.class, 1))} ${nounFor(elsewhere.class, 1)} here, not ${articleFor(wanted)} ${wanted}.`
2759
+ : "";
2760
+ return { content: `no ${wanted} named "${term}" in this index.${clash}`, miss: true, ambiguous: false };
2761
+ }
2568
2762
  return { content: `couldn't compile this compositional question${result.reason ? ` (${result.reason})` : ""}. ${compositionalHint()}.`, miss: true, ambiguous: false };
2569
2763
  }
2570
2764
  if (result.compositeKind === "exists") {
@@ -2794,6 +2988,24 @@ function renderComposite(parsed, result, graph) {
2794
2988
  }
2795
2989
  // set-producing
2796
2990
  if (!result.matches.length) {
2991
+ // The qualifier, not the clause, is what emptied this set — so name the
2992
+ // entities the clause did hold and point at that branch on its own,
2993
+ // instead of a blanket "nothing matches" beside an unrelated recovery.
2994
+ const narrowed = result.narrowedFrom;
2995
+ if (narrowed) {
2996
+ const kindPlural = nounFor(narrowed.entityType || "Module", 2);
2997
+ const filters = listJoin(narrowed.filters);
2998
+ const clause = narrowed.negated
2999
+ ? { one: `but it is not ${filters}`, many: `but none of them is ${filters}` }
3000
+ : { one: `but it is ${filters}`, many: `but all of them are ${filters}` };
3001
+ const held = narrowed.count === 1
3002
+ ? `1 ${nounFor(narrowed.entityType || "Module", 1)} ${thirdPersonVerbFor(narrowed.kind)} ${narrowed.object}, ${clause.one}`
3003
+ : `${narrowed.count} ${kindPlural} ${bareVerbFor(narrowed.kind)} ${narrowed.object}, ${clause.many}`;
3004
+ return {
3005
+ content: `${held}. Try "which ${kindPlural} ${bareVerbFor(narrowed.kind)} ${narrowed.object}" for that branch on its own.`,
3006
+ miss: true, ambiguous: false, matches: [],
3007
+ };
3008
+ }
2797
3009
  const hint = coverageGrainNote(parsed, result.entityType) || touchesRephraseHint(graph);
2798
3010
  return { content: `nothing in the index matches that${result.entityType ? ` (${nounFor(result.entityType, 2)})` : ""}. ${hint}`, miss: true, ambiguous: false, matches: [] };
2799
3011
  }
@@ -3366,10 +3578,40 @@ function rankEntryPointModules(graph, term) {
3366
3578
  * gets an honest "not supported yet" response, never a silent fallback to
3367
3579
  * direct-only behavior. */
3368
3580
  function modifierIsWired(shape, kind, entityType) {
3369
- return shape === "reverse" && (kind === "imports" || kind === "calls") && (!entityType || entityType === "Module");
3581
+ if (shape !== "reverse") return false;
3582
+ if (kind === "imports" || kind === "calls") return !entityType || entityType === "Module";
3583
+ if (kind === "inherits") return !entityType || entityType === "Class";
3584
+ return false;
3370
3585
  }
3371
3586
  const TRANSITIVE_MAX_DEPTH = 8; // matches renderImpact's own default (codegraph.mjs)
3372
3587
 
3588
+ /** Every class below `ind` in the inherits hierarchy. A subclass edge whose
3589
+ * base sits in another module is recorded against an unresolved `ext:<Name>`
3590
+ * endpoint — the extractor declines to assert identity across modules — so an
3591
+ * id-strict walk reads a real hierarchy as flat. The direct reverse traversal
3592
+ * already falls back to matching those by name, and this closure reads them
3593
+ * the same way, one hop at a time. Cycle-safe, and sorted by label so the
3594
+ * answer is a pure function of the fact set. */
3595
+ function subclassClosure(graph, ind, kind) {
3596
+ const edges = kindsFor(kind).flatMap((k) => edgesOfKind(graph, k));
3597
+ const childrenOf = (parent) => {
3598
+ const extId = `ext:${String(parent.label).toLowerCase()}`;
3599
+ return edges
3600
+ .filter((e) => e.object === parent.id || String(e.object).toLowerCase() === extId)
3601
+ .map((e) => graph.byId.get(e.subject))
3602
+ .filter(Boolean);
3603
+ };
3604
+ const found = new Map();
3605
+ const queue = childrenOf(ind);
3606
+ while (queue.length) {
3607
+ const next = queue.shift();
3608
+ if (found.has(next.id) || next.id === ind.id) continue;
3609
+ found.set(next.id, next);
3610
+ queue.push(...childrenOf(next));
3611
+ }
3612
+ return [...found.values()].sort((a, b) => String(a.label).localeCompare(String(b.label)));
3613
+ }
3614
+
3373
3615
  /** A graph's own vocabulary nodes carry their definition text under one of
3374
3616
  * these properties. A code entity's docstring rides `seon:hasDoc` and shares
3375
3617
  * the plain `doc` key, so this set is what separates the two. */
@@ -3708,7 +3950,17 @@ export function traverse(graph, parsed, { contextId = null, prev = null, pinnedO
3708
3950
  // resolve to the same mixed closure — a deliberate scope decision, stated
3709
3951
  // honestly in the traversal receipt below.
3710
3952
  if (parsed.modifier === "transitive") {
3711
- const levels = impactClosure(graph, objMatch, { maxDepth: TRANSITIVE_MAX_DEPTH });
3953
+ // A subsumption closure is its own walk: nothing imports or calls a class,
3954
+ // so the dependency closure would answer an empty set for a hierarchy
3955
+ // question the graph can answer exactly.
3956
+ if (kind === "inherits") {
3957
+ const descendants = subclassClosure(graph, objMatch, kind);
3958
+ return {
3959
+ matches: descendants, objMatch, candidates, ambiguous, matchedVia,
3960
+ traversal: `subclass closure over inherits edges from ${objMatch.label}`,
3961
+ };
3962
+ }
3963
+ const levels = impactClosure(graph, objMatch, { maxDepth: TRANSITIVE_MAX_DEPTH, includeCycleReturn: true });
3712
3964
  const matches = levels.flat().map((d) => graph.byId.get(d.id)).filter(Boolean);
3713
3965
  return {
3714
3966
  matches, objMatch, candidates, ambiguous, matchedVia,
@@ -3924,6 +4176,15 @@ function bareVerbFor(kind) {
3924
4176
  return RELATIONS[kind]?.bare || kind;
3925
4177
  }
3926
4178
 
4179
+ /** The 3rd-person singular of a relation's bare form, keeping any preposition
4180
+ * the phrase carries: "inherit from" -> "inherits from". A one-member set
4181
+ * otherwise read "1 class inherits Base" beside the plural's "classes inherit
4182
+ * from Base" in the very next sentence. */
4183
+ function thirdPersonVerbFor(kind) {
4184
+ const [head, ...rest] = String(bareVerbFor(kind)).split(" ");
4185
+ return [`${head}s`, ...rest].join(" ");
4186
+ }
4187
+
3927
4188
  /** The passive participle of a relation ("uses" -> "used", "imports" ->
3928
4189
  * "imported"), for the confirming "X is <participle> by Y" frame. The bare
3929
4190
  * forms in this vocabulary are all regular, so a single +d/+ed rule covers
@@ -4414,8 +4675,11 @@ function renderCore(parsed, result, graph) {
4414
4675
  const object = (result.objMatch && CONTEXT_PRONOUNS.includes(String(parsed.object || "").toLowerCase()))
4415
4676
  ? result.objMatch.label
4416
4677
  : parsed.object;
4678
+ // A closure question searched more than the direct edge, so "directly"
4679
+ // would understate what came back empty.
4680
+ const reach = parsed.modifier === "transitive" ? "transitively" : "directly";
4417
4681
  return {
4418
- content: `No ${entityWord} found whose module directly ${verbFor(parsed.kind)} ${object}. ${touchesRephraseHint(graph)}`,
4682
+ content: `No ${entityWord} found whose module ${reach} ${verbFor(parsed.kind)} ${object}. ${touchesRephraseHint(graph)}`,
4419
4683
  miss: true, ambiguous: false,
4420
4684
  };
4421
4685
  }
@@ -5086,6 +5350,68 @@ const classLanesApply = (graph, parsed, result, rendered) => (rendered.ambiguous
5086
5350
  ? tieNamesAClass(graph, parsed, result)
5087
5351
  : !!rendered.miss);
5088
5352
 
5353
+ /** Is this individual part of the CODE graph — a module/file, or a symbol some
5354
+ * module holds? A taught memory fact can put a Class or a Variable in the same
5355
+ * store, and those carry no containing module. */
5356
+ function livesInCodeGraph(graph, ind) {
5357
+ if (!ind?.class) return false;
5358
+ if (ind.class === "Module" || ind.class === "File") return true;
5359
+ return !!moduleIdOf(graph, ind);
5360
+ }
5361
+
5362
+ /** A counterfactual deletion reads the closure its subject actually has.
5363
+ * interpret/normalize.mjs compiles the question to the reverse dependency
5364
+ * closure, which is the right reading for a module: what breaks is what
5365
+ * imports or calls it. Nothing imports a CLASS, so for a class the question
5366
+ * reads the subclass closure instead — deleting a base class breaks what
5367
+ * inherits from it. Returns the rewritten question, or null when the subject
5368
+ * is no class, resolves to nothing, or ties. */
5369
+ function counterfactualSubclassQuery(graph, query) {
5370
+ const subject = counterfactualSubjectOf(query);
5371
+ if (!subject) return null;
5372
+ const resolved = resolveObject(graph, subject);
5373
+ const ind = resolved?.ambiguous ? null : resolved?.match;
5374
+ if (!ind || ind.class !== "Class") return null;
5375
+ return `which classes transitively inherit from ${ind.label}`;
5376
+ }
5377
+
5378
+ const SPECULATIVE_CONDITIONAL_RE = new RegExp(
5379
+ "^if\\s+(.+?)\\s+(?:were|was|had|has|is|are|becomes?|became|gets?|got|stops?|stopped|starts?|started)\\s+"
5380
+ + "[^,]*,?\\s*(?:would|will|could|might|should)\\b",
5381
+ "i",
5382
+ );
5383
+
5384
+ /** The conditional lane's boundary. The graph records what IS, so the one
5385
+ * hypothetical world it can evaluate is a deletion — the edges that would
5386
+ * break are edges it already holds. A rename, a speed, a test nobody wrote:
5387
+ * nothing in the fact set decides those, and the ordinary grammar answered
5388
+ * them by grabbing the nearest predicate it could see ("if fnAlpha were
5389
+ * renamed, would the tests still pass" compiled to a tests question about a
5390
+ * term called "fnAlpha renamed"). This says which conditionals it can read
5391
+ * instead. Fires only on a subject the CODE graph actually holds, so an
5392
+ * unknown term keeps the ordinary wall and a taught memory subject is never
5393
+ * answered with code-graph advice. */
5394
+ function speculativeConditionalRefusal(graph, query) {
5395
+ const q = expandContractions(String(query || "")).trim();
5396
+ if (counterfactualSubjectOf(q)) return null;
5397
+ if (applyConditionalFrames(q) !== q) return null;
5398
+ const m = q.match(SPECULATIVE_CONDITIONAL_RE);
5399
+ if (!m) return null;
5400
+ const resolved = resolveObject(graph, m[1].trim());
5401
+ const ind = resolved?.ambiguous ? null : resolved?.match;
5402
+ if (!ind || !livesInCodeGraph(graph, ind)) return null;
5403
+ const closure = ind.class === "Class" ? "what inherits from it"
5404
+ : ind.class === "Module" || ind.class === "File" ? "what imports or calls it"
5405
+ : "what calls it";
5406
+ return {
5407
+ 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.`,
5408
+ tmct_ask: {
5409
+ mechanical: true, parsed: null, canonical: null, matches: [], traversal: null,
5410
+ miss: true, ambiguous: false, matchedVia: null, relaxed: null,
5411
+ },
5412
+ };
5413
+ }
5414
+
5089
5415
  export function ask(graph, query, { contextId = null, nlp = undefined, prev = null } = {}) {
5090
5416
  if (isHelpRequest(query)) {
5091
5417
  return {
@@ -5096,6 +5422,9 @@ export function ask(graph, query, { contextId = null, nlp = undefined, prev = nu
5096
5422
  },
5097
5423
  };
5098
5424
  }
5425
+ const speculative = speculativeConditionalRefusal(graph, query);
5426
+ if (speculative) return speculative;
5427
+ query = counterfactualSubclassQuery(graph, query) || query;
5099
5428
  query = substituteLastCommitPhrase(graph, query);
5100
5429
  const directFull = parseQueryFull(query, { nlp });
5101
5430
  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