@polycode-projects/the-mechanical-code-talker 6.0.0 → 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.
@@ -0,0 +1,120 @@
1
+ // retrieval-marker.mjs — the trailing line an answer carries when a corpus
2
+ // retrieval stood behind it, or when one was supposed to and did not.
3
+ //
4
+ // A bounded retrieval reads a slice of the corpus, never the whole of it. A
5
+ // point answer is unaffected: it either grounds on what came back or misses.
6
+ // An answer that reports the extent of a set is different. Reporting the
7
+ // slice's contents as the store's would be a completeness claim nothing
8
+ // checked, so those answers say what they counted over.
9
+ //
10
+ // Three states, three fixed lines. The wording is written once here and pinned
11
+ // byte for byte, because it lands in prose a reader judges the whole product
12
+ // by.
13
+
14
+ import { SUPPLEMENTED_MODE, SEED_SESSION_MODE } from "./retrieval-modes.mjs";
15
+
16
+ export { SUPPLEMENTED_MODE, SEED_SESSION_MODE };
17
+
18
+ /** Retrieval ran and nothing stopped it early. */
19
+ export const CORPUS_SCOPE_LINE = "Corpus scope: the rows this query pulled from the corpus.";
20
+
21
+ /** Retrieval ran and a budget stopped it, or a read failed. Over a dense
22
+ * corpus this is the ordinary case rather than the exception — the
23
+ * subClassOf closure branches, so a grounded turn spends its query budget
24
+ * and comes back with a prefix. The line reads as a routine statement of
25
+ * scope for that reason. */
26
+ export const CORPUS_SCOPE_BOUNDED_LINE = "Corpus scope: the rows this query pulled from the corpus. The corpus may hold more.";
27
+
28
+ /** No corpus read happened while bands were configured — the breaker is open,
29
+ * so the turn answered from the bundled seed and the session alone. Under
30
+ * that floor this line is the reader's only signal that a thin answer came
31
+ * from the degraded mode, so it rides every answer, not only the ones that
32
+ * count a set. */
33
+ export const CORPUS_SUPPLEMENT_ABSENT_LINE = "Corpus scope: none. Answered without the corpus supplement.";
34
+
35
+ /** The enumeration-class lanes: the answers that report a set's extent, and so
36
+ * have to say what they counted over.
37
+ *
38
+ * Every entry is referenced from the composer that mints it, and the lane
39
+ * inventory test holds that both ways — a registered lane no composer sets is
40
+ * dead, and a composer naming a lane that is not registered is a lane nobody
41
+ * classified. */
42
+ export const ENUMERATION_LANES = Object.freeze({
43
+ /** "how many facts do you know" — a tally of a memory-store kind. */
44
+ MEMORY_COUNT: "memory-count",
45
+ /** "list facts" / "how many sessions are there" — the stored individuals. */
46
+ MEMORY_CLASS: "memory-class",
47
+ /** "which words have a p in them" — the store's own vocabulary, filtered. */
48
+ LETTER_WORDS: "letter-words",
49
+ /** "list the letters in the alphabet" — a declared collection's contents. */
50
+ COLLECTION_CONTENTS: "collection-contents",
51
+ /** "how many animals are there" — a taught class's members, tallied. */
52
+ TAUGHT_CLASS_COUNT: "taught-class-count",
53
+ /** "list the animals" — a taught class's members, named. */
54
+ MEMBERSHIP_LIST: "membership-list",
55
+ /** "name an animal" — one member, and a count of the rest. */
56
+ MEMBERSHIP_EXAMPLE: "membership-example",
57
+ /** "another word for dog" — the remembered synonym neighbourhood. */
58
+ SKOS_NEIGHBOURHOOD: "skos-neighbourhood",
59
+ /** "what else about a dog" — everything past the primary definition. */
60
+ WHAT_ELSE: "what-else",
61
+ /** "which animals can fly" and its siblings, read out of the fact store. */
62
+ FACT_SET: "fact-set",
63
+ /** "what did you learn about dogs" — the read-back cascade's listings. */
64
+ FACT_READBACK: "fact-readback",
65
+ });
66
+
67
+ const REGISTERED_LANES = Object.freeze(Object.values(ENUMERATION_LANES));
68
+
69
+ /** Is this a lane name the registry knows? */
70
+ export function isEnumerationLane(lane) {
71
+ return typeof lane === "string" && REGISTERED_LANES.includes(lane);
72
+ }
73
+
74
+ /** Does this answer report the extent of a set?
75
+ *
76
+ * A truncated listing does by definition — it is holding a remainder. So does
77
+ * any answer that renders more than one fact line: two lines are a set, and a
78
+ * reader takes them as everything there was. One line is a point answer and
79
+ * changes nothing.
80
+ *
81
+ * The fact-store lanes derive their marker through this rather than tagging
82
+ * each of their twenty-odd return sites, which means a reader added to those
83
+ * cascades later is covered the moment it renders a set. */
84
+ export function answerAssertsASet(text, { pending = null } = {}) {
85
+ if (pending) return true;
86
+ return String(text ?? "").split("\n").filter((line) => line.trim() !== "").length > 1;
87
+ }
88
+
89
+ /** The retrieval context in the shape the marker reads, or null when the
90
+ * caller passed none. Accepts `retrieveSubgraph`'s own metrics object
91
+ * unchanged, and the smaller `{mode, bounded, bands}` literal a handler may
92
+ * build by hand. Anything without a recognised mode reads as no context, so a
93
+ * malformed input can never mint a marker. */
94
+ export function retrievalContextOf(input) {
95
+ if (!input || typeof input !== "object") return null;
96
+ const mode = input.mode;
97
+ if (mode !== SUPPLEMENTED_MODE && mode !== SEED_SESSION_MODE) return null;
98
+ return {
99
+ mode,
100
+ bounded: Boolean(input.bounded),
101
+ bands: Array.isArray(input.bands) ? input.bands : [],
102
+ };
103
+ }
104
+
105
+ /** The trailing line this turn's answer carries, or null for no line.
106
+ *
107
+ * No context at all means no line, which is what every caller that never
108
+ * retrieves gets: the local shell, the browser page, every existing test.
109
+ *
110
+ * A seed-session turn with no bands configured is not a degraded mode, it is
111
+ * a deployment without a corpus, so it says nothing either. */
112
+ export function retrievalMarkerLine(retrieval, { enumerationLane = null } = {}) {
113
+ const context = retrievalContextOf(retrieval);
114
+ if (!context) return null;
115
+ if (context.mode === SEED_SESSION_MODE) {
116
+ return context.bands.length ? CORPUS_SUPPLEMENT_ABSENT_LINE : null;
117
+ }
118
+ if (!isEnumerationLane(enumerationLane)) return null;
119
+ return context.bounded ? CORPUS_SCOPE_BOUNDED_LINE : CORPUS_SCOPE_LINE;
120
+ }
@@ -0,0 +1,13 @@
1
+ // retrieval-modes.mjs — the two honest modes a turn's retrieval payload can
2
+ // carry. Every layer that needs to say "the corpus supplement ran" or "it
3
+ // did not" reads these two strings rather than minting its own, so a
4
+ // retrieval-layer skip and a breaker-forced skip land in an answer looking
5
+ // identical.
6
+
7
+ /** Retrieval ran and the answer stands on the corpus supplement as well as
8
+ * the seed and the session. */
9
+ export const SUPPLEMENTED_MODE = "supplemented";
10
+
11
+ /** No corpus read happened — no bands are configured, or the breaker is
12
+ * open. The answer stands on the bundled seed and the session alone. */
13
+ export const SEED_SESSION_MODE = "seed-session";
@@ -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
+ }
@@ -117,6 +117,8 @@ const promptFor = (focus) => (focus ? `tmct(${shortLabel(focus.label)})> ` : PRO
117
117
  * logFile, sidecarFile, bannerLines, empty, focus, lastAnswer, turns, promptFor(),
118
118
  * turn(line), close() }. `turn(line)` runs one dispatched turn through runTurn and the
