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

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.
@@ -31,15 +31,20 @@
31
31
  // or ms), or a fixed reading directly. Never read from here —
32
32
  // the wall clock enters only through this parameter.
33
33
  // notify an optional, failure-tolerated status hook.
34
+ // shouldAbort an optional predicate the long loops read at every awaited
35
+ // yield point. Once it answers true the cycle stops between
36
+ // whole units of work — never inside one — and reports
37
+ // `aborted: true` alongside whatever it had already finished.
34
38
  //
35
39
  // Determinism: given the same fetched payloads and the same `now`, the same
36
40
  // facts land and the same feed renders, byte for byte (PLAN_NEWS_FEED.md
37
41
  // section 3). Network lives in the adapters this module is handed, never
38
42
  // inside it.
39
43
 
40
- import { normFactTerm, normFactPredicate, factIdFor, sha256Bytes } from "../domain/hash.mjs";
44
+ import { normFactTerm, normFactPredicate, factIdFor } from "../domain/hash.mjs";
41
45
  import {
42
- newsWindowRows, scoreHubs, subgraphAround, buildTermAdjacency, renderNewsParagraph, buildNewsItems, evictNewsFacts,
46
+ newsWindowRows, renderNewsParagraph, buildNewsItems, evictNewsFacts,
47
+ conceptTerms, isQuantityTerm,
43
48
  } from "../domain/news-feed.mjs";
