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

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.
@@ -6,10 +6,18 @@
6
6
  // the news worker Lambda, against this session's own row partition — the
7
7
  // same `pollNewsSources`/`enrichTopTerms`/`buildFeed` calls the CLI's `tmct
8
8
  // news` verb runs, just running there instead of here. This module is the
9
- // thin client over that: mint a session key, call the row service's five
10
- // routes, and hand the result to the page's own render code
9
+ // thin client over that: mint a session key, call the row and turn
10
+ // services' routes, and hand the result to the page's own render code
11
11
  // (src/services/news-viz.mjs's inline script). Nothing here parses a feed,
12
- // extracts a fact, or ranks a term.
12
+ // extracts a fact, ranks a term, or renders an answer.
13
+ //
14
+ // The chat area's one call, `turn()`, is the odd one out: it answers
15
+ // synchronously (POST /api/sessions/<uuid>/turn) rather than through a
16
+ // trigger-and-settle cycle, and it never touches the materialized feed at
17
+ // all — a taught fact lands as a session row the same way an ingest trigger's
18
+ // row does, and reaches the feed only at whatever poll/enrich/ingest cycle
19
+ // materializes next. This module says nothing about that timing either way;
20
+ // it just reports what the turn itself returned.
13
21
  //
14
22
  // The one rule every method below honours: NOTHING here calls the row
15
23
  // service until the visitor presses something, unless a session key already
@@ -24,13 +32,25 @@
24
32
  // builds it fresh on every deploy, never committed, the same posture every
25
33
  // sibling *-browser-entry.mjs documents for its own output.
26
34
 
27
- import { createHttpRowBackend } from "./http-row-backend.mjs";
35
+ import { createHttpRowBackend, sha256Hex } from "./http-row-backend.mjs";
28
36
  import { publishTmctSurface } from "./tmct-surface.mjs";
37
+ import { factSentence, findingCaveat } from "../../domain/fact-phrase.mjs";
29
38
 
30
39
  const SESSION_HEADER = "x-tmct-session";
40
+ const PAYLOAD_HASH_HEADER = "x-amz-content-sha256";
31
41
  const DEFAULT_CYCLE_POLL_MS = 400;
32
42
  const DEFAULT_CYCLE_WAIT_TIMEOUT_MS = 20_000;
33
43
 
