@polycode-projects/the-mechanical-code-talker 5.0.35 → 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,19 @@
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,
43
47
  conceptTerms, isQuantityTerm,
44
48
  } from "../domain/news-feed.mjs";
45
49
  import {
@@ -55,8 +59,7 @@ import {
55
59
  } from "../adapters/corpus/news-sources.mjs";
56
60
  import { DEFAULT_MIN_INTERVAL_MS } from "../adapters/corpus/courtesy.mjs";
57
61
  import { researchFacts } from "../adapters/corpus/research-source.mjs";
58
- import { ingestText, optimisticTriples } from "./extract-facts.mjs";
59
- import { splitSentences } from "./sentences.mjs";
62
+ import { ingestText, readsAsEntityTerm } from "./extract-facts.mjs";
60
63
 
61
64
  export { NEWS_SOURCE_RECORDS, DEFAULT_NEWS_SOURCE_IDS, DEFAULT_NEWS_KB_IDS };
62
65
 
@@ -236,6 +239,12 @@ function invalidateCache(cache) {
236
239
  if (cache) cache.rows = null;
237
240
  }
238
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
+
239
248
  // A feed title rarely carries its own terminal punctuation ("Scientists
240
249
  // Discover New Species"); a fixture built from a full sentence ("A module is
241
250
  // a component.") already does. Joining unconditionally with ". " doubles the
@@ -250,81 +259,28 @@ function joinTitleAndSummary(title, summary) {
250
259
  return `${t}${SENTENCE_END_RE.test(t) ? " " : ". "}${s}`;
251
260
  }
252
261
 
253
- function sha256HexPrefix(str, nBytes) {
254
- const bytes = sha256Bytes(str);
255
- let hex = "";
256
- for (let i = 0; i < nBytes; i += 1) hex += bytes[i].toString(16).padStart(2, "0");
257
- return hex;
258
- }
259
-
260
262
  function toMs(value) {
261
263
  if (typeof value === "number") return value;
262
264
  const t = Date.parse(value);
263
265
  return Number.isFinite(t) ? t : NaN;
264
266
  }
265
267
 
266
- const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
267
-
268
- function tierOfRows(rows) {
269
- if (!rows.length) return "";
270
- let strongest = rows[0];
271
- for (const row of rows) {
272
- if (Number(row.trust ?? 0) > Number(strongest.trust ?? 0)) strongest = row;
273
- }
274
- const kinds = Array.isArray(strongest.sourceTypes) ? strongest.sourceTypes : [];
275
- return kinds[0] || "";
276
- }
277
-
278
- function collectItemSources(subgraphRows, sourcesByFactId) {
279
- const seen = new Set();
280
- const sources = [];
281
- for (const row of subgraphRows) {
282
- const src = sourcesByFactId.get(row.id);
283
- if (!src) continue;
284
- const key = src.url || src.title || "";
285
- if (!key || seen.has(key)) continue;
286
- seen.add(key);
287
- sources.push({ title: src.title || "", url: src.url || "", name: src.name || "" });
288
- }
289
- return sources;
290
- }
291
-
292
- /** The item-assembly buildNewsItems runs internally, exposed here so
293
- * buildFeed's seed-only fallback (S1: score hubs over the WHOLE graph, not
294
- * just news/research-tagged rows) can reuse the same shape without widening
295
- * buildNewsItems's own, already-pinned window contract.
296
- *
297
- * The newsworthiness gate's test 2 only (PLAN_NEWS_FEED.md section 17.6): a
298
- * seed-only graph carries no news rows at all, so tests 1 (reported) and 3
299
- * (anchored) have nothing to read — every candidate would fail them
300
- * trivially and empty the page, which is exactly the fallback exists to
301
- * prevent. Dropping class and bare-quantity terms still holds: neither ever
302
- * makes a good card title, seed graph or not. */
303
- function assembleNewsItems(rows, windowRows, { now, limit, sourcesByFactId }) {
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) {
304
275
  const concepts = conceptTerms(rows);
305
- const candidates = scoreHubs(rows, windowRows, { limit: Infinity })
306
- .filter(({ term }) => !concepts.has(term) && !isQuantityTerm(term));
307
- const hubs = candidates.slice(0, limit);
308
- const adjacency = buildTermAdjacency(rows);
309
- const items = hubs.map(({ term, changed }) => {
310
- const subgraphRows = subgraphAround(rows, term, { adjacency });
311
- const factIds = subgraphRows.map((r) => r.id).sort();
312
- return {
313
- id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
314
- hub: term,
315
- factIds,
316
- changedCount: changed,
317
- builtAt: now,
318
- paragraph: renderNewsParagraph(term, subgraphRows),
319
- tier: tierOfRows(subgraphRows),
320
- sources: collectItemSources(subgraphRows, sourcesByFactId),
321
- background: [],
322
- backgroundParagraph: "",
323
- };
324
- });
325
- return items.sort((a, b) => (toMs(b.builtAt) - toMs(a.builtAt)) || byId(a, b));
276
+ return entries.filter(({ term }) => !concepts.has(term) && !isQuantityTerm(term));
326
277
  }
327
278
 
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;
283
+
328
284
  function buildSourcesByFactId(items) {
329
285
  const map = new Map();
330
286
  const recordsById = new Map(newsSourceRecords().map((r) => [r.id, r]));
@@ -427,6 +383,7 @@ function snapshotMentionsAny(snapshot, terms) {
427
383
  * fact-grounding alone. */
428
384
  export async function reprocessAfterGrounding(ctx, groundedTerms) {
429
385
  const { memoryDir, store, state, config } = ctx;
386
+ const shouldAbort = abortSignalOf(ctx);
430
387
  const terms = [...new Set((groundedTerms || []).map((t) => normFactTerm(t)).filter(Boolean))];
431
388
  if (!terms.length) return { facts: 0, derived: 0, flipped: [] };
432
389
 
@@ -434,6 +391,7 @@ export async function reprocessAfterGrounding(ctx, groundedTerms) {
434
391
  let factsTotal = 0;
435
392
  const allNewFacts = [];
436
393
  for (const snap of touched) {
394
+ if (shouldAbort()) break;
437
395
  const { facts } = await ingestSnapshotFacts(ctx, snap);
438
396
  factsTotal += facts.length;
439
397
  allNewFacts.push(...facts);
@@ -540,14 +498,18 @@ function emptyCycleAccumulator(at) {
540
498
  /** Polls every enabled contemporary source (config order), skipping any
541
499
  * whose health says wait; ingests every genuinely new snapshot; evicts
542
500
  * news-tagged facts past the configured cap. Never touches a source with no
543
- * 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`. */
544
504
  export async function pollNewsSources(ctx) {
545
505
  const { memoryDir, store, config, state, providers, now } = ctx;
506
+ const shouldAbort = abortSignalOf(ctx);
546
507
  const nowVal = resolveNow(now);
547
508
  const enabledIds = normalizeNewsSourceIds(config.sources);
548
509
  if (!enabledIds.length) {
549
- 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: [] };
550
511
  }
512
+ let aborted = false;
551
513
 
552
514
  const recordsById = new Map(newsSourceRecords().map((r) => [r.id, r]));
553
515
  const perSource = [];
@@ -558,6 +520,7 @@ export async function pollNewsSources(ctx) {
558
520
  let derivedTotal = 0;
559
521
 
560
522
  for (const sourceId of enabledIds) {
523
+ if (shouldAbort()) { aborted = true; break; }
561
524
  const record = recordsById.get(sourceId);
562
525
  const health = findOrCreateHealth(state, sourceId);
563
526
  if (!record) { perSource.push({ sourceId, status: "unknown-source" }); continue; }
@@ -595,6 +558,7 @@ export async function pollNewsSources(ctx) {
595
558
  const before = emptyCycleAccumulator(nowVal);
596
559
  const after = emptyCycleAccumulator(nowVal);
597
560
  for (const snapshot of added) {
561
+ if (shouldAbort()) { aborted = true; break; }
598
562
  const r = await ingestNewsSnapshot(ctx, snapshot);
599
563
  after.sentences += r.sentences;
600
564
  after.recognized += r.recognized;
@@ -608,6 +572,7 @@ export async function pollNewsSources(ctx) {
608
572
  state.metrics = [...(state.metrics || []), cycleMetrics(before, after, { source: sourceId })];
609
573
  }
610
574
  perSource.push({ sourceId, status: "ok", newItems: added.length });
575
+ if (aborted) break;
611
576
  }
612
577
 
613
578
  const memory = await store.loadMemory(memoryDir);
@@ -619,7 +584,10 @@ export async function pollNewsSources(ctx) {
619
584
  }
620
585
 
621
586
  state.lastPollAt = nowVal;
622
- 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
+ };
623
591
  }
624
592
 
625
593
  // ---------------------------------------------------------------------------
@@ -633,35 +601,45 @@ const KB_SOURCE_TO_RESEARCH_CHOICE = Object.freeze({
633
601
  "dbpedia-lookup": "dbpedia",
634
602
  });
635
603
 
636
- /** Grounds `article` under `provider`'s own provenance tag: the structured
637
- * or isa facts the research-source seam licenses (researchFacts), plus the
638
- * optimistic tier's read of the summary — the same two-tier posture
639
- * chat.mjs's own reference-article ingest takes, reached here through the
640
- * 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. */
641
612
  async function ingestResearchArticle(ctx, term, provider, article) {
642
- const { memoryDir, store, config, lexicon } = ctx;
613
+ const { memoryDir, store, config, lexicon, now } = ctx;
643
614
  const provenance = provider.provenanceTag(term);
644
- const facts = researchFacts(provider, term, article);
645
- const seen = new Set(facts.map((f) => `${f.subject}\0${f.predicate}\0${f.object}`));
646
- for (const sentence of splitSentences(article.summary || article.text || "")) {
647
- for (const t of optimisticTriples(sentence, { lexicon: lexicon ?? undefined })) {
648
- if (!t.subject || !t.object || t.subject === t.object) continue;
649
- const key = `${t.subject}\0${t.predicate}\0${t.object}`;
650
- if (seen.has(key)) continue;
651
- seen.add(key);
652
- facts.push({ subject: t.subject, predicate: t.predicate, object: t.object, provenance });
653
- }
615
+ const structured = researchFacts(provider, term, article);
616
+ if (structured.length) {
617
+ await store.appendFacts(memoryDir, structured);
618
+ invalidateCache(ctx.cache);
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);
654
629
  }
630
+
631
+ const facts = [...structured, ...ingested.extracted, ...ingested.optimistic];
655
632
  if (!facts.length) return { facts: 0, derived: 0 };
656
- await store.appendFacts(memoryDir, facts);
657
- invalidateCache(ctx.cache);
633
+ const distinct = new Set(facts.map(
634
+ (f) => `${normFactTerm(f.subject)}\0${normFactPredicate(f.predicate)}\0${normFactTerm(f.object)}`,
635
+ ));
658
636
  let derived = 0;
659
637
  if (config.syllogismsPerIngest > 0) {
660
638
  const focus = [...termFocusOf(facts)];
661
639
  const res = await syllogise(memoryDir, { focus, expandFocus: true, budget: config.syllogismsPerIngest, store });
662
640
  derived = res?.count || 0;
663
641
  }
664
- return { facts: facts.length, derived };
642
+ return { facts: distinct.size, derived };
665
643
  }
666
644
 
667
645
  /** Takes the top `limit` pending (negative-cache-expired) terms and walks
@@ -671,6 +649,7 @@ async function ingestResearchArticle(ctx, term, provider, article) {
671
649
  * all-null term enters the negative cache. */
672
650
  export async function enrichTopTerms(ctx, { limit } = {}) {
673
651
  const { memoryDir, store, state, providers, config, now } = ctx;
652
+ const shouldAbort = abortSignalOf(ctx);
674
653
  const nowVal = resolveNow(now);
675
654
  const cap = Number.isFinite(limit) ? limit : config.enrichTermsPerCycle;
676
655
 
@@ -683,11 +662,14 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
683
662
  const missed = [];
684
663
  let factsTotal = 0;
685
664
  let derivedTotal = 0;
665
+ let aborted = false;
686
666
 
687
667
  for (const entry of candidates) {
668
+ if (shouldAbort()) { aborted = true; break; }
688
669
  markTerm(ledger, entry.term, "enriching", nowVal);
689
670
  let hit = null;
690
671
  for (const sourceId of config.kbSources) {
672
+ if (shouldAbort()) { aborted = true; break; }
691
673
  const choice = KB_SOURCE_TO_RESEARCH_CHOICE[sourceId];
692
674
  if (!choice || typeof providers?.getResearchProvider !== "function") continue;
693
675
  const provider = providers.getResearchProvider({ source: choice });
@@ -696,6 +678,9 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
696
678
  try { article = await provider.lookup(entry.term); } catch { article = null; }
697
679
  if (article) { hit = { provider, article }; break; }
698
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; }
699
684
  if (!hit) {
700
685
  markTerm(ledger, entry.term, "missed", nowVal);
701
686
  missed.push(entry.term);
@@ -724,7 +709,7 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
724
709
  state.lastEnrichAt = nowVal;
725
710
 
726
711
  return {
727
- enriched, missed,
712
+ enriched, missed, aborted,
728
713
  facts: factsTotal + reprocessResult.facts,
729
714
  derived: derivedTotal + reprocessResult.derived,
730
715
  };
@@ -734,25 +719,30 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
734
719
  // feed
735
720
  // ---------------------------------------------------------------------------
736
721
 
737
- /** Reads the current fact rows and builds the feed. On a seed-only graph
738
- * (nothing news/research-tagged yet) scoreHubs falls back to whole-graph
739
- * degree so the first paint is never empty — the caller renders every item
740
- * 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. */
741
733
  export async function buildFeed(ctx) {
742
- const { memoryDir, store, config, state, now } = ctx;
734
+ const { memoryDir, store, config, state, now, lexicon } = ctx;
743
735
  const nowVal = resolveNow(now);
744
736
  const memory = await store.loadMemory(memoryDir);
745
737
  const rows = store.readFactRows(memory);
746
738
  const sourcesByFactId = buildSourcesByFactId(state.items);
747
739
  const windowMs = config.windowHours * 3600000;
748
740
 
749
- let items = buildNewsItems(rows, { now: nowVal, windowMs, limit: config.itemCap, sourcesByFactId });
750
- let seedFallback = false;
751
- if (!items.length) {
752
- items = assembleNewsItems(rows, rows, { now: nowVal, limit: config.itemCap, sourcesByFactId });
753
- seedFallback = items.length > 0;
754
- }
755
- 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 };
756
746
  }
757
747
 
758
748
  // ---------------------------------------------------------------------------
@@ -803,10 +793,13 @@ function renderFeedText(feed, focus) {
803
793
  .join("\n");
804
794
  }
805
795
 
806
- function renderRankText(ctx) {
796
+ async function renderRankText(ctx) {
807
797
  const nowVal = resolveNow(ctx.now);
808
798
  const ledger = ledgerFromPayload(ctx.state.ledger);
809
- 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);
810
803
  if (!entries.length) return "no fact-ungrounded terms yet — poll a source or teach something first.";
811
804
  return entries
812
805
  .map((e, i) => `${i + 1}. ${e.term} (${e.count}) — ${e.vocabGrounded ? "parseable but knowledge-free" : "unknown word"}`)
@@ -829,11 +822,14 @@ function renderSourcesText(ctx) {
829
822
  .join("\n");
830
823
  }
831
824
 
825
+ const STOPPED_SUFFIX = " stopped before the rest.";
826
+
832
827
  function renderPollResult(result) {
833
- 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 };
834
829
  const text = `polled ${pluralize(result.fetched, "source")}: ${pluralize(result.newItems, "new item")}, `
835
830
  + `${pluralize(result.facts, "fact")} stored, ${result.derived} derived, `
836
- + `${pluralize(result.failures, "failure")}, ${result.evicted} evicted.`;
831
+ + `${pluralize(result.failures, "failure")}, ${result.evicted} evicted.`
832
+ + (result.aborted ? STOPPED_SUFFIX : "");
837
833
  return { text, miss: false };
838
834
  }
839
835
 
@@ -842,8 +838,9 @@ function renderEnrichResult(result) {
842
838
  const missedText = result.missed.length ? ` (${result.missed.join(", ")})` : "";
843
839
  const text = `enriched ${pluralize(result.enriched.length, "term")}${enrichedText}; `
844
840
  + `${pluralize(result.missed.length, "miss")}${missedText}; `
845
- + `${pluralize(result.facts, "fact")} stored, ${result.derived} derived.`;
846
- 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 };
847
844
  }
848
845
 
849
846
  async function handleAddSource(ctx, url) {
@@ -887,7 +884,7 @@ export async function newsTurn(line, ctx) {
887
884
  if (!ctx.config.sources.length) return { text: "no sources enabled — nothing to poll.", miss: true };
888
885
  return renderPollResult(await pollNewsSources(ctx));
889
886
  }
890
- if (req.kind === "rank") return { text: renderRankText(ctx), miss: false };
887
+ if (req.kind === "rank") return { text: await renderRankText(ctx), miss: false };
891
888
  if (req.kind === "enrich") return renderEnrichResult(await enrichTopTerms(ctx));
892
889
  if (req.kind === "sources") return { text: renderSourcesText(ctx), miss: false };
893
890
  if (req.kind === "add") return handleAddSource(ctx, req.url);