44
49
  import {
45
50
  createTermLedger, bumpTerms, rankedTerms, markTerm, groundedSweep, ledgerPayload, ledgerFromPayload,
@@ -54,8 +59,7 @@ import {
54
59
  } from "../adapters/corpus/news-sources.mjs";
55
60
  import { DEFAULT_MIN_INTERVAL_MS } from "../adapters/corpus/courtesy.mjs";
56
61
  import { researchFacts } from "../adapters/corpus/research-source.mjs";
57
- import { ingestText, optimisticTriples } from "./extract-facts.mjs";
58
- import { splitSentences } from "./sentences.mjs";
62
+ import { ingestText, readsAsEntityTerm } from "./extract-facts.mjs";
59
63
 
60
64
  export { NEWS_SOURCE_RECORDS, DEFAULT_NEWS_SOURCE_IDS, DEFAULT_NEWS_KB_IDS };
61
65
 
@@ -235,6 +239,12 @@ function invalidateCache(cache) {
235
239
  if (cache) cache.rows = null;
236
240
  }
237
241
 
242
+ /** The ctx's own stop signal, or a predicate that never stops. Read once per
243
+ * call site so a ctx without one costs nothing. */
244
+ function abortSignalOf(ctx) {
245
+ return typeof ctx?.shouldAbort === "function" ? ctx.shouldAbort : () => false;
246
+ }
247
+
238
248
  // A feed title rarely carries its own terminal punctuation ("Scientists
239
249
  // Discover New Species"); a fixture built from a full sentence ("A module is
240
250
  // a component.") already does. Joining unconditionally with ". " doubles the
@@ -249,68 +259,27 @@ function joinTitleAndSummary(title, summary) {
249
259
  return `${t}${SENTENCE_END_RE.test(t) ? " " : ". "}${s}`;
250
260
  }
251
261
 
252
- function sha256HexPrefix(str, nBytes) {
253
- const bytes = sha256Bytes(str);
254
- let hex = "";
255
- for (let i = 0; i < nBytes; i += 1) hex += bytes[i].toString(16).padStart(2, "0");
256
- return hex;
257
- }
258
-
259
262
  function toMs(value) {
260
263
  if (typeof value === "number") return value;
261
264
  const t = Date.parse(value);
262
265
  return Number.isFinite(t) ? t : NaN;
263
266
  }
264
267
 
265
- const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
266
-
267
- function tierOfRows(rows) {
268
- if (!rows.length) return "";
269
- let strongest = rows[0];
270
- for (const row of rows) {
271
- if (Number(row.trust ?? 0) > Number(strongest.trust ?? 0)) strongest = row;
272
- }
273
- const kinds = Array.isArray(strongest.sourceTypes) ? strongest.sourceTypes : [];
274
- return kinds[0] || "";
268
+ /** The ranked-terms panel's own display filter (PLAN_NEWSWORTHINESS.md
269
+ * section 3): a bare class object or a bare quantity is never a useful
270
+ * "unknown word" entry. The concept-card fallback used to drop both from
271
+ * its own candidate list before it retired from the feed path; this is
272
+ * where that filter lives now, so the panel stops leading with bare
273
+ * classes too. */
274
+ export function filterRankedTermEntries(rows, entries) {
275
+ const concepts = conceptTerms(rows);
276
+ return entries.filter(({ term }) => !concepts.has(term) && !isQuantityTerm(term));
275
277
  }
276
278
 
277
- function collectItemSources(subgraphRows, sourcesByFactId) {
278
- const seen = new Set();
279
- const sources = [];
280
- for (const row of subgraphRows) {
281
- const src = sourcesByFactId.get(row.id);
282
- if (!src) continue;
283
- const key = src.url || src.title || "";
284
- if (!key || seen.has(key)) continue;
285
- seen.add(key);
286
- sources.push({ title: src.title || "", url: src.url || "", name: src.name || "" });
287
- }
288
- return sources;
289
- }
290
-
291
- /** The item-assembly buildNewsItems runs internally, exposed here so
292
- * buildFeed's seed-only fallback (S1: score hubs over the WHOLE graph, not
293
- * just news/research-tagged rows) can reuse the same shape without widening
294
- * buildNewsItems's own, already-pinned window contract. */
295
- function assembleNewsItems(rows, windowRows, { now, limit, sourcesByFactId }) {
296
- const hubs = scoreHubs(rows, windowRows, { limit });
297
- const adjacency = buildTermAdjacency(rows);
298
- const items = hubs.map(({ term, changed }) => {
299
- const subgraphRows = subgraphAround(rows, term, { adjacency });
300
- const factIds = subgraphRows.map((r) => r.id).sort();
301
- return {
302
- id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
303
- hub: term,
304
- factIds,
305
- changedCount: changed,
306
- builtAt: now,
307
- paragraph: renderNewsParagraph(term, subgraphRows),
308
- tier: tierOfRows(subgraphRows),
309
- sources: collectItemSources(subgraphRows, sourcesByFactId),
310
- };
311
- });
312
- return items.sort((a, b) => (toMs(b.builtAt) - toMs(a.builtAt)) || byId(a, b));
313
- }
279
+ // filterRankedTermEntries can shrink the ledger's own limited slice, so both
280
+ // rank() call sites ask the ledger for more than the display wants and trim
281
+ // afterward — the display count stays full even when some entries filter out.
282
+ const RANK_OVERFETCH = 4;
314
283
 
315
284
  function buildSourcesByFactId(items) {
316
285
  const map = new Map();
@@ -414,6 +383,7 @@ function snapshotMentionsAny(snapshot, terms) {
414
383
  * fact-grounding alone. */
415
384
  export async function reprocessAfterGrounding(ctx, groundedTerms) {
416
385
  const { memoryDir, store, state, config } = ctx;
386
+ const shouldAbort = abortSignalOf(ctx);
417
387
  const terms = [...new Set((groundedTerms || []).map((t) => normFactTerm(t)).filter(Boolean))];
418
388
  if (!terms.length) return { facts: 0, derived: 0, flipped: [] };
419
389
 
@@ -421,6 +391,7 @@ export async function reprocessAfterGrounding(ctx, groundedTerms) {
421
391
  let factsTotal = 0;
422
392
  const allNewFacts = [];
423
393
  for (const snap of touched) {
394
+ if (shouldAbort()) break;
424
395
  const { facts } = await ingestSnapshotFacts(ctx, snap);
425
396
  factsTotal += facts.length;
426
397
  allNewFacts.push(...facts);
@@ -527,14 +498,18 @@ function emptyCycleAccumulator(at) {
527
498
  /** Polls every enabled contemporary source (config order), skipping any
528
499
  * whose health says wait; ingests every genuinely new snapshot; evicts
529
500
  * news-tagged facts past the configured cap. Never touches a source with no
530
- * enabled ids — that reads as "nothing to poll", not a failure. */
501
+ * enabled ids — that reads as "nothing to poll", not a failure. A ctx
502
+ * carrying `shouldAbort` can stop the cycle between sources or between
503
+ * articles; what already landed stays, and the result says `aborted`. */
531
504
  export async function pollNewsSources(ctx) {
532
505
  const { memoryDir, store, config, state, providers, now } = ctx;
506
+ const shouldAbort = abortSignalOf(ctx);
533
507
  const nowVal = resolveNow(now);
534
508
  const enabledIds = normalizeNewsSourceIds(config.sources);
535
509
  if (!enabledIds.length) {
536
- return { fetched: 0, newItems: 0, failures: 0, evicted: 0, facts: 0, derived: 0, sources: [] };
510
+ return { fetched: 0, newItems: 0, failures: 0, evicted: 0, facts: 0, derived: 0, aborted: false, sources: [] };
537
511
  }
512
+ let aborted = false;
538
513
 
539
514
  const recordsById = new Map(newsSourceRecords().map((r) => [r.id, r]));
540
515
  const perSource = [];
@@ -545,6 +520,7 @@ export async function pollNewsSources(ctx) {
545
520
  let derivedTotal = 0;
546
521
 
547
522
  for (const sourceId of enabledIds) {
523
+ if (shouldAbort()) { aborted = true; break; }
548
524
  const record = recordsById.get(sourceId);
549
525
  const health = findOrCreateHealth(state, sourceId);
550
526
  if (!record) { perSource.push({ sourceId, status: "unknown-source" }); continue; }
@@ -582,6 +558,7 @@ export async function pollNewsSources(ctx) {
582
558
  const before = emptyCycleAccumulator(nowVal);
583
559
  const after = emptyCycleAccumulator(nowVal);
584
560
  for (const snapshot of added) {
561
+ if (shouldAbort()) { aborted = true; break; }
585
562
  const r = await ingestNewsSnapshot(ctx, snapshot);
586
563
  after.sentences += r.sentences;
587
564
  after.recognized += r.recognized;
@@ -595,6 +572,7 @@ export async function pollNewsSources(ctx) {
595
572
  state.metrics = [...(state.metrics || []), cycleMetrics(before, after, { source: sourceId })];
596
573
  }
597
574
  perSource.push({ sourceId, status: "ok", newItems: added.length });
575
+ if (aborted) break;
598
576
  }
599
577
 
600
578
  const memory = await store.loadMemory(memoryDir);
@@ -606,7 +584,10 @@ export async function pollNewsSources(ctx) {
606
584
  }
607
585
 
608
586
  state.lastPollAt = nowVal;
609
- return { fetched, newItems: newItemsTotal, failures, evicted: evictIds.length, facts: factsTotal, derived: derivedTotal, sources: perSource };
587
+ return {
588
+ fetched, newItems: newItemsTotal, failures, evicted: evictIds.length,
589
+ facts: factsTotal, derived: derivedTotal, aborted, sources: perSource,
590
+ };
610
591
  }
611
592
 
612
593
  // ---------------------------------------------------------------------------
@@ -620,35 +601,45 @@ const KB_SOURCE_TO_RESEARCH_CHOICE = Object.freeze({
620
601
  "dbpedia-lookup": "dbpedia",
621
602
  });
622
603
 
623
- /** Grounds `article` under `provider`'s own provenance tag: the structured
624
- * or isa facts the research-source seam licenses (researchFacts), plus the
625
- * optimistic tier's read of the summary — the same two-tier posture
626
- * chat.mjs's own reference-article ingest takes, reached here through the
627
- * shared seam instead of a duplicated private function. */
604
+ /** Grounds `article` under `provider`'s own provenance tag, through the SAME
605
+ * ingest seam a polled article takes: the structured or isa facts the
606
+ * research-source seam licenses (researchFacts), then the article's own
607
+ * prose through ingestText's strict recognizer plus optimistic tier. A
608
+ * looked-up article therefore reaches the graph with the density of
609
+ * relations a polled one does, and the feed's paraphrase templates have the
610
+ * same kind of material to write a card from — a bare isa edge left the
611
+ * reader with one bald sentence where a polled item got a paragraph. */
628
612
  async function ingestResearchArticle(ctx, term, provider, article) {
629
- const { memoryDir, store, config, lexicon } = ctx;
613
+ const { memoryDir, store, config, lexicon, now } = ctx;
630
614
  const provenance = provider.provenanceTag(term);
631
- const facts = researchFacts(provider, term, article);
632
- const seen = new Set(facts.map((f) => `${f.subject}\0${f.predicate}\0${f.object}`));
633
- for (const sentence of splitSentences(article.summary || article.text || "")) {
634
- for (const t of optimisticTriples(sentence, { lexicon: lexicon ?? undefined })) {
635
- if (!t.subject || !t.object || t.subject === t.object) continue;
636
- const key = `${t.subject}\0${t.predicate}\0${t.object}`;
637
- if (seen.has(key)) continue;
638
- seen.add(key);
639
- facts.push({ subject: t.subject, predicate: t.predicate, object: t.object, provenance });
640
- }
615
+ const structured = researchFacts(provider, term, article);
616
+ if (structured.length) {
617
+ await store.appendFacts(memoryDir, structured);
618
+ invalidateCache(ctx.cache);
641
619
  }
620
+
621
+ const prose = String(article.summary || article.text || "").trim();
622
+ let ingested = { extracted: [], optimistic: [] };
623
+ if (prose) {
624
+ ingested = await ingestText(prose, {
625
+ memoryDir, sourceTag: provenance, optimistic: true,
626
+ lexicon: lexicon || loadLexicon(), observedAt: resolveNow(now),
627
+ });
628
+ invalidateCache(ctx.cache);
629
+ }
630
+
631
+ const facts = [...structured, ...ingested.extracted, ...ingested.optimistic];
642
632
  if (!facts.length) return { facts: 0, derived: 0 };
643
- await store.appendFacts(memoryDir, facts);
644
- invalidateCache(ctx.cache);
633
+ const distinct = new Set(facts.map(
634
+ (f) => `${normFactTerm(f.subject)}\0${normFactPredicate(f.predicate)}\0${normFactTerm(f.object)}`,
635
+ ));
645
636
  let derived = 0;
646
637
  if (config.syllogismsPerIngest > 0) {
647
638
  const focus = [...termFocusOf(facts)];
648
639
  const res = await syllogise(memoryDir, { focus, expandFocus: true, budget: config.syllogismsPerIngest, store });
649
640
  derived = res?.count || 0;
650
641
  }
651
- return { facts: facts.length, derived };
642
+ return { facts: distinct.size, derived };
652
643
  }
653
644
 
654
645
  /** Takes the top `limit` pending (negative-cache-expired) terms and walks
@@ -658,6 +649,7 @@ async function ingestResearchArticle(ctx, term, provider, article) {
658
649
  * all-null term enters the negative cache. */
659
650
  export async function enrichTopTerms(ctx, { limit } = {}) {
660
651
  const { memoryDir, store, state, providers, config, now } = ctx;
652
+ const shouldAbort = abortSignalOf(ctx);
661
653
  const nowVal = resolveNow(now);
662
654
  const cap = Number.isFinite(limit) ? limit : config.enrichTermsPerCycle;
663
655
 
@@ -670,11 +662,14 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
670
662
  const missed = [];
671
663
  let factsTotal = 0;
672
664
  let derivedTotal = 0;
665
+ let aborted = false;
673
666
 
674
667
  for (const entry of candidates) {
668
+ if (shouldAbort()) { aborted = true; break; }
675
669
  markTerm(ledger, entry.term, "enriching", nowVal);
676
670
  let hit = null;
677
671
  for (const sourceId of config.kbSources) {
672
+ if (shouldAbort()) { aborted = true; break; }
678
673
  const choice = KB_SOURCE_TO_RESEARCH_CHOICE[sourceId];
679
674
  if (!choice || typeof providers?.getResearchProvider !== "function") continue;
680
675
  const provider = providers.getResearchProvider({ source: choice });
@@ -683,6 +678,9 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
683
678
  try { article = await provider.lookup(entry.term); } catch { article = null; }
684
679
  if (article) { hit = { provider, article }; break; }
685
680
  }
681
+ // A stop mid-lookup is not a verdict on the term: it goes back to
682
+ // pending so the next cycle picks it up, never into the negative cache.
683
+ if (aborted) { markTerm(ledger, entry.term, "pending", nowVal); break; }
686
684
  if (!hit) {
687
685
  markTerm(ledger, entry.term, "missed", nowVal);
688
686
  missed.push(entry.term);
@@ -711,7 +709,7 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
711
709
  state.lastEnrichAt = nowVal;
712
710
 
713
711
  return {
714
- enriched, missed,
712
+ enriched, missed, aborted,
715
713
  facts: factsTotal + reprocessResult.facts,
716
714
  derived: derivedTotal + reprocessResult.derived,
717
715
  };
@@ -721,25 +719,30 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
721
719
  // feed
722
720
  // ---------------------------------------------------------------------------
723
721
 
724
- /** Reads the current fact rows and builds the feed. On a seed-only graph
725
- * (nothing news/research-tagged yet) scoreHubs falls back to whole-graph
726
- * degree so the first paint is never empty — the caller renders every item
727
- * in that state with the seed label until pollNewsSources runs once. */
722
+ /** Reads the current fact rows and builds the feed: every hub that passes
723
+ * the newsworthiness gate's test E or test A (PLAN_NEWSWORTHINESS.md
724
+ * section 2), nothing else. A seed-only graph — or any graph where no
725
+ * reported row anchors anything new — answers `items: []`; the page renders
726
+ * its own designed empty state for that case rather than falling back to
727
+ * concept cards off the whole graph. `seedFallback` stays in the shape at
728
+ * `false` for one release so an existing consumer does not break.
729
+ *
730
+ * `newName` is a display-only badge (never a gate): true when the lexicon
731
+ * has no everyday-noun reading for the hub, computed here rather than in
732
+ * buildNewsItems because the domain layer carries no lexicon. */
728
733
  export async function buildFeed(ctx) {
729
- const { memoryDir, store, config, state, now } = ctx;
734
+ const { memoryDir, store, config, state, now, lexicon } = ctx;
730
735
  const nowVal = resolveNow(now);
731
736
  const memory = await store.loadMemory(memoryDir);
732
737
  const rows = store.readFactRows(memory);
733
738
  const sourcesByFactId = buildSourcesByFactId(state.items);
734
739
  const windowMs = config.windowHours * 3600000;
735
740
 
736
- let items = buildNewsItems(rows, { now: nowVal, windowMs, limit: config.itemCap, sourcesByFactId });
737
- let seedFallback = false;
738
- if (!items.length) {
739
- items = assembleNewsItems(rows, rows, { now: nowVal, limit: config.itemCap, sourcesByFactId });
740
- seedFallback = items.length > 0;
741
- }
742
- return { items, seedFallback, builtAt: nowVal };
741
+ const lex = lexicon || loadLexicon();
742
+ const items = buildNewsItems(rows, {
743
+ now: nowVal, windowMs, limit: config.itemCap, sourcesByFactId, readsAsEntityTerm,
744
+ }).map((item) => ({ ...item, newName: !isVocabGroundedTerm(lex, item.hub) }));
745
+ return { items, seedFallback: false, builtAt: nowVal };
743
746
  }
744
747
 
745
748
  // ---------------------------------------------------------------------------
@@ -784,15 +787,19 @@ function renderFeedText(feed, focus) {
784
787
  const seedTag = feed.seedFallback ? " (from the seed graph — start to poll live sources)" : "";
785
788
  const sourceNames = it.sources.map((s) => s.title || s.url).filter(Boolean);
786
789
  const sourcesText = sourceNames.length ? ` sources: ${sourceNames.join(", ")}` : "";
787
- return `${i + 1}. ${it.paragraph} (${it.tier || "unranked"})${sourcesText}${seedTag}`;
790
+ const backgroundText = it.backgroundParagraph ? ` what the graph already knew: ${it.backgroundParagraph}` : "";
791
+ return `${i + 1}. ${it.paragraph} (${it.tier || "unranked"})${sourcesText}${seedTag}${backgroundText}`;
788
792
  })
789
793
  .join("\n");
790
794
  }
791
795
 
792
- function renderRankText(ctx) {
796
+ async function renderRankText(ctx) {
793
797
  const nowVal = resolveNow(ctx.now);
794
798
  const ledger = ledgerFromPayload(ctx.state.ledger);
795
- const entries = rankedTerms(ledger, { limit: 20, now: nowVal, ttlMs: ctx.config.negativeCacheTtlHours * 3600000 });
799
+ const raw = rankedTerms(ledger, { limit: 20 * RANK_OVERFETCH, now: nowVal, ttlMs: ctx.config.negativeCacheTtlHours * 3600000 });
800
+ const memory = await ctx.store.loadMemory(ctx.memoryDir);
801
+ const rows = ctx.store.readFactRows(memory);
802
+ const entries = filterRankedTermEntries(rows, raw).slice(0, 20);
796
803
  if (!entries.length) return "no fact-ungrounded terms yet — poll a source or teach something first.";
797
804
  return entries
798
805
  .map((e, i) => `${i + 1}. ${e.term} (${e.count}) — ${e.vocabGrounded ? "parseable but knowledge-free" : "unknown word"}`)
@@ -815,11 +822,14 @@ function renderSourcesText(ctx) {
815
822
  .join("\n");
816
823
  }
817
824
 
825
+ const STOPPED_SUFFIX = " stopped before the rest.";
826
+
818
827
  function renderPollResult(result) {
819
- if (!result.sources.length) return { text: "no sources enabled — nothing to poll.", miss: true };
828
+ if (!result.sources.length && !result.aborted) return { text: "no sources enabled — nothing to poll.", miss: true };
820
829
  const text = `polled ${pluralize(result.fetched, "source")}: ${pluralize(result.newItems, "new item")}, `
821
830
  + `${pluralize(result.facts, "fact")} stored, ${result.derived} derived, `
822
- + `${pluralize(result.failures, "failure")}, ${result.evicted} evicted.`;
831
+ + `${pluralize(result.failures, "failure")}, ${result.evicted} evicted.`
832
+ + (result.aborted ? STOPPED_SUFFIX : "");
823
833
  return { text, miss: false };
824
834
  }
825
835
 
@@ -828,8 +838,9 @@ function renderEnrichResult(result) {
828
838
  const missedText = result.missed.length ? ` (${result.missed.join(", ")})` : "";
829
839
  const text = `enriched ${pluralize(result.enriched.length, "term")}${enrichedText}; `
830
840
  + `${pluralize(result.missed.length, "miss")}${missedText}; `
831
- + `${pluralize(result.facts, "fact")} stored, ${result.derived} derived.`;
832
- return { text, miss: !result.enriched.length && !result.missed.length };
841
+ + `${pluralize(result.facts, "fact")} stored, ${result.derived} derived.`
842
+ + (result.aborted ? STOPPED_SUFFIX : "");
843
+ return { text, miss: !result.enriched.length && !result.missed.length && !result.aborted };
833
844
  }
834
845
 
835
846
  async function handleAddSource(ctx, url) {
@@ -873,7 +884,7 @@ export async function newsTurn(line, ctx) {
873
884
  if (!ctx.config.sources.length) return { text: "no sources enabled — nothing to poll.", miss: true };
874
885
  return renderPollResult(await pollNewsSources(ctx));
875
886
  }
876
- if (req.kind === "rank") return { text: renderRankText(ctx), miss: false };
887
+ if (req.kind === "rank") return { text: await renderRankText(ctx), miss: false };
877
888
  if (req.kind === "enrich") return renderEnrichResult(await enrichTopTerms(ctx));
878
889
  if (req.kind === "sources") return { text: renderSourcesText(ctx), miss: false };
879
890
  if (req.kind === "add") return handleAddSource(ctx, req.url);