@polycode-projects/the-mechanical-code-talker 5.0.32 → 5.0.34

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.32",
3
+ "version": "5.0.34",
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.",
@@ -51,6 +51,7 @@
51
51
  "./repository-interface": "./src/adapters/repository-interface.mjs",
52
52
  "./conformance": "./src/tools/conformance.mjs",
53
53
  "./ask-browser": "./src/surfaces/web/graph-ask-browser-entry.mjs",
54
+ "./news": "./src/services/news-exports.mjs",
54
55
  "./envelope": "./test-benchmarks/agentbench/envelope-reader.mjs"
55
56
  },
56
57
  "files": [
@@ -50,11 +50,20 @@ function rowObservedMs(row) {
50
50
  return toMs(row.createdAt || "");
51
51
  }
52
52
 
53
+ /** Does this provenance carry a news/research tag anywhere in it? True for a
54
+ * bare `news:…` and for both ingest wrappers (`extracted:news:…`,
55
+ * `optimistic-extract:news:…`), which is what the live poll path writes. The
56
+ * window filter below and any surface counting "facts from news" read the
57
+ * same rule from here, so a tile can never drift from the feed. */
58
+ export function isNewsProvenance(provenance) {
59
+ return NEWS_WINDOW_PROVENANCE_RE.test(String(provenance || ""));
60
+ }
61
+
53
62
  export function newsWindowRows(rows, { now, windowMs }) {
54
63
  const nowMs = toMs(now);
55
64
  const startMs = nowMs - windowMs;
56
65
  return rows.filter((row) => {
57
- if (!NEWS_WINDOW_PROVENANCE_RE.test(String(row.provenance || ""))) return false;
66
+ if (!isNewsProvenance(row.provenance)) return false;
58
67
  const t = rowObservedMs(row);
59
68
  return Number.isFinite(t) && t >= startMs && t <= nowMs;
60
69
  });
@@ -4251,11 +4251,23 @@ async function unknownAdjectiveFallback(payload, { memoryDir, sessionId, lexicon
4251
4251
  // "every p is a glyph" teach while "every p is venomous" refuses, an
4252
4252
  // unpredictable asymmetry between two universally-quantified sentences
4253
4253
  // over the same corpus-anchored subject.
4254
- const universalQuantifier = /^(?:every|each|all|any)$/i.test((det || "").trim());
4254
+ // A bare GENERIC PLURAL subject with no determiner at all ("animals are
4255
+ // alive") carries the same implicit-universal reading matchBareHabitualTeach
4256
+ // already gives a bare plural verb subject ("dogs bark" mints the same
4257
+ // capability "every dog can bark" reaches for) — an English plural with no
4258
+ // article generalizes over the whole class. Gated on the LEXICON's own
4259
+ // plural fold, never the naive suffix strip alone, so only a genuinely
4260
+ // plural noun qualifies: "redis" ends in "s" but has no lexicon singular,
4261
+ // so it stays outside this reading and falls through to the ordinary bare
4262
+ // (single-entity) property gate below, unaffected.
4263
+ const lexiconSingular = /^are$/i.test(verb) ? lookupNoun(lex, subjectRaw)?.lemma : null;
4264
+ const bareGenericPlural = !String(det || "").trim() && !!lexiconSingular
4265
+ && lexiconSingular.toLowerCase() !== String(subjectRaw).toLowerCase();
4266
+ const universalQuantifier = /^(?:every|each|all|any)$/i.test((det || "").trim()) || bareGenericPlural;
4255
4267
  if (universalQuantifier && (await isAnchorableTerm(subjectRaw, lex, memoryDir, cache, graph))
4256
4268
  && (lookupAdjective(lex, objectRaw) || (await objectReadsAsNonNoun(objectRaw)))) {
4257
4269
  const classSubject = /^are$/i.test(verb)
4258
- ? (lookupNoun(lex, subjectRaw)?.lemma || singularizeSurface(subjectRaw))
4270
+ ? (lexiconSingular || singularizeSurface(subjectRaw))
4259
4271
  : subjectRaw;
4260
4272
  return teachFact(memoryDir, sessionId, {
4261
4273
  subject: classSubject, predicate: HAS_PROPERTY_PREDICATE, object: objectRaw, quantifier: "every", observedAt, dateText,
@@ -4499,6 +4511,17 @@ const quantifiedHasObject = (m) => (/^all$/i.test(m[1])
4499
4511
  * the single noun between the determiner and the verb; a two-token subject stays
4500
4512
  * declined, like the preposition-pinned frame, because nothing names its head. */
4501
4513
  const DETERMINER_HAS_TEACH_RE = /^(?:the|an?|my|your|our|their|his|her|its)\s+([\w'-]+)\s+(?:has|have|had)\s+(.+?)[.!?]*$/i;
4514
+ /** The determiner-led CAPABILITY teach ("a pig can be alive", "the wolf can
4515
+ * swim") — DETERMINER_HAS_TEACH_RE's own sibling for the "can" verb family.
4516
+ * The closed modal pins the split the same way "has"/"have" pins
4517
+ * DETERMINER_HAS_TEACH_RE's, so a leading article needs no verb-position
4518
+ * guessing. Its own object slot is unbounded ("can VERB", "can be
4519
+ * ADJECTIVE" — matchBareCanTeach/parseCapability already own the
4520
+ * single-word-verb case; this is the multi-word remainder both decline on),
4521
+ * so a plural bare subject ("animals can be alive") and its singular
4522
+ * articled twin ("a pig can be alive") land through the same generalVerbTeach
4523
+ * mint instead of one of the two silently declining. */
4524
+ const DETERMINER_CAN_TEACH_RE = /^(?:the|an?|every|each|all|my|your|our|their|his|her|its)\s+([\w'-]+)\s+can\s+(.+?)[.!?]*$/i;
4502
4525
  /** The quantified LOCATIVE teach ("every disk rests on peg-a", "each disk
4503
4526
  * rests on peg-a", "all disks rest on peg-a") — QUANTIFIED_HAS_TEACH_RE's own
4504
4527
  * sibling for the board-fact verb family. The has/have frame can pin the
@@ -4721,6 +4744,7 @@ async function generalVerbTeach(payload) {
4721
4744
  if (GENERAL_VERB_DETERMINER_RE.test(subjectRaw) || quantLoc || countLoc) {
4722
4745
  const quantHas = (!quantLoc && !countLoc) ? p.match(QUANTIFIED_HAS_TEACH_RE) : null;
4723
4746
  const detHas = (!quantHas && !quantLoc && !countLoc) ? p.match(DETERMINER_HAS_TEACH_RE) : null;
4747
+ const detCan = (!quantHas && !detHas && !quantLoc && !countLoc) ? p.match(DETERMINER_CAN_TEACH_RE) : null;
4724
4748
  if (quantHas) {
4725
4749
  subjectRaw = quantifiedHasSubject(quantHas);
4726
4750
  verbRaw = "has";
@@ -4729,6 +4753,10 @@ async function generalVerbTeach(payload) {
4729
4753
  subjectRaw = detHas[1];
4730
4754
  verbRaw = "has";
4731
4755
  objectRaw = detHas[2];
4756
+ } else if (detCan) {
4757
+ subjectRaw = detCan[1];
4758
+ verbRaw = "can";
4759
+ objectRaw = detCan[2];
4732
4760
  } else if (quantLoc) {
4733
4761
  // Universal locative ("every disk rests on peg-a") — the same
4734
4762
  // "every"-only quantifier-field convention unknownSubjectFallback's
@@ -6630,20 +6658,35 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6630
6658
  // every other sentence reading its first word exactly as before.
6631
6659
  const detLed = raw.match(GENERAL_VERB_DETERMINER_TEACH_RE);
6632
6660
  const detHasLed = detLed ? null : raw.match(DETERMINER_HAS_TEACH_RE);
6633
- const quantHasLed = (detLed || detHasLed) ? null : raw.match(QUANTIFIED_HAS_TEACH_RE);
6661
+ // A determiner-led CAPABILITY lead ("a pig can be alive") needs the same
6662
+ // override as detHasLed: its own first word ("a") never POS-tags as a
6663
+ // NOUN/PROPN, and matchBareCanTeach/parseCapability both decline on a
6664
+ // multi-word verb ("be alive"), so without this the sentence never even
6665
+ // reaches generalVerbTeach — exactly the gap that let the bare-plural
6666
+ // twin ("animals can be alive") teach while its singular-articled form
6667
+ // silently declined. Read through splitTeachNegation first (its own
6668
+ // idempotent rebuild — generalVerbTeach re-derives the identical
6669
+ // positive form later) so a negated lead ("a rock cannot be alive")
6670
+ // is recognized here too: the bare-plural twin ("rocks cannot be
6671
+ // alive") never needed this, since its own no-article subject already
6672
+ // passes the POS gate below without going through any det-led shape at
6673
+ // all, which is exactly the asymmetry this lead exists to close.
6674
+ const detCanLed = (detLed || detHasLed) ? null : splitTeachNegation(raw).payload.match(DETERMINER_CAN_TEACH_RE);
6675
+ const quantHasLed = (detLed || detHasLed || detCanLed) ? null : raw.match(QUANTIFIED_HAS_TEACH_RE);
6634
6676
  // The two locative quantifier leads ("every disk rests…", "one more disk
6635
6677
  // rests…") need the same override as quantHasLed/detHasLed just below:
6636
6678
  // their own first word ("every"/"one"/"another") never POS-tags as a
6637
6679
  // NOUN/PROPN, so without this the bare-sentence POS gate silently drops
6638
6680
  // them exactly the way it used to drop "every overbid has a gouger".
6639
- const quantLocLed = (detLed || detHasLed || quantHasLed) ? null : raw.match(QUANTIFIED_LOCATIVE_TEACH_RE);
6640
- const countLocLed = (detLed || detHasLed || quantHasLed || quantLocLed)
6681
+ const quantLocLed = (detLed || detHasLed || detCanLed || quantHasLed) ? null : raw.match(QUANTIFIED_LOCATIVE_TEACH_RE);
6682
+ const countLocLed = (detLed || detHasLed || detCanLed || quantHasLed || quantLocLed)
6641
6683
  ? null : raw.match(LOCATIVE_COUNTING_TEACH_RE);
6642
6684
  const subjectWord = detLed ? detLed[1].split(/\s+/).pop()
6643
6685
  : (detHasLed ? detHasLed[1]
6644
- : (quantHasLed ? quantifiedHasSubject(quantHasLed)
6645
- : (quantLocLed ? quantifiedLocativeSubject(quantLocLed)
6646
- : (countLocLed ? countLocLed[1] : raw.match(/^([\w'-]+)/)?.[1]))));
6686
+ : (detCanLed ? detCanLed[1]
6687
+ : (quantHasLed ? quantifiedHasSubject(quantHasLed)
6688
+ : (quantLocLed ? quantifiedLocativeSubject(quantLocLed)
6689
+ : (countLocLed ? countLocLed[1] : raw.match(/^([\w'-]+)/)?.[1])))));
6647
6690
  // The quantifier lead ("every … has …") is itself a strong declarative
6648
6691
  // signal, so it overrides the single-token POS gate: a noun that doubles
6649
6692
  // as a verb ("every overbid has a gouger" — wink tags "overbid" VERB)
@@ -6652,7 +6695,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6652
6695
  // NON_DECLARATIVE_OPENER_RE runs even for these leads — "every umm has a
6653
6696
  // thing" isn't a real quantified sentence, just filler that fits the shape.
6654
6697
  if (subjectWord && !NON_DECLARATIVE_OPENER_RE.test(subjectWord)
6655
- && (quantHasLed || detHasLed || quantLocLed || countLocLed || (await subjectIsNounOrPropn(subjectWord)))) {
6698
+ && (quantHasLed || detHasLed || detCanLed || quantLocLed || countLocLed || (await subjectIsNounOrPropn(subjectWord)))) {
6656
6699
  // A PLURAL explicit-capability surface ("wrens can hum") whose
6657
6700
  // SINGULAR is a grounded term stores under the singular first — the
6658
6701
  // spelling the grounding fact and every query-side variant fold use —
@@ -10538,9 +10581,17 @@ async function synonymFactAnswer(memoryDir, query, envelope) {
10538
10581
  * factAnswer's "what do you know about X" KNOW_ABOUT form): everything remembered
10539
10582
  * that mentions X on either side. */
10540
10583
  const TOLD_ABOUT_RE = /^what\s+(?:did|have)\s+(?:i|we|you)\s+(?:told|tell|said|say)\s+(?:you|me|us)?\s*about\s+(.+?)[?.!\s]*$/i;
10541
- /** "what kind of thing is an X" — the subject-side membership phrasing the grammar
10542
- * doesn't parse: reports X's OWN remembered type (falling back to X's members). */
10543
- const KIND_OF_RE = /^what\s+kind\s+of\s+(?:thing|class|type|category|entity)?\s*(?:is|are)\s+(?:an?\s+)?(.+?)[?.!\s]*$/i;
10584
+ /** "what kind of thing is an X" / "what type of creature is X" — the
10585
+ * subject-side membership phrasing the grammar doesn't parse: reports X's
10586
+ * OWN remembered type (falling back to X's members). "kind" and "type" both
10587
+ * lead (English uses them interchangeably here); the qualifier noun between
10588
+ * "kind/type of" and "is/are" is OPTIONAL and, when present, captured
10589
+ * separately (group 1) rather than restricted to a closed generic set — "a
10590
+ * creature"/"an animal" reads exactly like the bare "thing"/"class" the
10591
+ * original five-word set already covered, since the qualifier only narrows
10592
+ * how the question reads (see this function's own qualifier-confirmation
10593
+ * block below), never which shapes the regex accepts. */
10594
+ const KIND_OF_RE = /^what\s+(?:kind|type)\s+of\s+(?:an?\s+)?([\w-]+(?:\s+[\w-]+)?)?\s*(?:is|are)\s+(?:an?\s+)?(.+?)[?.!\s]*$/i;
10544
10595
  /** "does every <N1> have at least <m> <N2>" — cardinality monotonicity: a
10545
10596
  * class's OWN declared exactly/min cardinality restriction proves "at least
10546
10597
  * m" for any queried m <= n (src/domain/syllogise.mjs's proveCardinalityAtLeast). */
@@ -12237,8 +12288,9 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
12237
12288
  // article) does, for every term alike.
12238
12289
  let term = envelope?.parsed?.shape === "meta" ? envelope.parsed.object : null;
12239
12290
  let kindOf = false;
12291
+ let qualifier = null;
12240
12292
  const mk = q.match(KIND_OF_RE);
12241
- if (mk) { term = mk[1]; kindOf = true; }
12293
+ if (mk) { qualifier = mk[1] ? mk[1].trim() : null; term = mk[2]; kindOf = true; }
12242
12294
  else if (!term && !envelope?.parsed) {
12243
12295
  const m = q.match(/^what\s+(?:is|are)\s+(?:an?\s+)?(.+?)[?.!\s]*$/i);
12244
12296
  if (m) term = m[1];
@@ -12251,6 +12303,23 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
12251
12303
  ? (subjectHits.length ? subjectHits : objectHits)
12252
12304
  : (objectHits.length ? objectHits : subjectHits);
12253
12305
  if (!hits.length) return null;
12306
+ // The qualifier noun ("creature" in "what type of creature is john") never
12307
+ // gates the answer — it narrows how the question reads, the same way
12308
+ // grammar.resolve.type-word-describes-subject's "the Store class" narrows
12309
+ // presentation without excluding an answer. When the answered type is
12310
+ // ALSO directly taught as a kind of the qualifier ("pig rdfs:subClassOf
12311
+ // creature"), that confirming fact rides along with the answer; when no
12312
+ // such fact is known, the plain type answer stands on its own — never a
12313
+ // fabricated confirmation, and never a refusal over a qualifier word the
12314
+ // store simply hasn't linked yet.
12315
+ if (qualifier && hits === subjectHits) {
12316
+ const qualifierVariants = factTermVariants(normFactTerm, qualifier);
12317
+ const bridgeFor = (hit) => isa.find((g) => g.subject === hit.object && qualifierVariants.has(g.object));
12318
+ const confirmed = hits.map((hit) => ({ hit, bridge: bridgeFor(hit) })).find(({ bridge }) => bridge);
12319
+ if (confirmed) {
12320
+ return { text: `${renderFactLine(confirmed.hit)} — ${renderFactLine(confirmed.bridge)}`, replace: true };
12321
+ }
12322
+ }
12254
12323
  return renderMany(hits);
12255
12324
  }
12256
12325
 
@@ -15312,6 +15381,15 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15312
15381
  // sides singularizing to KNOWN lexicon nouns, so real chatter ("these are
15313
15382
  // yours") stays with the orientation card.
15314
15383
  let isPluralMembershipTeach = false;
15384
+ // The property-teach sibling: "animals are alive" — the SAME 3-word
15385
+ // deferral, but the OBJECT is an ADJECTIVE, not a noun class, so it needs
15386
+ // its own noun-vs-adjective read below rather than isPluralMembershipTeach's
15387
+ // noun-noun gate. Matches unknownAdjectiveFallback's own bare-generic-plural
15388
+ // mint gate (chat.mjs's teach-side write) exactly, so the two lanes can
15389
+ // never disagree about which "X are Y" sentences are teachable — without
15390
+ // this, the sentence never reaches teachLane at all, and the mint gate's
15391
+ // own widening below has nothing to widen.
15392
+ let isPluralPropertyTeach = false;
15315
15393
  // A bare habitual naming a subject grounded NOWHERE ("penguins swim", no
15316
15394
  // prior grounding) gets an honest grounding hint instead of the
15317
15395
  // orientation card — computed here, rendered inside the conversational
@@ -15331,12 +15409,19 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15331
15409
  ? null : (matchBareHabitualTeach(bareLine) || matchBareCanTeach(bareLine));
15332
15410
  if (pm || habitual) {
15333
15411
  try {
15334
- const { loadLexicon, lookupNoun } = await import("../domain/grammar/lexicon.mjs");
15412
+ const { loadLexicon, lookupNoun, lookupAdjective } = await import("../domain/grammar/lexicon.mjs");
15335
15413
  const lex = loadLexicon();
15336
15414
  if (pm) {
15337
15415
  const s = singularizeSurface(pm[1].toLowerCase());
15338
15416
  const o = singularizeSurface(pm[2].toLowerCase());
15339
15417
  isPluralMembershipTeach = s !== pm[1].toLowerCase() && !!lookupNoun(lex, s) && !!lookupNoun(lex, o);
15418
+ if (!isPluralMembershipTeach) {
15419
+ const subjSingular = lookupNoun(lex, pm[1])?.lemma;
15420
+ if (subjSingular && subjSingular.toLowerCase() !== pm[1].toLowerCase()
15421
+ && (lookupAdjective(lex, pm[2]) || (await objectReadsAsNonNoun(pm[2])))) {
15422
+ isPluralPropertyTeach = true;
15423
+ }
15424
+ }
15340
15425
  } else {
15341
15426
  // The bare habitual/capability siblings ("dogs bark", "a dog
15342
15427
  // barks", "wrens can sing") — same deferral, same known-subject
@@ -15394,7 +15479,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15394
15479
  } catch { /* leave false — the ordinary path decides */ }
15395
15480
  }
15396
15481
  }
15397
- const conversationalCandidateBaseGate = !handled && miss && !envelope?.parsed && !isWhatAboutContinuation && !isVagueTouchResolvable && !isDescribePronounContinuation && !isExplainTouch && !isStaccatoNegation && !isVagueRelationTouch && !isStaccatoComparative && !isStaccatoPronounNoFocus && !isPluralMembershipTeach && !isBareRelationalVerbTeach;
15482
+ const conversationalCandidateBaseGate = !handled && miss && !envelope?.parsed && !isWhatAboutContinuation && !isVagueTouchResolvable && !isDescribePronounContinuation && !isExplainTouch && !isStaccatoNegation && !isVagueRelationTouch && !isStaccatoComparative && !isStaccatoPronounNoFocus && !isPluralMembershipTeach && !isPluralPropertyTeach && !isBareRelationalVerbTeach;
15398
15483
  // A turn whose pronoun was bound to a vocabulary antecedent is PROVABLY a
15399
15484
  // fact question ("can it bark" → "can dog bark") — never conversational,
15400
15485
  // however short. Without this, the substituted 3-worder still trips
@@ -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
@@ -68,11 +68,13 @@ export { generateCompletion, createCompletionsGraphAdapter } from "./completions
68
68
  // The news capability: scheduled multi-source ingestion, occurrence-ranked
69
69
  // grounding gaps, KB enrichment and the fact-churn feed builder — one
70
70
  // library contract every surface (news.html, chat's `/news`, the CLI verb,
71
- // a JS import) consumes the same way.
71
+ // a JS import) consumes the same way. The `./news` subpath (news-exports.mjs)
72
+ // carries this same contract plus the built-in fetchers and courtesy gate,
73
+ // reachable without the chat/grammar engine this "." entry also pulls in.
72
74
  export {
73
75
  resolveNewsConfig, parseNewsRequest, pollNewsSources, ingestNewsSnapshot,
74
76
  enrichTopTerms, reprocessAfterGrounding, isVocabGroundedTerm, isFactGroundedTerm,
75
- ingestUploadedFactRows, buildFeed, newsTurn,
77
+ ingestUploadedFactRows, buildFeed, newsTurn, cycleMetrics, createNewsState,
76
78
  } from "./news.mjs";
77
79
  export { buildNewsItems } from "../domain/news-feed.mjs";
78
80
  export { rankedTerms } from "../domain/term-ledger.mjs";
@@ -536,6 +536,17 @@ async function mudiiiBeliefAnswer(match, { memoryDir, gameConfig = DEFAULT_GAME_
536
536
  const RIVER_CROSSING_ACTION = "ferry onto";
537
537
  const RIVER_CROSSING_GOAL = [{ universal: true, term: "passenger", predicate: "currently-in", object: "bank-west" }];
538
538
 
539
+ /** Who stands where, in one plain `{ individual: place }` map, read off a
540
+ * planner state's own rows. The state carries one row per individual under
541
+ * the domain's dynamic predicates, so this is a straight transcription — no
542
+ * predicate is privileged, and a puzzle with a different position predicate
543
+ * reads the same way. Pure. */
544
+ function placesInState(state) {
545
+ const places = {};
546
+ for (const row of state || []) places[row.subject] = row.object;
547
+ return places;
548
+ }
549
+
539
550
  /** The river-crossing puzzle's own plan, recomputed from `rows`/`ruleRows` as
540
551
  * they stand right now: the world's own action rules plus whatever
541
552
  * action-constraint rows the drive facts themselves imply
@@ -543,11 +554,18 @@ const RIVER_CROSSING_GOAL = [{ universal: true, term: "passenger", predicate: "c
543
554
  * data/games/river.txt. Null on a world whose rule rows carry no "ferry
544
555
  * onto" action-signature, or whose action domain does not carry a
545
556
  * "passenger" class the goal can quantify over. Returns `{ moves, plan,
546
- * miss }`: `moves` is every legal move from the CURRENT position (the empty
547
- * list when nothing may move), `plan` is the found action sequence or null,
548
- * `miss` is null when a plan was found and the stated reason otherwise — a
549
- * budget decline as well as an exhausted search, never a shortened plan
550
- * either way. Pure. */
557
+ * places, goalPlace, miss }`: `moves` is every legal move from the CURRENT
558
+ * position (the empty list when nothing may move), `plan` is the found action
559
+ * sequence or null, `miss` is null when a plan was found and the stated reason
560
+ * otherwise — a budget decline as well as an exhausted search, never a
561
+ * shortened plan either way.
562
+ *
563
+ * `places` is what a player watches the plan through: one `{ individual:
564
+ * place }` map per position the plan passes through, opening arrangement
565
+ * first, so `places[k]` is where everyone stands after `k` moves and
566
+ * `places.length` is `plan.length + 1`. A miss still carries the opening
567
+ * arrangement alone, so a board can be drawn for a puzzle with no crossing.
568
+ * `goalPlace` names where the goal wants the passengers. Pure. */
551
569
  function riverPuzzleOutlook(rows, ruleRows) {
552
570
  const hasFerryAction = (ruleRows || []).some((r) => r.kind === "action-signature" && r.name === RIVER_CROSSING_ACTION);
553
571
  if (!hasFerryAction) return null;
@@ -561,13 +579,27 @@ function riverPuzzleOutlook(rows, ruleRows) {
561
579
  }
562
580
  const start = stateFromFacts(rows, domain);
563
581
  const moves = movesFromRules(start, domain).map((m) => m.action.label);
582
+ const opening = [placesInState(start)];
583
+ const goalPlace = RIVER_CROSSING_GOAL[0].object;
564
584
  const maxDepth = DEFAULT_GAME_CONFIG.planning.maxDepth;
565
585
  try {
566
586
  const found = findActionPath(start, isGoal, (s) => movesFromRules(s, domain), { maxDepth, stateKey: stateKeyFor });
567
- return { moves, plan: found ? found.actions : null, miss: found ? null : `no plan found within ${maxDepth} moves` };
587
+ return {
588
+ moves,
589
+ plan: found ? found.actions : null,
590
+ places: found ? found.states.map(placesInState) : opening,
591
+ goalPlace,
592
+ miss: found ? null : `no plan found within ${maxDepth} moves`,
593
+ };
568
594
  } catch (err) {
569
595
  if (!(err instanceof PlanBudgetError)) throw err;
570
- return { moves, plan: null, miss: `action grounding count ${err.groundings} exceeds the budget of ${err.budget}` };
596
+ return {
597
+ moves,
598
+ plan: null,
599
+ places: opening,
600
+ goalPlace,
601
+ miss: `action grounding count ${err.groundings} exceeds the budget of ${err.budget}`,
602
+ };
571
603
  }
572
604
  }
573
605