44
+ /** The standing refresh loop's own cadence: `~2 s interval with backoff
45
+ * toward ~10 s while nothing changes` (PLAN_MEMORY_BACKEND.md's materialized-
46
+ * feed section). A version change resets the interval back to the floor —
47
+ * something is actively happening, so the loop goes back to checking often —
48
+ * and a quiet tick or a failed read both step it toward the ceiling, never
49
+ * past it. The loop never stops outright: it only ever slows down. */
50
+ const DEFAULT_VERSION_POLL_MS = 2_000;
51
+ const DEFAULT_VERSION_POLL_STEP_MS = 2_000;
52
+ const DEFAULT_VERSION_POLL_MAX_MS = 10_000;
53
+
34
54
  /** The localStorage keys the shipped page persists under — exported so the
35
55
  * page's own inline script and a test can both name them without
36
56
  * retyping the string. `NEWS_SESSION_PREF_KEY` is the ONE fact beyond the
@@ -86,10 +106,25 @@ export function parseJsonlRows(text) {
86
106
  return rows;
87
107
  }
88
108
 
109
+ /** One line per row a turn's own write touched, through the phrase layer —
110
+ * `factSentence` turned into English, with any extraction caveat appended.
111
+ * No provenance tag rides along: a chat-taught row's own tag names this
112
+ * session and this moment, which the visitor already knows from having just
113
+ * typed it, so citing it back would be noise rather than information —
114
+ * unlike a corpus-grounded answer's citation, which names something the
115
+ * visitor could not otherwise know. */
116
+ export function turnCitationLines(factsTouched) {
117
+ return (factsTouched || []).map((row) => {
118
+ const caveat = findingCaveat(row);
119
+ return caveat ? `${factSentence(row)} ${caveat}` : factSentence(row);
120
+ });
121
+ }
122
+
89
123
  /**
90
- * The thin API session over the row service's news-facing routes:
91
- * `{ sessionKey, consented, unavailable, fetchFeed, fetchFeedVersion, start,
92
- * poll, enrich, ingestText, ingestRows, revokeConsent, destroy }`.
124
+ * The thin API session over the row and turn services' news-facing routes:
125
+ * `{ sessionKey, consented, unavailable, fetchFeed, fetchFeedVersion,
126
+ * fetchCycle, onFeedUpdate, start, poll, enrich, ingestText, ingestRows,
127
+ * turn, revokeConsent, destroy }`.
93
128
  *
94
129
  * `fetchImpl` defaults to the ambient `fetch`, so a page never has to pass
95
130
  * one; every path this module requests is root-relative ("/api/…"), which a
@@ -97,17 +132,34 @@ export function parseJsonlRows(text) {
97
132
  * behaviour §3.7 draws. A test hands in a `fetchImpl` that resolves those
98
133
  * same paths against a running `local.mjs` double instead.
99
134
  *
100
- * `cyclePollMs`/`cycleWaitTimeoutMs` govern the one polling loop this module
101
- * runs: after a trigger's own 202, waiting for `feedVersion` to move past
135
+ * `cyclePollMs`/`cycleWaitTimeoutMs` govern the one polling loop a trigger's
136
+ * own press runs: after its 202, waiting for `feedVersion` to move past
102
137
  * where it stood before that trigger, so the button that fired it can settle
103
138
  * once the cycle it started has actually materialized. It gives up and
104
139
  * renders whatever is there once `cycleWaitTimeoutMs` elapses — a cycle that
105
- * failed before materializing must never wedge the button forever.
140
+ * failed before materializing must never wedge the button forever. While
141
+ * that wait is running, each of its own ticks also reads the cycle marker
142
+ * and hands it to the press's own `onCycle` callback, if it supplied one —
143
+ * that is the page's live "polling…" / per-source-chip feed, not a separate
144
+ * standing read.
145
+ *
146
+ * `versionPollMs`/`versionPollStepMs`/`versionPollMaxMs` govern the OTHER
147
+ * loop: a standing watcher that starts the moment a session key exists (a
148
+ * restored visit, or the first press that mints one) and keeps polling
149
+ * `feedVersion` for as long as the session lives, backing off from
150
+ * `versionPollMs` toward `versionPollMaxMs` while nothing changes and
151
+ * dropping back to `versionPollMs` the moment it does — refetching the feed
152
+ * and notifying every `onFeedUpdate` listener only on an actual version
153
+ * change. It never stops outright (a cycle triggered from another tab, or
154
+ * left running past a reload, still needs to reach this page), only ever
155
+ * slows down; `destroy()`/`revokeConsent()` are the only ways to stop it.
106
156
  */
