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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,59 +1,43 @@
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 service's five
10
+ // 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, or ranks a term.
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 one rule every method below honours: NOTHING here calls the row
15
+ // service until the visitor presses something, unless a session key already
16
+ // exists from a previous visit (a reload restores that session's last
17
+ // materialized feed with one read, per the plan's own reload contract).
18
+ // `start()` is the first press — it mints the key, records consent, and
19
+ // runs a poll. `enrich()`/`ingestText()`/`ingestRows()` each run their own
20
+ // trigger on their own press, independent of `start()`'s consent, the same
21
+ // way the in-page engine's `addSource()` used to run its own preflight.
19
22
  //
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.
27
- //
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.
23
+ // Gitignored, Pages-demo-site-only output — scripts/build-demo-site.mjs
24
+ // builds it fresh on every deploy, never committed, the same posture every
25
+ // sibling *-browser-entry.mjs documents for its own output.
32
26
 
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";
27
+ import { createHttpRowBackend } from "./http-row-backend.mjs";
51
28
  import { publishTmctSurface } from "./tmct-surface.mjs";
52
29
 
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. */
30
+ const SESSION_HEADER = "x-tmct-session";
31
+ const DEFAULT_CYCLE_POLL_MS = 400;
32
+ const DEFAULT_CYCLE_WAIT_TIMEOUT_MS = 20_000;
33
+
34
+ /** The localStorage keys the shipped page persists under — exported so the
35
+ * page's own inline script and a test can both name them without
36
+ * retyping the string. `NEWS_SESSION_PREF_KEY` is the ONE fact beyond the
37
+ * consent preference this page ever keeps locally: a random session
38
+ * pointer, never a fact. */
56
39
  export const NEWS_START_PREF_KEY = "tmct.news.started";
40
+ export const NEWS_SESSION_PREF_KEY = "tmct.news.sessionKey";
57
41
 
58
42
  function localStoragePrefStore() {
59
43
  return {
@@ -74,472 +58,228 @@ function memoryPrefStore() {
74
58
  };
75
59
  }
76
60
 
77
- function resolveNowMs() {
78
- return Date.now();
79
- }
80
-
81
- function isoNow() {
82
- return new Date().toISOString();
61
+ function mintSessionKey() {
62
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
63
+ throw new Error("no UUIDv4 source available (crypto.randomUUID is missing)");
83
64
  }
84
65
 
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);
66
+ async function readJsonOrNull(response) {
67
+ try { return await response.json(); } catch { return null; }
92
68
  }
93
69
 
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
- }));
114
- }
70
+ const EMPTY_FEED = Object.freeze({
71
+ items: [], rankedTerms: [], stats: { graphSize: 0, factsFromNews: 0 }, sourceStatus: [], requestLog: [], builtAt: null,
72
+ });
115
73
 
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 });
74
+ /** One non-empty line per row: an uploaded `.jsonl` file is exactly this,
75
+ * and the teach panel's own "example: facts" button fills the textarea with
76
+ * the same shape. An unparseable line is dropped rather than thrown — the
77
+ * ingest trigger downgrades whatever rows do arrive, so a stray typo in one
78
+ * line should not cost every other line in the file. */
79
+ export function parseJsonlRows(text) {
80
+ const rows = [];
81
+ for (const line of String(text || "").split("\n")) {
82
+ const trimmed = line.trim();
83
+ if (!trimmed) continue;
84
+ try { rows.push(JSON.parse(trimmed)); } catch { /* skipped, never thrown */ }
85
+ }
86
+ return rows;
121
87
  }
122
88
 
123
89
  /**
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.
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 }`.
127
93
  *
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 }`.
94
+ * `fetchImpl` defaults to the ambient `fetch`, so a page never has to pass
95
+ * one; every path this module requests is root-relative ("/api/…"), which a
96
+ * browser resolves against its own origin — the same-origin CloudFront
97
+ * behaviour §3.7 draws. A test hands in a `fetchImpl` that resolves those
98
+ * same paths against a running `local.mjs` double instead.
99
+ *
100
+ * `cyclePollMs`/`cycleWaitTimeoutMs` govern the one polling loop this module
101
+ * runs: after a trigger's own 202, waiting for `feedVersion` to move past
102
+ * where it stood before that trigger, so the button that fired it can settle
103
+ * once the cycle it started has actually materialized. It gives up and
104
+ * renders whatever is there once `cycleWaitTimeoutMs` elapses — a cycle that
105
+ * failed before materializing must never wedge the button forever.
132
106
  */
