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

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.
@@ -59,6 +59,7 @@ import {
59
59
  } from "../adapters/corpus/news-sources.mjs";
60
60
  import { DEFAULT_MIN_INTERVAL_MS } from "../adapters/corpus/courtesy.mjs";
61
61
  import { researchFacts } from "../adapters/corpus/research-source.mjs";
62
+ import { throughSourceBreaker, sourceSkipStatusLine } from "../domain/source-breaker.mjs";
62
63
  import { ingestText, readsAsEntityTerm } from "./extract-facts.mjs";
63
64
 
64
65
  export { NEWS_SOURCE_RECORDS, DEFAULT_NEWS_SOURCE_IDS, DEFAULT_NEWS_KB_IDS };
@@ -644,11 +645,37 @@ async function ingestResearchArticle(ctx, term, provider, article) {
644
645
  return { facts: distinct.size, derived };
645
646
  }
646
647
 
648
+ /** One KB lookup behind its source's circuit breaker. A source that has been
649
+ * timing out or throttling is skipped without a round trip, and the skip is
650
+ * reported so the cycle can tell "this source had nothing" from "this source
651
+ * was never asked". The negative cache catches the first; the breaker
652
+ * catches the second, and neither ever stands in for the other. */
653
+ async function lookupThroughBreaker(ctx, provider, sourceId, term, skipped) {
654
+ const source = String(provider?.name || sourceId);
655
+ const systemicFailuresOf = typeof provider?.stats === "function"
656
+ ? () => provider.stats().systemicFailures ?? 0
657
+ : null;
658
+ let asked = false;
659
+ const article = await throughSourceBreaker(source, async () => {
660
+ asked = true;
661
+ try { provider.beginTurn?.(); } catch { /* an older provider has no budget */ }
662
+ try { return await provider.lookup(term); } catch { return null; }
663
+ }, {
664
+ registry: ctx?.sourceBreakers ?? undefined,
665
+ skipped,
666
+ label: provider?.label,
667
+ systemicFailuresOf,
668
+ });
669
+ return { article, asked };
670
+ }
671
+
647
672
  /** Takes the top `limit` pending (negative-cache-expired) terms and walks
648
673
  * the enabled KB sources in config order for each; first lookup hit wins.
649
674
  * A grounded term is marked "grounded" and folded into one
650
675
  * reprocessAfterGrounding pass over every term this cycle grounded; an
651
- * all-null term enters the negative cache. */
676
+ * all-null term enters the negative cache. A term whose sources were all
677
+ * skipped goes back to pending instead: nothing asked it, so nothing knows
678
+ * it is missing. */
652
679
  export async function enrichTopTerms(ctx, { limit } = {}) {
653
680
  const { memoryDir, store, state, providers, config, now } = ctx;
654
681
  const shouldAbort = abortSignalOf(ctx);
@@ -662,6 +689,7 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
662
689
 
663
690
  const enriched = [];
664
691
  const missed = [];
692
+ const skippedSources = new Set();
665
693
  let factsTotal = 0;
666
694
  let derivedTotal = 0;
667
695
  let aborted = false;
@@ -670,22 +698,25 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
670
698
  if (shouldAbort()) { aborted = true; break; }
671
699
  markTerm(ledger, entry.term, "enriching", nowVal);
672
700
  let hit = null;
701
+ let askedAnySource = false;
673
702
  for (const sourceId of config.kbSources) {
674
703
  if (shouldAbort()) { aborted = true; break; }
675
704
  const choice = KB_SOURCE_TO_RESEARCH_CHOICE[sourceId];
676
705
  if (!choice || typeof providers?.getResearchProvider !== "function") continue;
677
706
  const provider = providers.getResearchProvider({ source: choice });
678
707
  if (!provider) continue;
679
- let article = null;
680
- try { article = await provider.lookup(entry.term); } catch { article = null; }
708
+ const { article, asked } = await lookupThroughBreaker(ctx, provider, sourceId, entry.term, skippedSources);
709
+ if (asked) askedAnySource = true;
681
710
  if (article) { hit = { provider, article }; break; }
682
711
  }
683
712
  // A stop mid-lookup is not a verdict on the term: it goes back to
684
713
  // pending so the next cycle picks it up, never into the negative cache.
685
714
  if (aborted) { markTerm(ledger, entry.term, "pending", nowVal); break; }
686
715
  if (!hit) {
687
- markTerm(ledger, entry.term, "missed", nowVal);
688
- missed.push(entry.term);
716
+ // No source was asked, so nothing learned this term is missing —
717
+ // the same posture a stop takes, for the same reason.
718
+ markTerm(ledger, entry.term, askedAnySource ? "missed" : "pending", nowVal);
719
+ if (askedAnySource) missed.push(entry.term);
689
720
  continue;
690
721
  }
691
722
  const res = await ingestResearchArticle(ctx, entry.term, hit.provider, hit.article);
@@ -712,6 +743,7 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
712
743
 
713
744
  return {
714
745
  enriched, missed, aborted,
746
+ skippedSources: [...skippedSources].sort(),
715
747
  facts: factsTotal + reprocessResult.facts,
716
748
  derived: derivedTotal + reprocessResult.derived,
717
749
  };
@@ -838,11 +870,13 @@ function renderPollResult(result) {
838
870
  function renderEnrichResult(result) {
839
871
  const enrichedText = result.enriched.length ? ` (${result.enriched.join(", ")})` : "";
840
872
  const missedText = result.missed.length ? ` (${result.missed.join(", ")})` : "";
873
+ const skipped = result.skippedSources || [];
841
874
  const text = `enriched ${pluralize(result.enriched.length, "term")}${enrichedText}; `
842
875
  + `${pluralize(result.missed.length, "miss")}${missedText}; `
843
876
  + `${pluralize(result.facts, "fact")} stored, ${result.derived} derived.`
844
- + (result.aborted ? STOPPED_SUFFIX : "");
845
- return { text, miss: !result.enriched.length && !result.missed.length && !result.aborted };
877
+ + (result.aborted ? STOPPED_SUFFIX : "")
878
+ + (skipped.length ? ` ${sourceSkipStatusLine(skipped)}` : "");
879
+ return { text, miss: !result.enriched.length && !result.missed.length && !result.aborted && !skipped.length };
846
880
  }
847
881
 
848
882
  async function handleAddSource(ctx, url) {
@@ -91,24 +91,27 @@ const ALREADY_PEER_LABELED = /^teach:peer:/;
91
91
  * same tag again, so the union stops growing once every peer has seen it. */
92
92
  /** `observedAtBySegment` maps a STORED (pre-relabel) tag to the observedAt its
93
93
  * own record carries, when it has one — the dated-teach frame's own
94
- * `mgx:observedAt`, threaded onto the wire fact each tag becomes. Returns
95
- * `{ tag, observedAt }` pairs, deduped by the RELABELED tag (the first
96
- * observedAt seen for a given output tag wins, matching the prior de-dup by
97
- * tag string alone). */
98
- function wireProvenanceTags(provenance, identity, fallbackTimestamp, observedAtBySegment) {
94
+ * `mgx:observedAt`, threaded onto the wire fact each tag becomes.
95
+ * `extractionBySegment` does the same for that record's own extraction
96
+ * findings, so a peer replicating the tag reads back the same findings the
97
+ * original assertion recorded. Returns `{ tag, observedAt, extraction }`
98
+ * triples, deduped by the RELABELED tag (the first value seen for a given
99
+ * output tag wins, matching the prior de-dup by tag string alone). */
100
+ function wireProvenanceTags(provenance, identity, fallbackTimestamp, observedAtBySegment, extractionBySegment) {
99
101
  const stored = String(provenance || "").split(" | ").filter(Boolean);
100
- if (!stored.length) return [{ tag: "", observedAt: undefined }];
102
+ if (!stored.length) return [{ tag: "", observedAt: undefined, extraction: undefined }];
101
103
  const byTag = new Map();
102
104
  for (const segment of stored) {
103
105
  const observedAt = observedAtBySegment?.get(segment);
106
+ const extraction = extractionBySegment?.get(segment);
104
107
  const tag = ALREADY_PEER_LABELED.test(segment) ? segment : (() => {
105
108
  const assertedAt = latestProvenanceTimestamp(segment);
106
109
  const timestamp = assertedAt === null ? fallbackTimestamp : new Date(assertedAt).toISOString();
107
110
  return relabelForBroadcast(segment, identity.displayName, timestamp, identity.nodeId);
108
111
  })();
109
- if (!byTag.has(tag)) byTag.set(tag, observedAt);
112
+ if (!byTag.has(tag)) byTag.set(tag, { observedAt, extraction });
110
113
  }
111
- return [...byTag].map(([tag, observedAt]) => ({ tag, observedAt }));
114
+ return [...byTag].map(([tag, meta]) => ({ tag, ...meta }));
112
115
  }
113
116
 
114
117
  /** This store's own node id, minted on first use and never regenerated: it
@@ -137,28 +140,34 @@ const isFactShaped = (f) => !!f
137
140
  * every hop and never settle. Sending each tag on its own row keeps the merge
138
141
  * idempotent, and a repeated triple inside one batch unions correctly.
139
142
  *
140
- * `mgx:observedAt` is record content the same way the tag is: each of
141
- * row.assertions is one live head, and its own `provenance` (that head's own
142
- * tags) is the join key back to which outgoing wire fact carries its
143
- * observedAt. A dated taught fact's broadcast carries the date, so a peer
144
- * that receives it can resolve it against a fresher OR staler claim the same
145
- * way the local store already does (memory/resolution.mjs's
146
- * effectiveObservedAt chain). */
143
+ * `mgx:observedAt` and `mgx:extractionFinding` are both record content the
144
+ * same way the tag is: each of row.assertions is one live head, and its own
145
+ * `provenance` (that head's own tags) is the join key back to which outgoing
146
+ * wire fact carries its observedAt and its extraction findings. A dated
147
+ * taught fact's broadcast carries the date, so a peer that receives it can
148
+ * resolve it against a fresher OR staler claim the same way the local store
149
+ * already does (memory/resolution.mjs's effectiveObservedAt chain), and a
150
+ * finding-bearing assertion's broadcast carries its findings, so a peer
151
+ * renders the same caveat the origin did rather than reading a clean
152
+ * reading that never happened. Sent per assertion, never unioned at the wire
153
+ * layer — the row's own union is a read-time fold over exactly these
154
+ * per-assertion values, so unioning again here would double up on merge. */
147
155
  const toWireFacts = (row, identity, fallbackTimestamp) => {
148
156
  const observedAtBySegment = new Map();
157
+ const extractionBySegment = new Map();
149
158
  for (const a of row.assertions || []) {
150
- if (!a.observedAt) continue;
151
- for (const segment of String(a.provenance || "").split(" | ").filter(Boolean)) {
152
- observedAtBySegment.set(segment, a.observedAt);
153
- }
159
+ const segments = String(a.provenance || "").split(" | ").filter(Boolean);
160
+ if (a.observedAt) for (const segment of segments) observedAtBySegment.set(segment, a.observedAt);
161
+ if (a.extraction?.length) for (const segment of segments) extractionBySegment.set(segment, a.extraction);
154
162
  }
155
- return wireProvenanceTags(row.provenance, identity, fallbackTimestamp, observedAtBySegment)
156
- .map(({ tag, observedAt }) => ({
163
+ return wireProvenanceTags(row.provenance, identity, fallbackTimestamp, observedAtBySegment, extractionBySegment)
164
+ .map(({ tag, observedAt, extraction }) => ({
157
165
  subject: row.subject,
158
166
  predicate: row.predicate,
159
167
  object: row.object,
160
168
  provenance: tag,
161
169
  ...(observedAt ? { observedAt } : {}),
170
+ ...(extraction?.length ? { extraction } : {}),
162
171
  }));
163
172
  };
164
173
 
@@ -462,6 +471,11 @@ export function createP2pRoom({
462
471
  // this is the passthrough that lets a dated taught fact's wire fact
463
472
  // reach it at all.
464
473
  ...(typeof f.observedAt === "string" && f.observedAt ? { observedAt: f.observedAt } : {}),
474
+ // Same passthrough for the extraction findings the origin recorded on
475
+ // this same assertion — appendFacts dedupes and sorts them the same way
476
+ // a local write does, so a merged record reads back exactly as its
477
+ // origin stored it.
478
+ ...(Array.isArray(f.extraction) && f.extraction.length ? { extraction: f.extraction } : {}),
465
479
  }))) : { ids: [] };
466
480
  await sortFactIndividualsById();
467
481
  await refreshRows();