@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.
@@ -1,59 +1,62 @@
1
- // news-browser-entry.mjs — the esbuild entry for news.html's engine
1
+ // news-browser-entry.mjs — the esbuild entry for news.html's bundle
2
2
  // (public/news-browser.bundle.js, built by scripts/build-news-bundle.mjs).
3
3
  //
4
- // news.html is the scheduled-ingestion demo: one in-memory Backend-B store,
5
- // seeded from chat-seed.json exactly as chat.html and research.html are,
6
- // that then grows through the news capability (src/services/news.mjs) —
7
- // polling contemporary sources, ranking what does not ground, walking
8
- // knowledge-base sources to close the gap, and building the fact-churn feed —
9
- // all over the SAME library contract the CLI's `tmct news` verb runs.
4
+ // news.html carries no engine and no seed. Every fact this page ever shows
5
+ // came from a poll, an enrich pass or a teach upload that ran server-side, in
6
+ // the news worker Lambda, against this session's own row partition — the
7
+ // same `pollNewsSources`/`enrichTopTerms`/`buildFeed` calls the CLI's `tmct
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 and turn
10
+ // services' routes, and hand the result to the page's own render code
11
+ // (src/services/news-viz.mjs's inline script). Nothing here parses a feed,
12
+ // extracts a fact, ranks a term, or renders an answer.
10
13
  //
11
- // The one rule every method below honours: NOTHING here calls a fetcher
12
- // until the visitor presses something. `start()` (or a returning visit's own
13
- // `start()` replay) is the press that also arms the recurring timer;
14
- // `poll()`/`pollOnce()`/`enrich()`/`addSource()` each run one round of
15
- // requests on their own press and schedule nothing, the same reasoning that
16
- // lets pasting a URL and pressing "add" authorise its own preflight;
17
- // `replayFixture()` never touches the network at all — it re-runs the exact
18
- // ingest pipeline over an already-downloaded fixture body.
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.
19
21
  //
20
- // The start-consent PREFERENCE (which localStorage key, and whether to persist
21
- // at all) is a page concern, not this session's — the same split
22
- // chat-page-viz.mjs's own WIKI_MODE_KEY draws between the page's own storage
23
- // and chat-browser-entry.mjs's pure session. `prefs` here defaults to a real
24
- // localStorage-backed store when one exists (so a caller doing nothing extra
25
- // still gets persistence), and is fully injectable for tests, which never
26
- // touch a real browser storage API.
22
+ // The one rule every method below honours: NOTHING here calls the row
23
+ // service until the visitor presses something, unless a session key already
24
+ // exists from a previous visit (a reload restores that session's last
25
+ // materialized feed with one read, per the plan's own reload contract).
26
+ // `start()` is the first press — it mints the key, records consent, and
27
+ // runs a poll. `enrich()`/`ingestText()`/`ingestRows()` each run their own
28
+ // trigger on their own press, independent of `start()`'s consent, the same
29
+ // way the in-page engine's `addSource()` used to run its own preflight.
27
30
  //
28
- // Gitignored, Pages-demo-site-only output — scripts/build-demo-site.mjs will
29
- // build it fresh on every deploy once news.html joins DEMO_PAGES (a later
30
- // round), never committed, the same posture every sibling *-browser-entry.mjs
31
- // documents for its own output.
32
-
33
- import { createInMemoryStore, applySeedPayload, loadMemory, readFactRows, appendFacts, removeFacts, normFactTerm, normFactPredicate } from "../../adapters/memory/core.mjs";
34
- import { factIdFor } from "../../domain/hash.mjs";
35
- import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
36
- import { ingestText, setIngestYield } from "../../services/extract-facts.mjs";
37
- import { isNewsProvenance } from "../../domain/news-feed.mjs";
38
- import {
39
- resolveNewsConfig, createNewsState, pollNewsSources, enrichTopTerms, buildFeed,
40
- ingestUploadedFactRows, isVocabGroundedTerm, filterRankedTermEntries,
41
- } from "../../services/news.mjs";
42
- import { rankedTerms, ledgerFromPayload, bumpTerms, ledgerPayload } from "../../domain/term-ledger.mjs";
43
- import {
44
- newsSourceRecords, normalizeNewsSourceIds, createNewsFetcher, preflightNewsUrl, registerNewsSource,
45
- } from "../../adapters/corpus/news-sources.mjs";
46
- import { detectFeedFormat, parseFeed, normalizeFeedItems, stripMarkup } from "../../domain/feed-normalize.mjs";
47
- import { DEFAULT_MIN_INTERVAL_MS } from "../../adapters/corpus/courtesy.mjs";
48
- import { getResearchProvider } from "../../adapters/corpus/wikipedia-live.mjs";
49
- import { registerWinkModel } from "../../adapters/wink-model.mjs";
50
- import { openPersistedStore } from "./idb-persist.mjs";
51
- import { publishTmctSurface } from "./tmct-surface.mjs";
31
+ // Gitignored, Pages-demo-site-only output — scripts/build-demo-site.mjs
32
+ // builds it fresh on every deploy, never committed, the same posture every
33
+ // sibling *-browser-entry.mjs documents for its own output.
52
34
 