133
107
  export function createNewsSession({
134
- seedPayload = null, vocabSeeded = false, fetchImpl = null, now = isoNow,
135
- prefs = null, prefKey = NEWS_START_PREF_KEY, yieldToHost,
108
+ fetchImpl = null, prefs = null,
109
+ consentPrefKey = NEWS_START_PREF_KEY, sessionPrefKey = NEWS_SESSION_PREF_KEY,
110
+ cyclePollMs = DEFAULT_CYCLE_POLL_MS, cycleWaitTimeoutMs = DEFAULT_CYCLE_WAIT_TIMEOUT_MS,
136
111
  } = {}) {
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
112
  const doFetch = fetchImpl || ((...args) => globalThis.fetch(...args));
173
-
174
113
  const prefStore = prefs || (typeof globalThis !== "undefined" && globalThis.localStorage ? localStoragePrefStore() : memoryPrefStore());
175
- let consented = prefStore.get(prefKey) === "on";
176
114
 
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 = "";
115
+ let sessionKey = prefStore.get(sessionPrefKey) || null;
116
+ let consented = Boolean(sessionKey) && prefStore.get(consentPrefKey) === "on";
117
+ let unavailable = false;
193
118
 
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 }));
119
+ function ensureSessionKey() {
120
+ if (!sessionKey) {
121
+ sessionKey = mintSessionKey();
122
+ prefStore.set(sessionPrefKey, sessionKey);
202
123
  }
203
- }
204
- rebuildFetchers();
205
-
206
- const providers = {
207
- newsFetchers: fetchersById,
208
- getResearchProvider: ({ source } = {}) => getResearchProvider({ source }),
209
- preflightNewsUrl: (url) => preflightNewsUrl(url, { fetchImpl: doFetch }),
210
- };
211
-
212
- function ctx() {
213
- return { memoryDir, store, cache, lexicon, config, state, providers, now, shouldAbort: () => stopRequested };
124
+ return sessionKey;
214
125
  }
215
126
 
216
- function clearTimer() {
217
- if (timer !== null) { clearTimeout(timer); timer = null; }
218
- nextPollAt = "";
127
+ /** Every request funnels through here: a thrown/rejected fetch or a 5xx
128
+ * both mean the service itself is unreachable, and the flag this sets is
129
+ * what the page reads to show feed-and-chat-unavailable and disable its
130
+ * controls. A later request that actually gets a response under 500
131
+ * clears it again — the same session object recovers on its own once the
132
+ * service answers, without needing a page reload. */
133
+ async function request(path, init) {
134
+ let response;
135
+ try {
136
+ response = await doFetch(path, init);
137
+ } catch (error) {
138
+ unavailable = true;
139
+ throw new Error(`could not reach the news service: ${error.message}`);
140
+ }
141
+ if (response.status >= 500) {
142
+ unavailable = true;
143
+ throw new Error(`the news service failed (status ${response.status})`);
144
+ }
145
+ unavailable = false;
146
+ return response;
219
147
  }
220
148
 
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);
149
+ async function readFeed() {
150
+ if (!sessionKey) return { ...EMPTY_FEED, missing: true };
151
+ const response = await request("/api/feed", { headers: { [SESSION_HEADER]: sessionKey } });
152
+ if (response.status === 404) return { ...EMPTY_FEED, missing: true };
153
+ if (!response.ok) throw new Error(`GET /api/feed failed (status ${response.status})`);
154
+ const body = await readJsonOrNull(response);
155
+ return { ...EMPTY_FEED, ...(body?.feed || {}), missing: false };
227
156
  }
228
157
 
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;
158
+ async function readFeedVersion() {
159
+ if (!sessionKey) return 0;
160
+ const response = await request("/api/meta/feedVersion", { headers: { [SESSION_HEADER]: sessionKey } });
161
+ if (response.status === 404) return 0;
162
+ if (!response.ok) throw new Error(`GET /api/meta/feedVersion failed (status ${response.status})`);
163
+ const body = await readJsonOrNull(response);
164
+ const n = Number(body?.value);
165
+ return Number.isFinite(n) ? n : 0;
233
166
  }
234
167
 
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;
168
+ async function postTrigger(kind, body) {
169
+ const key = ensureSessionKey();
170
+ const response = await request(`/api/sessions/${key}/${kind}`, {
171
+ method: "POST",
172
+ headers: { "content-type": "application/json" },
173
+ body: JSON.stringify(body || {}),
174
+ });
175
+ // A 409 means a cycle this session already had running is still going —
176
+ // never this call's own fault. Falling through to the version-wait below
177
+ // still settles correctly once THAT cycle materializes.
178
+ if (response.status === 409 || response.status === 202) {
179
+ const parsed = response.status === 202 ? await readJsonOrNull(response) : null;
180
+ return { cycleId: parsed?.cycleId || null };
181
+ }
182
+ const errBody = await readJsonOrNull(response);
183
+ throw new Error(errBody?.error?.message || `${kind} trigger failed (status ${response.status})`);
248
184
  }
