@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.
package/README.md CHANGED
@@ -103,6 +103,18 @@ Teach it a fact in plain English and it mints a node. Ask it a question and
103
103
  it answers from what it was seeded with, what you taught it, and what it can
104
104
  derive by rule from both. Every answer is either grounded or an honest miss.
105
105
 
106
+ ## Host it yourself
107
+
108
+ tmct is a library first. You can embed it as a backend, running the engine
109
+ server-side over your own fact store (DynamoDB, SQLite, in-memory, or a
110
+ custom backend that passes the published conformance kit). Load corpus data from your own sources using the shipped
111
+ `tmct corpus` CLI verb; the reference bands (WordNet, ConceptNet, Wikidata)
112
+ are built in-tree. The deployed demos at tmct.polycode.co.uk show this
113
+ architecture end to end: the chat and ledger pages run the engine in-page
114
+ locally, while the news page is a thin client that calls server-side turn
115
+ and feed endpoints — both run on the same tmct library backend and session
116
+ table. Choose the architecture that fits your use case.
117
+
106
118
  ## Repository layout
107
119
 
108
120
  | directory | contains |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "6.0.1",
3
+ "version": "6.0.3",
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.",
@@ -92,9 +92,13 @@
92
92
  "wink-nlp": "^2.4.0"
93
93
  },
94
94
  "peerDependencies": {
95
+ "@aws-sdk/client-lambda": ">=3",
95
96
  "@aws-sdk/lib-dynamodb": ">=3"
96
97
  },