53
- /** The localStorage key the shipped page persists start-consent under —
54
- * exported so the page's own inline script and a test can both name it
55
- * without retyping the string. */
35
+ import { createHttpRowBackend } from "./http-row-backend.mjs";
36
+ import { publishTmctSurface } from "./tmct-surface.mjs";
37
+ import { factSentence, findingCaveat } from "../../domain/fact-phrase.mjs";
38
+
39
+ const SESSION_HEADER = "x-tmct-session";
40
+ const DEFAULT_CYCLE_POLL_MS = 400;
41
+ const DEFAULT_CYCLE_WAIT_TIMEOUT_MS = 20_000;
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
+
53
+ /** The localStorage keys the shipped page persists under — exported so the
54
+ * page's own inline script and a test can both name them without
55
+ * retyping the string. `NEWS_SESSION_PREF_KEY` is the ONE fact beyond the
56
+ * consent preference this page ever keeps locally: a random session
57
+ * pointer, never a fact. */
56
58
  export const NEWS_START_PREF_KEY = "tmct.news.started";
59
+ export const NEWS_SESSION_PREF_KEY = "tmct.news.sessionKey";
57
60
 
58
61
  function localStoragePrefStore() {
59
62
  return {
@@ -74,472 +77,442 @@ function memoryPrefStore() {
74
77
  };
75
78
  }
76
79
 
77
- function resolveNowMs() {
78
- return Date.now();
80
+ function mintSessionKey() {
81
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
82
+ throw new Error("no UUIDv4 source available (crypto.randomUUID is missing)");
79
83
  }
80
84
 
81
- function isoNow() {
82
- return new Date().toISOString();
85
+ async function readJsonOrNull(response) {
86
+ try { return await response.json(); } catch { return null; }
83
87
  }
84
88
 
85
- const POLL_FLOOR_MINUTES = 5;
86
-
87
- function clampPollMinutesLocal(n) {
88
- const v = Number(n);
89
- if (!Number.isFinite(v)) return POLL_FLOOR_MINUTES;
90
- const floored = Math.max(0, Math.floor(v));
91
- return floored === 0 ? 0 : Math.max(POLL_FLOOR_MINUTES, floored);
92
- }
89
+ const EMPTY_FEED = Object.freeze({
90
+ items: [], rankedTerms: [], stats: { graphSize: 0, factsFromNews: 0 }, sourceStatus: [], requestLog: [], builtAt: null,
91
+ });
93
92
 
94
- /** The wikimedia-feed body shape (`{ news: [...] }` or `{ mostread: {
95
- * articles: [...] } }`) turned into the same raw-item shape
96
- * createNewsFetcher's own network path builds — the pure half of that
97
- * adapter's private fetchWikimediaFeed, restated here because a fixture
98
- * replay never calls the network wrapper that owns it. Kept intentionally
99
- * small: only the mapping a fixture-replay demo button needs, never the
100
- * courtesy-gated fetch itself. */
101
- function wikimediaFixtureRawItems(body) {
102
- const articles = Array.isArray(body?.news)
103
- ? body.news.flatMap((story) => (Array.isArray(story?.links) ? story.links : []))
104
- : Array.isArray(body?.mostread?.articles)
105
- ? body.mostread.articles
106
- : [];
107
- return articles.map((a) => ({
108
- guid: a?.wikibase_item || a?.normalizedtitle || a?.title || "",
109
- title: stripMarkup(a?.normalizedtitle || a?.displaytitle || a?.title || ""),
110
- url: a?.content_urls?.desktop?.page || "",
111
- summary: stripMarkup(a?.extract || ""),
112
- publishedAt: "",
113
- }));
93
+ /** One non-empty line per row: an uploaded `.jsonl` file is exactly this,
94
+ * and the teach panel's own "example: facts" button fills the textarea with
95
+ * the same shape. An unparseable line is dropped rather than thrown — the
96
+ * ingest trigger downgrades whatever rows do arrive, so a stray typo in one
97
+ * line should not cost every other line in the file. */
98
+ export function parseJsonlRows(text) {
99
+ const rows = [];
100
+ for (const line of String(text || "").split("\n")) {
101
+ const trimmed = line.trim();
102
+ if (!trimmed) continue;
103
+ try { rows.push(JSON.parse(trimmed)); } catch { /* skipped, never thrown */ }
104
+ }
105
+ return rows;
114
106
  }
115
107
 
116
- /** A fixture body's raw items, for whichever wire shape the demo buttons
117
- * ship: `format` names it explicitly so this never has to guess. */
118
- function fixtureRawItems(format, body) {
119
- if (format === "wikimedia-feed") return wikimediaFixtureRawItems(body);
120
- return parseFeed(body, { format });
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
+ });
121
120
  }
122
121
 
123
122
  /**
124
- * The graph-growing session over the real news capability (news.mjs), pure
125
- * except for the fetches `start()`/`poll()`/`pollOnce()`/`enrich()`/
126
- * `addSource()` themselves trigger — each one a press the visitor made.
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 }`.
127
+ *
128
+ * `fetchImpl` defaults to the ambient `fetch`, so a page never has to pass
129
+ * one; every path this module requests is root-relative ("/api/…"), which a
130
+ * browser resolves against its own origin — the same-origin CloudFront
131
+ * behaviour §3.7 draws. A test hands in a `fetchImpl` that resolves those
132
+ * same paths against a running `local.mjs` double instead.
127
133
  *
128
- * Returns `{ memoryDir, phase, consented, busy, metrics, nextPollAt, config,
129
- * requestLog, health, start, poll, pollOnce, stopPolling, enrich, buildFeed,
130
- * stats, rank, addSource, setInterval, ingestText, ingestFile, replayFixture,
131
- * revokeConsent, destroy }`.
134
+ * `cyclePollMs`/`cycleWaitTimeoutMs` govern the one polling loop a trigger's
135
+ * own press runs: after its 202, waiting for `feedVersion` to move past
136
+ * where it stood before that trigger, so the button that fired it can settle
137
+ * once the cycle it started has actually materialized. It gives up and
138
+ * renders whatever is there once `cycleWaitTimeoutMs` elapses — a cycle that
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.
132
155
  */
133
156
  export function createNewsSession({
134
- seedPayload = null, vocabSeeded = false, fetchImpl = null, now = isoNow,
135
- prefs = null, prefKey = NEWS_START_PREF_KEY, yieldToHost,
157
+ fetchImpl = null, prefs = null,
158
+ consentPrefKey = NEWS_START_PREF_KEY, sessionPrefKey = NEWS_SESSION_PREF_KEY,
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,
136
162
  } = {}) {
137
- // Grounding one article is seconds of straight-line work, and the page has
138
- // only the one thread. A macrotask between candidates lets it paint, answer
139
- // a click and keep the "polling…" affordance honest instead of going
140
- // unresponsive mid-poll. A Node caller gets no yield and pays nothing.
141
- setIngestYield(yieldToHost === undefined
142
- ? (typeof document === "undefined" ? null : () => new Promise((resolve) => setTimeout(resolve, 0)))
143
- : yieldToHost);
144
-
145
- const memoryDir = createInMemoryStore();
146
- applySeedPayload(memoryDir, seedPayload);
147
-
148
- // Folding the seeded store is seconds of main-thread work in a browser,
149
- // and every session verb reads rows — uncached, a 30-item feed render
150
- // folds the whole store once per item and freezes the page for minutes.
151
- // One fold per write epoch keeps every read on the same rows.
152
- let foldedRows = null;
153
- const store = {
154
- loadMemory,
155
- readFactRows(memory) {
156
- if (!foldedRows) foldedRows = readFactRows(memory);
157
- return foldedRows;
158
- },
159
- async appendFacts(...args) {
160
- foldedRows = null;
161
- return appendFacts(...args);
162
- },
163
- async removeFacts(...args) {
164
- foldedRows = null;
165
- return removeFacts(...args);
166
- },
167
- };
168
- const cache = { rows: null };
169
- let lexicon = loadLexicon();
170
- let config = resolveNewsConfig();
171
- const state = createNewsState();
172
163
  const doFetch = fetchImpl || ((...args) => globalThis.fetch(...args));
173
-
174
164
  const prefStore = prefs || (typeof globalThis !== "undefined" && globalThis.localStorage ? localStoragePrefStore() : memoryPrefStore());
175
- let consented = prefStore.get(prefKey) === "on";
176
-
177
- let phase = "seeded"; // the page-level "seeding" state (S0) precedes this session existing at all
178
- let timer = null;
179
- // Set by revokeConsent, cleared by the next action that puts content back.
180
- // While it holds, buildFeed answers with nothing rather than falling back to
181
- // the seed graph: a visitor who pressed "stop & forget" asked for an empty
182
- // feed, and seed-derived cards in its place read as articles that survived
183
- // the purge.
184
- let forgotten = false;
185
- // Raised by stopPolling(), lowered when the next cycle starts. The ingest
186
- // loops read it at their own awaited yield points, so a stop lands between
187
- // whole articles and never half-way through folding one.
188
- let stopRequested = false;
189
- let cycleRunning = false;
190
- const bootMs = resolveNowMs();
191
- const metrics = { timeToFirstArticleMs: null, timeToFirstCompletePollMs: null };
192
- let nextPollAt = "";
193
-
194
- const validators = new Map();
195
- const fetchersById = new Map();
196
- function rebuildFetchers() {
197
- fetchersById.clear();
198
- for (const id of normalizeNewsSourceIds(config.sources)) {
199
- const record = newsSourceRecords().find((r) => r.id === id);
200
- if (!record) continue;
201
- fetchersById.set(id, createNewsFetcher(record, { fetchImpl: doFetch, validators, now }));
165
+
166
+ let sessionKey = prefStore.get(sessionPrefKey) || null;
167
+ let consented = Boolean(sessionKey) && prefStore.get(consentPrefKey) === "on";
168
+ let unavailable = false;
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
202
  }
203
- }
204
- rebuildFetchers();
205
203
 
206
- const providers = {
207
- newsFetchers: fetchersById,
208
- getResearchProvider: ({ source } = {}) => getResearchProvider({ source }),
209
- preflightNewsUrl: (url) => preflightNewsUrl(url, { fetchImpl: doFetch }),
210
- };
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
+ }
211
222
 
212
- function ctx() {
213
- return { memoryDir, store, cache, lexicon, config, state, providers, now, shouldAbort: () => stopRequested };
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
+ })();
214
236
  }
