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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,7 +70,7 @@ import { newsTurn, resolveNewsConfig, NEWS_DEFAULTS, createNewsState } from "./n
70
70
  import { CHILD_PACK_NAME, childProvenanceTag } from "../domain/child-pack.mjs";
71
71
  import { getChildPackProvider } from "../adapters/corpus/child-pack.mjs";
72
72
  import { dialogueActForLane } from "../domain/dialogue-acts.mjs";
73
- import { splitChoiceQuestion, routeChoiceRelation, lemmaFoldVariants, headNounOf } from "../domain/choice-question.mjs";
73
+ import { splitChoiceQuestion, routeChoiceRelation, lemmaFoldVariants, headNounOf, stemTopicCandidates, stemConstraintTerms } from "../domain/choice-question.mjs";
74
74
  import { subClassParents, subClassChildren, descendantSet, ancestryChain, clusterSenses } from "../domain/sense-split.mjs";
75
75
  import { ANSWER_STOP_SET } from "../domain/hub-terms.mjs";
76
76
  import { relatedForTerm } from "../domain/skos-view.mjs";
@@ -3793,6 +3793,133 @@ async function choiceWordnetTags(text) {
3793
3793
  for (const syn of synonyms) for (const v of factTermVariants(normFactTermStatic, syn)) tags.set(v, "wordnet");
3794
3794
  return tags;
3795
3795
  }
