@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.1

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.
Files changed (34) hide show
  1. package/README.md +27 -0
  2. package/bin/tmct.mjs +61 -0
  3. package/package.json +14 -2
  4. package/src/adapters/memory/backends-exports.mjs +8 -0
  5. package/src/adapters/memory/core.mjs +812 -175
  6. package/src/adapters/memory/corpus-bands.mjs +155 -0
  7. package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
  8. package/src/adapters/memory/row-backend-dynamo.mjs +315 -0
  9. package/src/adapters/memory/row-backend-memory.mjs +85 -0
  10. package/src/adapters/memory/row-backend.mjs +162 -0
  11. package/src/adapters/memory/rows.mjs +328 -0
  12. package/src/adapters/memory/shacl.mjs +24 -0
  13. package/src/adapters/memory/systemic-failure.mjs +28 -0
  14. package/src/adapters/research-queue-store.mjs +215 -32
  15. package/src/domain/ask.mjs +341 -75
  16. package/src/domain/cli-verbs.mjs +17 -0
  17. package/src/domain/fact-phrase.mjs +40 -0
  18. package/src/domain/news-feed.mjs +42 -4
  19. package/src/domain/phrase-exports.mjs +4 -0
  20. package/src/domain/retrieval-marker.mjs +120 -0
  21. package/src/domain/retrieval-modes.mjs +13 -0
  22. package/src/domain/retrieval-plan.mjs +224 -0
  23. package/src/services/chat-session.mjs +36 -9
  24. package/src/services/chat.mjs +73 -16
  25. package/src/services/corpus-loader.mjs +222 -0
  26. package/src/services/extract-facts.mjs +244 -33
  27. package/src/services/init.mjs +15 -5
  28. package/src/services/news.mjs +4 -2
  29. package/src/services/subgraph-retrieval.mjs +332 -0
  30. package/src/surfaces/web/http-row-backend.mjs +150 -0
  31. package/src/surfaces/web/memory-ask-browser.bundle.js +134 -131
  32. package/src/surfaces/web/news-browser-entry.mjs +6 -2
  33. package/src/tools/handlers/tmct-ingest.mjs +3 -1
  34. package/src/tools/memory-backend-conformance.mjs +238 -0
@@ -26,7 +26,7 @@ import {
26
26
  PASSIVE_PARTICIPLE_TO_KIND, GENERIC_AGENT_WORDS, REDUCED_RELATIVE_CLAUSES,
27
27
  AGGREGATE_TRIGGERS, LIST_TRIGGERS, SUPERLATIVE_EXTREMES, EDGE_NOUN_TO_METRIC, METRIC_IMPLIES_ENTITY, ANAPHORA_TRIGGERS,
28
28
  MEMBERSHIP_KINDS, CASCADE_NOISE, CASCADE_SYNONYMS, HELP_TRIGGERS,
29
- WORLD_RELATIONS, WORLD_NOUN_TO_RELATION, WORLD_PREDICATES, locativePreposition,
29
+ WORLD_RELATIONS, WORLD_NOUN_TO_RELATION, WORLD_PREDICATES, locativePreposition, phraseForRelation,
30
30
  stripTrailingScopeFiller, stripTrailingTemporalAdverb, CALLS_VERB_REPORT_NOUNS,
31
31
  } from "./ask-vocab.mjs";
32
32
  import { expandContractions, normalizeQuery, applyNegationFrames, applyPhrasingFrames, applyConditionalFrames, counterfactualSubjectOf, matchNegationSet, STOPWORDS, splitWords, wordsOf, escapeRegex } from "./interpret/normalize.mjs";
@@ -2223,28 +2223,41 @@ function oppositeQualifierWord(word) {
2223
2223
  return Object.keys(QUALIFIERS).find((k) => QUALIFIERS[k].via === opposite.via && QUALIFIERS[k].value === opposite.value) || null;
2224
2224
  }
2225
2225
 
