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

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();
@@ -38,7 +38,8 @@
38
38
  // (see that module's header), so the call is harmless either way, never
39
39
  // a load error and never a behavior change on the Node side.
40
40
  import { vocabExampleHint } from "../../services/chat.mjs";
41
- import { createInMemoryStore, normFactTerm, loadMemory, readFactRows, applySeedPayload } from "../../adapters/memory/core.mjs";
41
+ import { createInMemoryStore, normFactTerm, loadMemory, readFactRows, applySeedPayload, wrapRowBackend, isRowHandle } from "../../adapters/memory/core.mjs";
42
+ import { createHttpRowBackend, withOneRetryOnUnavailable } from "./http-row-backend.mjs";
42
43
  import { splitSentencesPreservingPaths } from "../../services/sentences.mjs";
43
44
  import { parseEntities } from "../../domain/codegraph.mjs";
44
45
  import { memoryFactGraphPayload } from "../../domain/memory-facts.mjs";
@@ -90,6 +91,16 @@ import { graphAsk, enginePlan } from "./engine-surface.mjs";
90
91
  * is module-scope, last write wins, and every session created after this one
91
92
  * shares it.
92
93
  *
94
+ * `awsSessionKey` (optional): the page's AWS-mode backend choice. Given, the
95
+ * session's memory binds to `createHttpRowBackend({apiBase: "/", sessionKey:
96
+ * awsSessionKey, fetchImpl})` wrapped with `seedPayload` as its read-only
97
+ * seed overlay (§3.1's basePayload — the seed is never written back to the
98
+ * service; only what a turn actually teaches lands as rows). Omitted (the
99
+ * default), memory stays the plain in-memory store it always was, seeded the
100
+ * same way. `fetchImpl` (optional) overrides the ambient `fetch` the row
101
+ * backend calls through — a page never passes it; a test points it at a
102
+ * running row-service double instead.
103
+ *
93
104
  * Returns { memoryDir, sessionId, graph, codeGraph, refreshGraph, turn }.
94
105
  * `turn(line)` resolves to { answer, end, record, plan } and threads
95
106
  * focus/last/planState between calls exactly as the CLI session does.
@@ -141,10 +152,27 @@ function newsProvidersFor(config) {
141
152
  };
142
153
  }
143
154
 
144
- export function createChatSession({ seedPayload = null, vocabSeeded = false, liveReference = false, onLiveLookup = null, synthesisBudget = 12, digestStructures = null } = {}) {
155
+ export function createChatSession({
156
+ seedPayload = null, vocabSeeded = false, liveReference = false, onLiveLookup = null,
157
+ synthesisBudget = 12, digestStructures = null, awsSessionKey = null,
158
+ fetchImpl = (...args) => globalThis.fetch(...args),
159
+ } = {}) {
145
160
  setDigestStructures(digestStructures || []);
146
- const memoryDir = createInMemoryStore();
147
- applySeedPayload(memoryDir, seedPayload);
161
+ // onOversizedRow: "drop" — a WRITE-side posture only (core.mjs's own
162
+ // read-side base projection always keeps every seed row regardless, so the
163
+ // seed itself is never lossy). A real corpus seed's own high-fan-out
164
+ // property (mgx:statedBy: one edge per fact) is already over the row cap
165
+ // before this session ever teaches anything; a session's own new fact adds
166
+ // one more edge to that same, already-uncapped group, which can never fit
167
+ // one wire row either way. Dropping that one write is the visitor's own
168
+ // "turn is itself the last resort" case the option exists for: the fact
169
+ // itself still writes and answers correctly (it is its own separate row),
170
+ // only that property's cross-fact edge index stays exactly as unwritable
171
+ // as the seed's own copy of it already was.
172
+ const memoryDir = awsSessionKey
173
+ ? wrapRowBackend(withOneRetryOnUnavailable(createHttpRowBackend({ apiBase: "/", sessionKey: awsSessionKey, fetchImpl })), { basePayload: seedPayload, onOversizedRow: "drop" })
174
+ : createInMemoryStore();
175
+ if (!awsSessionKey) applySeedPayload(memoryDir, seedPayload);
148
176
 
149
177
  // A known-empty code graph: code-structure questions get the same honest
150
178
  // no-code-graph answer an un-pointed CLI session gives, never a crash. The
@@ -235,6 +263,15 @@ export async function researchedFactRows(memoryDir) {
235
263
  .map((row) => ({ subject: row.subject, predicate: row.predicate, object: row.object }));
236
264
  }
237
265
 
266
+ /** The AWS-mode "forget everything"/"reset to seed" seam: marks every row
267
+ * and meta entry this session's row backend holds absent server-side. A
268
+ * no-op for a local (in-memory) session — there is nothing server-side to
269
+ * discard, so a page can call this unconditionally on its own memoryDir
270
+ * without first checking which mode it opened in. */
271
+ export async function discardAwsSession(memoryDir) {
272
+ if (isRowHandle(memoryDir)) await memoryDir.impl.deleteAll();
273
+ }
274
+
238
275
  // The page reaches the engine through the one shared surface: `tmct.open()`
239
276
  // opens this session, `tmct.turn()` runs the dock, `tmct.ask()` puts a
240
277
  // question to the session's own graph. What stays on `tmct.page` is what has
@@ -253,7 +290,7 @@ publishTmctSurface({
253
290
  page: {
254
291
  registerWinkModel, registerReferencePackProvider, registerLiveReferenceProvider,
255
292
  registerResearchProvider, registerNewsProvider, normFactTerm, vocabExampleHint, memoryStats,
256
- openPersistedStore, exportFactsJsonl, researchedFactRows,
293
+ openPersistedStore, exportFactsJsonl, researchedFactRows, discardAwsSession,
257
294
  splitSentences: splitSentencesPreservingPaths,
258
295
  },
259
296
  });
@@ -148,3 +148,42 @@ export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch }
148
148
  },
149
149
  };
150
150
  }
151
+
152
+ function retryOnceOnUnavailable(fn) {
153
+ return async (...args) => {
154
+ try {
155
+ return await fn(...args);
156
+ } catch (err) {
157
+ if (!(err instanceof BackendUnavailable)) throw err;
158
+ return fn(...args);
159
+ }
160
+ };
161
+ }
162
+
163
+ /** Wraps a row backend so every method retries once on `BackendUnavailable`
164
+ * — a network-level failure, never `BackendRejected`, which a retry cannot
165
+ * fix. Every method here is safe to repeat: reads are read-only,
166
+ * `putRows`/`deleteRows` are upserts/keyed-deletes the service already
167
+ * documents as per-row atomic (a repeat just upserts or re-marks the same
168
+ * rows), and `deleteAll` already carries its own retry. The one race this
169
+ * covers: a consumer whose memory binds a large read-only seed as its base
170
+ * overlay (`wrapRowBackend`'s `basePayload`) does one CPU-heavy row
171
+ * projection the first time that session's memory is read — long enough,
172
+ * in a same-process test double, to occasionally land the very next
173
+ * network call on a socket the server had already begun tearing down.
174
+ * Real deployments (browser ↔ a separate Lambda-backed service) don't
175
+ * share an event loop with the store, so this is a same-process artifact,
176
+ * not a form of casual unreliability to paper over broadly — hence one
177
+ * retry, not a backoff loop. */
178
+ export function withOneRetryOnUnavailable(rowBackend) {
179
+ const wrapped = {
180
+ ...rowBackend,
181
+ readRows: retryOnceOnUnavailable(rowBackend.readRows),
182
+ putRows: retryOnceOnUnavailable(rowBackend.putRows),
183
+ deleteRows: retryOnceOnUnavailable(rowBackend.deleteRows),
184
+ readMeta: retryOnceOnUnavailable(rowBackend.readMeta),
185
+ putMeta: retryOnceOnUnavailable(rowBackend.putMeta),
186
+ };
187
+ if (typeof rowBackend.readRowsByTerm === "function") wrapped.readRowsByTerm = retryOnceOnUnavailable(rowBackend.readRowsByTerm);
188
+ return wrapped;
189
+ }
@@ -17,7 +17,8 @@
17
17
  // never published — only the hosted demo site's public/ledger.html links to
18
18
  // it, as an optional sibling script the page degrades honestly without.
19
19
  import { vocabExampleHint } from "../../services/chat.mjs";
20
- import { createInMemoryStore, normFactTerm, applySeedPayload, loadMemory, readFactRows } from "../../adapters/memory/core.mjs";
20
+ import { createInMemoryStore, normFactTerm, applySeedPayload, loadMemory, readFactRows, wrapRowBackend } from "../../adapters/memory/core.mjs";
21
+ import { createHttpRowBackend, withOneRetryOnUnavailable } from "./http-row-backend.mjs";
21
22
  import { splitSentencesPreservingPaths } from "../../services/sentences.mjs";
22
23
  import { parseEntities } from "../../domain/codegraph.mjs";
23
24
  import { memoryFactGraphPayload } from "../../domain/memory-facts.mjs";
@@ -45,14 +46,35 @@ import { graphAsk, enginePlan } from "./engine-surface.mjs";
45
46
  * traverses those facts while a code-structure question still refuses honestly.
46
47
  *
47
48
  * ledger-viz.mjs's own inline script calls computeLedgerDataFromPayload
48
- * (re-exported below) on `memoryDir.payload` after a turn whose record shows
49
- * a successful write (`via: "assert"` or `via: "retract"`, `miss: false`) to
50
- * re-derive the page's rows/terms/edges/stats and re-mount the same view a
51
- * fresh page load would have rendered — a plain query never re-derives.
49
+ * (re-exported below) on the session's current payload after a turn whose
50
+ * record shows a successful write (`via: "assert"` or `via: "retract"`,
51
+ * `miss: false`) to re-derive the page's rows/terms/edges/stats and re-mount
52
+ * the same view a fresh page load would have rendered — a plain query never
53
+ * re-derives.
54
+ *
55
+ * `awsSessionKey` (optional): the page's AWS-mode backend choice, the same
56
+ * seam chat-browser-entry.mjs's own createChatSession takes — given, the
57
+ * session's memory binds to `createHttpRowBackend({apiBase: "/", sessionKey:
58
+ * awsSessionKey, fetchImpl})` wrapped with `seedPayload` as its read-only
59
+ * seed overlay; omitted, memory stays the plain in-memory store. `fetchImpl`
60
+ * (optional) overrides the ambient `fetch` the row backend calls through —
61
+ * a test points it at a running row-service double.
52
62
  */
53
- export function createLedgerSession({ seedPayload = null, vocabSeeded = false } = {}) {
54
- const memoryDir = createInMemoryStore();
55
- applySeedPayload(memoryDir, seedPayload);
63
+ export function createLedgerSession({
64
+ seedPayload = null, vocabSeeded = false, awsSessionKey = null,
65
+ fetchImpl = (...args) => globalThis.fetch(...args),
66
+ } = {}) {
67
+ // onOversizedRow: "drop" — see chat-browser-entry.mjs's own createChatSession
68
+ // for why: a real corpus seed's high-fan-out mgx:statedBy group is already
69
+ // over the row cap before this session teaches anything, and a session's
70
+ // own new fact adding one more edge to it can't fit one wire row either.
71
+ // The read side (core.mjs) always keeps every seed row regardless, so
72
+ // nothing about the seed itself is lossy — only that one property's
73
+ // cross-fact edge index stays as unwritable as the seed's own copy of it.
74
+ const memoryDir = awsSessionKey
75
+ ? wrapRowBackend(withOneRetryOnUnavailable(createHttpRowBackend({ apiBase: "/", sessionKey: awsSessionKey, fetchImpl })), { basePayload: seedPayload, onOversizedRow: "drop" })
76
+ : createInMemoryStore();
77
+ if (!awsSessionKey) applySeedPayload(memoryDir, seedPayload);
56
78
 
57
79
  const codeGraph = parseEntities({ individuals: [], objectProperties: [] });
58
80