215
237
 
216
- function clearTimer() {
217
- if (timer !== null) { clearTimeout(timer); timer = null; }
218
- nextPollAt = "";
238
+ function stopVersionWatcher() {
239
+ versionWatcher?.stop();
219
240
  }
220
241
 
221
- function armTimer() {
222
- clearTimer();
223
- if (!consented || !config.pollMinutes) return;
224
- const delayMs = config.pollMinutes * 60000;
225
- nextPollAt = new Date(resolveNowMs() + delayMs).toISOString();
226
- timer = setTimeout(() => { runCycle({ armNext: true }).catch(() => {}); }, delayMs);
242
+ function ensureSessionKey() {
243
+ if (!sessionKey) {
244
+ sessionKey = mintSessionKey();
245
+ prefStore.set(sessionPrefKey, sessionKey);
246
+ }
247
+ startVersionWatcher();
248
+ return sessionKey;
227
249
  }
228
250
 
229
- async function noteFirstArticle() {
230
- if (metrics.timeToFirstArticleMs !== null) return;
231
- const feed = await buildFeed(ctx());
232
- if (feed.items.length) metrics.timeToFirstArticleMs = resolveNowMs() - bootMs;
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
+
256
+ /** Every request funnels through here: a thrown/rejected fetch or a 5xx
257
+ * both mean the service itself is unreachable, and the flag this sets is
258
+ * what the page reads to show feed-and-chat-unavailable and disable its
259
+ * controls. A later request that actually gets a response under 500
260
+ * clears it again — the same session object recovers on its own once the
261
+ * service answers, without needing a page reload. */
262
+ async function request(path, init) {
263
+ let response;
264
+ try {
265
+ response = await doFetch(path, init);
266
+ } catch (error) {
267
+ unavailable = true;
268
+ throw new Error(`could not reach the news service: ${error.message}`);
269
+ }
270
+ if (response.status >= 500) {
271
+ unavailable = true;
272
+ throw new Error(`the news service failed (status ${response.status})`);
273
+ }
274
+ unavailable = false;
275
+ return response;
233
276
  }
234
277
 
235
- async function runPollCycle() {
236
- forgotten = false;
237
- cycleRunning = true;
238
- phase = "polling";
239
- const result = await pollNewsSources(ctx());
240
- // The cycle's ingest writes through core appendFact directly, never the
241
- // wrapping store, so the fold cache must drop here by hand.
242
- foldedRows = null;
243
- cache.rows = null;
244
- if (metrics.timeToFirstCompletePollMs === null) metrics.timeToFirstCompletePollMs = resolveNowMs() - bootMs;
245
- phase = "grounding";
246
- await noteFirstArticle();
247
- return result;
278
+ async function readFeed() {
279
+ if (!sessionKey) return { ...EMPTY_FEED, missing: true };
280
+ const response = await request("/api/feed", { headers: { [SESSION_HEADER]: sessionKey } });
281
+ if (response.status === 404) return { ...EMPTY_FEED, missing: true };
282
+ if (!response.ok) throw new Error(`GET /api/feed failed (status ${response.status})`);
283
+ const body = await readJsonOrNull(response);
284
+ return { ...EMPTY_FEED, ...(body?.feed || {}), missing: false };
248
285
  }
249
286
 
250
- async function runEnrichCycle({ armNext = true } = {}) {
251
- forgotten = false;
252
- cycleRunning = true;
253
- phase = "enriching";
254
- const result = await enrichTopTerms(ctx());
255
- foldedRows = null;
256
- cache.rows = null;
257
- phase = "idle";
258
- cycleRunning = false;
259
- if (armNext) armTimer();
260
- return result;
287
+ async function readFeedVersion() {
288
+ if (!sessionKey) return 0;
289
+ const response = await request("/api/meta/feedVersion", { headers: { [SESSION_HEADER]: sessionKey } });
290
+ if (response.status === 404) return 0;
291
+ if (!response.ok) throw new Error(`GET /api/meta/feedVersion failed (status ${response.status})`);
292
+ const body = await readJsonOrNull(response);
293
+ const n = Number(body?.value);
294
+ return Number.isFinite(n) ? n : 0;
261
295
  }
262
296
 
263
- /** One poll-then-enrich pass, with the stop flag lowered first so a cycle
264
- * the visitor asked for is never cancelled by an older stop. `armNext`
265
- * false runs the pass without scheduling another — what "poll once"
266
- * means. */
267
- async function runCycle({ armNext } = {}) {
268
- stopRequested = false;
269
- try {
270
- const poll = await runPollCycle();
271
- const enrich = await runEnrichCycle({ armNext });
272
- return { poll, enrich };
273
- } finally {
274
- cycleRunning = false;
275
- stopRequested = false;
297
+ async function postTrigger(kind, body) {
298
+ const key = ensureSessionKey();
299
+ const response = await request(`/api/sessions/${key}/${kind}`, {
300
+ method: "POST",
301
+ headers: { "content-type": "application/json" },
302
+ body: JSON.stringify(body || {}),
303
+ });
304
+ // A 409 means a cycle this session already had running is still going —
305
+ // never this call's own fault. Falling through to the version-wait below
306
+ // still settles correctly once THAT cycle materializes.
307
+ if (response.status === 409 || response.status === 202) {
308
+ const parsed = response.status === 202 ? await readJsonOrNull(response) : null;
309
+ return { cycleId: parsed?.cycleId || null };
276
310
  }
311
+ const errBody = await readJsonOrNull(response);
312
+ throw new Error(errBody?.error?.message || `${kind} trigger failed (status ${response.status})`);
277
313
  }
278
314
 
279
- return {
280
- memoryDir,
281
- get phase() { return phase; },
282
- get consented() { return consented; },
283
- get metrics() { return { ...metrics }; },
284
- get nextPollAt() { return nextPollAt; },
285
- get config() { return { ...config }; },
286
- get requestLog() { return state.requestLog; },
287
- get health() { return state.health; },
288
-
289
- /** First run: records the start-consent preference. Every run (first or
290
- * a returning visit's own replay): one poll cycle, then one enrich
291
- * cycle, then the timer arms for the next one — "poll on load" for a
292
- * returning visit is exactly this same call. */
293
- async start() {
294
- consented = true;
295
- prefStore.set(prefKey, "on");
296
- return runCycle({ armNext: true });
297
- },
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
+ }
298
329
 
299
- /** One poll cycle, now, on its own: the click IS the authorisation for
300
- * that one round of requests, the same way addSource's own preflight
301
- * is. It never records the start preference and never schedules
302
- * another, so "poll once" really does mean once. */
303
- async poll() {
304
- stopRequested = false;
305
- try {
306
- return await runPollCycle();
307
- } finally {
308
- cycleRunning = false;
309
- stopRequested = false;
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) {
342
+ const deadline = Date.now() + cycleWaitTimeoutMs;
343
+ while (Date.now() < deadline) {
344
+ await new Promise((resolve) => setTimeout(resolve, cyclePollMs));
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 */ }
310
351
  }
311
- },
312
-
313
- /** One poll-then-enrich pass on demand, scheduling nothing after it. */
314
- async pollOnce() {
315
- return runCycle({ armNext: false });
316
- },
317
-
318
- /** A manual "enrich now": one lookup round over the terms the feed could
319
- * not ground, scheduling nothing after it. */
320
- async enrich() {
321
- stopRequested = false;
322
- return runEnrichCycle({ armNext: false });
323
- },
324
-
325
- /** Stops polling: the recurring timer is cancelled, and a cycle already
326
- * running abandons at its next yield point — between whole articles,
327
- * never part-way through folding one, so nothing half-ingested lands. */
328
- stopPolling() {
329
- stopRequested = true;
330
- clearTimer();
331
- return { wasRunning: cycleRunning };
332
- },
333
-
334
- /** True while a poll or enrich cycle is mid-flight. */
335
- get busy() { return cycleRunning; },
336
-
337
- async buildFeed() {
338
- if (forgotten) return { items: [], seedFallback: false, builtAt: typeof now === "function" ? now() : now };
339
- return buildFeed(ctx());
340
- },
352
+ if (version > versionBefore) return version;
353
+ }
354
+ return versionBefore; // gives up; the caller renders whatever is there
355
+ }
341
356
 
342
- /** The two whole-graph counts the dashboard shows: every fact the store
343
- * holds, and the subset a news, fixture-replay or research ingest
344
- * contributed. Read off the same provenance rule the feed window uses,
345
- * so a tile and the feed can never disagree about what came from news. */
346
- async stats() {
347
- const memory = await store.loadMemory(memoryDir);
348
- const rows = store.readFactRows(memory);
349
- let fromNews = 0;
350
- for (const row of rows) if (isNewsProvenance(row.provenance)) fromNews += 1;
351
- return { graphSize: rows.length, factsFromNews: fromNews };
352
- },
357
+ async function triggerAndSettle(kind, body, { onCycle } = {}) {
358
+ const versionBefore = await readFeedVersion();
359
+ knownFeedVersion = versionBefore;
360
+ await postTrigger(kind, body);
361
+ await waitForFeedVersionBump(versionBefore, onCycle);
362
+ return readFeed();
363
+ }
353
364
 
354
- /** The fact rows behind a set of ids — a feed item's own `factIds`,
355
- * expanded so the page's `<details>` fact list can show each one as a
356
- * sentence and, nested under it, the raw triple record. */
357
- async factRows(ids) {
358
- const wanted = new Set(ids || []);
359
- if (!wanted.size) return [];
360
- const memory = await store.loadMemory(memoryDir);
361
- return store.readFactRows(memory).filter((r) => wanted.has(r.id));
365
+ return {
366
+ get sessionKey() { return sessionKey; },
367
+ get consented() { return consented; },
368
+ /** True once a request has failed to reach the service or answered 5xx;
369
+ * cleared again the moment a later request succeeds. */
370
+ get unavailable() { return unavailable; },
371
+
372
+ /** One `GET /api/feed` — cards, ranked terms, tiles, source panel status
373
+ * and the request log all come from here, and nothing else recomputes
374
+ * any of it client-side. Answers the empty document (never throws) when
375
+ * no session exists yet: a first visit renders the empty shell without
376
+ * making a request at all. */
377
+ async fetchFeed() { return readFeed(); },
378
+
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. */
382
+ async fetchFeedVersion() { return readFeedVersion(); },
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);
362
398
  },
363
399
 
364
- // filterRankedTermEntries can shrink the ledger's own limited slice, so
365
- // this asks for more than the display wants and trims afterward — the
366
- // panel's own count stays full even when a class term or a bare
367
- // quantity filters out.
368
- async rank({ limit = 20 } = {}) {
369
- const nowVal = typeof now === "function" ? now() : now;
370
- const ledger = ledgerFromPayload(state.ledger);
371
- const raw = rankedTerms(ledger, { limit: limit * 4, now: nowVal, ttlMs: config.negativeCacheTtlHours * 3600000 });
372
- const memory = await store.loadMemory(memoryDir);
373
- const rows = store.readFactRows(memory);
374
- return filterRankedTermEntries(rows, raw).slice(0, limit);
400
+ /** First press: mints the session key if this is a first visit, records
401
+ * the start-consent preference, and runs one poll cycle. Every later
402
+ * press of the same button is just another poll — there is no
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 } = {}) {
407
+ ensureSessionKey();
408
+ prefStore.set(consentPrefKey, "on");
409
+ consented = true;
410
+ return triggerAndSettle("poll", sources?.length ? { sources } : {}, { onCycle });
375
411
  },
376
412
 
377
- /** Add-by-URL: its own one-off preflight fetch, independent of the poll
378
- * cycle's start()-gated consent — pasting a URL and pressing "add" IS
379
- * the explicit action authorising that one request. */
380
- async addSource(url) {
381
- const result = await preflightNewsUrl(url, { fetchImpl: doFetch });
382
- if (!result.ok) return { ok: false, reason: result.reason };
383
- const id = `custom:${normFactTerm(url)}`;
384
- registerNewsSource({
385
- id, name: url, kind: "contemporary", format: result.format, url, homepage: url,
386
- licence: "unknown", browserVerified: "", minIntervalMs: DEFAULT_MIN_INTERVAL_MS, enabledByDefault: false,
387
- });
388
- config.sources = normalizeNewsSourceIds([...config.sources, id]);
389
- rebuildFetchers();
390
- return { ok: true, id, format: result.format };
413
+ /** One enrich cycle, on its own press — independent of `start()`'s
414
+ * consent, the same way the old page's `addSource()` ran its own
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 });
391
422
  },
392
423
 
393
- /** The sources panel's checkbox path: replaces the enabled contemporary
394
- * and kb id sets in one call. `config` is only ever handed out as a
395
- * copy, so a real setter is the one way a toggle can narrow what the
396
- * next poll fetches. */
397
- setSources(ids) {
398
- const normalized = normalizeNewsSourceIds(ids);
399
- const kindOf = new Map(newsSourceRecords().map((r) => [r.id, r.kind]));
400
- config.sources = normalized.filter((id) => kindOf.get(id) !== "kb");
401
- config.kbSources = normalized.filter((id) => kindOf.get(id) === "kb");
402
- rebuildFetchers();
403
- return { sources: [...config.sources], kbSources: [...config.kbSources] };
424
+ /** The teach panel's free-text path. */
425
+ async ingestText(text, { onCycle } = {}) {
426
+ return triggerAndSettle("ingest", { text }, { onCycle });
404
427
  },
405
428
 
406
- /** Re-arms the poll timer at `minutes`, clamped to the same floor the
407
- * service config enforces (0 disarms). */
408
- setInterval(minutes) {
409
- config.pollMinutes = clampPollMinutesLocal(minutes);
410
- armTimer();
411
- return config.pollMinutes;
429
+ /** The teach panel's uploaded-`.jsonl` path. */
430
+ async ingestRows(rows, { onCycle } = {}) {
431
+ return triggerAndSettle("ingest", { rows }, { onCycle });
412
432
  },
413
433
 
414
- /** The teach panel's free-text path: prose ingested under this upload's
415
- * own teach tag, the same tier a typed teach turn earns. */
416
- async ingestText(text, { fileLabel = "free-text" } = {}) {
417
- forgotten = false;
418
- const nowVal = typeof now === "function" ? now() : now;
419
- const sourceTag = `teach:upload:${fileLabel}@${nowVal}`;
420
- const result = await ingestText(text, {
421
- memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal, findings: true,
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),
422
462
  });
423
- cache.rows = null;
424
- foldedRows = null;
425
- return { facts: result.extracted.length + result.optimistic.length, sentences: result.sentences };
426
- },
427
-
428
- /** One uploaded file, routed by its own kind: `.txt`/`.md` prose through
429
- * the same free-text path as ingestText; `.json` (a lexicon-core-shaped
430
- * extra vocabulary) widens this session's own lexicon so later
431
- * grounding can resolve terms it could not before; `.jsonl` (fact rows)
432
- * through ingestUploadedFactRows's validate-and-downgrade before they
433
- * land, so an uploaded row can never claim trust it did not earn. */
434
- async ingestFile({ name, text, kind } = {}) {
435
- forgotten = false;
436
- const nowVal = typeof now === "function" ? now() : now;
437
- const resolvedKind = kind || (/\.jsonl$/i.test(name || "") ? "jsonl" : /\.json$/i.test(name || "") ? "json" : "prose");
438
- if (resolvedKind === "prose") {
439
- return this.ingestText(text, { fileLabel: name || "upload" });
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.");
440
465
  }
441
- if (resolvedKind === "json") {
442
- let extra;
443
- try { extra = JSON.parse(text); } catch { return { facts: 0, vocabAdded: 0, error: "not valid JSON" }; }
444
- lexicon = loadLexicon(extra);
445
- return { facts: 0, vocabAdded: (extra?.nouns ? Object.keys(extra.nouns).length : 0), error: null };
466
+ if (!response.ok) {
467
+ const errBody = await readJsonOrNull(response);
468
+ throw new Error(errBody?.error?.message || `the turn failed (status ${response.status})`);
446
469
  }
447
- // jsonl: one fact row per non-empty line.
448
- const rows = [];
449
- for (const line of String(text || "").split("\n")) {
450
- const trimmed = line.trim();
451
- if (!trimmed) continue;
452
- try { rows.push(JSON.parse(trimmed)); } catch { /* an unparseable line is skipped, never thrown */ }
453
- }
454
- const downgraded = ingestUploadedFactRows(rows, { fileLabel: name || "upload", now: nowVal })
455
- .filter((r) => r.subject && r.predicate && r.object);
456
- if (downgraded.length) { await appendFacts(memoryDir, downgraded); cache.rows = null;
457
- foldedRows = null; }
458
- return { facts: downgraded.length, vocabAdded: 0, error: null };
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
+ };
459
478
  },
460
479
 
461
- /** Replays a committed fixture's raw wire body through the exact live
462
- * parse -> ingest pipeline, under `news-fixture:<sourceId>@<itemId>`
463
- * provenance (the corpus-tier demo path) rather than `news:` — never a
464
- * network call, so it works with the network fully blocked. */
465
- async replayFixture(sourceId, { format, body } = {}) {
466
- forgotten = false;
467
- const nowVal = typeof now === "function" ? now() : now;
468
- const raw = fixtureRawItems(format, body);
469
- const items = normalizeFeedItems(sourceId, raw, { now: nowVal });
470
- let factsTotal = 0;
471
- for (const snapshot of items) {
472
- const text = [snapshot.title, snapshot.summary].filter(Boolean).join(". ");
473
- const sourceTag = `news-fixture:${sourceId}@${snapshot.id}`;
474
- const result = await ingestText(text, {
475
- memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal, findings: true,
476
- });
477
- const allFacts = [...result.extracted, ...result.optimistic];
478
- snapshot.factIds = allFacts.map((f) => factIdFor(normFactTerm(f.subject), normFactPredicate(f.predicate), normFactTerm(f.object)));
479
- factsTotal += allFacts.length;
480
-
481
- const vocabGroundedByTerm = new Map();
482
- for (const term of result.ungroundedCounts.keys()) vocabGroundedByTerm.set(term, isVocabGroundedTerm(lexicon, term));
483
- const ledger = ledgerFromPayload(state.ledger);
484
- bumpTerms(ledger, result.ungroundedCounts, snapshot.id, nowVal, vocabGroundedByTerm);
485
- state.ledger = ledgerPayload(ledger);
486
- }
487
- if (factsTotal) cache.rows = null;
488
- foldedRows = null;
489
- const existingIds = new Set(state.items.map((s) => s.id));
490
- state.items = [...state.items, ...items.filter((s) => !existingIds.has(s.id))];
491
- await noteFirstArticle();
492
- return { items: items.length, facts: factsTotal };
493
- },
494
-
495
- /** Forgets everything this session gathered: the start-consent
496
- * preference, the poll timer, every article snapshot, the term ledger,
497
- * the health and request logs, and every fact a news, fixture-replay or
498
- * enrichment ingest wrote into the graph. The next load of this page
499
- * reads back as first-visit, and the feed here and now is empty — a
500
- * visitor who pressed this asked for the articles to go, not just the
501
- * preference. The seed graph itself is untouched. */
480
+ /** Purges every row and meta entry this session's key reaches, then
481
+ * discards the key and the consent preference regardless of whether
482
+ * the purge itself succeeded — the visitor's own pointer to any
483
+ * residue is gone either way, the same reasoning `deleteAll`'s own
484
+ * sharp edge documents. Stops the standing refresh loop first: there is
485
+ * nothing left for it to watch. */
502
486
  async revokeConsent() {
487
+ const key = sessionKey;
488
+ let error = null;
489
+ stopVersionWatcher();
490
+ knownFeedVersion = null; // a later start() mints a different key with its own numbering from zero
491
+ if (key) {
492
+ try {
493
+ const backend = createHttpRowBackend({ apiBase: "/", sessionKey: key, fetchImpl: doFetch });
494
+ await backend.deleteAll();
495
+ await backend.close();
496
+ unavailable = false;
497
+ } catch (err) {
498
+ error = err.message;
499
+ unavailable = true;
500
+ }
501
+ }
502
+ prefStore.remove(consentPrefKey);
503
+ prefStore.remove(sessionPrefKey);
504
+ sessionKey = null;
503
505
  consented = false;
504
- forgotten = true;
505
- stopRequested = true;
506
- prefStore.remove(prefKey);
507
- clearTimer();
508
- phase = "seeded";
509
-
510
- const nowVal = typeof now === "function" ? now() : now;
511
- const memory = await store.loadMemory(memoryDir);
512
- const newsFactIds = store.readFactRows(memory)
513
- .filter((row) => isNewsProvenance(row.provenance))
514
- .map((row) => row.id);
515
- if (newsFactIds.length) await store.removeFacts(memoryDir, newsFactIds, { retractedAt: nowVal });
516
-
517
- const fresh = createNewsState();
518
- state.items = fresh.items;
519
- state.ledger = fresh.ledger;
520
- state.health = fresh.health;
521
- state.requestLog = fresh.requestLog;
522
- state.metrics = fresh.metrics;
523
- state.lastPollAt = "";
524
- state.lastEnrichAt = "";
525
- metrics.timeToFirstArticleMs = null;
526
- metrics.timeToFirstCompletePollMs = null;
527
- cache.rows = null;
528
- foldedRows = null;
529
- return { factsRemoved: newsFactIds.length };
506
+ return { ok: !error, error };
530
507
  },
531
508
 
532
- /** Stops the poll timer and any running cycle without touching consent —
533
- * a test's own teardown, and a page's own unload hook. */
534
- destroy() { stopRequested = true; clearTimer(); },
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(); },
535
512
  };
536
513
  }
537
514
 
538
515
  publishTmctSurface({
539
516
  open: createNewsSession,
540
- page: {
541
- NEWS_START_PREF_KEY,
542
- registerWinkModel, openPersistedStore, normFactTerm,
543
- newsSourceRecords, detectFeedFormat,
544
- },
517
+ page: { NEWS_START_PREF_KEY, NEWS_SESSION_PREF_KEY, parseJsonlRows },
545
518
  });