2226
- function evalBoolean(graph, ast, opts) {
2226
+ /** The fold itself, keeping the set that reached every atom. An empty answer
2227
+ * reads those intermediates to say which branch emptied it, so the receipt is
2228
+ * the fold's own record rather than a second evaluation of the seed. Each step
2229
+ * gets a fresh array, so a later atom can never rewrite an earlier `before`. */
2230
+ function foldBoolean(graph, ast, opts) {
2231
+ const steps = [];
2227
2232
  let acc = [];
2228
2233
  for (const atom of ast.atoms) {
2229
- if (atom.op === "seed") { acc = evalSet(graph, atom.ast, opts); continue; }
2230
- if (atom.kind === "qual") {
2234
+ const before = acc;
2235
+ if (atom.op === "seed") acc = evalSet(graph, atom.ast, opts);
2236
+ else if (atom.kind === "qual") {
2231
2237
  const holds = (ind) => atom.filters.every((f) => qualHolds(graph, ind, QUALIFIERS[f]));
2232
2238
  const complementHolds = (ind) => atom.filters.every((f) => {
2233
2239
  const opposite = oppositeQualifierSpec(QUALIFIERS[f]);
2234
2240
  return opposite ? qualHolds(graph, ind, opposite) : !qualHolds(graph, ind, QUALIFIERS[f]);
2235
2241
  });
2236
- acc = atom.op === "difference" ? acc.filter(complementHolds) : acc.filter(holds);
2237
- continue;
2238
- }
2239
- const oids = new Set(evalSet(graph, atom.ast, opts).map((i) => i.id));
2240
- if (atom.op === "intersection") acc = acc.filter((i) => oids.has(i.id));
2241
- else if (atom.op === "difference") acc = acc.filter((i) => !oids.has(i.id));
2242
- else if (atom.op === "union") {
2243
- const seen = new Set(acc.map((i) => i.id));
2244
- for (const other of evalSet(graph, atom.ast, opts)) if (!seen.has(other.id)) { seen.add(other.id); acc.push(other); }
2242
+ acc = atom.op === "difference" ? before.filter(complementHolds) : before.filter(holds);
2243
+ } else {
2244
+ const other = evalSet(graph, atom.ast, opts);
2245
+ const oids = new Set(other.map((i) => i.id));
2246
+ if (atom.op === "intersection") acc = before.filter((i) => oids.has(i.id));
2247
+ else if (atom.op === "difference") acc = before.filter((i) => !oids.has(i.id));
2248
+ else if (atom.op === "union") {
2249
+ const seen = new Set(before.map((i) => i.id));
2250
+ acc = before.slice();
2251
+ for (const o of other) if (!seen.has(o.id)) { seen.add(o.id); acc.push(o); }
2252
+ }
2245
2253
  }
2254
+ steps.push({ atom, before, after: acc });
2246
2255
  }
2247
- return acc;
2256
+ return { matches: acc, steps };
2257
+ }
2258
+
2259
+ function evalBoolean(graph, ast, opts) {
2260
+ return foldBoolean(graph, ast, opts).matches;
2248
2261
  }
2249
2262
 
2250
2263
  /** Resolve parseAnaphora's in-sentence candidateTerms to real graph entities,
@@ -2305,7 +2318,25 @@ function evalAnaphora(graph, ast, opts) {
2305
2318
  // session layer's register() does not evict the set on the class change a
2306
2319
  // narrowing produces.
2307
2320
  const referents = setReferentsFor(common, items, "anaphora", { bound: true });
2308
- return { compositeKind: "set", matches: items, entityType: common, referents };
2321
+ // The prior answer is the set this filter emptied, so the empty case names
2322
+ // those entities rather than reading as a claim about the whole index.
2323
+ const emptied = items.length ? null : priorSetEmptiedBy(graph, baseItems, f);
2324
+ return { compositeKind: "set", matches: items, entityType: common, referents, ...(emptied ? { emptied } : {}) };
2325
+ }
2326
+
2327
+ /** What a follow-up filter did to the set the previous answer established. */
2328
+ function priorSetEmptiedBy(graph, baseItems, filter) {
2329
+ if (!baseItems.length || !filter) return null;
2330
+ const held = { ...heldSet(baseItems, null, null) };
2331
+ if (filter.type === "qual") {
2332
+ const step = qualifierStep(graph, filter.filters, false, baseItems);
2333
+ return step ? { held, step } : null;
2334
+ }
2335
+ if (filter.type === "entity") return { held, step: { type: "entityKind", entityType: filter.entityType } };
2336
+ if (filter.type === "clause" && filter.clause?.kind && filter.clause.object) {
2337
+ return { held, step: { type: "clause", clause: { kind: filter.clause.kind, object: filter.clause.object }, excluded: false } };
2338
+ }
2339
+ return null;
2309
2340
  }
2310
2341
 
2311
2342
  // Structural kinds counted for "most-connected" (total degree). Symbol-grain and
@@ -2488,13 +2519,26 @@ function evalMembershipComposite(graph, ast, opts) {
2488
2519
  const { own, inherited, viaLabel } = computeMembership(graph, owner.id, owner.entityClass, entityType, filterFn);
2489
2520
  const inheritedNotOwn = !own.length && inherited.length > 0;
2490
2521
  const finalMatches = inheritedNotOwn ? inherited : own;
2522
+ // An owner that holds members the qualifier rejected is a different answer
2523
+ // from an owner that holds none at all, so the empty case says which.
2524
+ const emptied = finalMatches.length ? null : membershipEmptiedBy(graph, owner, entityType, qualNode);
2491
2525
  return {
2492
2526
  compositeKind: "membership", entityType, matches: finalMatches,
2493
2527
  inheritedNotOwn, viaLabel, ownerLabel: owner.label,
2494
2528
  referents: membershipReferents(finalMatches),
2529
+ ...(emptied ? { emptied } : {}),
2495
2530
  };
2496
2531
  }
2497
2532
 
2533
+ function membershipEmptiedBy(graph, owner, entityType, qualNode) {
2534
+ if (!qualNode) return null;
2535
+ const { own, inherited } = computeMembership(graph, owner.id, owner.entityClass, entityType, null);
2536
+ const held = own.length ? own : inherited;
2537
+ if (!held.length) return null;
2538
+ const step = qualifierStep(graph, qualNode.filters, false, held);
2539
+ return step ? { held: { ...heldSet(held, null, { entityType }), owner: owner.label }, step } : null;
2540
+ }
2541
+
2498
2542
  /** Existence eval — a direct membership/name check against the graph, never
2499
2543
  * routed through the relation-verb machinery. `expectedClass` pins the
2500
2544
  * resolve pool so "is there a class called Store" can't resolve to a
@@ -2661,45 +2705,131 @@ function evalComposite(graph, ast, opts = {}) {
2661
2705
  // qualifier listing ("which modules are tested") registers the same way, just
2662
2706
  // under its own lane name.
2663
2707
  const referents = setReferentsFor(entityType, matches, ast.node === "qualifier" ? "qualifierListing" : "compositeSet");
2664
- const narrowedFrom = matches.length ? null : qualifierEmptiedSet(graph, ast, opts);
2665
- return { compositeKind: "set", matches, entityType, referents, ...(narrowedFrom ? { narrowedFrom } : {}) };
2708
+ const emptied = matches.length ? null : emptiedBranch(graph, ast, opts);
2709
+ return { compositeKind: "set", matches, entityType, referents, ...(emptied ? { emptied } : {}) };
2710
+ }
2711
+
2712
+ /** The clause a set node states in words, or null where it states none the
2713
+ * receipt may quote. The reverse reading ("which modules IMPORT x.mjs") reads
2714
+ * as an active sentence about the set itself; the forward one ("the classes
2715
+ * x.mjs DEFINES") reads as a passive about the same set, and only where the
2716
+ * relation's own verb is a single word — "inherit from" has no passive that
2717
+ * keeps the direction the question asked in. */
2718
+ function quotableClause(node) {
2719
+ const clause = node?.node === "clause" ? node.clause : null;
2720
+ if (!clause?.kind || !clause.object || clause.modifier === "transitive") return null;
2721
+ if (clause.shape !== "reverse" && clause.shape !== "forward") return null;
2722
+ const passive = clause.shape === "forward";
2723
+ if (passive && bareVerbFor(clause.kind).includes(" ")) return null;
2724
+ return {
2725
+ kind: clause.kind, object: clause.object, passive,
2726
+ entityType: clause.entityType || node.entityType || null,
2727
+ };
2666
2728
  }
2667
2729
 
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;
2730
+ // The agent a passive reading names its subject with. A module DEFINES its
2731
+ // symbols, and they read as defined IN it, not by it.
2732
+ const PASSIVE_AGENT_PREPOSITION = { defines: "in", contains: "in" };
2733
+
2734
+ /** "is imported by app/lib/f.mjs", "is defined in app/lib/c.mjs" — the passive
2735
+ * half of a forward clause, built from the relation's own bare verb. */
2736
+ function passiveClausePhrase(clause) {
2737
+ const bare = bareVerbFor(clause.kind);
2738
+ const participle = bare.endsWith("e") ? `${bare}d` : `${bare}ed`;
2739
+ return `${participle} ${PASSIVE_AGENT_PREPOSITION[clause.kind] || "by"} ${clause.object}`;
2740
+ }
2741
+
2742
+ const sameClassOf = (list) => (list.length && list.every((x) => x.class === list[0].class) ? list[0].class : null);
2743
+
2744
+ /** What a qualifier step may claim about the set it emptied, or null where it
2745
+ * may claim nothing.
2746
+ *
2747
+ * A difference reports what the exclusion took away, so it may only name the
2748
+ * qualifier where the members really do satisfy it. A member the qualifier
2749
+ * does not apply to at either polarity leaves by the same door, and saying it
2750
+ * was tested would be a guess about a coverage fact nothing records.
2751
+ *
2752
+ * An intersection's members failed the filter, which is all that is proven, so
2753
+ * the receipt negates it. A filter that is already a negative adjective would
2754
+ * stack into "but it is not untested", so where the vocabulary carries the
2755
+ * positive word AND every member satisfies it, the receipt says that instead. */
2756
+ function qualifierStep(graph, filters, excluded, held) {
2684
2757
  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);
2758
+ if (excluded && !allHold(filters)) return null;
2759
+ const opposites = excluded || !filters.every((f) => QUALIFIERS[f]?.value === false)
2760
+ ? [] : filters.map(oppositeQualifierWord);
2697
2761
  const statable = opposites.length > 0 && opposites.every(Boolean) && allHold(opposites);
2762
+ return { type: "qual", filters: statable ? opposites : filters, negated: !excluded && !statable };
2763
+ }
2764
+
2765
+ /** What one boolean atom did to the set that reached it. */
2766
+ function atomStep(graph, atom, held) {
2767
+ if (atom.kind === "qual") {
2768
+ if (atom.op !== "difference" && atom.op !== "intersection") return null;
2769
+ return qualifierStep(graph, atom.filters, atom.op === "difference", held);
2770
+ }
2771
+ if (atom.op !== "difference" && atom.op !== "intersection") return null;
2772
+ const excluded = atom.op === "difference";
2773
+ if (atom.ast?.node === "named") return { type: "named", term: atom.ast.term, excluded };
2774
+ const clause = quotableClause(atom.ast);
2775
+ return clause ? { type: "clause", clause, excluded } : null;
2776
+ }
2777
+
2778
+ /** An empty composite tells the reader nothing about WHICH branch emptied it.
2779
+ * Two very different answers read the same: a clause nothing satisfied, and a
2780
+ * clause that held real entities until the next step took them away.
2781
+ *
2782
+ * This walks the composition from the outside in and stops at the step that
2783
+ * turned a non-empty set into an empty one. `held` is that step's own input —
2784
+ * a boolean reads it straight off the fold's record, a relation hop off the
2785
+ * inner set it was about to traverse. Where nothing held anywhere, the walk
2786
+ * bottoms out on the clause that started empty and names that instead. Every
2787
+ * evaluation here happens on the empty path only, so a question that answered
2788
+ * pays nothing for it. */
2789
+ function emptiedBranch(graph, ast, opts) {
2790
+ if (!ast || typeof ast !== "object") return null;
2791
+ if (ast.node === "boolean") {
2792
+ const { steps } = foldBoolean(graph, ast, opts);
2793
+ // The LAST step that emptied a non-empty set is the one that decided this
2794
+ // answer: a union later in the fold can refill a set an earlier step
2795
+ // emptied, and then the earlier step is not what the reader is missing.
2796
+ const emptying = [...steps].reverse().find((s) => s.before.length && !s.after.length);
2797
+ if (!emptying) return emptiedBranch(graph, steps[0]?.atom?.ast, opts);
2798
+ const step = atomStep(graph, emptying.atom, emptying.before);
2799
+ if (!step) return null;
2800
+ // Only the seed ran before the emptying atom, so the seed's own clause is
2801
+ // what the held set is. Any longer prefix is a composition no single clause
2802
+ // states, and the receipt names its members instead of glossing it.
2803
+ const source = steps.indexOf(emptying) === 1 ? steps[0].atom.ast : null;
2804
+ return { held: heldSet(emptying.before, source, ast), step };
2805
+ }
2806
+ if (ast.node === "qualifier" && ast.inner?.node !== "membership" && ast.filters?.length) {
2807
+ const inner = evalSet(graph, ast.inner, opts);
2808
+ if (!inner.length) return emptiedBranch(graph, ast.inner, opts);
2809
+ const step = qualifierStep(graph, ast.filters, false, inner);
2810
+ return step ? { held: heldSet(inner, ast.inner, ast), step } : null;
2811
+ }
2812
+ if (ast.node === "reverseSet" || ast.node === "forwardSet" || ast.node === "membershipSet") {
2813
+ const inner = evalSet(graph, ast.inner, opts);
2814
+ if (!inner.length) return emptiedBranch(graph, ast.inner, opts);
2815
+ const step = ast.node === "membershipSet"
2816
+ ? (ast.entityType ? { type: "membership", entityType: ast.entityType } : null)
2817
+ : { type: ast.node === "reverseSet" ? "reverse" : "forward", kind: ast.kind, entityType: ast.entityType || null };
2818
+ return step ? { held: heldSet(inner, ast.inner, ast), step } : null;
2819
+ }
2820
+ const clause = quotableClause(ast);
2821
+ return clause ? { leaf: clause } : null;
2822
+ }
2823
+
2824
+ /** The set a step was handed, in the terms a receipt can state it: how many,
2825
+ * which kind, the clause that states it (where one does), and whether it is a
2826
+ * whole kind the index holds rather than a narrowed set. */
2827
+ function heldSet(members, sourceNode, ast) {
2828
+ const clause = quotableClause(sourceNode);
2698
2829
  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,
2830
+ count: members.length,
2831
+ entityType: sameClassOf(members) || clause?.entityType || ast?.entityType || null,
2832
+ clause, wholeKind: sourceNode?.node === "allOfClass", members,
2703
2833
  };
2704
2834
  }