249
185
 
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;
186
+ async function waitForFeedVersionBump(versionBefore) {
187
+ const deadline = Date.now() + cycleWaitTimeoutMs;
188
+ while (Date.now() < deadline) {
189
+ await new Promise((resolve) => setTimeout(resolve, cyclePollMs));
190
+ const version = await readFeedVersion();
191
+ if (version > versionBefore) return version;
192
+ }
193
+ return versionBefore; // gives up; the caller renders whatever is there
261
194
  }
262
195
 
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;
276
- }
196
+ async function triggerAndSettle(kind, body) {
197
+ const versionBefore = await readFeedVersion();
198
+ await postTrigger(kind, body);
199
+ await waitForFeedVersionBump(versionBefore);
200
+ return readFeed();
277
201
  }
278
202
 
279
203
  return {
280
- memoryDir,
281
- get phase() { return phase; },
204
+ get sessionKey() { return sessionKey; },
282
205
  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() {
206
+ /** True once a request has failed to reach the service or answered 5xx;
207
+ * cleared again the moment a later request succeeds. */
208
+ get unavailable() { return unavailable; },
209
+
210
+ /** One `GET /api/feed` — cards, ranked terms, tiles, source panel status
211
+ * and the request log all come from here, and nothing else recomputes
212
+ * any of it client-side. Answers the empty document (never throws) when
213
+ * no session exists yet: a first visit renders the empty shell without
214
+ * making a request at all. */
215
+ async fetchFeed() { return readFeed(); },
216
+
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`. */
220
+ async fetchFeedVersion() { return readFeedVersion(); },
221
+
222
+ /** First press: mints the session key if this is a first visit, records
223
+ * the start-consent preference, and runs one poll cycle. Every later
224
+ * 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) {
227
+ ensureSessionKey();
228
+ prefStore.set(consentPrefKey, "on");
294
229
  consented = true;
295
- prefStore.set(prefKey, "on");
296
- return runCycle({ armNext: true });
297
- },
298
-
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;
310
- }
311
- },
312
-
313
- /** One poll-then-enrich pass on demand, scheduling nothing after it. */
314
- async pollOnce() {
315
- return runCycle({ armNext: false });
230
+ return triggerAndSettle("poll", sources?.length ? { sources } : {});
316
231
  },
317
232
 
318
- /** A manual "enrich now": one lookup round over the terms the feed could
319
- * not ground, scheduling nothing after it. */
233
+ /** One enrich cycle, on its own press — independent of `start()`'s
234
+ * consent, the same way the old page's `addSource()` ran its own
235
+ * preflight regardless of whether polling had started. */
320
236
  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
- },
341
-
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
- },
353
-
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));
362
- },
363
-
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);
375
- },
376
-
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 };
391
- },
392
-
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] };
404
- },
405
-
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;
237
+ return triggerAndSettle("enrich", {});
412
238
  },
413
239
 
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,
422
- });
423
- cache.rows = null;
424
- foldedRows = null;
425
- return { facts: result.extracted.length + result.optimistic.length, sentences: result.sentences };
240
+ /** The teach panel's free-text path. */
241
+ async ingestText(text) {
242
+ return triggerAndSettle("ingest", { text });
426
243
  },
427
244
 
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" });
440
- }
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 };
446
- }
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 };
245
+ /** The teach panel's uploaded-`.jsonl` path. */
246
+ async ingestRows(rows) {
247
+ return triggerAndSettle("ingest", { rows });
459
248
  },
460
249
 
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. */
250
+ /** Purges every row and meta entry this session's key reaches, then
251
+ * discards the key and the consent preference regardless of whether
252
+ * the purge itself succeeded — the visitor's own pointer to any
253
+ * residue is gone either way, the same reasoning `deleteAll`'s own
254
+ * sharp edge documents. */
502
255
  async revokeConsent() {
256
+ const key = sessionKey;
257
+ let error = null;
258
+ if (key) {
259
+ try {
260
+ const backend = createHttpRowBackend({ apiBase: "/", sessionKey: key, fetchImpl: doFetch });
261
+ await backend.deleteAll();
262
+ await backend.close();
263
+ unavailable = false;
264
+ } catch (err) {
265
+ error = err.message;
266
+ unavailable = true;
267
+ }
268
+ }
269
+ prefStore.remove(consentPrefKey);
270
+ prefStore.remove(sessionPrefKey);
271
+ sessionKey = null;
503
272
  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 };
273
+ return { ok: !error, error };
530
274
  },
531
275
 
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(); },
276
+ /** Nothing to tear down — kept for the same lifecycle shape every other
277
+ * page's session exposes. */
278
+ destroy() {},
535
279
  };
536
280
  }
537
281
 
538
282
  publishTmctSurface({
539
283
  open: createNewsSession,
540
- page: {
541
- NEWS_START_PREF_KEY,
542
- registerWinkModel, openPersistedStore, normFactTerm,
543
- newsSourceRecords, detectFeedFormat,
544
- },
284
+ page: { NEWS_START_PREF_KEY, NEWS_SESSION_PREF_KEY, parseJsonlRows },
545
285
  });