@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.
- package/README.md +12 -0
- 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/adapters/memory/core.mjs +7 -1
- package/src/adapters/memory/rows.mjs +18 -10
- package/src/adapters/source.mjs +12 -9
- package/src/domain/source-breaker.mjs +259 -0
- package/src/services/chat-page-viz.mjs +189 -26
- package/src/services/chat.mjs +242 -77
- package/src/services/ledger-viz.mjs +91 -6
- package/src/services/memory-panel-viz.mjs +12 -8
- package/src/services/news-viz.mjs +388 -348
- package/src/services/news.mjs +41 -7
- package/src/services/p2p-room.mjs +35 -21
- package/src/surfaces/web/chat-browser-entry.mjs +42 -5
- package/src/surfaces/web/http-row-backend.mjs +39 -0
- package/src/surfaces/web/ledger-browser-entry.mjs +30 -8
- package/src/surfaces/web/memory-ask-browser.bundle.js +135 -135
- package/src/surfaces/web/news-browser-entry.mjs +428 -455
- package/src/tools/graph-load.mjs +4 -2
|
@@ -1,59 +1,62 @@
|
|
|
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 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
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
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
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
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
|
|
29
|
-
//
|
|
30
|
-
//
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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
|
|
78
|
-
return
|
|
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
|
|
82
|
-
return
|
|
85
|
+
async function readJsonOrNull(response) {
|
|
86
|
+
try { return await response.json(); } catch { return null; }
|
|
83
87
|
}
|
|
84
88
|
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
-
/**
|
|
117
|
-
*
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
|
125
|
-
*
|
|
126
|
-
*
|
|
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
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
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
|
-
|
|
135
|
-
|
|
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
|
-
|
|
176
|
-
|
|
177
|
-
let
|
|
178
|
-
let
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
|
|
213
|
-
|
|
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
|
|
217
|
-
|
|
218
|
-
nextPollAt = "";
|
|
238
|
+
function stopVersionWatcher() {
|
|
239
|
+
versionWatcher?.stop();
|
|
219
240
|
}
|
|
220
241
|
|
|
221
|
-
function
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
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
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
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
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
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
|
-
|
|
314
|
-
|
|
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
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
return
|
|
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
|
-
/**
|
|
378
|
-
*
|
|
379
|
-
*
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
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
|
|
394
|
-
|
|
395
|
-
|
|
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
|
-
/**
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
/**
|
|
415
|
-
*
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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
|
-
|
|
424
|
-
|
|
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 (
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
448
|
-
const
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
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
|
-
/**
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
|
|
466
|
-
|
|
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
|
-
|
|
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
|
|
533
|
-
*
|
|
534
|
-
destroy() {
|
|
509
|
+
/** Stops the standing refresh loop — a page tearing itself down (or a
|
|
510
|
+
* test moving on to the next case) leaves nothing still polling. */
|
|
511
|
+
destroy() { stopVersionWatcher(); },
|
|
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
|
});
|