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