2705
2835
 
@@ -2785,6 +2915,147 @@ function qualifierBranchNote(parsed) {
2785
2915
  return `Try "which ${kindPlural} are ${polarity}${listJoin(filtered.filters)}" for that branch on its own.`;
2786
2916
  }
2787
2917
 
2918
+ /** How many individuals of a kind the index holds at all. This is the fact
2919
+ * that separates "there are no functions here" from "there are functions here
2920
+ * and none of them answers the question" — one line used to claim both. */
2921
+ function kindPopulation(graph, entityType) {
2922
+ if (!graph || !entityType) return null;
2923
+ if (entityType === "Package") return packageIndividuals(graph).length;
2924
+ return graph.individuals.filter((i) => i.class === entityType).length;
2925
+ }
2926
+
2927
+ /** What the emptying step did, read for a held set of one and of several.
2928
+ * A closed set: one entry per step shape a composition can end on. */
2929
+ function stepPhrases(step) {
2930
+ const kindNoun = (n) => (step.entityType ? nounFor(step.entityType, n) : null);
2931
+ switch (step.type) {
2932
+ case "qual": {
2933
+ const words = listJoin(step.filters);
2934
+ return step.negated
2935
+ ? { one: `it is not ${words}`, many: `none of them is ${words}` }
2936
+ : { one: `it is ${words}`, many: `all of them are ${words}` };
2937
+ }
2938
+ case "named":
2939
+ return step.excluded
2940
+ ? { one: `it is named "${step.term}"`, many: `all of them are named "${step.term}"` }
2941
+ : { one: `it is not named "${step.term}"`, many: `none of them is named "${step.term}"` };
2942
+ case "clause": {
2943
+ const { clause } = step;
2944
+ if (clause.passive) {
2945
+ const phrase = passiveClausePhrase(clause);
2946
+ return step.excluded
2947
+ ? { one: `it is ${phrase}`, many: `all of them are ${phrase}` }
2948
+ : { one: `it is not ${phrase}`, many: `none of them is ${phrase}` };
2949
+ }
2950
+ const bare = bareVerbFor(clause.kind);
2951
+ const third = thirdPersonVerbFor(clause.kind);
2952
+ return step.excluded
2953
+ ? { one: `it ${third} ${clause.object} too`, many: `all of them ${bare} ${clause.object} too` }
2954
+ : { one: `it does not ${bare} ${clause.object}`, many: `none of them ${third} ${clause.object}` };
2955
+ }
2956
+ case "reverse": {
2957
+ const third = thirdPersonVerbFor(step.kind);
2958
+ const subject = kindNoun(1) ? `no ${kindNoun(1)} in this index` : "nothing in this index";
2959
+ return { one: `${subject} ${third} it`, many: `${subject} ${third} them` };
2960
+ }
2961
+ case "forward": {
2962
+ const third = thirdPersonVerbFor(step.kind);
2963
+ return { one: `it ${third} nothing in this index`, many: `none of them ${third} anything in this index` };
2964
+ }
2965
+ case "membership":
2966
+ return { one: `it has no ${kindNoun(2)}`, many: `none of them has any ${kindNoun(2)}` };
2967
+ case "entityKind":
2968
+ return { one: `it is not a ${kindNoun(1)}`, many: `none of them is a ${kindNoun(1)}` };
2969
+ default:
2970
+ return null;
2971
+ }
2972
+ }
2973
+
2974
+ /** The set that reached the emptying step, said out loud. A whole kind says so
2975
+ * ("the index has 3 classes"); a clause-shaped set restates its clause; any
2976
+ * other composition names its members rather than glossing how they got
2977
+ * there. */
2978
+ function heldPhrases(held) {
2979
+ const singular = nounFor(held.entityType, 1);
2980
+ const plural = nounFor(held.entityType, 2);
2981
+ if (held.owner) {
2982
+ return { one: `${held.owner} has 1 ${singular}`, many: `${held.owner} has ${held.count} ${plural}` };
2983
+ }
2984
+ if (held.wholeKind) {
2985
+ return { one: `The index has 1 ${singular}`, many: `The index has ${held.count} ${plural}` };
2986
+ }
2987
+ if (held.clause?.passive) {
2988
+ const phrase = passiveClausePhrase(held.clause);
2989
+ return { one: `1 ${singular} is ${phrase}`, many: `${held.count} ${plural} are ${phrase}` };
2990
+ }
2991
+ if (held.clause) {
2992
+ return {
2993
+ one: `1 ${singular} ${thirdPersonVerbFor(held.clause.kind)} ${held.clause.object}`,
2994
+ many: `${held.count} ${plural} ${bareVerbFor(held.clause.kind)} ${held.clause.object}`,
2995
+ };
2996
+ }
2997
+ const cited = compositeList(held.members);
2998
+ return {
2999
+ one: `1 ${singular} matched that far (${cited})`,
3000
+ many: `${held.count} ${plural} matched that far (${cited})`,
3001
+ };
3002
+ }
3003
+
3004
+ /** The question a held clause answers on its own, phrased the way the clause
3005
+ * was asked. Both readings parse, so the nudge can never name a shape that
3006
+ * misses. */
3007
+ function heldBranchQuestion(held) {
3008
+ if (!held.clause || !held.entityType) return null;
3009
+ const plural = nounFor(held.entityType, 2);
3010
+ const ask = held.clause.passive
3011
+ ? `which ${plural} are ${passiveClausePhrase(held.clause)}`
3012
+ : `which ${plural} ${bareVerbFor(held.clause.kind)} ${held.clause.object}`;
3013
+ return `Try "${ask}" for that branch on its own.`;
3014
+ }
3015
+
3016
+ /** The receipt for an empty composition: the empty answer first, then what
3017
+ * held, what emptied it, and a branch to ask on its own.
3018
+ *
3019
+ * The verdict leads because the receipt alone reads as a description. An
3020
+ * answer that opens by naming an entity the question rejected is one a reader
3021
+ * can mistake for the answer, however carefully the rest of the sentence
3022
+ * excludes it. Null where the step may claim nothing, which leaves the caller
3023
+ * its own honest empty. */
3024
+ function emptiedBranchLine(emptied, entityType, fallbackBranchNote = null) {
3025
+ if (!emptied?.held) return null;
3026
+ const step = stepPhrases(emptied.step);
3027
+ if (!step) return null;
3028
+ const held = emptied.held;
3029
+ const phrases = heldPhrases(held);
3030
+ const one = held.count === 1;
3031
+ const branch = heldBranchQuestion(held) || fallbackBranchNote;
3032
+ const verdict = entityType ? `no ${nounFor(entityType, 2)} match that` : "nothing matches that";
3033
+ return `${verdict}. ${one ? phrases.one : phrases.many}, but ${one ? step.one : step.many}.${branch ? ` ${branch}` : ""}`;
3034
+ }
3035
+
3036
+ /** The empty line for a composition whose first clause held nothing: the
3037
+ * clause itself is the whole answer, so it is stated instead of the reader
3038
+ * being told the kind is missing. */
3039
+ function emptyClauseLine(leaf) {
3040
+ if (leaf.passive) {
3041
+ const object = leaf.entityType ? `no ${nounFor(leaf.entityType, 2)}` : "nothing";
3042
+ return `${leaf.object} ${thirdPersonVerbFor(leaf.kind)} ${object} in this index`;
3043
+ }
3044
+ const subject = leaf.entityType ? `no ${nounFor(leaf.entityType, 1)} in this index` : "nothing in this index";
3045
+ return `${subject} ${thirdPersonVerbFor(leaf.kind)} ${leaf.object}`;
3046
+ }
3047
+
3048
+ /** The last resort, and the one sentence that must never over-claim: an index
3049
+ * holding none of a kind and an index holding plenty of it are different
3050
+ * answers, so they get different words. */
3051
+ function emptyKindLine(graph, entityType) {
3052
+ const total = kindPopulation(graph, entityType);
3053
+ if (total === null) return `nothing in the index matches that${entityType ? ` (${nounFor(entityType, 2)})` : ""}.`;
3054
+ if (total === 0) return `no ${nounFor(entityType, 2)} in this index.`;
3055
+ if (total === 1) return `the index has 1 ${nounFor(entityType, 1)}, and it does not match that.`;
3056
+ return `the index has ${total} ${nounFor(entityType, 2)}, and none of them matches that.`;
3057
+ }
3058
+
2788
3059
  function renderComposite(parsed, result, graph) {
2789
3060
  if (result.compositeMiss) {
2790
3061
  if (result.reason === "no-prev") {
@@ -2890,7 +3161,12 @@ function renderComposite(parsed, result, graph) {
2890
3161
  // — inherited from <ancestor>: …"), never silently presented as the owner's own.
2891
3162
  if (result.compositeKind === "membership") {
2892
3163
  if (!result.matches.length) {
2893
- return { content: `nothing in the index matches that${result.entityType ? ` (${nounFor(result.entityType, 2)})` : ""}. ${touchesRephraseHint(graph)}`, miss: true, ambiguous: false, matches: [] };
3164
+ const receipt = emptiedBranchLine(result.emptied, result.entityType);
3165
+ if (receipt) return { content: receipt, miss: true, ambiguous: false, matches: [] };
3166
+ const lead = result.ownerLabel && result.entityType
3167
+ ? `${result.ownerLabel} has no ${nounFor(result.entityType, 2)} in this index.`
3168
+ : emptyKindLine(graph, result.entityType);
3169
+ return { content: `${lead} ${touchesRephraseHint(graph)}`, miss: true, ambiguous: false, matches: [] };
2894
3170
  }
2895
3171
  if (result.inheritedNotOwn) {
2896
3172
  const kindPlural = nounFor(result.entityType, 2);
@@ -3027,28 +3303,18 @@ function renderComposite(parsed, result, graph) {
3027
3303
  }
3028
3304
  // set-producing
3029
3305
  if (!result.matches.length) {
3030
- // The qualifier, not the clause, is what emptied this set — so name the
3031
- // entities the clause did hold and point at that branch on its own,
3032
- // instead of a blanket "nothing matches" beside an unrelated recovery.
3033
- const narrowed = result.narrowedFrom;
3034
- if (narrowed) {
3035
- const kindPlural = nounFor(narrowed.entityType || "Module", 2);
3036
- const filters = listJoin(narrowed.filters);
3037
- const clause = narrowed.negated
3038
- ? { one: `but it is not ${filters}`, many: `but none of them is ${filters}` }
3039
- : { one: `but it is ${filters}`, many: `but all of them are ${filters}` };
3040
- const held = narrowed.count === 1
3041
- ? `1 ${nounFor(narrowed.entityType || "Module", 1)} ${thirdPersonVerbFor(narrowed.kind)} ${narrowed.object}, ${clause.one}`
3042
- : `${narrowed.count} ${kindPlural} ${bareVerbFor(narrowed.kind)} ${narrowed.object}, ${clause.many}`;
3043
- return {
3044
- content: `${held}. Try "which ${kindPlural} ${bareVerbFor(narrowed.kind)} ${narrowed.object}" for that branch on its own.`,
3045
- miss: true, ambiguous: false, matches: [],
3046
- };
3047
- }
3048
- const hint = coverageGrainNote(parsed, result.entityType)
3049
- || qualifierBranchNote(parsed)
3050
- || touchesRephraseHint(graph);
3051
- return { content: `nothing in the index matches that${result.entityType ? ` (${nounFor(result.entityType, 2)})` : ""}. ${hint}`, miss: true, ambiguous: false, matches: [] };
3306
+ // The step that emptied this set, not the whole question, is what the
3307
+ // reader is missing — so name the entities that reached it and what it did
3308
+ // to them, instead of a blanket "nothing matches" beside an unrelated
3309
+ // recovery.
3310
+ const branchNote = coverageGrainNote(parsed, result.entityType) || qualifierBranchNote(parsed);
3311
+ const receipt = emptiedBranchLine(result.emptied, result.entityType, branchNote);
3312
+ if (receipt) return { content: receipt, miss: true, ambiguous: false, matches: [] };
3313
+ const hint = branchNote || touchesRephraseHint(graph);
3314
+ const lead = result.emptied?.leaf
3315
+ ? `${emptyClauseLine(result.emptied.leaf)}.`
3316
+ : emptyKindLine(graph, result.entityType);
3317
+ return { content: `${lead} ${hint}`, miss: true, ambiguous: false, matches: [] };
3052
3318
  }
3053
3319
  return { content: `${compositeList(result.matches)}.`, miss: false, ambiguous: false, matches: result.matches };
3054
3320
  }
@@ -4220,10 +4486,10 @@ function bareVerbFor(kind) {
4220
4486
  /** The 3rd-person singular of a relation's bare form, keeping any preposition
4221
4487
  * the phrase carries: "inherit from" -> "inherits from". A one-member set
4222
4488
  * otherwise read "1 class inherits Base" beside the plural's "classes inherit
4223
- * from Base" in the very next sentence. */
4489
+ * from Base" in the very next sentence. The vocabulary owns the suffix rule,
4490
+ * so "touch" reads "touches" rather than a bare +s. */
4224
4491
  function thirdPersonVerbFor(kind) {
4225
- const [head, ...rest] = String(bareVerbFor(kind)).split(" ");
4226
- return [`${head}s`, ...rest].join(" ");
4492
+ return phraseForRelation(kind);
4227
4493
  }
4228
4494
 
4229
4495
  /** The passive participle of a relation ("uses" -> "used", "imports" ->
@@ -212,6 +212,23 @@ export const CLI_VERBS = [
212
212
  usage: "tmct cli digest '{…}'",
213
213
  prose: ["architecture map + per-module context bundles"],
214
214
  },
215
+ {
216
+ mode: "corpus",
217
+ errorLabel: "corpus load",
218
+ usage: "tmct corpus load <band> [--table <name>] [--source <path>] [--dry-run]",
219
+ prose: ["load a shared, read-only corpus band (wikidata-slice, wordnet-complete,"],
220
+ flags: [
221
+ { flag: "[--table <name>]", prose: ["conceptnet-full) into a DynamoDB row-backend table from a jsonl of", "wire-row-shaped facts (default table from TMCT_DYNAMO_TABLE); a", "source whose digest already matches the band's manifest is a no-op"] },
222
+ { flag: "[--source <path>]", prose: ["the band's jsonl (a scripts/corpus-bands/ build output, or any jsonl", "in the same wire-row shape)"] },
223
+ { flag: "[--dry-run]", prose: ["report the row count and source digest without writing anything"] },
224
+ ],
225
+ },
226
+ {
227
+ mode: "corpus",
228
+ errorLabel: "corpus clear",
229
+ usage: "tmct corpus clear <band> [--table <name>]",
230
+ prose: ["physically delete every row and the manifest for one band"],
231
+ },
215
232
  {
216
233
  mode: null,
217
234
  usage: "tmct --help",
@@ -44,6 +44,7 @@ export const FACT_PREDICATE_PHRASES = Object.freeze({
44
44
  "mgx:hasPrerequisite": "requires",
45
45
  "mgx:ownedBy": "is owned by", // the teach lane's ownership frame ("Priya owns tasks.mjs")
46
46
  "mgx:rendersAs": "renders as", // the render-template binding ("a disk renders as a block")
47
+ "mgx:nameFor": "is the name for", // the definitional frame's edge ("latency is the name for time period")
47
48
  "mgx:synonym": "means the same as",
48
49
  "mgx:antonym": "is the opposite of",
49
50
  "mgx:similarTo": "is similar to",
@@ -174,6 +175,45 @@ export function factSentence(row) {
174
175
  return `${row.subject} ${predicatePhrase(row.predicate)} ${row.object}`;
175
176
  }
176
177
 
178
+ /**
179
+ * The short curated caveat each KEPT extraction finding reads as beside a
180
+ * citation. One template per finding, byte-pinned, so an answer that leans on a
181
+ * row the extractor had something to say about says so in the same words every
182
+ * time.
183
+ *
184
+ * `definitional-frame` is deliberately absent: its own phrase ("is the name
185
+ * for") already says how the row was read, so a caveat would repeat it. So are
186
+ * the decline reasons — a declined candidate was never stored, so no answer can
187
+ * lean on it.
188
+ */
189
+ export const FINDING_CAVEATS = Object.freeze({
190
+ "clause-fallback": "(read from a clause fragment)",
191
+ "pronoun-carry": "(subject carried from the previous sentence)",
192
+ "identifier-token": "(identifier token)",
193
+ });
194
+
195
+ /**
196
+ * The caveat text for one fact row's findings, or "" when it has none to
197
+ * declare. Takes a row ({ extraction: [...] }, readFactRows' shape), a bare
198
+ * finding name, or a list of them, so a renderer can pass whatever it holds.
199
+ *
200
+ * A row carrying several findings reads them in the table's own order above,
201
+ * never the row's, so the same finding set always renders the same string.
202
+ * Returns the caveats alone — the caller owns the space before them and the
203
+ * citation after.
204
+ */
205
+ export function findingCaveat(finding) {
206
+ const named = typeof finding === "string"
207
+ ? [finding]
208
+ : Array.isArray(finding) ? finding : finding?.extraction;
209
+ if (!Array.isArray(named) || !named.length) return "";
210
+ const held = new Set(named.map((f) => String(f)));
211
+ return Object.entries(FINDING_CAVEATS)
212
+ .filter(([name]) => held.has(name))
213
+ .map(([, caveat]) => caveat)
214
+ .join(" ");
215
+ }
216
+
177
217
  /** The phrase layer as browser source, for a generated page that renders fact
178
218
  * rows in its own inline script. The page supplies FACT_PREDICATE_PHRASES
179
219
  * (it embeds the table as JSON) and this supplies everything the reader