3796
+ /**
3797
+ * Picks the one candidate the question is about: the candidate the graph
3798
+ * holds the most facts about, counting rows where the term is the subject or
3799
+ * the object under any predicate. Ties in that count go to the phrase
3800
+ * extractStemSourceTerm captured (a structural read beats a graph count when
3801
+ * the graph cannot separate), then to the longer phrase, then to the leftmost.
3802
+ * Returns "" when no candidate is named in the store at all, which the lane
3803
+ * reports as the no-topic miss it already has.
3804
+ *
3805
+ * Pure in the fact set: the same rows in any order give the same topic, the
3806
+ * discipline sortFactIndividualsById already holds the store to.
3807
+ *
3808
+ * @returns {Promise<{ topic: string, salience: number, runnerUp: string }>}
3809
+ */
3810
+ async function chooseChoiceTopic(candidates, { memoryDir, cache, templateCapture }) {
3811
+ if (!candidates.length) return { topic: "", salience: 0, runnerUp: "" };
3812
+ const rows = await factRows(memoryDir, cache);
3813
+ const salienceOf = (text) => {
3814
+ const variants = factTermVariants(normFactTermStatic, text);
3815
+ let count = 0;
3816
+ for (const f of rows) { if (variants.has(f.subject) || variants.has(f.object)) count += 1; }
3817
+ return count;
3818
+ };
3819
+ const scored = candidates
3820
+ .map((c) => ({ ...c, salience: salienceOf(c.text) }))
3821
+ .sort((a, b) => {
3822
+ if (b.salience !== a.salience) return b.salience - a.salience;
3823
+ const aIsCapture = a.text === templateCapture;
3824
+ const bIsCapture = b.text === templateCapture;
3825
+ if (aIsCapture !== bIsCapture) return aIsCapture ? -1 : 1;
3826
+ if (b.words !== a.words) return b.words - a.words;
3827
+ return a.position - b.position;
3828
+ });
3829
+ const best = scored[0];
3830
+ if (best.salience === 0) return { topic: "", salience: 0, runnerUp: "" };
3831
+ const runnerUp = scored.find((c) => c.text !== best.text)?.text ?? "";
3832
+ return { topic: best.text, salience: best.salience, runnerUp };
3833
+ }
3834
+
3835
+ /**
3836
+ * Pulls the child pack once per constraint term, so the constraint check in
3837
+ * the tie branch has rows to read. Bounded three ways: at most
3838
+ * CHOICE_CONSTRAINT_PULL_BUDGET terms per turn, in stemConstraintTerms order;
3839
+ * nothing pulled for a term memory already holds a fact for; nothing pulled
3840
+ * for any option term, ever — terms reaching here already went through
3841
+ * stemConstraintTerms' own option-word filter, the same discipline
3842
+ * probeChoiceOptions' own docblock states for the topic pull.
3843
+ *
3844
+ * @returns {Promise<string[]>} the terms actually pulled, for the trace note
3845
+ */
3846
+ async function pullChoiceConstraintFacts(terms, { memoryDir, env, cache, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3847
+ const pulled = [];
3848
+ if (!memoryDir) return pulled;
3849
+ for (const term of terms.slice(0, CHOICE_CONSTRAINT_PULL_BUDGET)) {
3850
+ const rows = await factRows(memoryDir, cache);
3851
+ const variants = factTermVariants(normFactTermStatic, term);
3852
+ const hasFact = rows.some((f) => variants.has(f.subject) || variants.has(f.object));
3853
+ if (hasFact) continue;
3854
+ const learned = await childPackFactsForKey(term, { memoryDir, env, cache, synthesisBudget });
3855
+ if (learned) pulled.push(term);
3856
+ }
3857
+ return pulled;
3858
+ }
3859
+
3860
+ /** Every constraint term the graph links `option`'s own term to, each with
3861
+ * the ONE fact row that proves it (first match in `rows`' own order, which
3862
+ * is already canonical — the store sorts fact individuals by content-
3863
+ * addressed id, so this reads the same regardless of insertion order).
3864
+ * Unrouted, either direction: this is not the topic probe's grounding
3865
+ * check, it is "does the graph also connect this option to something else
3866
+ * the question said", and section 2.6 of the design survey found that rule
3867
+ * only under any predicate. */
3868
+ function choiceOptionSatisfiedConstraints(option, constraintTerms, rows) {
3869
+ const optionVariants = factTermVariants(normFactTermStatic, option.text);
3870
+ const satisfied = [];
3871
+ for (const term of constraintTerms) {
3872
+ const termVariants = factTermVariants(normFactTermStatic, term);
3873
+ const fact = rows.find((f) => (optionVariants.has(f.subject) && termVariants.has(f.object))
3874
+ || (optionVariants.has(f.object) && termVariants.has(f.subject)));
3875
+ if (fact) satisfied.push({ term, fact });
3876
+ }
3877
+ return satisfied;
3878
+ }
3879
+
3880
+ /**
3881
+ * Splits a tie by how much of the question each grounded option answers.
3882
+ * `satisfied` is the constraint terms the graph links that option to, each
3883
+ * with the fact row that proves it, so the answer can cite them. Returns
3884
+ * null when no option is strictly ahead, or when the leader satisfies
3885
+ * nothing — both of which stay refusals. The ties-never-broken rule this
3886
+ * answers to: a pick is made only against MORE satisfied constraints, never
3887
+ * a strength ordering over any single piece of evidence.
3888
+ *
3889
+ * @returns {null | {
3890
+ * winner: { label, text, facts, chain, satisfied: Array<{ term, fact }> },
3891
+ * runnerUp: { label, text, satisfied: Array<{ term, fact }> },
3892
+ * missedByRunnerUp: string[],
3893
+ * }}
3894
+ */
3895
+ function separateChoiceTie(grounded, constraintTerms, rows) {
3896
+ if (!constraintTerms.length) return null;
3897
+ const scored = grounded.map((option) => ({
3898
+ option,
3899
+ satisfied: choiceOptionSatisfiedConstraints(option, constraintTerms, rows),
3900
+ }));
3901
+ const bestCount = Math.max(...scored.map((s) => s.satisfied.length));
3902
+ if (bestCount === 0) return null;
3903
+ const leaders = scored.filter((s) => s.satisfied.length === bestCount);
3904
+ if (leaders.length > 1) return null;
3905
+ const winner = leaders[0];
3906
+ const runnerUp = scored
3907
+ .filter((s) => s.option.label !== winner.option.label)
3908
+ .reduce((best, cur) => {
3909
+ if (!best) return cur;
3910
+ if (cur.satisfied.length > best.satisfied.length) return cur;
3911
+ if (cur.satisfied.length === best.satisfied.length && cur.option.label < best.option.label) return cur;
3912
+ return best;
3913
+ }, null);
3914
+ const runnerUpTerms = new Set(runnerUp.satisfied.map((s) => s.term));
3915
+ const missedByRunnerUp = winner.satisfied.map((s) => s.term).filter((term) => !runnerUpTerms.has(term));
3916
+ return {
3917
+ winner: { label: winner.option.label, text: winner.option.text, facts: winner.option.facts, chain: winner.option.chain, satisfied: winner.satisfied },
3918
+ runnerUp: { label: runnerUp.option.label, text: runnerUp.option.text, satisfied: runnerUp.satisfied },
3919
+ missedByRunnerUp,
3920
+ };
3921
+ }
3922
+
3796
3923
  async function probeChoiceOptions(parsed, { memoryDir, env, cache, graph, synthesisBudget = AUTO_SYNTHESIS_BUDGET }) {
3797
3924
  const sourceVariants = factTermVariants(normFactTermStatic, parsed.sourceTerm);
3798
3925
  let rows = await factRows(memoryDir, cache);
@@ -12982,6 +13109,14 @@ async function ingestReferenceArticle(memoryDir, key, article, cache, tagFor = r
12982
13109
  // materialisation, not the whole-store maintenance job /syllogise runs.
12983
13110
  const AUTO_SYNTHESIS_BUDGET = 12;
12984
13111
 
13112
+ // Caps how many child-pack pulls one tied choice-question turn may spend on
13113
+ // the stem's own constraint terms (pullChoiceConstraintFacts, above). Five
13114
+ // covers every constraint term a CommonsenseQA stem carries after stopword
13115
+ // filtering; the cap is what stops a long stem from turning one turn into a
13116
+ // bulk import. A constant rather than config: it bounds work per turn, which
13117
+ // is a design decision, not a preference.
13118
+ const CHOICE_CONSTRAINT_PULL_BUDGET = 5;
13119
+
12985
13120
  /** The `[reasoning]` knobs for a classification pass rooted at `memoryDir` —
12986
13121
  * the repo's own `tmct.toml` when it sets one, the shipped defaults
12987
13122
  * otherwise. `resolveReasoningConfig` wants the NORMALIZED sparse pass-
@@ -17421,6 +17556,11 @@ const joinList = (a) => (a.length > 1 ? `${a.slice(0, -1).join(", ")} and ${a[a.
17421
17556
  // deliberately not the resolver's longer numbered ambiguity format.
17422
17557
  const joinOr = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, or ${a[a.length - 1]}`
17423
17558
  : a.length === 2 ? `${a[0]} or ${a[1]}` : (a[0] ?? ""));
17559
+ // Same Oxford-comma join as joinOr, "and" for a list every member of which
17560
+ // holds at once (the constraint terms a runner-up failed to satisfy), not a
17561
+ // set of alternatives.
17562
+ const joinAnd = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, and ${a[a.length - 1]}`
17563
+ : a.length === 2 ? `${a[0]} and ${a[1]}` : (a[0] ?? ""));
17424
17564
 
17425
17565
  /** Render the next page of a held remainder (pending: {items:[str], noun}). Returns a
17426
17566
  * plain turn whose `detail.pending` carries what's still unseen (null when the batch
@@ -18524,31 +18664,84 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18524
18664
  const parsed = splitChoiceQuestion(workingLine);
18525
18665
  if (parsed) {
18526
18666
  const choiceGoal = "pick the option a stated relation grounds, among a closed set of alternatives";
18527
- const refMiss = (text) => {
18667
+ const refMiss = (text, extraDetail = null) => {
18528
18668
  note(trace, `goal: ${choiceGoal}`);
18529
18669
  note(trace, `lane: splitChoiceQuestion — "${workingLine}" parsed as a ${parsed.shape} choice question but could not compose an answer`);
18530
- return withLast(plainTurn(workingLine, text, { via: "miss", miss: true, focus, goal: choiceGoal }), choiceGoal);
18670
+ const turn = plainTurn(workingLine, text, { via: "miss", miss: true, focus, goal: choiceGoal });
18671
+ if (extraDetail) turn.detail = { ...turn.detail, ...extraDetail };
18672
+ return withLast(turn, choiceGoal);
18531
18673
  };
18532
- if (!parsed.sourceTerm) {
18674
+ // The topic is read off a CANDIDATE LIST (stemTopicCandidates), not off
18675
+ // a single fixed-shape template capture: extractStemSourceTerm's own
18676
+ // capture (parsed.sourceTerm) survives only as chooseChoiceTopic's tie-
18677
+ // break, because a template is right about a fronted "where would you
18678
+ // find X" stem, exactly the stems where several candidates tie on
18679
+ // salience. A stem naming no usable candidate, or naming several that
18680
+ // the graph holds nothing about, both come back as "" here — the same
18681
+ // no-topic miss either way.
18682
+ const candidates = stemTopicCandidates(parsed.stem, parsed.options);
18683
+ const { topic } = await chooseChoiceTopic(candidates, {
18684
+ memoryDir, cache: factRowsCache, templateCapture: parsed.sourceTerm,
18685
+ });
18686
+ if (!topic) {
18533
18687
  return refMiss(`I can't tell what these options are alternatives about — nothing in "${parsed.stem}" reads as a subject term to check them against.`);
18534
18688
  }
18535
- const probed = await probeChoiceOptions(parsed, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
18689
+ const probed = await probeChoiceOptions({ ...parsed, sourceTerm: topic }, { memoryDir, env, cache: factRowsCache, graph, synthesisBudget });
18536
18690
  const grounded = probed.filter((o) => o.grounds);
18537
18691
  note(trace, `goal: ${choiceGoal}`);
18538
18692
  if (grounded.length === 0) {
18539
- note(trace, `lane: splitChoiceQuestion — no stated relation between "${parsed.sourceTerm}" and any of ${probed.length} options; the honest miss, never a guess`);
18540
- return refMiss(`I don't know how "${parsed.sourceTerm}" relates to any of ${joinOr(probed.map((o) => o.text))}. Nothing I hold connects it to one of them.`);
18693
+ note(trace, `lane: splitChoiceQuestion — no stated relation between "${topic}" and any of ${probed.length} options; the honest miss, never a guess`);
18694
+ return refMiss(`I don't know how "${topic}" relates to any of ${joinOr(probed.map((o) => o.text))}. Nothing I hold connects it to one of them.`, { topic });
18541
18695
  }
18542
18696
  if (grounded.length > 1) {
18697
+ // The stem's OTHER content terms are constraints the question stated
18698
+ // beyond naming its topic — pulled here, not at the topic probe
18699
+ // above, because they only matter once a tie needs something to
18700
+ // separate on. Never pulled for an option term (stemConstraintTerms'
18701
+ // own filter already excludes those).
18702
+ const constraintTerms = stemConstraintTerms(parsed.stem, topic, parsed.options);
18703
+ await pullChoiceConstraintFacts(constraintTerms, { memoryDir, env, cache: factRowsCache, synthesisBudget });
18704
+ const rowsAfterPull = await factRows(memoryDir, factRowsCache);
18705
+ // Separate on constraints, never on strength: separateChoiceTie only
18706
+ // picks when exactly one option satisfies STRICTLY MORE of the
18707
+ // stem's other content terms than every rival — a level count, a
18708
+ // zero count, or more than one option level all stay a refusal.
18709
+ const separated = separateChoiceTie(grounded, constraintTerms, rowsAfterPull);
18710
+ if (separated) {
18711
+ const { winner, runnerUp, missedByRunnerUp } = separated;
18712
+ const groundingFact = winner.facts.length > 0 ? winner.facts.slice().sort((a, b) => b.trust - a.trust)[0] : null;
18713
+ const groundingClause = groundingFact
18714
+ ? `${factPhrase(groundingFact)} (source: ${citationProvenance(groundingFact.provenance)})`
18715
+ : renderIsaChain(winner.chain);
18716
+ const constraintClause = winner.satisfied
18717
+ .map(({ term, fact }) => `the question also says ${term}, which ${factPhrase(fact)} (source: ${citationProvenance(fact.provenance)})`)
18718
+ .join("; ");
18719
+ const text = `${winner.text} — ${groundingClause}, and ${constraintClause}. The other option that `
18720
+ + `grounds is ${runnerUp.text}, and I hold nothing linking it to ${joinAnd(missedByRunnerUp)}.`;
18721
+ note(trace, `lane: splitChoiceQuestion — "${winner.label}" satisfies ${winner.satisfied.length} constraint term(s) the runner-up "${runnerUp.label}" does not; separated, not a broken tie`);
18722
+ const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18723
+ turn.lane = "ask-choice";
18724
+ turn.detail = {
18725
+ traversal: `option "${winner.label}" separated from a ${grounded.length}-way tie against "${topic}" by ${winner.satisfied.length} constraint term(s)`,
18726
+ matches: [...(groundingFact ? [groundingFact] : winner.chain), ...winner.satisfied.map((s) => s.fact)],
18727
+ selectedLabel: winner.label,
18728
+ topic,
18729
+ separatedBy: winner.satisfied.map((s) => s.term),
18730
+ runnerUpLabel: runnerUp.label,
18731
+ };
18732
+ return withLast(turn, choiceGoal);
18733
+ }
18543
18734
  // A tie is reported, never broken — whatever the grounded options'
18544
- // own edge weights, this branch fires on COUNT alone.
18545
- note(trace, `lane: splitChoiceQuestion — ${grounded.length} of ${probed.length} options ground against "${parsed.sourceTerm}"; reported as a tie`);
18546
- const text = `More than one of those grounds: ${joinOr(grounded.map((o) => o.text))}. I have a stated relation from ${parsed.sourceTerm} to each, so nothing in what I hold picks between them.`;
18735
+ // own edge weights, this branch fires on COUNT alone (or on a level
18736
+ // constraint count above, which is the same rule at a finer grain).
18737
+ note(trace, `lane: splitChoiceQuestion — ${grounded.length} of ${probed.length} options ground against "${topic}"; reported as a tie`);
18738
+ const text = `More than one of those grounds: ${joinOr(grounded.map((o) => o.text))}. I have a stated relation from ${topic} to each, so nothing in what I hold picks between them.`;
18547
18739
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18548
18740
  turn.lane = "ask-choice";
18549
18741
  turn.detail = {
18550
- traversal: `${grounded.length} of ${probed.length} options grounded against "${parsed.sourceTerm}"`,
18742
+ traversal: `${grounded.length} of ${probed.length} options grounded against "${topic}"`,
18551
18743
  matches: grounded.flatMap((o) => (o.facts.length ? o.facts : o.chain || [])),
18744
+ topic,
18552
18745
  };
18553
18746
  return withLast(turn, choiceGoal);
18554
18747
  }
@@ -18562,14 +18755,14 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18562
18755
  matches = winner.facts;
18563
18756
  hop = 1;
18564
18757
  matchedBy = fact.matchedBy;
18565
- traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via ${fact.predicate}`;
18758
+ traversalNote = `option "${winner.label}" grounded against "${topic}" via ${fact.predicate}`;
18566
18759
  } else {
18567
18760
  text = `${winner.text} — ${renderIsaChain(winner.chain)}.`;
18568
18761
  matches = winner.chain;
18569
18762
  hop = winner.chain.length;
18570
- traversalNote = `option "${winner.label}" grounded against "${parsed.sourceTerm}" via a ${winner.chain.length}-hop isa chain`;
18763
+ traversalNote = `option "${winner.label}" grounded against "${topic}" via a ${winner.chain.length}-hop isa chain`;
18571
18764
  }
18572
- note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${parsed.sourceTerm}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18765
+ note(trace, `lane: splitChoiceQuestion — exactly one option ("${winner.label}") grounds against "${topic}"; cited the deciding ${winner.facts.length > 0 ? "fact" : "chain"}`);
18573
18766
  const turn = plainTurn(workingLine, text, { via: "composed", miss: false, focus, goal: choiceGoal });
18574
18767
  turn.lane = "ask-choice";
18575
18768
  turn.detail = {
@@ -18577,6 +18770,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18577
18770
  matches,
18578
18771
  selectedLabel: winner.label,
18579
18772
  hop,
18773
+ topic,
18580
18774
  ...(matchedBy ? { matchedBy } : {}),
18581
18775
  };
18582
18776
  return withLast(turn, choiceGoal);
@@ -56,7 +56,7 @@ import { basename, join, resolve } from "node:path";
56
56
  import { runTurn, uuidv7, stripLeadingDiscourseAdverb } from "./chat.mjs";
57
57
  import { beginsWithVowelSound, grammarRules } from "./finish.mjs";
58
58
  import { splitSentencesPreservingPaths, stripCitationResidue } from "./sentences.mjs";
59
- import { loadMemory, readFactRows, appendFact } from "../adapters/memory/core.mjs";
59
+ import { loadMemory, readFactRows, appendFact, removeFacts } from "../adapters/memory/core.mjs";
60
60
  import { loadConfig } from "../adapters/config.mjs";
61
61
  import { touchedFactRows } from "../domain/memory/touched-facts.mjs";
62
62
  import { normFactTerm } from "../domain/hash.mjs";
@@ -86,16 +86,28 @@ export function parseArgs(argv) {
86
86
 
87
87
  /**
88
88
  * Run one already-split sentence through runTurn against `memoryDir`, and
89
- * report the Fact rows THIS turn actually touched. Returns { recognized, rows }
90
- * — `recognized` true iff runTurn's own record called this a stored assertion,
91
- * `rows` the Fact rows it touched (possibly empty for a Rule-only write).
89
+ * report the Fact rows THIS turn actually touched. Returns { recognized, rows,
90
+ * afterRows } — `recognized` true iff runTurn's own record called this a
91
+ * stored assertion, `rows` the Fact rows it touched (possibly empty for a
92
+ * Rule-only write), `afterRows` the post-turn fold when one was taken.
93
+ *
94
+ * `beforeRows` is the caller's already-folded view of the store. Folding is
95
+ * the single most expensive thing an ingest does — three quarters of a second
96
+ * on a browser-sized graph — so the caller threads one fold from sentence to
97
+ * sentence instead of paying a fresh one per candidate.
92
98
  */
93
- async function runSentence(sentence, { config, memoryDir, env }) {
94
- const before = readFactRows(await loadMemory(memoryDir));
99
+ async function runSentence(sentence, { config, memoryDir, env, beforeRows }) {
100
+ const before = beforeRows || readFactRows(await loadMemory(memoryDir));
101
+ if (ingestYield) await ingestYield();
95
102
  const { record, answer } = await runTurn(sentence, { config, memoryDir, sessionId: uuidv7(), env });
96
- if (record?.via !== "assert" || record?.miss) return { recognized: false, rows: [], decline: String(answer || "") };
103
+ // Only an assert turn can have written a Fact, so only an assert turn earns
104
+ // the post-turn fold; every other turn hands the caller's own view straight
105
+ // back untouched.
106
+ if (record?.via !== "assert") return { recognized: false, rows: [], afterRows: before, decline: String(answer || "") };
107
+ if (ingestYield) await ingestYield();
97
108
  const after = readFactRows(await loadMemory(memoryDir));
98
- return { recognized: true, rows: touchedFactRows(before, after) };
109
+ if (record?.miss) return { recognized: false, rows: [], afterRows: after, decline: String(answer || "") };
110
+ return { recognized: true, rows: touchedFactRows(before, after), afterRows: after };
99
111
  }
100
112
 
101
113
  /** The recognizer's own words for why it turned a sentence down, when it named
@@ -551,6 +563,66 @@ export function clauseCandidates(sentence, { nlp } = {}) {
551
563
  return out;
552
564
  }
553
565
 
566
+ // A stored term names a thing. These words open a predicate remainder or a new
567
+ // clause, so a term that STARTS with one is the tail of a sentence a recognizer
568
+ // frame over-read, never an entity — "has a population of 1,683,115" and "and
569
+ // killed his two grandparents" are both that shape, and both surface as a feed
570
+ // card's own title once they reach the graph.
571
+ const FRAGMENT_LEAD_WORDS = new Set([
572
+ "and", "or", "but", "because", "since", "although", "though", "whereas", "while", "so",
573
+ "that", "which", "who", "whom", "whose", "if", "when", "then", "also", "however",
574
+ "is", "are", "was", "were", "be", "been", "being", "am", "has", "have", "had",
575
+ "do", "does", "did", "can", "could", "will", "would", "should", "may", "might", "must",
576
+ "of", "in", "on", "at", "for", "to", "with", "from", "by", "as", "into", "onto",
577
+ "over", "under", "after", "before", "between", "during", "about", "near", "through",
578
+ "against", "among", "within", "without", "per",
579
+ ]);
580
+ // Longest a stored term may run. Real multi-word entities are short compounds
581
+ // ("string instrument", "american guitarist"); past this a "term" is a clause
582
+ // the split lost the subject of.
583
+ const MAX_TERM_WORDS = 6;
584
+ // The tags a MULTI-WORD term's leading token may not carry — the POS reading
585
+ // of the same rule FRAGMENT_LEAD_WORDS states lexically, so an unlisted verb
586
+ // ("killed", "borders") is caught the same way a listed auxiliary is. A
587
+ // one-word term is exempt: a bare verb is a perfectly good object for a
588
+ // capability or relation fact ("a cell is capable of grow"), and a single word
589
+ // is never the clause fragment this rule exists to catch.
590
+ const FRAGMENT_LEAD_TAGS = new Set(["VERB", "AUX", "ADP", "CCONJ", "SCONJ", "PART"]);
591
+
592
+ /** Does `term` read as a thing's name rather than a clause fragment? Bounds
593
+ * the word count and rejects a leading conjunction, auxiliary or preposition.
594
+ * Used to keep an over-read recognizer frame's predicate remainder out of the
595
+ * graph, where it would otherwise hub a feed card. */
596
+ export function readsAsEntityTerm(term, nlp) {
597
+ const text = String(term ?? "").trim();
598
+ if (!text) return false;
599
+ const words = text.split(/\s+/);
600
+ if (words.length > MAX_TERM_WORDS) return false;
601
+ const first = words[0].toLowerCase().replace(/^[^a-z0-9]+/, "");
602
+ if (!first) return false;
603
+ if (FRAGMENT_LEAD_WORDS.has(first)) return false;
604
+ if (words.length === 1) return true;
605
+ const engine = nlp === undefined ? winkInstance() : nlp;
606
+ if (!engine) return true;
607
+ try {
608
+ const pos = engine.readDoc(text).tokens().out(engine.its.pos);
609
+ if (pos.length && FRAGMENT_LEAD_TAGS.has(pos[0])) return false;
610
+ } catch { /* an untaggable term falls back to the lexical rule above */ }
611
+ return true;
612
+ }
613
+
614
+ const readsAsEntityFact = (fact, nlp) => readsAsEntityTerm(fact.subject, nlp) && readsAsEntityTerm(fact.object, nlp);
615
+
616
+ // A host that shares one thread with a UI hands the thread back through this;
617
+ // a Node run leaves it unset and pays nothing.
618
+ let ingestYield = null;
619
+
620
+ /** Sets the function `ingestText` awaits between sentences so a browser can
621
+ * paint and answer input while a long article grounds. Pass null to clear. */
622
+ export function setIngestYield(fn) {
623
+ ingestYield = typeof fn === "function" ? fn : null;
624
+ }
625
+
554
626
  // The pronoun subjects a bounded carry substitutes with the paragraph's last
555
627
  // grounded subject. Ingest only — a chat turn resolves "it"/"they" against the
556
628
  // live focus, never a stale paragraph carry.
@@ -663,13 +735,41 @@ export async function ingestText(text, {
663
735
  // landed.
664
736
  const cleanedSentences = [];
665
737
 
738
+ // One fold, threaded through every candidate below. A fold costs about a
739
+ // second on a browser-sized graph and the old shape paid two per candidate,
740
+ // which is what made a poll block the page for minutes.
741
+ let currentRows = readFactRows(await loadMemory(dir));
742
+ // Facts this call has already written its own tag onto. Their provenance in
743
+ // `currentRows` is a tag behind, so a later sentence would otherwise read
744
+ // them back as freshly touched; skipping them is what a re-fold would have
745
+ // said, without the re-fold.
746
+ const taggedIds = new Set();
747
+
666
748
  // One recognized read of some text form: null when the strict recognizer
667
- // grounds nothing, else the Fact rows it touched.
749
+ // grounds nothing, else the Fact rows it touched. A row whose subject or
750
+ // object reads as a clause fragment rather than an entity is retracted here
751
+ // — the recognizer has already written it by the time this sees it — and
752
+ // the sentence falls through to the optimistic tier instead.
668
753
  let lastDecline = "";
669
754
  const strictRows = async (form) => {
670
- const { recognized, rows, decline } = await runSentence(form, { config: cfg, memoryDir: dir, env: runEnv });
671
- if (!recognized) lastDecline = decline || lastDecline;
672
- return recognized && rows.length ? rows : null;
755
+ if (ingestYield) await ingestYield();
756
+ const knownIds = new Set(currentRows.map((r) => r.id));
757
+ const { recognized, rows, afterRows, decline } = await runSentence(form, {
758
+ config: cfg, memoryDir: dir, env: runEnv, beforeRows: currentRows,
759
+ });
760
+ currentRows = afterRows;
761
+ if (!recognized) { lastDecline = decline || lastDecline; return null; }
762
+ const fresh = rows.filter((row) => !taggedIds.has(row.id));
763
+ const kept = fresh.filter((row) => readsAsEntityFact(row, termNlp));
764
+ if (kept.length !== fresh.length) {
765
+ const retractIds = fresh.filter((row) => !kept.includes(row) && !knownIds.has(row.id)).map((row) => row.id);
766
+ if (retractIds.length) {
767
+ await removeFacts(dir, retractIds);
768
+ const retracted = new Set(retractIds);
769
+ currentRows = currentRows.filter((row) => !retracted.has(row.id));
770
+ }
771
+ }
772
+ return kept.length ? kept : null;
673
773
  };
674
774
 
675
775
  try {
@@ -714,26 +814,35 @@ export async function ingestText(text, {
714
814
  subject: row.subject, predicate: row.predicate, object: row.object,
715
815
  provenance: tag, quantifier: row.quantifier || "", sentence,
716
816
  });
817
+ taggedIds.add(row.id);
717
818
  }
718
819
  continue;
719
820
  }
720
821
  const ungrounded = ungroundedTermsIn(lastDecline);
721
822
  if (ungrounded) for (const term of ungrounded) ungroundedTerms.add(term);
722
823
  if (!optimistic) continue;
723
- const candidates = optimisticTriples(cleaned, { lexicon: lex, nlp });
824
+ const candidates = optimisticTriples(cleaned, { lexicon: lex, nlp }).filter((t) => readsAsEntityFact(t, termNlp));
724
825
  if (!candidates.length) continue;
725
826
  optimisticSentences += 1;
726
827
  const tag = `optimistic-extract:${sourceTag}`;
727
828
  for (const t of candidates) {
728
- await appendFact(dir, {
829
+ const written = await appendFact(dir, {
729
830
  subject: t.subject, predicate: t.predicate, object: t.object, provenance: tag, observedAt,
730
831
  });
731
832
  optimisticFacts.push({ ...t, provenance: tag, sentence });
833
+ taggedIds.add(written.id);
732
834
  }
733
835
  }
734
836
  }
735
837
 
736
- const finalRows = readFactRows(await loadMemory(dir));
838
+ // The fact-degree scan below only reads each row's subject and object, so
839
+ // the threaded fold plus this call's own writes answers it exactly.
840
+ // `canonical` prices every endpoint's degree instead, which needs the
841
+ // store's real row set.
842
+ if (ingestYield) await ingestYield();
843
+ const finalRows = canonical
844
+ ? readFactRows(await loadMemory(dir))
845
+ : currentRows.concat(extracted, optimisticFacts);
737
846
  // ungroundedCounts widens the legacy ungroundedTerms rule (a lexicon-miss
738
847
  // named in a decline) to the fact-degree rule: every term with zero fact
739
848
  // rows, lexicon-known or not. ungroundedTerms stays a subset by