@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.
- package/package.json +9 -2
- package/src/adapters/corpus/courtesy.mjs +67 -3
- package/src/adapters/corpus/dbpedia-lookup-live.mjs +8 -0
- package/src/adapters/corpus/wikidata-live.mjs +8 -0
- package/src/adapters/corpus/wikipedia-live.mjs +18 -0
- package/src/adapters/corpus/wiktionary-live.mjs +8 -0
- package/src/domain/source-breaker.mjs +259 -0
- package/src/services/chat.mjs +242 -77
- package/src/services/news-viz.mjs +213 -348
- package/src/services/news.mjs +41 -7
- package/src/services/p2p-room.mjs +35 -21
- package/src/surfaces/web/memory-ask-browser.bundle.js +135 -135
- package/src/surfaces/web/news-browser-entry.mjs +204 -464
|
@@ -1,59 +1,43 @@
|
|
|
1
|
-
// news-browser-entry.mjs — the esbuild entry for news.html's
|
|
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
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
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
|
|
12
|
-
// until the visitor presses something
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
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
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
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 {
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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
|
|
78
|
-
return
|
|
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
|
-
|
|
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
|
-
|
|
95
|
-
|
|
96
|
-
|
|
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
|
-
/**
|
|
117
|
-
*
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
|
125
|
-
*
|
|
126
|
-
*
|
|
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
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
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
|
-
|
|
135
|
-
|
|
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
|
|
178
|
-
let
|
|
179
|
-
|
|
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
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
-
|
|
217
|
-
|
|
218
|
-
|
|
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
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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
|
|
230
|
-
if (
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
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
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
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
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
-
|
|
281
|
-
get phase() { return phase; },
|
|
204
|
+
get sessionKey() { return sessionKey; },
|
|
282
205
|
get consented() { return consented; },
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
get
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
|
|
293
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
319
|
-
*
|
|
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
|
-
|
|
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
|
|
415
|
-
|
|
416
|
-
|
|
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
|
-
/**
|
|
429
|
-
|
|
430
|
-
|
|
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
|
-
/**
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
533
|
-
*
|
|
534
|
-
destroy() {
|
|
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
|
});
|