119
119
  * full sink sequencing, returning { answer, end, prompt }; `close()` is idempotent.
120
+ * `turn(line, {retrieval})` passes this turn's own corpus-retrieval context,
121
+ * overriding the session-level `retrieval` option for that turn.
120
122
  */
121
123
  export async function createSession({
122
124
  repoPath,
@@ -168,6 +170,15 @@ export async function createSession({
168
170
  // lifetime (four mud.html characters means four sessions, not one session
169
171
  // switching identity turn to turn).
170
172
  actingSubject,
173
+ // What the corpus retrieval behind this session's turns did, in
174
+ // retrieve-subgraph's own metrics shape ({mode, bounded, bands}). It decides
175
+ // the corpus-scope line an answer carries: what the query pulled in, whether
176
+ // a budget cut it short, or that the supplement was absent altogether. A
177
+ // caller that retrieves per turn passes its own context to `turn(line,
178
+ // {retrieval})` instead, which wins over this one. Omitted (the default)
179
+ // means no corpus behind this session, and every answer is byte-identical to
180
+ // a run without the seam.
181
+ retrieval = null,
171
182
  // The session-log filesystem seam: mkdir/createWriteStream, injectable so a
172
183
  // test can exercise the unwritable-log guard by rejecting at the seam
173
184
  // itself rather than by making a real directory unwritable — chmod-based
@@ -553,10 +564,10 @@ export async function createSession({
553
564
  * (empty when the turn wrote nothing). A throwing runTurn must never abort
554
565
  * the session: a piped/non-interactive driver has no other chance to see
555
566
  * this turn's answer. */
556
- async turn(line) {
567
+ async turn(line, { retrieval: turnRetrieval = null } = {}) {
557
568
  let result;
558
569
  try {
559
- result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
570
+ result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks, retrieval: turnRetrieval ?? retrieval });
560
571
  } catch (e) {
561
572
  const ts = new Date().toISOString();
562
573
  const message = e instanceof Error ? e.message : String(e);