@polycode-projects/the-mechanical-code-talker 5.0.38 → 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.38",
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";
@@ -516,6 +516,8 @@ function parseSetPhrase(text, nlp, depth) {
516
516
  if (negated) return negated;
517
517
  const w = splitWords(text);
518
518
  const lc = w.map((x) => x.toLowerCase());
519
+ const window = parseCommitFilter(w, lc);
520
+ if (window) return window;
519
521
  const definitionSite = parseDefinitionSiteMembership(w, lc, nlp, depth);
520
522
  if (definitionSite) return definitionSite;
521
523
  const nested = parseNested(w, lc, nlp, depth);
@@ -695,16 +697,33 @@ function parseTemporal(w, lc, nlp, depth = 0) {
695
697
  // when-shape above (which dates one named entity's touch history). "in"/
696
698
  // "during" are deliberately excluded — "what changed in <commit>" means that
697
699
  // commit's own touch-set instead.
700
+ //
701
+ // An entity kind may head the question ("which MODULES changed on 2026-06-28"),
702
+ // which asks the same window and then reads what those commits touched at that
703
+ // grain. Without it the sentence fell through to the flat shapes, which read the
704
+ // date as an entity name and offered a confident ambiguity list about the index's
705
+ // modules — the miss-over-guess contract's worst shape, over a window the graph
706
+ // can bound exactly.
698
707
  const COMMIT_FILTER_OPS = new Set(["since", "before", "after", "on"]);
708
+ const COMMIT_FILTER_LEADS = new Set(["what", "which"]);
699
709
  function parseCommitFilter(w, lc) {
700
- if (lc[0] !== "what" || lc[1] !== "changed") return null;
701
- let i = 2;
710
+ if (!COMMIT_FILTER_LEADS.has(lc[0])) return null;
711
+ let i = 1;
712
+ let entityType = null;
713
+ if (lc[i] !== "changed") {
714
+ const noun = entityNoun(lc[i]);
715
+ if (!noun || noun.placeholder) return null;
716
+ entityType = noun.entityType;
717
+ i += 1;
718
+ }
719
+ if (lc[i] !== "changed") return null;
720
+ i += 1;
702
721
  if (lc[i] === "ever") i += 1;
703
722
  if (!COMMIT_FILTER_OPS.has(lc[i])) return null;
704
723
  const op = lc[i];
705
724
  const pivotRaw = w.slice(i + 1).join(" ").trim();
706
- if (!pivotRaw) return { node: "miss", reason: `"what changed ${op}" needs a date or commit afterward` };
707
- return { node: "commitFilter", op, pivotRaw };
725
+ if (!pivotRaw) return { node: "miss", reason: `"changed ${op}" needs a date or commit afterward` };
726
+ return { node: "commitFilter", op, pivotRaw, entityType };
708
727
  }
709
728
 
710
729
  // "<kind> in|of <owner>" where the OWNER is itself a relative clause ("functions
@@ -1555,22 +1574,55 @@ function reverseOverSet(graph, kind, entityType, objectIds) {
1555
1574
 
1556
1575
  const GIT_PROV_REF_RE = /^git:(.+)$/i;
1557
1576
 
1558
- /** How many distinct commits are attested to have touched a SET of entities —
1559
- * the same "touched by N commit(s)" convention renderDescribe's attestation
1560
- * line already uses (codegraph.mjs's turnRefCount), not the narrower "touches
1561
- * edge count" reverseOverSet(kind="touches") returns. A commit can be recorded
1562
- * in an entity's own `derived_from` provenance with no full Commit individual
1563
- * of its own (the ingester's touches-edge and provenance-ref writes can drift,
1564
- * e.g. a truncated commit walk) — reverseOverSet alone then undercounts, or
1565
- * misses entirely when NO touches edge survived. Deduped by short sha so a
1566
- * provenance ref naming a commit that DOES have a touches-edge individual
1567
- * isn't double-counted. */
1577
+ /** The shas a `git:<sha>` provenance ref is still allowed to attest a touch for.
1578
+ *
1579
+ * A ref in an entity's `derived_from` names a commit. It does not say the commit
1580
+ * touched that entity, and it carries no date, so it can only be counted where
1581
+ * the graph has nothing better. Three cases, and the window is what separates
1582
+ * them:
1583
+ *
1584
+ * - the graph holds the Commit AND records what it touched — that recorded touch
1585
+ * set is the index's own statement of the commit's reach, so it decides on its
1586
+ * own and the ref adds nothing;
1587
+ * - the graph holds the Commit but records no touch edge for it anywhere (a
1588
+ * truncated commit walk drops them) — the index is silent on its reach, so the
1589
+ * ref is the only attestation left and it counts;
1590
+ * - the graph holds no Commit for the sha — the index can neither name nor date
1591
+ * it, so it sits outside the history this graph can count over and stays
1592
+ * uncounted rather than being guessed into the total.
1593
+ *
1594
+ * Returns the labels from case two, lowercased and sorted, so the count is a
1595
+ * pure function of the fact set whatever order the individuals arrived in. */
1596
+ function provenanceAttestableShas(graph) {
1597
+ const withTouchSet = new Set();
1598
+ for (const kind of ["touches", "touchesSymbol"]) {
1599
+ for (const e of edgesOfKind(graph, kind)) {
1600
+ const commit = graph.byId.get(e.subject);
1601
+ if (commit?.class === "Commit") withTouchSet.add(String(commit.label || "").toLowerCase());
1602
+ }
1603
+ }
1604
+ return graph.individuals
1605
+ .filter((i) => i.class === "Commit")
1606
+ .map((i) => String(i.label || "").toLowerCase())
1607
+ .filter((label) => label && !withTouchSet.has(label))
1608
+ .sort();
1609
+ }
1610
+
1611
+ /** How many distinct commits inside this index's own recorded history are
1612
+ * attested to have touched a SET of entities. The touch edges reaching the set
1613
+ * are the spine; a `git:<sha>` provenance ref adds a commit only under
1614
+ * provenanceAttestableShas's rule above, so a count can never name a larger
1615
+ * number than "which commits touched X" can list. */
1568
1616
  function commitTouchCount(graph, objectIds) {
1569
1617
  const shas = new Set(reverseOverSet(graph, "touches", "Commit", objectIds).map((c) => String(c.label || "").toLowerCase()));
1618
+ const attestable = provenanceAttestableShas(graph);
1570
1619
  for (const id of objectIds) {
1571
1620
  for (const ref of graph.byId.get(id)?.derived_from || []) {
1572
1621
  const m = GIT_PROV_REF_RE.exec(String(ref || ""));
1573
- if (m) shas.add(m[1].toLowerCase());
1622
+ if (!m) continue;
1623
+ const sha = m[1].toLowerCase();
1624
+ const known = attestable.find((label) => label.startsWith(sha) || sha.startsWith(label));
1625
+ if (known) shas.add(known);
1574
1626
  }
1575
1627
  }
1576
1628
  return shas.size;
@@ -1932,6 +1984,10 @@ function evalSet(graph, ast, opts) {
1932
1984
  const positive = new Set(forwardOverSet(graph, ast.kind, new Set([r.match.id])).map((x) => x.id));
1933
1985
  return graph.individuals.filter((i) => i.class === universeType && !positive.has(i.id));
1934
1986
  }
1987
+ // A date-or-commit window as a set atom, so "how many modules changed on
1988
+ // <date>" composes through the ordinary count path. An unresolved pivot is
1989
+ // caught by the count branch before it can read as a bare zero.
1990
+ case "commitFilter": return evalCommitFilter(graph, ast).matches;
1935
1991
  case "reverseSet": {
1936
1992
  const ids = new Set(evalSet(graph, ast.inner, opts).map((i) => i.id));
1937
1993
  return reverseOverSet(graph, ast.kind, ast.entityType, ids);
@@ -2148,7 +2204,7 @@ const COMMIT_FILTER_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
2148
2204
  * here, beside the fully typed result, before render() flattens it all to a
2149
2205
  * sentence; the session layer is what registers them into its record. */
2150
2206
  function evalCommitFilter(graph, ast) {
2151
- const { op, pivotRaw } = ast;
2207
+ const { op, pivotRaw, entityType = null } = ast;
2152
2208
  const dateOf = (c) => String((c.attributes || []).find((a) => a.key === "date")?.value || "").slice(0, 10);
2153
2209
  let pivotDate = null;
2154
2210
  let pivotId = null;
@@ -2163,8 +2219,11 @@ function evalCommitFilter(graph, ast) {
2163
2219
  pivotDate = dateOf(match);
2164
2220
  }
2165
2221
  }
2166
- if (!pivotDate) return { compositeKind: "commitFilter", op, pivotRaw, pivotResolved: false, matches: [] };
2167
- const matches = graph.individuals
2222
+ if (!pivotDate) return { compositeKind: "commitFilter", op, pivotRaw, entityType, pivotResolved: false, matches: [] };
2223
+ // Two dates on the same day tie under a lexical compare, so the id breaks the
2224
+ // tie: the window's answer must not depend on which order the individuals
2225
+ // arrived in.
2226
+ const inWindow = graph.individuals
2168
2227
  .filter((i) => i.class === "Commit" && i.id !== pivotId && dateOf(i))
2169
2228
  .filter((c) => {
2170
2229
  const d = dateOf(c);
@@ -2173,12 +2232,19 @@ function evalCommitFilter(graph, ast) {
2173
2232
  if (op === "after") return d > pivotDate;
2174
2233
  return d === pivotDate; // "on"
2175
2234
  })
2176
- .sort((a, b) => dateOf(b).localeCompare(dateOf(a)));
2235
+ .sort((a, b) => dateOf(b).localeCompare(dateOf(a)) || String(a.id).localeCompare(String(b.id)));
2236
+ // A kind-headed window reads what the qualifying commits touched at that
2237
+ // grain; the bare shape answers with the commits themselves.
2238
+ const touched = entityType && entityType !== "Commit" && entityType !== "Change"
2239
+ ? uniqueById(inWindow.flatMap((c) => commitTouches(graph, c, entityType).matches))
2240
+ : null;
2241
+ const matches = touched || inWindow;
2177
2242
  const referents = [];
2178
2243
  if (matches.length) {
2244
+ const setClass = touched ? entityType : "Commit";
2179
2245
  referents.push({
2180
- kind: "set", class: "Commit",
2181
- label: `${matches.length} commit${matches.length === 1 ? "" : "s"} ${op} ${pivotRaw}`,
2246
+ kind: "set", class: setClass,
2247
+ label: `${matches.length} ${nounFor(setClass, matches.length)} ${op} ${pivotRaw}`,
2182
2248
  ids: matches.map((c) => c.id),
2183
2249
  attrs: { count: matches.length, op, ...(pivotId ? { pivot: pivotId } : {}) },
2184
2250
  lane: "commitFilter",
@@ -2191,7 +2257,10 @@ function evalCommitFilter(graph, ast) {
2191
2257
  lane: "commitFilter",
2192
2258
  });
2193
2259
  }
2194
- return { compositeKind: "commitFilter", op, pivotRaw, pivotDate, pivotResolved: true, matches, referents };
2260
+ return {
2261
+ compositeKind: "commitFilter", op, pivotRaw, pivotDate, pivotResolved: true,
2262
+ entityType, windowCount: inWindow.length, matches, referents,
2263
+ };
2195
2264
  }
2196
2265
 
2197
2266
  /** Temporal over a nested set: the commits that touched any member of the
@@ -2395,6 +2464,13 @@ function evalComposite(graph, ast, opts = {}) {
2395
2464
  if (ast.node === "qualCheck") return evalQualCheck(graph, ast, opts);
2396
2465
  if (ast.node === "universal") return evalUniversal(graph, ast, opts);
2397
2466
  if (ast.node === "count") {
2467
+ // A window the pivot can't bound refuses, so the count never reads as a
2468
+ // grounded zero over a window nobody could place.
2469
+ if (ast.base.node === "commitFilter") {
2470
+ const window = evalCommitFilter(graph, ast.base);
2471
+ if (!window.pivotResolved) return window;
2472
+ return { compositeKind: "count", count: window.matches.length, entityType: ast.entityType, matches: [] };
2473
+ }
2398
2474
  // "how many commits touched <X>" — count against provenance attestation
2399
2475
  // (commitTouchCount), not the bare touches-edge set evalSet(base) would
2400
2476
  // give: see commitTouchCount's own doc for why the two can disagree.
@@ -2439,7 +2515,28 @@ function evalComposite(graph, ast, opts = {}) {
2439
2515
  // qualifier listing ("which modules are tested") registers the same way, just
2440
2516
  // under its own lane name.
2441
2517
  const referents = setReferentsFor(entityType, matches, ast.node === "qualifier" ? "qualifierListing" : "compositeSet");
2442
- 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
+ };
2443
2540
  }
2444
2541
 
2445
2542
  // ---- compositional render: templated, same "honest miss vs cited hit"
@@ -2641,9 +2738,18 @@ function renderComposite(parsed, result, graph) {
2641
2738
  miss: true, ambiguous: false, matches: [],
2642
2739
  };
2643
2740
  }
2644
- if (!result.matches.length) {
2741
+ if (!result.windowCount) {
2645
2742
  return { content: `no commits recorded ${result.op} ${result.pivotRaw}.`, miss: true, ambiguous: false, matches: [] };
2646
2743
  }
2744
+ // A kind-headed window that no commit reached at that grain is an honest
2745
+ // empty naming both the kind and the window, never the commit list.
2746
+ if (result.entityType && result.entityType !== "Commit" && result.entityType !== "Change") {
2747
+ const kindNoun = nounFor(result.entityType, result.matches.length || 2);
2748
+ if (!result.matches.length) {
2749
+ return { content: `no ${kindNoun} changed ${result.op} ${result.pivotRaw}.`, miss: true, ambiguous: false, matches: [] };
2750
+ }
2751
+ return { content: `${compositeList(result.matches)}.`, miss: false, ambiguous: false, matches: result.matches };
2752
+ }
2647
2753
  const dateOf = (c) => String((c.attributes || []).find((a) => a.key === "date")?.value || "");
2648
2754
  const shown = result.matches.slice(0, HISTORY_CAP).map((c) => {
2649
2755
  const day = dateOf(c).slice(0, 10);
@@ -2709,7 +2815,24 @@ function renderComposite(parsed, result, graph) {
2709
2815
  }
2710
2816
  // set-producing
2711
2817
  if (!result.matches.length) {
2712
- 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);
2713
2836
  return { content: `nothing in the index matches that${result.entityType ? ` (${nounFor(result.entityType, 2)})` : ""}. ${hint}`, miss: true, ambiguous: false, matches: [] };
2714
2837
  }
2715
2838
  return { content: `${compositeList(result.matches)}.`, miss: false, ambiguous: false, matches: result.matches };
@@ -3281,10 +3404,40 @@ function rankEntryPointModules(graph, term) {
3281
3404
  * gets an honest "not supported yet" response, never a silent fallback to
3282
3405
  * direct-only behavior. */
3283
3406
  function modifierIsWired(shape, kind, entityType) {
3284
- 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;
3285
3411
  }
3286
3412
  const TRANSITIVE_MAX_DEPTH = 8; // matches renderImpact's own default (codegraph.mjs)
3287
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
+
3288
3441
  /** A graph's own vocabulary nodes carry their definition text under one of
3289
3442
  * these properties. A code entity's docstring rides `seon:hasDoc` and shares
3290
3443
  * the plain `doc` key, so this set is what separates the two. */
@@ -3623,7 +3776,17 @@ export function traverse(graph, parsed, { contextId = null, prev = null, pinnedO
3623
3776
  // resolve to the same mixed closure — a deliberate scope decision, stated
3624
3777
  // honestly in the traversal receipt below.
3625
3778
  if (parsed.modifier === "transitive") {
3626
- 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 });
3627
3790
  const matches = levels.flat().map((d) => graph.byId.get(d.id)).filter(Boolean);
3628
3791
  return {
3629
3792
  matches, objMatch, candidates, ambiguous, matchedVia,
@@ -4329,8 +4492,11 @@ function renderCore(parsed, result, graph) {
4329
4492
  const object = (result.objMatch && CONTEXT_PRONOUNS.includes(String(parsed.object || "").toLowerCase()))
4330
4493
  ? result.objMatch.label
4331
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";
4332
4498
  return {
4333
- 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)}`,
4334
4500
  miss: true, ambiguous: false,
4335
4501
  };
4336
4502
  }
@@ -5001,6 +5167,68 @@ const classLanesApply = (graph, parsed, result, rendered) => (rendered.ambiguous
5001
5167
  ? tieNamesAClass(graph, parsed, result)
5002
5168
  : !!rendered.miss);
5003
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
+
5004
5232
  export function ask(graph, query, { contextId = null, nlp = undefined, prev = null } = {}) {
5005
5233
  if (isHelpRequest(query)) {
5006
5234
  return {
@@ -5011,6 +5239,9 @@ export function ask(graph, query, { contextId = null, nlp = undefined, prev = nu
5011
5239
  },
5012
5240
  };
5013
5241
  }
5242
+ const speculative = speculativeConditionalRefusal(graph, query);
5243
+ if (speculative) return speculative;
5244
+ query = counterfactualSubclassQuery(graph, query) || query;
5014
5245
  query = substituteLastCommitPhrase(graph, query);
5015
5246
  const directFull = parseQueryFull(query, { nlp });
5016
5247
  const direct = directFull.parsed;
@@ -250,8 +250,12 @@ export function renderDescribe(graph, ind, { candidates = [] } = {}) {
250
250
  const lines = [];
251
251
  lines.push(`${ind.label} — ${classHeading(ind.class)} (id: ${ind.id})`);
252
252
 
253
+ // Counts the entity's own provenance refs, which is not the same as the number
254
+ // of commits that touched it: a `turn:` ref is no commit at all, and a `git:`
255
+ // ref may name a commit this index never ingested. The touches edges below say
256
+ // what touched it; saying "touched by N commit(s)" here contradicted them.
253
257
  const refs = (ind.derived_from || []).filter(isProvRef);
254
- if (refs.length) lines.push(`attestation: touched by ${refs.length} commit(s)`);
258
+ if (refs.length) lines.push(`attestation: ${refs.length} provenance ref(s)`);
255
259
 
256
260
  for (const a of ind.attributes || []) {
257
261
  lines.push(`attribute: ${a.key} = ${a.value}${a.prop ? ` [${a.prop}]` : ""}`);
@@ -354,8 +358,16 @@ export function renderCompare(graph, indA, indB) {
354
358
  /** BFS the reverse of imports/calls edges from `ind` — "what would break".
355
359
  * Diamonds collapse to shortest depth; cycles terminate via the visited set.
356
360
  * `callsSymbol` is folded in too, coarsened to module level on read: it has
357
- * no import-backing requirement, so it can reach dependents "calls" alone would miss. */
358
- 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 } = {}) {
359
371
  const dependents = new Map();
360
372
  const coveredBy = new Map(); // moduleId → [test labels]
361
373
  const addDependent = (objectId, subjectId, subjectLabel, via) => {
@@ -404,6 +416,21 @@ export function impactClosure(graph, ind, { maxDepth = 8 } = {}) {
404
416
  .sort((a, b) => String(a.label).localeCompare(String(b.label)));
405
417
  levels.push(withTests);
406
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
+ }
407
434
  return levels;
408
435
  }
409
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 —