97
98
  "peerDependenciesMeta": {
99
+ "@aws-sdk/client-lambda": {
100
+ "optional": true
101
+ },
98
102
  "@aws-sdk/lib-dynamodb": {
99
103
  "optional": true
100
104
  }
@@ -183,7 +187,10 @@
183
187
  "claim:news": "node scripts/news-rig.mjs",
184
188
  "roll": "node scripts/roll.mjs",
185
189
  "build:ask-bundle": "node scripts/build-ask-bundle.mjs",
186
- "build:row-service": "esbuild server/row-service/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --outfile=server/row-service/dist/handler.js",
190
+ "build:row-service": "esbuild server/row-service/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --external:@aws-sdk/client-lambda --outfile=server/row-service/dist/handler.js",
191
+ "build:turn-service": "esbuild server/turn-service/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --external:@aws-sdk/client-lambda --outfile=server/turn-service/dist/handler.js",
192
+ "build:turn-seed": "node server/turn-service/build-seed.mjs",
193
+ "build:news-worker": "esbuild server/news-worker/handler.mjs --bundle --platform=node --target=node20 --external:@aws-sdk/lib-dynamodb --external:@aws-sdk/client-dynamodb --external:@aws-sdk/client-lambda --outfile=server/news-worker/dist/handler.js",
187
194
  "build:chat-bundle": "node scripts/build-chat-bundle.mjs",
188
195
  "build:spider-fly-bundle": "node scripts/build-spider-fly-bundle.mjs",
189
196
  "build:plan-bundle": "node scripts/build-plan-bundle.mjs",
@@ -8,12 +8,28 @@
8
8
  // keeps hits AND misses so a term is never asked twice. Every failure of any
9
9
  // kind reads as null, so the caller's honest miss stands.
10
10
  //
11
+ // The gate also counts what its fetches cost and what they hit: how many round
12
+ // trips a turn has spent, and how many of its failures said the source itself
13
+ // is struggling. The first bounds a turn (`beginTurn` opens the budget window,
14
+ // and a turn past its cap stops fetching and misses honestly); the second is
15
+ // what a source's circuit breaker reads through `stats()`, so an empty answer
16
+ // and a timing-out source never look alike to it.
17
+ //
11
18
  // No node builtins — this module ships in the browser bundles unchanged; the
12
19
  // only I/O is fetch.
13
20
 
21
+ import { isSystemicSourceStatus } from "../../domain/source-breaker.mjs";
22
+
23
+ /** The abort timeout on every single fetch: one source's slowness costs a turn
24
+ * this much and no more. */
14
25
  export const DEFAULT_TIMEOUT_MS = 4000;
15
26
  export const DEFAULT_MIN_INTERVAL_MS = 2000;
16
27
  export const RETRY_AFTER_FLOOR_MS = 5000;
28
+ /** How many round trips one turn may spend on a single source. A live
29
+ * reference lookup costs two (search, then read), a research step three at
30
+ * most, so the cap sits above what an honest turn needs and below what a
31
+ * retrying loop could spend. Only counted once a caller declares a turn. */
32
+ export const DEFAULT_MAX_FETCHES_PER_TURN = 6;
17
33
  // Action-API requests carry maxlag so an overloaded replica set answers with
18
34
  // an error we back off from instead of adding to its load (Wikimedia's own
19
35
  // recommended default for non-interactive clients).
@@ -43,6 +59,7 @@ export function createCourtesyGate({
43
59
  timeoutMs = DEFAULT_TIMEOUT_MS,
44
60
  minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
45
61
  retryAfterFloorMs = RETRY_AFTER_FLOOR_MS,
62
+ maxFetchesPerTurn = DEFAULT_MAX_FETCHES_PER_TURN,
46
63
  userAgent,
47
64
  waitForSlot = false,
48
65
  validators = null,
@@ -52,6 +69,11 @@ export function createCourtesyGate({
52
69
  let lastLookupAt = 0;
53
70
  let coolOffUntil = 0;
54
71
  let inFlight = false;
72
+ let fetches = 0;
73
+ let systemicFailures = 0;
74
+ let fetchesThisTurn = 0;
75
+ let turnBudgetOpen = false;
76
+ let budgetExhausted = false;
55
77
 
56
78
  const identifyingHeaders = () => {
57
79
  if (!userAgent) return null;
@@ -98,6 +120,12 @@ export function createCourtesyGate({
98
120
  * else could have earned a 304 in the first place). `asJson` picks the
99
121
  * body shape: parsed JSON (with the maxlag check) or raw text. */
100
122
  async function fetchRaw(url, { asJson }) {
123
+ if (turnBudgetOpen && fetchesThisTurn >= maxFetchesPerTurn) {
124
+ budgetExhausted = true;
125
+ return null;
126
+ }
127
+ fetches += 1;
128
+ fetchesThisTurn += 1;
101
129
  const controller = typeof AbortController === "function" ? new AbortController() : null;
102
130
  const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
103
131
  try {
@@ -105,13 +133,27 @@ export function createCourtesyGate({
105
133
  if (controller) opts.signal = controller.signal;
106
134
  const headers = { ...(identifyingHeaders() ?? {}), ...(conditionalHeaders(url) ?? {}) };
107
135
  if (Object.keys(headers).length) opts.headers = headers;
108
- const res = await doFetch(url, opts);
136
+ let res;
137
+ try {
138
+ res = await doFetch(url, opts);
139
+ } catch {
140
+ // Nothing came back at all: a dropped connection, a refused host, or
141
+ // this fetch's own abort timer. Every one of those is the source
142
+ // failing, not answering.
143
+ systemicFailures += 1;
144
+ return null;
145
+ }
109
146
  if (res.status === 429) {
110
147
  openCoolOff(res.headers?.get?.("retry-after"));
148
+ systemicFailures += 1;
111
149
  return null;
112
150
  }
113
151
  if (res.status === 304) return validators ? { notModified: true } : null;
114
- if (!res.ok) return null;
152
+ if (!res.ok) {
153
+ // A 404 for a term nobody wrote about is an answer; a 5xx is not.
154
+ if (isSystemicSourceStatus(res.status)) systemicFailures += 1;
155
+ return null;
156
+ }
115
157
  rememberValidators(url, res);
116
158
  if (asJson) {
117
159
  const body = await res.json();
@@ -119,12 +161,17 @@ export function createCourtesyGate({
119
161
  // Retry-After header — back off exactly as a 429 asks.
120
162
  if (body?.error?.code === "maxlag") {
121
163
  openCoolOff(res.headers?.get?.("retry-after"));
164
+ systemicFailures += 1;
122
165
  return null;
123
166
  }
124
167
  return body;
125
168
  }
126
169
  return await res.text();
127
170
  } catch {
171
+ // The response arrived and its body did not. A body cut off by this
172
+ // fetch's own timer is the source failing; an unparseable one is just
173
+ // an answer we cannot use.
174
+ if (controller?.signal?.aborted) systemicFailures += 1;
128
175
  return null;
129
176
  } finally {
130
177
  if (timer !== null) clearTimeout(timer);
@@ -188,5 +235,22 @@ export function createCourtesyGate({
188
235
  return value;
189
236
  }
190
237
 
191
- return { fetchJson, fetchText, cachedFetch };
238
+ /** Opens this gate's per-turn fetch budget and resets its count. A caller
239
+ * that never calls this spends no budget at all — a library consumer with
240
+ * no turn boundary keeps today's behaviour, and the cap applies exactly
241
+ * where a turn declares itself. */
242
+ function beginTurn() {
243
+ turnBudgetOpen = true;
244
+ fetchesThisTurn = 0;
245
+ budgetExhausted = false;
246
+ }
247
+
248
+ /** What this gate has spent and hit since it was created. `fetches` and
249
+ * `systemicFailures` only ever climb, so a caller reads them either side of
250
+ * one lookup and takes the difference. */
251
+ function stats() {
252
+ return { fetches, systemicFailures, fetchesThisTurn, budgetExhausted };
253
+ }
254
+
255
+ return { fetchJson, fetchText, cachedFetch, beginTurn, stats };
192
256
  }
@@ -89,6 +89,14 @@ export function createDbpediaLookupLiveProvider({
89
89
  return {
90
90
  name: sourceName,
91
91
  origin,
92
+ label: DBPEDIA_LOOKUP_SOURCE_LABEL,
93
+
94
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). */
95
+ beginTurn() { gate.beginTurn(); },
96
+
97
+ /** The source's own running totals, including the failures that said the
98
+ * source itself is struggling — what a circuit breaker reads. */
99
+ stats() { return gate.stats(); },
92
100
 
93
101
  provenanceTag(term) {
94
102
  return researchSourceTag(sourceName, term);
@@ -231,6 +231,14 @@ export function createWikidataLiveProvider({
231
231
  return {
232
232
  name: sourceName,
233
233
  origin,
234
+ label: WIKIDATA_SOURCE_LABEL,
235
+
236
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). */
237
+ beginTurn() { gate.beginTurn(); },
238
+
239
+ /** The source's own running totals, including the failures that said the
240
+ * source itself is struggling — what a circuit breaker reads. */
241
+ stats() { return gate.stats(); },
234
242
 
235
243
  /** The tag every fact this source contributes carries. */
236
244
  provenanceTag(term) {
@@ -43,6 +43,11 @@ export const SIMPLE_WIKIPEDIA_ORIGIN = "https://simple.wikipedia.org";
43
43
  export const WIKIPEDIA_LIVE_SOURCE_NAME = "wikipedia-live";
44
44
  export const SIMPLE_WIKIPEDIA_SOURCE_NAME = "simple-wikipedia";
45
45
 
46
+ /** What each of the two goes by in prose a reader sees, the same names their
47
+ * citations already carry. */
48
+ export const WIKIPEDIA_SOURCE_LABEL = "Wikipedia";
49
+ export const SIMPLE_WIKIPEDIA_SOURCE_LABEL = "Simple English Wikipedia";
50
+
46
51
  /** The identification string Wikimedia's robot policy asks API clients to
47
52
  * carry, pointing at this project's public site as the contact. Browsers
48
53
  * refuse to override the User-Agent request header, so the API-recognised
@@ -81,6 +86,7 @@ export function createWikipediaLiveProvider({
81
86
  userAgent = WIKIMEDIA_USER_AGENT,
82
87
  waitForSlot = false,
83
88
  sourceName = WIKIPEDIA_LIVE_SOURCE_NAME,
89
+ label = WIKIPEDIA_SOURCE_LABEL,
84
90
  } = {}) {
85
91
  const gate = createCourtesyGate({ fetchImpl, timeoutMs, minIntervalMs, userAgent, waitForSlot });
86
92
 
@@ -130,6 +136,17 @@ export function createWikipediaLiveProvider({
130
136
  return {
131
137
  name: sourceName,
132
138
  origin,
139
+ label,
140
+
141
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). A caller with
142
+ * a turn boundary calls it once at the top of the turn; one that has none
143
+ * never calls it and spends no budget. */
144
+ beginTurn() { gate.beginTurn(); },
145
+
146
+ /** The source's own running totals, including how many of its failures
147
+ * said the source itself is struggling — what a circuit breaker reads to
148
+ * tell a timing-out source from one that simply has no article. */
149
+ stats() { return gate.stats(); },
133
150
 
134
151
  /** The tag a fact gained through the research source contract carries. The
135
152
  * research lane stamps its own `research:<topic>@<depth>` tag instead when
@@ -257,6 +274,7 @@ export function createSimpleWikipediaResearchSource(options = {}) {
257
274
  return createWikipediaLiveProvider({
258
275
  origin: SIMPLE_WIKIPEDIA_ORIGIN,
259
276
  sourceName: SIMPLE_WIKIPEDIA_SOURCE_NAME,
277
+ label: SIMPLE_WIKIPEDIA_SOURCE_LABEL,
260
278
  waitForSlot: true,
261
279
  ...options,
262
280
  });
@@ -131,6 +131,14 @@ export function createWiktionaryLiveProvider({
131
131
  return {
132
132
  name: sourceName,
133
133
  origin,
134
+ label: WIKTIONARY_SOURCE_LABEL,
135
+
136
+ /** Opens this source's per-turn fetch budget (courtesy.mjs). */
137
+ beginTurn() { gate.beginTurn(); },
138
+
139
+ /** The source's own running totals, including the failures that said the
140
+ * source itself is struggling — what a circuit breaker reads. */
141
+ stats() { return gate.stats(); },
134
142
 
135
143
  provenanceTag(term) {
136
144
  return researchSourceTag(sourceName, term);
@@ -796,7 +796,13 @@ async function readRowPayload(handle) {
796
796
  if (!handle.cachedPayload) {
797
797
  const empty = emptyMemory();
798
798
  const stored = await collectRows(handle.impl.readRows());
799
- handle.baseRows = payloadToRows(handle.basePayload || empty);
799
+ // "keep": the base overlay's own rows never reach the wire (persistRowPayload
800
+ // excludes every seed key from every write via seedOnlyKeys below), so the
801
+ // per-row byte cap that protects a real backend's real item-size limit has
802
+ // nothing to protect here — capping it would silently drop a real corpus
803
+ // band's own high-fan-out property (one edge per fact is normal, not a
804
+ // pathology) and break every read that depends on it.
805
+ handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
800
806
  handle.storedRows = stored.filter((row) => row?.rowClass !== BOOKKEEPING_ROW_CLASS);
801
807
  handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
802
808
  meta: {
@@ -109,14 +109,20 @@ function ordAssigner(priorRows) {
109
109
  };
110
110
  }
111
111
 
112
- /** Refuse or drop an oversized row. The default posture throws: one fact that
113
- * big is an extraction pathology and the turn should fail loudly, naming the
114
- * provenance that produced it. A consumer whose turn is itself the last resort
115
- * passes `onOversizedRow: "drop"` instead, and the turn completes with
116
- * everything else persisted. */
112
+ /** Refuse, drop, or keep an oversized row. The default posture throws: one
113
+ * fact that big is an extraction pathology and the turn should fail loudly,
114
+ * naming the provenance that produced it. A consumer whose turn is itself
115
+ * the last resort passes `onOversizedRow: "drop"` instead, and the turn
116
+ * completes with everything else persisted. `"keep"` is for rows that will
117
+ * never actually reach the wire — a read-only seed overlay's own projection
118
+ * (core.mjs's `readRowPayload`), never a caller-facing choice: the cap
119
+ * protects a real backend's real per-item limit, which does not apply to a
120
+ * base payload `persistRowPayload` already excludes from every write
121
+ * (`seedOnlyKeys`). Silent — an oversized seed row is not a pathology, it's
122
+ * what a real corpus band's own high-fan-out property looks like. */
117
123
  function admitRow(row, provenance, { onOversizedRow, log }) {
118
124
  const bytes = rowJsonBytes(row);
119
- if (bytes <= MAX_ROW_BYTES) return true;
125
+ if (bytes <= MAX_ROW_BYTES || onOversizedRow === "keep") return true;
120
126
  const where = provenance ? ` (provenance: ${provenance})` : "";
121
127
  const detail = `${row.rowClass} row ${row.rowKey} serializes to ${bytes} bytes, over the ${MAX_ROW_BYTES}-byte cap${where}`;
122
128
  if (onOversizedRow === "drop") {
@@ -127,16 +133,18 @@ function admitRow(row, provenance, { onOversizedRow, log }) {
127
133
  }
128
134
 
129
135
  const warnToConsole = (message) => console.warn(message);
136
+ const OVERSIZED_ROW_POSTURES = new Set(["throw", "drop", "keep"]);
130
137
 
131
138
  /** Project a memory payload into wire rows.
132
139
  *
133
140
  * `priorRows` are the rows this payload was last projected as; pass them and
134
141
  * every unchanged row comes back byte-identical, so `diffRows` writes only
135
- * what actually moved. `onOversizedRow` is "throw" (default) or "drop", and
136
- * `log` takes the drop notices. */
142
+ * what actually moved. `onOversizedRow` is "throw" (default), "drop", or
143
+ * "keep" (rows that never reach the wire — see `admitRow`), and `log` takes
144
+ * the drop notices. */
137
145
  export function payloadToRows(payload, { priorRows = null, onOversizedRow = "throw", log = warnToConsole } = {}) {
138
- if (onOversizedRow !== "throw" && onOversizedRow !== "drop") {
139
- throw new TypeError(`onOversizedRow must be "throw" or "drop", got ${JSON.stringify(onOversizedRow)}`);
146
+ if (!OVERSIZED_ROW_POSTURES.has(onOversizedRow)) {
147
+ throw new TypeError(`onOversizedRow must be "throw", "drop", or "keep", got ${JSON.stringify(onOversizedRow)}`);
140
148
  }
141
149
  const ordFor = ordAssigner(priorRows);
142
150
  const posture = { onOversizedRow, log };
@@ -96,15 +96,17 @@ async function fetchMergedEntities(config) {
96
96
 
97
97
  /** Fetch the entities payload through the provider seam. With a registered provider, its
98
98
  * result is returned as-is (uncached); a non-object result is a clean ToolError. Default:
99
- * read + parse the local graph artifact, cached per file. A missing artifact (ENOENT)
99
+ * read + parse the local graph artifact, cached per file. A missing artifact (ENOENT), or
100
+ * no config/graphFile at all (a graph-less caller — nothing was ever configured to read),
100
101
  * returns the bootstrap payload, uncached, so a freshly written file is picked up next
101
102
  * fetch. When `config.graphFiles` names more than one file, delegates to
102
103
  * fetchMergedEntities instead. */
103
104
  export async function fetchEntities(config) {
105
+ const cfg = config || {};
104
106
  if (provider) {
105
107
  let payload;
106
108
  try {
107
- payload = await provider(config);
109
+ payload = await provider(cfg);
108
110
  } catch (e) {
109
111
  if (e instanceof ToolError) throw e;
110
112
  throw new ToolError(`graph provider failed (${e?.message || e})`);
@@ -114,25 +116,26 @@ export async function fetchEntities(config) {
114
116
  }
115
117
  return payload;
116
118
  }
117
- if (Array.isArray(config.graphFiles) && config.graphFiles.length > 1) {
118
- return fetchMergedEntities(config);
119
+ if (Array.isArray(cfg.graphFiles) && cfg.graphFiles.length > 1) {
120
+ return fetchMergedEntities(cfg);
119
121
  }
120
- if (cache && cache.file === config.graphFile) return cache.payload;
122
+ if (!cfg.graphFile) return emptyEntities();
123
+ if (cache && cache.file === cfg.graphFile) return cache.payload;
121
124
  let text;
122
125
  try {
123
- text = await readFile(config.graphFile, "utf8");
126
+ text = await readFile(cfg.graphFile, "utf8");
124
127
  } catch (e) {
125
128
  if (e?.code === "ENOENT") return emptyEntities();
126
129
  throw new ToolError(
127
- `cannot read graph artifact at ${config.graphFile} (${e?.code || e?.message || e})`,
130
+ `cannot read graph artifact at ${cfg.graphFile} (${e?.code || e?.message || e})`,
128
131
  );
129
132
  }
130
133
  let payload;
131
134
  try {
132
135
  payload = JSON.parse(text);
133
136
  } catch {
134
- throw new ToolError(`graph artifact ${config.graphFile} is not valid JSON`);
137
+ throw new ToolError(`graph artifact ${cfg.graphFile} is not valid JSON`);
135
138
  }
136
- cache = { file: config.graphFile, payload };
139
+ cache = { file: cfg.graphFile, payload };
137
140
  return payload;
138
141
  }
@@ -0,0 +1,259 @@
1
+ // source-breaker.mjs — the circuit breaker the external sources share: the
2
+ // live research adapters in a chat turn and the news page's KB lookups. Same
3
+ // machine as the turn surface's Dynamo-backed breaker, over state that needs
4
+ // no store behind it. A page has one writer and its state dies with the page;
5
+ // a CLI process has one writer and its state dies with the process. So the
6
+ // state is a plain object and every transition is a local assignment, with no
7
+ // conditional writes to settle races that cannot happen.
8
+ //
9
+ // Three states. Closed lets a lookup run; a systemic failure adds to a count
10
+ // inside a fixed window, and crossing a fixed threshold opens the breaker.
11
+ // Open skips the source outright until a fixed cooldown elapses, at which
12
+ // point the next caller probes once. The probe's own outcome decides closed
13
+ // or open again.
14
+ //
15
+ // What counts is the one rule every guard in this codebase shares: a throttle,
16
+ // a 5xx, or a timeout means the source is in trouble. A lookup that came back
17
+ // empty is an answer, and a 404 for a term nobody wrote an article about is
18
+ // the commonest answer of all — neither ever counts against a source.
19
+ //
20
+ // A skip changes what served an answer, so the caller collects the names it
21
+ // skipped and the answer says so through `sourceSkipNoteLine`.
22
+ //
23
+ // The clock is injected (default `Date.now`) so window rollover and cooldown
24
+ // expiry are reproducible without a real wall clock. No node builtins — this
25
+ // module ships in the browser bundles unchanged.
26
+
27
+ export const SOURCE_BREAKER_DEFAULTS = Object.freeze({
28
+ failureThreshold: 5,
29
+ windowMs: 60_000,
30
+ cooldownMs: 60_000,
31
+ });
32
+
33
+ export const SOURCE_BREAKER_CLOSED = "closed";
34
+ export const SOURCE_BREAKER_OPEN = "open";
35
+ export const SOURCE_BREAKER_HALF_OPEN = "half-open";
36
+
37
+ /** HTTP statuses that mean the source itself is struggling rather than
38
+ * answering. A 4xx that is not a throttle or a request timeout is an answer:
39
+ * the term has no page, or the request was wrong. */
40
+ export function isSystemicSourceStatus(status) {
41
+ const code = Number(status);
42
+ if (!Number.isFinite(code)) return false;
43
+ return code === 408 || code === 429 || code >= 500;
44
+ }
45
+
46
+ const TRANSPORT_FAILURE_NAMES = new Set(["AbortError", "TimeoutError", "NetworkError", "FetchError"]);
47
+
48
+ /** Does this failure mean the source itself is in trouble? Accepts whatever a
49
+ * fetch layer has to hand: a thrown transport error, an error carrying a
50
+ * status, or a response-shaped object. */
51
+ export function isSystemicSourceFailure(error) {
52
+ if (!error) return false;
53
+ if (TRANSPORT_FAILURE_NAMES.has(error.name)) return true;
54
+ if (error.timedOut === true || error.aborted === true) return true;
55
+ return isSystemicSourceStatus(error.status ?? error.statusCode);
56
+ }
57
+
58
+ /** How many systemic failures does this outcome carry? A bare number, an
59
+ * object counting its own (`{ systemicFailures }` — what a courtesy gate's
60
+ * stats diff hands back), or a single raw error to classify. */
61
+ export function failureCountFromOutcome(outcome) {
62
+ if (outcome == null) return 0;
63
+ if (typeof outcome === "number") return Number.isFinite(outcome) ? Math.max(0, Math.floor(outcome)) : 0;
64
+ if (typeof outcome.systemicFailures === "number") return Math.max(0, Math.floor(outcome.systemicFailures));
65
+ if ("error" in outcome) return isSystemicSourceFailure(outcome.error) ? 1 : 0;
66
+ return 0;
67
+ }
68
+
69
+ /** One source's breaker. `decide()` answers whether this caller may reach the
70
+ * source and hands back the one call that closes the loop afterward:
71
+ * `report(outcome)`, made once the lookup (or its failure) is over. A caller
72
+ * that was told to skip gets a report that does nothing, since it has
73
+ * nothing to report. */
74
+ export function createSourceBreaker({
75
+ source = "",
76
+ clock = Date.now,
77
+ failureThreshold = SOURCE_BREAKER_DEFAULTS.failureThreshold,
78
+ windowMs = SOURCE_BREAKER_DEFAULTS.windowMs,
79
+ cooldownMs = SOURCE_BREAKER_DEFAULTS.cooldownMs,
80
+ } = {}) {
81
+ let state = SOURCE_BREAKER_CLOSED;
82
+ let failures = 0;
83
+ let windowStart = null;
84
+ let openedAt = null;
85
+
86
+ const noopReport = () => {};
87
+
88
+ function open() {
89
+ state = SOURCE_BREAKER_OPEN;
90
+ openedAt = clock();
91
+ }
92
+
93
+ function recordSystemicFailure(count) {
94
+ const now = clock();
95
+ if (windowStart === null || now - windowStart >= windowMs) {
96
+ windowStart = now;
97
+ failures = count;
98
+ } else {
99
+ failures += count;
100
+ }
101
+ if (failures >= failureThreshold) open();
102
+ }
103
+
104
+ function resolveProbe(failed) {
105
+ if (state !== SOURCE_BREAKER_HALF_OPEN) return;
106
+ if (failed) { open(); return; }
107
+ state = SOURCE_BREAKER_CLOSED;
108
+ failures = 0;
109
+ windowStart = null;
110
+ openedAt = null;
111
+ }
112
+
113
+ return {
114
+ source,
115
+
116
+ /** The breaker's state, for narration and tests. Reading alone is never a
117
+ * transition — a caller deciding its own lookup goes through `decide`. */
118
+ read() {
119
+ return { source, state, failures, windowStart, openedAt };
120
+ },
121
+
122
+ decide() {
123
+ if (state === SOURCE_BREAKER_CLOSED) {
124
+ return {
125
+ source,
126
+ allowed: true,
127
+ probe: false,
128
+ report: (outcome) => {
129
+ const count = failureCountFromOutcome(outcome);
130
+ if (count > 0) recordSystemicFailure(count);
131
+ },
132
+ };
133
+ }
134
+
135
+ if (state === SOURCE_BREAKER_OPEN) {
136
+ if (openedAt === null || clock() - openedAt < cooldownMs) {
137
+ return { source, allowed: false, probe: false, report: noopReport };
138
+ }
139
+ state = SOURCE_BREAKER_HALF_OPEN;
140
+ return {
141
+ source,
142
+ allowed: true,
143
+ probe: true,
144
+ report: (outcome) => { resolveProbe(failureCountFromOutcome(outcome) > 0); },
145
+ };
146
+ }
147
+
148
+ // half-open: one probe is already out, so everyone else skips
149
+ return { source, allowed: false, probe: false, report: noopReport };
150
+ },
151
+ };
152
+ }
153
+
154
+ /** The breakers a page (or a process) holds, one per source name, minted on
155
+ * first use. */
156
+ export function createSourceBreakerRegistry(options = {}) {
157
+ const breakers = new Map();
158
+ return {
159
+ breakerFor(source) {
160
+ const name = String(source ?? "");
161
+ let breaker = breakers.get(name);
162
+ if (!breaker) {
163
+ breaker = createSourceBreaker({ ...options, source: name });
164
+ breakers.set(name, breaker);
165
+ }
166
+ return breaker;
167
+ },
168
+ read() {
169
+ return [...breakers.values()].map((breaker) => breaker.read());
170
+ },
171
+ };
172
+ }
173
+
174
+ let shared = null;
175
+
176
+ /** The registry every call site shares by default: page-lifetime in the
177
+ * browser, process-lifetime in the CLI. A source that trips its threshold in
178
+ * the news page's enrich cycle is therefore skipped by the chat lane too —
179
+ * one failing dependency, one decision about it. */
180
+ export function sourceBreakers() {
181
+ if (!shared) shared = createSourceBreakerRegistry();
182
+ return shared;
183
+ }
184
+
185
+ /** Drops the shared registry, so a test starts from an untouched machine. */
186
+ export function resetSourceBreakers() {
187
+ shared = null;
188
+ }
189
+
190
+ /** Runs `work` behind `source`'s breaker. A skipped source never runs the
191
+ * work: it answers null, adds its name to `skipped`, and the caller's
192
+ * existing empty-result path takes over unchanged.
193
+ *
194
+ * `systemicFailuresOf` reads the count this attempt earned — the courtesy
195
+ * gate's monotonic counter, diffed around the call by `throughSourceBreaker`
196
+ * itself. A source with no such counter reports nothing and its breaker
197
+ * never opens, which is the right posture for a source whose failures we
198
+ * cannot see. */
199
+ export async function throughSourceBreaker(source, work, {
200
+ registry = sourceBreakers(),
201
+ skipped = null,
202
+ label = null,
203
+ systemicFailuresOf = null,
204
+ } = {}) {
205
+ const name = String(source ?? "");
206
+ if (!name) return await work();
207
+ const decision = registry.breakerFor(name).decide();
208
+ if (!decision.allowed) {
209
+ // The breaker is keyed by the source's own name; the reader gets the name
210
+ // the source goes by in prose.
211
+ if (skipped && typeof skipped.add === "function") skipped.add(String(label || name));
212
+ return null;
213
+ }
214
+ const before = typeof systemicFailuresOf === "function" ? Number(systemicFailuresOf()) || 0 : 0;
215
+ try {
216
+ return await work();
217
+ } finally {
218
+ const after = typeof systemicFailuresOf === "function" ? Number(systemicFailuresOf()) || 0 : 0;
219
+ decision.report({ systemicFailures: Math.max(0, after - before) });
220
+ }
221
+ }
222
+
223
+ /** The names read out in the order a reader can check, so the same set of
224
+ * skips always renders the same line. */
225
+ function listNames(sources) {
226
+ const names = [...new Set([...(sources ?? [])].map((s) => String(s ?? "").trim()).filter(Boolean))].sort();
227
+ if (names.length <= 1) return names.join("");
228
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
229
+ }
230
+
231
+ /** The sentence that explains a skip, singular or plural. The wording is
232
+ * written once, here, because it lands in prose a reader judges the whole
233
+ * product by. */
234
+ function skipReason(many) {
235
+ return many
236
+ ? "Those sources kept failing, so this session stopped asking them."
237
+ : "That source kept failing, so this session stopped asking it.";
238
+ }
239
+
240
+ function skipLine(sources, lead) {
241
+ const names = listNames(sources);
242
+ if (!names) return null;
243
+ const many = names.includes(" and ");
244
+ return `${lead} ${names}. ${skipReason(many)}`;
245
+ }
246
+
247
+ /** The trailing line an answer carries when a skipped source changed what
248
+ * served it. Null when nothing was skipped, so an ordinary turn is
249
+ * byte-identical to a run without this seam. */
250
+ export function sourceSkipNoteLine(sources) {
251
+ return skipLine(sources, "Answered without");
252
+ }
253
+
254
+ /** The same fact stated by a cycle rather than an answer: an enrichment pass
255
+ * reports what it skipped, since a term nobody asked about is not a term
256
+ * nobody knows. */
257
+ export function sourceSkipStatusLine(sources) {
258
+ return skipLine(sources, "Skipped");
259
+ }