107
157
  export function createNewsSession({
108
158
  fetchImpl = null, prefs = null,
109
159
  consentPrefKey = NEWS_START_PREF_KEY, sessionPrefKey = NEWS_SESSION_PREF_KEY,
110
160
  cyclePollMs = DEFAULT_CYCLE_POLL_MS, cycleWaitTimeoutMs = DEFAULT_CYCLE_WAIT_TIMEOUT_MS,
161
+ versionPollMs = DEFAULT_VERSION_POLL_MS, versionPollStepMs = DEFAULT_VERSION_POLL_STEP_MS,
162
+ versionPollMaxMs = DEFAULT_VERSION_POLL_MAX_MS,
111
163
  } = {}) {
112
164
  const doFetch = fetchImpl || ((...args) => globalThis.fetch(...args));
113
165
  const prefStore = prefs || (typeof globalThis !== "undefined" && globalThis.localStorage ? localStoragePrefStore() : memoryPrefStore());
@@ -116,14 +168,92 @@ export function createNewsSession({
116
168
  let consented = Boolean(sessionKey) && prefStore.get(consentPrefKey) === "on";
117
169
  let unavailable = false;
118
170
 
171
+ const feedUpdateListeners = new Set();
172
+ let versionWatcher = null;
173
+
174
+ /** The last `feedVersion` any code path in this session has actually
175
+ * confirmed — the watcher's own ticks update it, and so does a trigger's
176
+ * own settle-wait (`waitForFeedVersionBump`), which already polls the
177
+ * same number for its own reasons. Sharing one value across both means a
178
+ * press's own wait already having caught a cycle's bump leaves nothing
179
+ * for the standing watcher to rediscover moments later — without it, the
180
+ * watcher's independent bookkeeping would treat that same bump as a
181
+ * change of its own the next time it ticked, and needlessly refetch the
182
+ * feed a second time for a change the page already rendered. `null` means
183
+ * nothing has confirmed a number yet. */
184
+ let knownFeedVersion = null;
185
+
186
+ /** The standing loop: one `feedVersion` read per tick, refetching the feed
187
+ * and notifying listeners only when the number actually moved from what
188
+ * `knownFeedVersion` last confirmed. A failed tick (service unreachable)
189
+ * backs off exactly like a quiet one — this loop never throws and never
190
+ * blocks anything else the page does. */
191
+ function startVersionWatcher() {
192
+ if (versionWatcher || !sessionKey) return;
193
+ let intervalMs = versionPollMs;
194
+ let stopped = false;
195
+ let timer = null;
196
+ versionWatcher = {
197
+ stop() { stopped = true; if (timer) clearTimeout(timer); versionWatcher = null; },
198
+ };
199
+
200
+ function scheduleTick() {
201
+ timer = setTimeout(tick, intervalMs);
202
+ if (typeof timer?.unref === "function") timer.unref();
203
+ }
204
+
205
+ async function tick() {
206
+ if (stopped) return;
207
+ try {
208
+ const version = await readFeedVersion();
209
+ if (knownFeedVersion !== null && version !== knownFeedVersion) {
210
+ knownFeedVersion = version;
211
+ intervalMs = versionPollMs;
212
+ const feed = await readFeed();
213
+ for (const listener of feedUpdateListeners) { try { listener(feed); } catch { /* a listener's own bug never stops the loop */ } }
214
+ } else {
215
+ knownFeedVersion = version;
216
+ intervalMs = Math.min(versionPollMaxMs, intervalMs + versionPollStepMs);
217
+ }
218
+ } catch {
219
+ intervalMs = Math.min(versionPollMaxMs, intervalMs + versionPollStepMs);
220
+ }
221
+ if (!stopped) scheduleTick();
222
+ }
223
+
224
+ // The baseline read happens right away, not on the first timer tick —
225
+ // waiting a whole interval to find out where the count already stood
226
+ // would silently swallow a change that lands in that gap (a cycle this
227
+ // same press just started, or one still running from an earlier visit).
228
+ // Skipped entirely when a trigger already confirmed a number moments
229
+ // earlier — see knownFeedVersion above. Every tick after this one runs
230
+ // on the ordinary schedule.
231
+ (async () => {
232
+ if (knownFeedVersion === null) {
233
+ try { knownFeedVersion = await readFeedVersion(); } catch { knownFeedVersion = 0; }
234
+ }
235
+ if (!stopped) scheduleTick();
236
+ })();
237
+ }
238
+
239
+ function stopVersionWatcher() {
240
+ versionWatcher?.stop();
241
+ }
242
+
119
243
  function ensureSessionKey() {
120
244
  if (!sessionKey) {
121
245
  sessionKey = mintSessionKey();
122
246
  prefStore.set(sessionPrefKey, sessionKey);
123
247
  }
248
+ startVersionWatcher();
124
249
  return sessionKey;
125
250
  }
126
251
 
252
+ // A restored visit (a session key already in the pref store) starts the
253
+ // standing loop right away — nothing here waited for a press, because the
254
+ // consent that authorised the loop already happened on an earlier visit.
255
+ startVersionWatcher();
256
+
127
257
  /** Every request funnels through here: a thrown/rejected fetch or a 5xx
128
258
  * both mean the service itself is unreachable, and the flag this sets is
129
259
  * what the page reads to show feed-and-chat-unavailable and disable its
@@ -167,10 +297,11 @@ export function createNewsSession({
167
297
 
168
298
  async function postTrigger(kind, body) {
169
299
  const key = ensureSessionKey();
300
+ const serializedBody = JSON.stringify(body || {});
170
301
  const response = await request(`/api/sessions/${key}/${kind}`, {
171
302
  method: "POST",
172
- headers: { "content-type": "application/json" },
173
- body: JSON.stringify(body || {}),
303
+ headers: { "content-type": "application/json", [PAYLOAD_HASH_HEADER]: await sha256Hex(serializedBody) },
304
+ body: serializedBody,
174
305
  });
175
306
  // A 409 means a cycle this session already had running is still going —
176
307
  // never this call's own fault. Falling through to the version-wait below
@@ -183,20 +314,53 @@ export function createNewsSession({
183
314
  throw new Error(errBody?.error?.message || `${kind} trigger failed (status ${response.status})`);
184
315
  }
185
316
 
186
- async function waitForFeedVersionBump(versionBefore) {
317
+ /** `GET /api/meta/cycle` — the running cycle's own marker: `{cycleId,
318
+ * kind, state, startedAt, sources, finishedAt?, reason?}`. Answers `null`
319
+ * before any cycle has ever run for this session (404) or once the
320
+ * session itself doesn't exist yet, never throws on a malformed value —
321
+ * a marker this module cannot parse is the same as no marker. */
322
+ async function readCycle() {
323
+ if (!sessionKey) return null;
324
+ const response = await request("/api/meta/cycle", { headers: { [SESSION_HEADER]: sessionKey } });
325
+ if (response.status === 404) return null;
326
+ if (!response.ok) throw new Error(`GET /api/meta/cycle failed (status ${response.status})`);
327
+ const body = await readJsonOrNull(response);
328
+ if (typeof body?.value !== "string") return null;
329
+ try { return JSON.parse(body.value); } catch { return null; }
330
+ }
331
+
332
+ /** Waits for `feedVersion` to move past `versionBefore`, the same tight
333
+ * loop every trigger settles on. Keeps `knownFeedVersion` current on every
334
+ * read — this loop is a trigger's own dedicated watch over the exact
335
+ * number the standing loop also tracks, so the standing loop must never
336
+ * end up rediscovering, and re-rendering, a change this wait already
337
+ * caught. `onCycle`, when supplied, is handed the cycle marker (or
338
+ * `null`) on every tick — the press's own live "polling…" /
339
+ * per-source-chip feed, read here because this is the one loop already
340
+ * running for the whole span a cycle is in flight; a read that fails is
341
+ * reported as `null` rather than aborting the wait over a display-only
342
+ * read. */
343
+ async function waitForFeedVersionBump(versionBefore, onCycle) {
187
344
  const deadline = Date.now() + cycleWaitTimeoutMs;
188
345
  while (Date.now() < deadline) {
189
346
  await new Promise((resolve) => setTimeout(resolve, cyclePollMs));
190
347
  const version = await readFeedVersion();
348
+ knownFeedVersion = version;
349
+ if (typeof onCycle === "function") {
350
+ let marker = null;
351
+ try { marker = await readCycle(); } catch { marker = null; }
352
+ try { onCycle(marker); } catch { /* a caller's own bug never stops the wait */ }
353
+ }
191
354
  if (version > versionBefore) return version;
192
355
  }
193
356
  return versionBefore; // gives up; the caller renders whatever is there
194
357
  }
195
358
 
196
- async function triggerAndSettle(kind, body) {
359
+ async function triggerAndSettle(kind, body, { onCycle } = {}) {
197
360
  const versionBefore = await readFeedVersion();
361
+ knownFeedVersion = versionBefore;
198
362
  await postTrigger(kind, body);
199
- await waitForFeedVersionBump(versionBefore);
363
+ await waitForFeedVersionBump(versionBefore, onCycle);
200
364
  return readFeed();
201
365
  }
202
366
 
@@ -214,47 +378,119 @@ export function createNewsSession({
214
378
  * making a request at all. */
215
379
  async fetchFeed() { return readFeed(); },
216
380
 
217
- /** `GET /api/meta/feedVersion` — the cheap poll a standing refresh loop
218
- * reads. Exposed for that loop to use; this module never runs one on
219
- * its own beyond the one-shot wait inside `triggerAndSettle`. */
381
+ /** `GET /api/meta/feedVersion` — the cheap poll the standing refresh
382
+ * loop reads on its own. Exposed too, for a caller that wants a one-off
383
+ * read outside that loop. */
220
384
  async fetchFeedVersion() { return readFeedVersion(); },
221
385
 
386
+ /** `GET /api/meta/cycle` — the cycle marker, for a caller that wants a
387
+ * one-off read of the current or most recent cycle's progress outside
388
+ * a trigger's own `onCycle` callback (a boot-time check, say). */
389
+ async fetchCycle() { return readCycle(); },
390
+
391
+ /** Subscribes to the standing refresh loop: `callback(feed)` fires every
392
+ * time `feedVersion` actually moves, with the freshly re-fetched feed
393
+ * already in hand. Returns an unsubscribe function. The loop itself
394
+ * runs independently of any subscriber — it starts the moment a
395
+ * session key exists, subscribed or not — so a page that boots after
396
+ * the loop already started still catches every later change. */
397
+ onFeedUpdate(callback) {
398
+ feedUpdateListeners.add(callback);
399
+ return () => feedUpdateListeners.delete(callback);
400
+ },
401
+
222
402
  /** First press: mints the session key if this is a first visit, records
223
403
  * the start-consent preference, and runs one poll cycle. Every later
224
404
  * press of the same button is just another poll — there is no
225
- * recurring timer to distinguish a "first" press from any other. */
226
- async start(sources) {
405
+ * recurring timer to distinguish a "first" press from any other.
406
+ * `onCycle`, if supplied, is reported the cycle marker on every tick of
407
+ * the settle-wait (see `waitForFeedVersionBump`). */
408
+ async start(sources, { onCycle } = {}) {
227
409
  ensureSessionKey();
228
410
  prefStore.set(consentPrefKey, "on");
229
411
  consented = true;
230
- return triggerAndSettle("poll", sources?.length ? { sources } : {});
412
+ return triggerAndSettle("poll", sources?.length ? { sources } : {}, { onCycle });
231
413
  },
232
414
 
233
415
  /** One enrich cycle, on its own press — independent of `start()`'s
234
416
  * consent, the same way the old page's `addSource()` ran its own
235
- * preflight regardless of whether polling had started. */
236
- async enrich() {
237
- return triggerAndSettle("enrich", {});
417
+ * preflight regardless of whether polling had started. `fuzzy`, when
418
+ * supplied, rides the trigger body as `{fuzzy: 0|1}` — §3.15.2's
419
+ * per-request rung, read by the worker's own corpus enrichment source;
420
+ * omitted entirely (not defaulted here) when the caller doesn't pass
421
+ * it, so the worker's own mode/env/config resolution still applies. */
422
+ async enrich({ fuzzy, onCycle } = {}) {
423
+ return triggerAndSettle("enrich", fuzzy === undefined ? {} : { fuzzy: fuzzy ? 1 : 0 }, { onCycle });
238
424
  },
239
425
 
240
426
  /** The teach panel's free-text path. */
241
- async ingestText(text) {
242
- return triggerAndSettle("ingest", { text });
427
+ async ingestText(text, { onCycle } = {}) {
428
+ return triggerAndSettle("ingest", { text }, { onCycle });
243
429
  },
244
430
 
245
431
  /** The teach panel's uploaded-`.jsonl` path. */
246
- async ingestRows(rows) {
247
- return triggerAndSettle("ingest", { rows });
432
+ async ingestRows(rows, { onCycle } = {}) {
433
+ return triggerAndSettle("ingest", { rows }, { onCycle });
434
+ },
435
+
436
+ /** POST /api/sessions/:uuid/turn — the chat area's one call. Mints the
437
+ * session key on a first call the same way every trigger does; never
438
+ * requires `start()`'s own consent by itself, the page decides whether
439
+ * to gate its own control on that. `fuzzy`, when supplied, rides the
440
+ * body as `retrieval: {fuzzy}`, the same per-request override
441
+ * `enrich()` threads through its own trigger.
442
+ *
443
+ * Resolves to `{reply, factsTouched, citations, narration}`: `reply` is
444
+ * the turn's own answer text, already worded for display; `citations`
445
+ * is `factsTouched` read through the phrase layer (`turnCitationLines`),
446
+ * one line per row this turn wrote; `narration` is the turn's trace.
447
+ * Never touches the feed, and never claims anything about it — a
448
+ * learned row reaches `GET /api/feed` only at whatever cycle
449
+ * materializes next, which this call has no way to know or wait for.
450
+ *
451
+ * A 429 (this session's hourly turn cap) rejects with a message already
452
+ * worded for direct display, distinct from the generic unavailable
453
+ * wording — the rate limit is not the service being down. Any other
454
+ * non-2xx, a thrown fetch, or a 5xx all reject the same way every other
455
+ * request does and mark `unavailable` accordingly. */
456
+ async turn(text, { fuzzy } = {}) {
457
+ const key = ensureSessionKey();
458
+ const body = { text };
459
+ if (fuzzy !== undefined) body.retrieval = { fuzzy: Boolean(fuzzy) };
460
+ const serializedBody = JSON.stringify(body);
461
+ const response = await request(`/api/sessions/${key}/turn`, {
462
+ method: "POST",
463
+ headers: { "content-type": "application/json", [PAYLOAD_HASH_HEADER]: await sha256Hex(serializedBody) },
464
+ body: serializedBody,
465
+ });
466
+ if (response.status === 429) {
467
+ throw new Error("this session has sent a lot of chat messages this hour — wait a bit and try again.");
468
+ }
469
+ if (!response.ok) {
470
+ const errBody = await readJsonOrNull(response);
471
+ throw new Error(errBody?.error?.message || `the turn failed (status ${response.status})`);
472
+ }
473
+ const parsed = await readJsonOrNull(response);
474
+ const factsTouched = Array.isArray(parsed?.factsTouched) ? parsed.factsTouched : [];
475
+ return {
476
+ reply: typeof parsed?.reply === "string" ? parsed.reply : "",
477
+ factsTouched,
478
+ citations: turnCitationLines(factsTouched),
479
+ narration: typeof parsed?.narration === "string" ? parsed.narration : "",
480
+ };
248
481
  },
249
482
 
250
483
  /** Purges every row and meta entry this session's key reaches, then
251
484
  * discards the key and the consent preference regardless of whether
252
485
  * the purge itself succeeded — the visitor's own pointer to any
253
486
  * residue is gone either way, the same reasoning `deleteAll`'s own
254
- * sharp edge documents. */
487
+ * sharp edge documents. Stops the standing refresh loop first: there is
488
+ * nothing left for it to watch. */
255
489
  async revokeConsent() {
256
490
  const key = sessionKey;
257
491
  let error = null;
492
+ stopVersionWatcher();
493
+ knownFeedVersion = null; // a later start() mints a different key with its own numbering from zero
258
494
  if (key) {
259
495
  try {
260
496
  const backend = createHttpRowBackend({ apiBase: "/", sessionKey: key, fetchImpl: doFetch });
@@ -273,9 +509,9 @@ export function createNewsSession({
273
509
  return { ok: !error, error };
274
510
  },
275
511
 
276
- /** Nothing to tear down — kept for the same lifecycle shape every other
277
- * page's session exposes. */
278
- destroy() {},
512
+ /** Stops the standing refresh loop — a page tearing itself down (or a
513
+ * test moving on to the next case) leaves nothing still polling. */
514
+ destroy() { stopVersionWatcher(); },
279
515
  };
280
516
  }
281
517
 
@@ -10,9 +10,11 @@ export async function loadGraph(config, source) {
10
10
  const graph = parseEntities(payload);
11
11
  if (!graph.individuals.length) {
12
12
  // Honest miss, never a stack: a fresh repo simply has no graph yet (the chat
13
- // session itself creates one as the conversation folds in).
13
+ // session itself creates one as the conversation folds in). A caller with
14
+ // no graphFile at all (no code domain configured, ever) reads the same:
15
+ // `config?.graphFile` in the message below just names nothing.
14
16
  const e = new ToolError(
15
- `the graph at ${config.graphFile} is empty — no entities to answer from yet ` +
17
+ `the graph at ${config?.graphFile} is empty — no entities to answer from yet ` +
16
18
  "(this repo starts with no graph; the chat session folds the conversation into one).",
17
19
  );
18
20
  // An empty CODE graph is not an empty world: a caller that can still answer