@polycode-projects/the-mechanical-code-talker 5.0.25 → 5.0.26
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 +74 -11
- package/bin/tmct.mjs +81 -0
- package/package.json +5 -1
- package/src/adapters/corpus/courtesy.mjs +91 -28
- package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
- package/src/adapters/corpus/news-sources.mjs +436 -0
- package/src/adapters/corpus/research-source.mjs +16 -3
- package/src/adapters/corpus/wiktionary-live.mjs +158 -0
- package/src/adapters/news-store.mjs +87 -0
- package/src/adapters/toml-config.mjs +18 -0
- package/src/domain/choice-question.mjs +275 -0
- package/src/domain/cli-verbs.mjs +20 -0
- package/src/domain/dialogue-acts.mjs +1 -0
- package/src/domain/el-classify.mjs +569 -0
- package/src/domain/fact-phrase.mjs +70 -0
- package/src/domain/feed-normalize.mjs +224 -0
- package/src/domain/grammar/ace.mjs +223 -7
- package/src/domain/grammar/lexicon-core.json +2 -0
- package/src/domain/memory/trust.mjs +15 -0
- package/src/domain/news-feed.mjs +219 -0
- package/src/domain/reasoning-config.mjs +56 -0
- package/src/domain/sprite-animation.mjs +20 -2
- package/src/domain/tableau.mjs +1225 -0
- package/src/domain/term-ledger.mjs +118 -0
- package/src/services/chat.mjs +420 -20
- package/src/services/extract-facts.mjs +91 -1
- package/src/services/index.mjs +12 -0
- package/src/services/init.mjs +33 -0
- package/src/services/news.mjs +918 -0
- package/src/services/sprite-catalog-viz.mjs +148 -78
- package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
- package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
|
@@ -0,0 +1,918 @@
|
|
|
1
|
+
// news.mjs — the news capability's orchestration and library contract
|
|
2
|
+
// (PLAN_NEWS_FEED.md section 10, phase 3): poll, ingest, ground, rank,
|
|
3
|
+
// enrich, re-process, syllogise, build, evict, measure. Every surface —
|
|
4
|
+
// news.html, chat's `/news`, the TUI (via chat), the CLI verb and a JS
|
|
5
|
+
// import — consumes the functions exported here; no surface re-implements a
|
|
6
|
+
// step.
|
|
7
|
+
//
|
|
8
|
+
// A ctx is built once per surface: { memoryDir, store, cache, lexicon,
|
|
9
|
+
// config, state, providers, now, notify }.
|
|
10
|
+
// memoryDir a repo path or backend handle, passed straight to the store
|
|
11
|
+
// functions and to ingestText/syllogise.
|
|
12
|
+
// store { loadMemory, readFactRows, appendFacts, removeFacts } — the
|
|
13
|
+
// syllogise store triple, plus the retraction path eviction
|
|
14
|
+
// uses; injected so this module never imports the memory
|
|
15
|
+
// adapter's I/O itself.
|
|
16
|
+
// cache optional; when present, cache.rows is cleared after a write
|
|
17
|
+
// (the same invalidation convention chat.mjs's own caches use).
|
|
18
|
+
// lexicon a loaded lexicon (loadLexicon() when absent).
|
|
19
|
+
// config resolveNewsConfig()'s shape.
|
|
20
|
+
// state the news-store shape (news-store.mjs): { items, ledger
|
|
21
|
+
// (ledgerPayload form), health, requestLog, metrics, lastPollAt,
|
|
22
|
+
// lastEnrichAt } — always JSON-plain; a live term ledger is
|
|
23
|
+
// built from state.ledger via ledgerFromPayload only for the
|
|
24
|
+
// span of one call, then folded back with ledgerPayload.
|
|
25
|
+
// providers { newsFetchers: Map<sourceId, { id, fetchItems }>,
|
|
26
|
+
// getResearchProvider({ source }), preflightNewsUrl?(url) } —
|
|
27
|
+
// every fetcher and provider this session may call, already
|
|
28
|
+
// constructed (adapters own I/O construction, never this
|
|
29
|
+
// module).
|
|
30
|
+
// now a function returning the caller's clock reading (ISO string
|
|
31
|
+
// or ms), or a fixed reading directly. Never read from here —
|
|
32
|
+
// the wall clock enters only through this parameter.
|
|
33
|
+
// notify an optional, failure-tolerated status hook.
|
|
34
|
+
//
|
|
35
|
+
// Determinism: given the same fetched payloads and the same `now`, the same
|
|
36
|
+
// facts land and the same feed renders, byte for byte (PLAN_NEWS_FEED.md
|
|
37
|
+
// section 3). Network lives in the adapters this module is handed, never
|
|
38
|
+
// inside it.
|
|
39
|
+
|
|
40
|
+
import { normFactTerm, normFactPredicate, factIdFor, sha256Bytes } from "../domain/hash.mjs";
|
|
41
|
+
import {
|
|
42
|
+
newsWindowRows, scoreHubs, subgraphAround, renderNewsParagraph, buildNewsItems, evictNewsFacts,
|
|
43
|
+
} from "../domain/news-feed.mjs";
|
|
44
|
+
import {
|
|
45
|
+
createTermLedger, bumpTerms, rankedTerms, markTerm, groundedSweep, ledgerPayload, ledgerFromPayload,
|
|
46
|
+
} from "../domain/term-ledger.mjs";
|
|
47
|
+
import { syllogise } from "../domain/syllogise.mjs";
|
|
48
|
+
import { loadLexicon, lookupNoun } from "../domain/grammar/lexicon.mjs";
|
|
49
|
+
import { provenanceTagToSource, SOURCE_PRIOR } from "../domain/memory/trust.mjs";
|
|
50
|
+
import {
|
|
51
|
+
NEWS_SOURCE_RECORDS, DEFAULT_NEWS_SOURCE_IDS, DEFAULT_NEWS_KB_IDS,
|
|
52
|
+
newsSourceRecords, normalizeNewsSourceIds, registerNewsSource,
|
|
53
|
+
} from "../adapters/corpus/news-sources.mjs";
|
|
54
|
+
import { DEFAULT_MIN_INTERVAL_MS } from "../adapters/corpus/courtesy.mjs";
|
|
55
|
+
import { researchFacts } from "../adapters/corpus/research-source.mjs";
|
|
56
|
+
import { ingestText, optimisticTriples } from "./extract-facts.mjs";
|
|
57
|
+
import { splitSentences } from "./sentences.mjs";
|
|
58
|
+
|
|
59
|
+
export { NEWS_SOURCE_RECORDS, DEFAULT_NEWS_SOURCE_IDS, DEFAULT_NEWS_KB_IDS };
|
|
60
|
+
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
// 10.1 — config and parsing
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
export const NEWS_DEFAULTS = Object.freeze({
|
|
66
|
+
sources: DEFAULT_NEWS_SOURCE_IDS,
|
|
67
|
+
kbSources: DEFAULT_NEWS_KB_IDS,
|
|
68
|
+
extraSources: Object.freeze([]),
|
|
69
|
+
pollMinutes: 15,
|
|
70
|
+
enrichMinutes: 10,
|
|
71
|
+
enrichTermsPerCycle: 3,
|
|
72
|
+
negativeCacheTtlHours: 24,
|
|
73
|
+
syllogismsPerIngest: 12,
|
|
74
|
+
itemCap: 30,
|
|
75
|
+
newsFactCap: 4000,
|
|
76
|
+
feedTop: 3,
|
|
77
|
+
windowHours: 48,
|
|
78
|
+
// 0 means "no override" — every source keeps its own registry floor
|
|
79
|
+
// (Math.max(sourceFloor, 0) === sourceFloor), never a real interval.
|
|
80
|
+
minIntervalMs: 0,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const clampInt = (n, lo, hi, fallback) => {
|
|
84
|
+
const v = Number(n);
|
|
85
|
+
if (!Number.isFinite(v)) return fallback;
|
|
86
|
+
return Math.min(hi, Math.max(lo, Math.floor(v)));
|
|
87
|
+
};
|
|
88
|
+
const clampNonNegInt = (n, fallback) => {
|
|
89
|
+
const v = Number(n);
|
|
90
|
+
if (!Number.isFinite(v)) return fallback;
|
|
91
|
+
return Math.max(0, Math.floor(v));
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** `poll_minutes`: 0 (on-demand only) is legal as-is; any other value floors
|
|
95
|
+
* at 5 — a page-set interval faster than that clamps up, never down. */
|
|
96
|
+
function clampPollMinutes(value) {
|
|
97
|
+
const n = Number(value);
|
|
98
|
+
if (!Number.isFinite(n)) return NEWS_DEFAULTS.pollMinutes;
|
|
99
|
+
const floored = Math.max(0, Math.floor(n));
|
|
100
|
+
return floored === 0 ? 0 : Math.max(5, floored);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeExtraSources(list) {
|
|
104
|
+
if (!Array.isArray(list)) return [];
|
|
105
|
+
const seen = new Set();
|
|
106
|
+
const out = [];
|
|
107
|
+
for (const raw of list) {
|
|
108
|
+
const id = String(raw?.id ?? "").trim();
|
|
109
|
+
const url = String(raw?.url ?? "").trim();
|
|
110
|
+
if (!id || !url.startsWith("https://") || seen.has(id)) continue;
|
|
111
|
+
seen.add(id);
|
|
112
|
+
out.push({ id, url });
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A partial (camelCase) config folded onto NEWS_DEFAULTS and clamped to the
|
|
118
|
+
* engineered ranges (PLAN_NEWS_FEED.md section 6.4). Every non-finite number
|
|
119
|
+
* falls back to its default; an unrecognized source id is dropped rather
|
|
120
|
+
* than rejected, so an older config degrades instead of failing. */
|
|
121
|
+
export function clampNewsConfig(partial = {}) {
|
|
122
|
+
const cfg = { ...NEWS_DEFAULTS };
|
|
123
|
+
cfg.sources = normalizeNewsSourceIds(partial.sources ?? NEWS_DEFAULTS.sources);
|
|
124
|
+
cfg.kbSources = normalizeNewsSourceIds(partial.kbSources ?? NEWS_DEFAULTS.kbSources);
|
|
125
|
+
cfg.extraSources = normalizeExtraSources(partial.extraSources ?? NEWS_DEFAULTS.extraSources);
|
|
126
|
+
cfg.pollMinutes = clampPollMinutes(partial.pollMinutes ?? NEWS_DEFAULTS.pollMinutes);
|
|
127
|
+
cfg.enrichMinutes = clampNonNegInt(partial.enrichMinutes, NEWS_DEFAULTS.enrichMinutes);
|
|
128
|
+
cfg.enrichTermsPerCycle = clampInt(partial.enrichTermsPerCycle, 1, 10, NEWS_DEFAULTS.enrichTermsPerCycle);
|
|
129
|
+
cfg.negativeCacheTtlHours = clampNonNegInt(partial.negativeCacheTtlHours, NEWS_DEFAULTS.negativeCacheTtlHours);
|
|
130
|
+
cfg.syllogismsPerIngest = clampInt(partial.syllogismsPerIngest, 0, 50, NEWS_DEFAULTS.syllogismsPerIngest);
|
|
131
|
+
cfg.itemCap = clampInt(partial.itemCap, 1, 200, NEWS_DEFAULTS.itemCap);
|
|
132
|
+
cfg.newsFactCap = clampNonNegInt(partial.newsFactCap, NEWS_DEFAULTS.newsFactCap);
|
|
133
|
+
cfg.feedTop = clampInt(partial.feedTop, 1, 10, NEWS_DEFAULTS.feedTop);
|
|
134
|
+
cfg.windowHours = clampNonNegInt(partial.windowHours, NEWS_DEFAULTS.windowHours);
|
|
135
|
+
cfg.minIntervalMs = clampNonNegInt(partial.minIntervalMs, NEWS_DEFAULTS.minIntervalMs);
|
|
136
|
+
return cfg;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** tmct.toml's `[news]` table -> the capability's effective knobs, following
|
|
140
|
+
* resolveResearchConfig's precedent. */
|
|
141
|
+
export function resolveNewsConfig(toml = null) {
|
|
142
|
+
const raw = toml?.news || {};
|
|
143
|
+
return clampNewsConfig({
|
|
144
|
+
sources: raw.sources,
|
|
145
|
+
kbSources: raw.kb_sources,
|
|
146
|
+
extraSources: raw.extra_sources,
|
|
147
|
+
pollMinutes: raw.poll_minutes,
|
|
148
|
+
enrichMinutes: raw.enrich_minutes,
|
|
149
|
+
enrichTermsPerCycle: raw.enrich_terms_per_cycle,
|
|
150
|
+
negativeCacheTtlHours: raw.negative_cache_ttl_hours,
|
|
151
|
+
syllogismsPerIngest: raw.syllogisms_per_ingest,
|
|
152
|
+
itemCap: raw.item_cap,
|
|
153
|
+
newsFactCap: raw.news_fact_cap,
|
|
154
|
+
feedTop: raw.feed_top,
|
|
155
|
+
windowHours: raw.window_hours,
|
|
156
|
+
minIntervalMs: raw.min_interval_ms,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const NEWS_SLASH_RE = /^\/news\b\s*(.*)$/i;
|
|
161
|
+
const NEWS_SHOW_RE = /^(?:news|latest news|what'?s in the news\??|show me the news)\s*[.!?]*$/i;
|
|
162
|
+
const NEWS_FOCUS_RE = /^(?:any news on|news on|news about)\s+(.+?)\s*\??$/i;
|
|
163
|
+
|
|
164
|
+
function parseNewsSubcommand(rest) {
|
|
165
|
+
const trimmed = String(rest || "").trim();
|
|
166
|
+
if (!trimmed) return { kind: "show" };
|
|
167
|
+
const [word, ...restWords] = trimmed.split(/\s+/);
|
|
168
|
+
const lower = word.toLowerCase();
|
|
169
|
+
if (lower === "poll") return { kind: "poll" };
|
|
170
|
+
if (lower === "rank") return { kind: "rank" };
|
|
171
|
+
if (lower === "enrich") return { kind: "enrich" };
|
|
172
|
+
if (lower === "sources") return { kind: "sources" };
|
|
173
|
+
if (lower === "add" && restWords[0]) return { kind: "add", url: restWords[0] };
|
|
174
|
+
if (lower === "interval" && /^\d+$/.test(restWords[0] || "")) {
|
|
175
|
+
return { kind: "interval", minutes: Number(restWords[0]) };
|
|
176
|
+
}
|
|
177
|
+
return { kind: "unknown", subcommand: word };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The news request a line carries, or null. Kinds: show (optionally
|
|
181
|
+
* {focus}), poll, rank, enrich, sources, add {url}, interval {minutes},
|
|
182
|
+
* unknown {subcommand}. Both `/news …` and the plain-English phrasings
|
|
183
|
+
* ("news", "latest news", "any news on X?") resolve to the same kinds. */
|
|
184
|
+
export function parseNewsRequest(line) {
|
|
185
|
+
const q = String(line || "").trim();
|
|
186
|
+
if (!q) return null;
|
|
187
|
+
const slash = q.match(NEWS_SLASH_RE);
|
|
188
|
+
if (slash) return parseNewsSubcommand(slash[1]);
|
|
189
|
+
if (NEWS_SHOW_RE.test(q)) return { kind: "show" };
|
|
190
|
+
const focus = q.match(NEWS_FOCUS_RE);
|
|
191
|
+
if (focus) return { kind: "show", focus: focus[1].trim() };
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
// shared helpers
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
function resolveNow(now) {
|
|
200
|
+
if (typeof now === "function") return now();
|
|
201
|
+
return typeof now === "string" || typeof now === "number" ? now : "";
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Every quantifier factTermVariants(chat.mjs) also strips, and the same
|
|
205
|
+
// -es/-s fold — a small, self-contained widening so this module never
|
|
206
|
+
// depends on chat.mjs (chat.mjs will depend on this module in the next
|
|
207
|
+
// phase; a reverse edge here would be circular).
|
|
208
|
+
const QUANTIFIER_LEAD_RE = /^(?:every|each|all|any)\s+/i;
|
|
209
|
+
function newsTermVariants(term) {
|
|
210
|
+
const t = normFactTerm(term);
|
|
211
|
+
const variants = new Set();
|
|
212
|
+
if (!t) return variants;
|
|
213
|
+
const bases = new Set([t]);
|
|
214
|
+
const unquantified = t.replace(QUANTIFIER_LEAD_RE, "").trim();
|
|
215
|
+
if (unquantified && unquantified !== t) bases.add(unquantified);
|
|
216
|
+
for (const base of bases) {
|
|
217
|
+
variants.add(base);
|
|
218
|
+
if (base.endsWith("es")) variants.add(base.slice(0, -2));
|
|
219
|
+
if (base.endsWith("s")) variants.add(base.slice(0, -1));
|
|
220
|
+
}
|
|
221
|
+
return variants;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function termFocusOf(facts) {
|
|
225
|
+
const focus = new Set();
|
|
226
|
+
for (const f of facts) {
|
|
227
|
+
for (const v of newsTermVariants(f.subject)) focus.add(v);
|
|
228
|
+
for (const v of newsTermVariants(f.object)) focus.add(v);
|
|
229
|
+
}
|
|
230
|
+
return focus;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function invalidateCache(cache) {
|
|
234
|
+
if (cache) cache.rows = null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// A feed title rarely carries its own terminal punctuation ("Scientists
|
|
238
|
+
// Discover New Species"); a fixture built from a full sentence ("A module is
|
|
239
|
+
// a component.") already does. Joining unconditionally with ". " doubles the
|
|
240
|
+
// period in the second case and corrupts sentence splitting downstream — so
|
|
241
|
+
// the separator is a bare space when the title already ends the sentence.
|
|
242
|
+
const SENTENCE_END_RE = /[.!?]["')\]]*$/;
|
|
243
|
+
function joinTitleAndSummary(title, summary) {
|
|
244
|
+
const t = String(title || "").trim();
|
|
245
|
+
const s = String(summary || "").trim();
|
|
246
|
+
if (!t) return s;
|
|
247
|
+
if (!s) return t;
|
|
248
|
+
return `${t}${SENTENCE_END_RE.test(t) ? " " : ". "}${s}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function sha256HexPrefix(str, nBytes) {
|
|
252
|
+
const bytes = sha256Bytes(str);
|
|
253
|
+
let hex = "";
|
|
254
|
+
for (let i = 0; i < nBytes; i += 1) hex += bytes[i].toString(16).padStart(2, "0");
|
|
255
|
+
return hex;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function toMs(value) {
|
|
259
|
+
if (typeof value === "number") return value;
|
|
260
|
+
const t = Date.parse(value);
|
|
261
|
+
return Number.isFinite(t) ? t : NaN;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
265
|
+
|
|
266
|
+
function tierOfRows(rows) {
|
|
267
|
+
if (!rows.length) return "";
|
|
268
|
+
let strongest = rows[0];
|
|
269
|
+
for (const row of rows) {
|
|
270
|
+
if (Number(row.trust ?? 0) > Number(strongest.trust ?? 0)) strongest = row;
|
|
271
|
+
}
|
|
272
|
+
const kinds = Array.isArray(strongest.sourceTypes) ? strongest.sourceTypes : [];
|
|
273
|
+
return kinds[0] || "";
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function collectItemSources(subgraphRows, sourcesByFactId) {
|
|
277
|
+
const seen = new Set();
|
|
278
|
+
const sources = [];
|
|
279
|
+
for (const row of subgraphRows) {
|
|
280
|
+
const src = sourcesByFactId.get(row.id);
|
|
281
|
+
if (!src) continue;
|
|
282
|
+
const key = src.url || src.title || "";
|
|
283
|
+
if (!key || seen.has(key)) continue;
|
|
284
|
+
seen.add(key);
|
|
285
|
+
sources.push({ title: src.title || "", url: src.url || "", name: src.name || "" });
|
|
286
|
+
}
|
|
287
|
+
return sources;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The item-assembly buildNewsItems runs internally, exposed here so
|
|
291
|
+
* buildFeed's seed-only fallback (S1: score hubs over the WHOLE graph, not
|
|
292
|
+
* just news/research-tagged rows) can reuse the same shape without widening
|
|
293
|
+
* buildNewsItems's own, already-pinned window contract. */
|
|
294
|
+
function assembleNewsItems(rows, windowRows, { now, limit, sourcesByFactId }) {
|
|
295
|
+
const hubs = scoreHubs(rows, windowRows, { limit });
|
|
296
|
+
const items = hubs.map(({ term, changed }) => {
|
|
297
|
+
const subgraphRows = subgraphAround(rows, term);
|
|
298
|
+
const factIds = subgraphRows.map((r) => r.id).sort();
|
|
299
|
+
return {
|
|
300
|
+
id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
|
|
301
|
+
hub: term,
|
|
302
|
+
factIds,
|
|
303
|
+
changedCount: changed,
|
|
304
|
+
builtAt: now,
|
|
305
|
+
paragraph: renderNewsParagraph(term, subgraphRows),
|
|
306
|
+
tier: tierOfRows(subgraphRows),
|
|
307
|
+
sources: collectItemSources(subgraphRows, sourcesByFactId),
|
|
308
|
+
};
|
|
309
|
+
});
|
|
310
|
+
return items.sort((a, b) => (toMs(b.builtAt) - toMs(a.builtAt)) || byId(a, b));
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function buildSourcesByFactId(items) {
|
|
314
|
+
const map = new Map();
|
|
315
|
+
const recordsById = new Map(newsSourceRecords().map((r) => [r.id, r]));
|
|
316
|
+
for (const snap of items || []) {
|
|
317
|
+
const record = recordsById.get(snap.sourceId);
|
|
318
|
+
const src = { title: snap.title || "", url: snap.url || "", name: record?.name || snap.sourceId || "" };
|
|
319
|
+
for (const factId of snap.factIds || []) map.set(factId, src);
|
|
320
|
+
}
|
|
321
|
+
return map;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// ---------------------------------------------------------------------------
|
|
325
|
+
// grounding definitions (10.2)
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
/** True when the lexicon resolves `term` as a noun. Answers parseability
|
|
329
|
+
* only — display for the ranked-terms panel, never a gate on ledger
|
|
330
|
+
* admission or enrichment eligibility (PLAN_NEWS_FEED.md section 6.3). */
|
|
331
|
+
export function isVocabGroundedTerm(lexicon, term) {
|
|
332
|
+
const t = normFactTerm(term);
|
|
333
|
+
if (!t) return false;
|
|
334
|
+
try { return Boolean(lookupNoun(lexicon, t)); } catch { return false; }
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** True when `rows` holds at least one fact whose subject or object matches
|
|
338
|
+
* `term` (through the same variant widening a plural/quantified spelling
|
|
339
|
+
* needs). THE fact-grounding definition — what ledger admission,
|
|
340
|
+
* groundedSweep and enrichment eligibility all test. */
|
|
341
|
+
export function isFactGroundedTerm(rows, term) {
|
|
342
|
+
const variants = newsTermVariants(term);
|
|
343
|
+
if (!variants.size) return false;
|
|
344
|
+
for (const row of rows) {
|
|
345
|
+
if (variants.has(normFactTerm(row.subject)) || variants.has(normFactTerm(row.object))) return true;
|
|
346
|
+
}
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ---------------------------------------------------------------------------
|
|
351
|
+
// ingest (shared by ingestNewsSnapshot and reprocessAfterGrounding)
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
|
|
354
|
+
/** Grounds one snapshot's title+summary, records the facts it contributed on
|
|
355
|
+
* the snapshot (content-addressed ids, so a re-run upserts rather than
|
|
356
|
+
* duplicates) and bumps the fact-ungrounded-term ledger. Does NOT run
|
|
357
|
+
* syllogise — callers that want one snapshot's own bounded round
|
|
358
|
+
* (ingestNewsSnapshot) or one combined round over several snapshots
|
|
359
|
+
* (reprocessAfterGrounding) run it themselves over this function's
|
|
360
|
+
* returned facts. */
|
|
361
|
+
async function ingestSnapshotFacts(ctx, snapshot) {
|
|
362
|
+
const { memoryDir, lexicon, state, now, cache } = ctx;
|
|
363
|
+
const nowVal = resolveNow(now);
|
|
364
|
+
const lex = lexicon || loadLexicon();
|
|
365
|
+
const text = joinTitleAndSummary(snapshot.title, snapshot.summary);
|
|
366
|
+
const sourceTag = `news:${snapshot.sourceId}@${snapshot.id}`;
|
|
367
|
+
const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon: lex });
|
|
368
|
+
invalidateCache(cache);
|
|
369
|
+
|
|
370
|
+
const allFacts = [...result.extracted, ...result.optimistic];
|
|
371
|
+
const newFactIds = allFacts.map((f) => factIdFor(normFactTerm(f.subject), normFactPredicate(f.predicate), normFactTerm(f.object)));
|
|
372
|
+
snapshot.factIds = [...new Set([...(snapshot.factIds || []), ...newFactIds])];
|
|
373
|
+
snapshot.processedRounds = (snapshot.processedRounds || 0) + 1;
|
|
374
|
+
|
|
375
|
+
const vocabGroundedByTerm = new Map();
|
|
376
|
+
for (const term of result.ungroundedCounts.keys()) vocabGroundedByTerm.set(term, isVocabGroundedTerm(lex, term));
|
|
377
|
+
const ledger = ledgerFromPayload(state.ledger);
|
|
378
|
+
bumpTerms(ledger, result.ungroundedCounts, snapshot.id, nowVal, vocabGroundedByTerm);
|
|
379
|
+
state.ledger = ledgerPayload(ledger);
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
facts: allFacts,
|
|
383
|
+
sentences: result.sentences,
|
|
384
|
+
recognized: result.recognized,
|
|
385
|
+
optimisticCount: result.optimistic.length,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Grounds one just-fetched snapshot and runs its own bounded syllogism
|
|
390
|
+
* round, focused on the terms its own new facts touched. */
|
|
391
|
+
export async function ingestNewsSnapshot(ctx, snapshot) {
|
|
392
|
+
const { memoryDir, store, config } = ctx;
|
|
393
|
+
const { facts, sentences, recognized, optimisticCount } = await ingestSnapshotFacts(ctx, snapshot);
|
|
394
|
+
let derived = 0;
|
|
395
|
+
if (facts.length && config.syllogismsPerIngest > 0) {
|
|
396
|
+
const focus = [...termFocusOf(facts)];
|
|
397
|
+
const res = await syllogise(memoryDir, { focus, expandFocus: true, budget: config.syllogismsPerIngest, store });
|
|
398
|
+
derived = res?.count || 0;
|
|
399
|
+
if (derived) invalidateCache(ctx.cache);
|
|
400
|
+
}
|
|
401
|
+
return { facts: facts.length, derived, sentences, recognized, optimisticCount };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function snapshotMentionsAny(snapshot, terms) {
|
|
405
|
+
const text = `${snapshot.title || ""} ${snapshot.summary || ""}`.toLowerCase();
|
|
406
|
+
return terms.some((term) => term && text.includes(term));
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Re-runs ingestNewsSnapshot's grounding step over every snapshot that
|
|
410
|
+
* mentions a newly grounded term, then one combined syllogism round over
|
|
411
|
+
* the union of what that re-run added, then sweeps the ledger by
|
|
412
|
+
* fact-grounding alone. */
|
|
413
|
+
export async function reprocessAfterGrounding(ctx, groundedTerms) {
|
|
414
|
+
const { memoryDir, store, state, config } = ctx;
|
|
415
|
+
const terms = [...new Set((groundedTerms || []).map((t) => normFactTerm(t)).filter(Boolean))];
|
|
416
|
+
if (!terms.length) return { facts: 0, derived: 0, flipped: [] };
|
|
417
|
+
|
|
418
|
+
const touched = (state.items || []).filter((snap) => snapshotMentionsAny(snap, terms));
|
|
419
|
+
let factsTotal = 0;
|
|
420
|
+
const allNewFacts = [];
|
|
421
|
+
for (const snap of touched) {
|
|
422
|
+
const { facts } = await ingestSnapshotFacts(ctx, snap);
|
|
423
|
+
factsTotal += facts.length;
|
|
424
|
+
allNewFacts.push(...facts);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
let derived = 0;
|
|
428
|
+
if (allNewFacts.length && config.syllogismsPerIngest > 0) {
|
|
429
|
+
const focus = [...termFocusOf(allNewFacts)];
|
|
430
|
+
const res = await syllogise(memoryDir, { focus, expandFocus: true, budget: config.syllogismsPerIngest, store });
|
|
431
|
+
derived = res?.count || 0;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const memory = await store.loadMemory(memoryDir);
|
|
435
|
+
const rows = store.readFactRows(memory);
|
|
436
|
+
const ledger = ledgerFromPayload(state.ledger);
|
|
437
|
+
const flipped = groundedSweep(ledger, (term) => isFactGroundedTerm(rows, term));
|
|
438
|
+
state.ledger = ledgerPayload(ledger);
|
|
439
|
+
if (factsTotal || derived) invalidateCache(ctx.cache);
|
|
440
|
+
|
|
441
|
+
return { facts: factsTotal, derived, flipped };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ---------------------------------------------------------------------------
|
|
445
|
+
// polling
|
|
446
|
+
// ---------------------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
const BACKOFF_CAP_MS = 6 * 3600000;
|
|
449
|
+
const AUTO_DISABLE_THRESHOLD = 3;
|
|
450
|
+
|
|
451
|
+
function findOrCreateHealth(state, sourceId) {
|
|
452
|
+
const rows = state.health || (state.health = []);
|
|
453
|
+
let row = rows.find((h) => h.sourceId === sourceId);
|
|
454
|
+
if (!row) {
|
|
455
|
+
row = {
|
|
456
|
+
sourceId, lastPolledAt: "", lastStatus: "", consecutiveFailures: 0,
|
|
457
|
+
backoffUntil: "", autoDisabled: false, browserBlocked: false, etag: "", lastModified: "",
|
|
458
|
+
};
|
|
459
|
+
rows.push(row);
|
|
460
|
+
}
|
|
461
|
+
return row;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function isBackedOff(health, nowVal) {
|
|
465
|
+
if (health.autoDisabled) return true;
|
|
466
|
+
if (!health.backoffUntil) return false;
|
|
467
|
+
const until = toMs(health.backoffUntil);
|
|
468
|
+
const now = toMs(nowVal);
|
|
469
|
+
return Number.isFinite(until) && Number.isFinite(now) && now < until;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Doubles the source's effective poll interval per consecutive failure
|
|
473
|
+
* (base: the configured poll cadence, or the shipped default when polling
|
|
474
|
+
* is on-demand only), capped at six hours; the third consecutive failure
|
|
475
|
+
* auto-disables instead of scheduling another backoff. */
|
|
476
|
+
function recordFailure(health, config, nowVal) {
|
|
477
|
+
health.lastPolledAt = nowVal;
|
|
478
|
+
health.lastStatus = "failed";
|
|
479
|
+
health.consecutiveFailures += 1;
|
|
480
|
+
if (health.consecutiveFailures >= AUTO_DISABLE_THRESHOLD) {
|
|
481
|
+
health.autoDisabled = true;
|
|
482
|
+
health.backoffUntil = "";
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const baseMs = Math.max(1, config.pollMinutes || NEWS_DEFAULTS.pollMinutes) * 60000;
|
|
486
|
+
const backoffMs = Math.min(BACKOFF_CAP_MS, baseMs * (2 ** health.consecutiveFailures));
|
|
487
|
+
const nowMs = toMs(nowVal);
|
|
488
|
+
health.backoffUntil = Number.isFinite(nowMs) ? new Date(nowMs + backoffMs).toISOString() : "";
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function recordSuccess(health, nowVal, status) {
|
|
492
|
+
health.lastPolledAt = nowVal;
|
|
493
|
+
health.lastStatus = status;
|
|
494
|
+
health.consecutiveFailures = 0;
|
|
495
|
+
health.backoffUntil = "";
|
|
496
|
+
health.autoDisabled = false;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** Merges `incoming` snapshots into `existing` by id (an already-seen id is
|
|
500
|
+
* never re-added or re-ingested), then enforces `cap` by dropping the
|
|
501
|
+
* oldest-by-fetchedAt entries. Returns the merged list and the genuinely
|
|
502
|
+
* new snapshots the caller still needs to ingest. */
|
|
503
|
+
function mergeSnapshotsById(existing, incoming, cap) {
|
|
504
|
+
const byIdMap = new Map((existing || []).map((s) => [s.id, s]));
|
|
505
|
+
const added = [];
|
|
506
|
+
for (const snap of incoming || []) {
|
|
507
|
+
if (byIdMap.has(snap.id)) continue;
|
|
508
|
+
byIdMap.set(snap.id, snap);
|
|
509
|
+
added.push(snap);
|
|
510
|
+
}
|
|
511
|
+
let items = [...byIdMap.values()];
|
|
512
|
+
if (items.length > cap) {
|
|
513
|
+
items = items
|
|
514
|
+
.slice()
|
|
515
|
+
.sort((a, b) => (toMs(a.fetchedAt) - toMs(b.fetchedAt)) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
516
|
+
.slice(items.length - cap);
|
|
517
|
+
}
|
|
518
|
+
return { items, added };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function emptyCycleAccumulator(at) {
|
|
522
|
+
return { at, sentences: 0, recognized: 0, optimisticCount: 0, factsAdded: 0, termsResolved: 0, derived: 0 };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Polls every enabled contemporary source (config order), skipping any
|
|
526
|
+
* whose health says wait; ingests every genuinely new snapshot; evicts
|
|
527
|
+
* news-tagged facts past the configured cap. Never touches a source with no
|
|
528
|
+
* enabled ids — that reads as "nothing to poll", not a failure. */
|
|
529
|
+
export async function pollNewsSources(ctx) {
|
|
530
|
+
const { memoryDir, store, config, state, providers, now } = ctx;
|
|
531
|
+
const nowVal = resolveNow(now);
|
|
532
|
+
const enabledIds = normalizeNewsSourceIds(config.sources);
|
|
533
|
+
if (!enabledIds.length) {
|
|
534
|
+
return { fetched: 0, newItems: 0, failures: 0, evicted: 0, facts: 0, derived: 0, sources: [] };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const recordsById = new Map(newsSourceRecords().map((r) => [r.id, r]));
|
|
538
|
+
const perSource = [];
|
|
539
|
+
let fetched = 0;
|
|
540
|
+
let newItemsTotal = 0;
|
|
541
|
+
let failures = 0;
|
|
542
|
+
let factsTotal = 0;
|
|
543
|
+
let derivedTotal = 0;
|
|
544
|
+
|
|
545
|
+
for (const sourceId of enabledIds) {
|
|
546
|
+
const record = recordsById.get(sourceId);
|
|
547
|
+
const health = findOrCreateHealth(state, sourceId);
|
|
548
|
+
if (!record) { perSource.push({ sourceId, status: "unknown-source" }); continue; }
|
|
549
|
+
if (isBackedOff(health, nowVal)) {
|
|
550
|
+
perSource.push({ sourceId, status: health.autoDisabled ? "auto-disabled" : "backed-off" });
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
const fetcher = providers?.newsFetchers?.get?.(sourceId);
|
|
554
|
+
if (!fetcher) { perSource.push({ sourceId, status: "no-fetcher" }); continue; }
|
|
555
|
+
|
|
556
|
+
let result = null;
|
|
557
|
+
try { result = await fetcher.fetchItems(); } catch { result = null; }
|
|
558
|
+
fetched += 1;
|
|
559
|
+
state.requestLog = [
|
|
560
|
+
{ url: record.url, at: nowVal, bytes: result?.bytes ?? 0, status: result === null ? "failed" : (result.notModified ? "not-modified" : "ok") },
|
|
561
|
+
...(state.requestLog || []),
|
|
562
|
+
];
|
|
563
|
+
|
|
564
|
+
if (result === null) {
|
|
565
|
+
recordFailure(health, config, nowVal);
|
|
566
|
+
failures += 1;
|
|
567
|
+
perSource.push({ sourceId, status: "failed" });
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (result.notModified) {
|
|
571
|
+
recordSuccess(health, nowVal, "not-modified");
|
|
572
|
+
perSource.push({ sourceId, status: "not-modified" });
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
recordSuccess(health, nowVal, "ok");
|
|
576
|
+
const { items: mergedItems, added } = mergeSnapshotsById(state.items, result.items, config.itemCap);
|
|
577
|
+
state.items = mergedItems;
|
|
578
|
+
newItemsTotal += added.length;
|
|
579
|
+
|
|
580
|
+
const before = emptyCycleAccumulator(nowVal);
|
|
581
|
+
const after = emptyCycleAccumulator(nowVal);
|
|
582
|
+
for (const snapshot of added) {
|
|
583
|
+
const r = await ingestNewsSnapshot(ctx, snapshot);
|
|
584
|
+
after.sentences += r.sentences;
|
|
585
|
+
after.recognized += r.recognized;
|
|
586
|
+
after.optimisticCount += r.optimisticCount;
|
|
587
|
+
after.factsAdded += r.facts;
|
|
588
|
+
after.derived += r.derived;
|
|
589
|
+
factsTotal += r.facts;
|
|
590
|
+
derivedTotal += r.derived;
|
|
591
|
+
}
|
|
592
|
+
if (added.length) {
|
|
593
|
+
state.metrics = [...(state.metrics || []), cycleMetrics(before, after, { source: sourceId })];
|
|
594
|
+
}
|
|
595
|
+
perSource.push({ sourceId, status: "ok", newItems: added.length });
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const memory = await store.loadMemory(memoryDir);
|
|
599
|
+
const rows = store.readFactRows(memory);
|
|
600
|
+
const evictIds = evictNewsFacts(rows, { cap: config.newsFactCap });
|
|
601
|
+
if (evictIds.length) {
|
|
602
|
+
await store.removeFacts(memoryDir, evictIds, { retractedAt: nowVal });
|
|
603
|
+
invalidateCache(ctx.cache);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
state.lastPollAt = nowVal;
|
|
607
|
+
return { fetched, newItems: newItemsTotal, failures, evicted: evictIds.length, facts: factsTotal, derived: derivedTotal, sources: perSource };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// ---------------------------------------------------------------------------
|
|
611
|
+
// enrichment
|
|
612
|
+
// ---------------------------------------------------------------------------
|
|
613
|
+
|
|
614
|
+
const KB_SOURCE_TO_RESEARCH_CHOICE = Object.freeze({
|
|
615
|
+
"simple-wikipedia": "simple-wikipedia",
|
|
616
|
+
wikidata: "wikidata",
|
|
617
|
+
wiktionary: "wiktionary",
|
|
618
|
+
"dbpedia-lookup": "dbpedia",
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
/** Grounds `article` under `provider`'s own provenance tag: the structured
|
|
622
|
+
* or isa facts the research-source seam licenses (researchFacts), plus the
|
|
623
|
+
* optimistic tier's read of the summary — the same two-tier posture
|
|
624
|
+
* chat.mjs's own reference-article ingest takes, reached here through the
|
|
625
|
+
* shared seam instead of a duplicated private function. */
|
|
626
|
+
async function ingestResearchArticle(ctx, term, provider, article) {
|
|
627
|
+
const { memoryDir, store, config, lexicon } = ctx;
|
|
628
|
+
const provenance = provider.provenanceTag(term);
|
|
629
|
+
const facts = researchFacts(provider, term, article);
|
|
630
|
+
const seen = new Set(facts.map((f) => `${f.subject}\0${f.predicate}\0${f.object}`));
|
|
631
|
+
for (const sentence of splitSentences(article.summary || article.text || "")) {
|
|
632
|
+
for (const t of optimisticTriples(sentence, { lexicon: lexicon ?? undefined })) {
|
|
633
|
+
if (!t.subject || !t.object || t.subject === t.object) continue;
|
|
634
|
+
const key = `${t.subject}\0${t.predicate}\0${t.object}`;
|
|
635
|
+
if (seen.has(key)) continue;
|
|
636
|
+
seen.add(key);
|
|
637
|
+
facts.push({ subject: t.subject, predicate: t.predicate, object: t.object, provenance });
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (!facts.length) return { facts: 0, derived: 0 };
|
|
641
|
+
await store.appendFacts(memoryDir, facts);
|
|
642
|
+
invalidateCache(ctx.cache);
|
|
643
|
+
let derived = 0;
|
|
644
|
+
if (config.syllogismsPerIngest > 0) {
|
|
645
|
+
const focus = [...termFocusOf(facts)];
|
|
646
|
+
const res = await syllogise(memoryDir, { focus, expandFocus: true, budget: config.syllogismsPerIngest, store });
|
|
647
|
+
derived = res?.count || 0;
|
|
648
|
+
}
|
|
649
|
+
return { facts: facts.length, derived };
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** Takes the top `limit` pending (negative-cache-expired) terms and walks
|
|
653
|
+
* the enabled KB sources in config order for each; first lookup hit wins.
|
|
654
|
+
* A grounded term is marked "grounded" and folded into one
|
|
655
|
+
* reprocessAfterGrounding pass over every term this cycle grounded; an
|
|
656
|
+
* all-null term enters the negative cache. */
|
|
657
|
+
export async function enrichTopTerms(ctx, { limit } = {}) {
|
|
658
|
+
const { memoryDir, store, state, providers, config, now } = ctx;
|
|
659
|
+
const nowVal = resolveNow(now);
|
|
660
|
+
const cap = Number.isFinite(limit) ? limit : config.enrichTermsPerCycle;
|
|
661
|
+
|
|
662
|
+
const ledger = ledgerFromPayload(state.ledger);
|
|
663
|
+
const candidates = rankedTerms(ledger, {
|
|
664
|
+
limit: cap, status: "pending", now: nowVal, ttlMs: config.negativeCacheTtlHours * 3600000,
|
|
665
|
+
});
|
|
666
|
+
|
|
667
|
+
const enriched = [];
|
|
668
|
+
const missed = [];
|
|
669
|
+
let factsTotal = 0;
|
|
670
|
+
let derivedTotal = 0;
|
|
671
|
+
|
|
672
|
+
for (const entry of candidates) {
|
|
673
|
+
markTerm(ledger, entry.term, "enriching", nowVal);
|
|
674
|
+
let hit = null;
|
|
675
|
+
for (const sourceId of config.kbSources) {
|
|
676
|
+
const choice = KB_SOURCE_TO_RESEARCH_CHOICE[sourceId];
|
|
677
|
+
if (!choice || typeof providers?.getResearchProvider !== "function") continue;
|
|
678
|
+
const provider = providers.getResearchProvider({ source: choice });
|
|
679
|
+
if (!provider) continue;
|
|
680
|
+
let article = null;
|
|
681
|
+
try { article = await provider.lookup(entry.term); } catch { article = null; }
|
|
682
|
+
if (article) { hit = { provider, article }; break; }
|
|
683
|
+
}
|
|
684
|
+
if (!hit) {
|
|
685
|
+
markTerm(ledger, entry.term, "missed", nowVal);
|
|
686
|
+
missed.push(entry.term);
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
const res = await ingestResearchArticle(ctx, entry.term, hit.provider, hit.article);
|
|
690
|
+
factsTotal += res.facts;
|
|
691
|
+
derivedTotal += res.derived;
|
|
692
|
+
markTerm(ledger, entry.term, "grounded", nowVal);
|
|
693
|
+
enriched.push(entry.term);
|
|
694
|
+
}
|
|
695
|
+
state.ledger = ledgerPayload(ledger);
|
|
696
|
+
|
|
697
|
+
const reprocessResult = enriched.length
|
|
698
|
+
? await reprocessAfterGrounding(ctx, enriched)
|
|
699
|
+
: { facts: 0, derived: 0, flipped: [] };
|
|
700
|
+
|
|
701
|
+
const before = emptyCycleAccumulator(nowVal);
|
|
702
|
+
const after = emptyCycleAccumulator(nowVal);
|
|
703
|
+
after.termsResolved = enriched.length;
|
|
704
|
+
after.factsAdded = factsTotal + reprocessResult.facts;
|
|
705
|
+
after.derived = derivedTotal + reprocessResult.derived;
|
|
706
|
+
if (candidates.length) {
|
|
707
|
+
state.metrics = [...(state.metrics || []), cycleMetrics(before, after, { source: "enrich" })];
|
|
708
|
+
}
|
|
709
|
+
state.lastEnrichAt = nowVal;
|
|
710
|
+
|
|
711
|
+
return {
|
|
712
|
+
enriched, missed,
|
|
713
|
+
facts: factsTotal + reprocessResult.facts,
|
|
714
|
+
derived: derivedTotal + reprocessResult.derived,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// ---------------------------------------------------------------------------
|
|
719
|
+
// feed
|
|
720
|
+
// ---------------------------------------------------------------------------
|
|
721
|
+
|
|
722
|
+
/** Reads the current fact rows and builds the feed. On a seed-only graph
|
|
723
|
+
* (nothing news/research-tagged yet) scoreHubs falls back to whole-graph
|
|
724
|
+
* degree so the first paint is never empty — the caller renders every item
|
|
725
|
+
* in that state with the seed label until pollNewsSources runs once. */
|
|
726
|
+
export async function buildFeed(ctx) {
|
|
727
|
+
const { memoryDir, store, config, state, now } = ctx;
|
|
728
|
+
const nowVal = resolveNow(now);
|
|
729
|
+
const memory = await store.loadMemory(memoryDir);
|
|
730
|
+
const rows = store.readFactRows(memory);
|
|
731
|
+
const sourcesByFactId = buildSourcesByFactId(state.items);
|
|
732
|
+
const windowMs = config.windowHours * 3600000;
|
|
733
|
+
|
|
734
|
+
let items = buildNewsItems(rows, { now: nowVal, windowMs, limit: config.itemCap, sourcesByFactId });
|
|
735
|
+
let seedFallback = false;
|
|
736
|
+
if (!items.length) {
|
|
737
|
+
items = assembleNewsItems(rows, rows, { now: nowVal, limit: config.itemCap, sourcesByFactId });
|
|
738
|
+
seedFallback = items.length > 0;
|
|
739
|
+
}
|
|
740
|
+
return { items, seedFallback, builtAt: nowVal };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// ---------------------------------------------------------------------------
|
|
744
|
+
// uploaded facts (10.2, provenance table 6.5)
|
|
745
|
+
// ---------------------------------------------------------------------------
|
|
746
|
+
|
|
747
|
+
const UPLOAD_PROVENANCE_CEILING = SOURCE_PRIOR.teach;
|
|
748
|
+
|
|
749
|
+
/** Validate-and-downgrade: a row whose stated provenance sits above the
|
|
750
|
+
* teach tier (only "operator" does) is re-tagged `teach:upload:<fileLabel>
|
|
751
|
+
* @<now>`; every other row — at or below teach, or unparseable — keeps its
|
|
752
|
+
* stated provenance. Pure; the caller appends the returned rows itself. */
|
|
753
|
+
export function ingestUploadedFactRows(rows, { fileLabel, now } = {}) {
|
|
754
|
+
const tag = `teach:upload:${fileLabel}@${resolveNow(now)}`;
|
|
755
|
+
return (rows || []).map((row) => {
|
|
756
|
+
const source = provenanceTagToSource(row?.provenance);
|
|
757
|
+
const prior = source?.kind ? (SOURCE_PRIOR[source.kind] ?? 0) : 0;
|
|
758
|
+
if (source?.kind && prior <= UPLOAD_PROVENANCE_CEILING) return { ...row };
|
|
759
|
+
return { ...row, provenance: tag };
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
// ---------------------------------------------------------------------------
|
|
764
|
+
// rendering / newsTurn
|
|
765
|
+
// ---------------------------------------------------------------------------
|
|
766
|
+
|
|
767
|
+
const NEWS_USAGE = "usage: /news [poll|rank|enrich|sources|add <url>|interval <minutes>]";
|
|
768
|
+
|
|
769
|
+
function pluralize(n, word) {
|
|
770
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function renderFeedText(feed, focus) {
|
|
774
|
+
let items = feed.items;
|
|
775
|
+
if (focus) {
|
|
776
|
+
const key = normFactTerm(focus);
|
|
777
|
+
items = items.filter((it) => it.hub === key);
|
|
778
|
+
}
|
|
779
|
+
if (!items.length) return "no news items yet — poll a source or teach something first.";
|
|
780
|
+
return items
|
|
781
|
+
.map((it, i) => {
|
|
782
|
+
const seedTag = feed.seedFallback ? " (from the seed graph — start to poll live sources)" : "";
|
|
783
|
+
const sourceNames = it.sources.map((s) => s.title || s.url).filter(Boolean);
|
|
784
|
+
const sourcesText = sourceNames.length ? ` sources: ${sourceNames.join(", ")}` : "";
|
|
785
|
+
return `${i + 1}. ${it.paragraph} (${it.tier || "unranked"})${sourcesText}${seedTag}`;
|
|
786
|
+
})
|
|
787
|
+
.join("\n");
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function renderRankText(ctx) {
|
|
791
|
+
const nowVal = resolveNow(ctx.now);
|
|
792
|
+
const ledger = ledgerFromPayload(ctx.state.ledger);
|
|
793
|
+
const entries = rankedTerms(ledger, { limit: 20, now: nowVal, ttlMs: ctx.config.negativeCacheTtlHours * 3600000 });
|
|
794
|
+
if (!entries.length) return "no fact-ungrounded terms yet — poll a source or teach something first.";
|
|
795
|
+
return entries
|
|
796
|
+
.map((e, i) => `${i + 1}. ${e.term} (${e.count}) — ${e.vocabGrounded ? "parseable but knowledge-free" : "unknown word"}`)
|
|
797
|
+
.join("\n");
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function renderSourcesText(ctx) {
|
|
801
|
+
const enabled = new Set(ctx.config.sources);
|
|
802
|
+
const records = newsSourceRecords().filter((r) => r.kind === "contemporary");
|
|
803
|
+
return records
|
|
804
|
+
.map((r) => {
|
|
805
|
+
const health = (ctx.state.health || []).find((h) => h.sourceId === r.id);
|
|
806
|
+
let status;
|
|
807
|
+
if (!enabled.has(r.id)) status = "off";
|
|
808
|
+
else if (health?.autoDisabled) status = "auto-disabled";
|
|
809
|
+
else if (health?.browserBlocked) status = "source does not permit browser access";
|
|
810
|
+
else status = health?.lastStatus || "not yet polled";
|
|
811
|
+
return `${r.name} (${r.id}): ${status}`;
|
|
812
|
+
})
|
|
813
|
+
.join("\n");
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
function renderPollResult(result) {
|
|
817
|
+
if (!result.sources.length) return { text: "no sources enabled — nothing to poll.", miss: true };
|
|
818
|
+
const text = `polled ${pluralize(result.fetched, "source")}: ${pluralize(result.newItems, "new item")}, `
|
|
819
|
+
+ `${pluralize(result.facts, "fact")} stored, ${result.derived} derived, `
|
|
820
|
+
+ `${pluralize(result.failures, "failure")}, ${result.evicted} evicted.`;
|
|
821
|
+
return { text, miss: false };
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function renderEnrichResult(result) {
|
|
825
|
+
const enrichedText = result.enriched.length ? ` (${result.enriched.join(", ")})` : "";
|
|
826
|
+
const missedText = result.missed.length ? ` (${result.missed.join(", ")})` : "";
|
|
827
|
+
const text = `enriched ${pluralize(result.enriched.length, "term")}${enrichedText}; `
|
|
828
|
+
+ `${pluralize(result.missed.length, "miss")}${missedText}; `
|
|
829
|
+
+ `${pluralize(result.facts, "fact")} stored, ${result.derived} derived.`;
|
|
830
|
+
return { text, miss: !result.enriched.length && !result.missed.length };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
async function handleAddSource(ctx, url) {
|
|
834
|
+
const preflight = ctx.providers?.preflightNewsUrl;
|
|
835
|
+
if (typeof preflight !== "function") {
|
|
836
|
+
return { text: "adding a source by url needs a preflight check this session has no way to run.", miss: true };
|
|
837
|
+
}
|
|
838
|
+
const result = await preflight(url);
|
|
839
|
+
if (!result.ok) {
|
|
840
|
+
const reason = result.reason === "browser-blocked" ? "source does not permit browser access"
|
|
841
|
+
: result.reason === "not-https" ? "only https sources are supported"
|
|
842
|
+
: "no readable feed found at that url";
|
|
843
|
+
return { text: `couldn't add ${url}: ${reason}.`, miss: true };
|
|
844
|
+
}
|
|
845
|
+
const id = `custom:${normFactTerm(url)}`;
|
|
846
|
+
registerNewsSource({
|
|
847
|
+
id, name: url, kind: "contemporary", format: result.format, url, homepage: url,
|
|
848
|
+
licence: "unknown", browserVerified: "", minIntervalMs: DEFAULT_MIN_INTERVAL_MS, enabledByDefault: false,
|
|
849
|
+
});
|
|
850
|
+
ctx.config.sources = normalizeNewsSourceIds([...ctx.config.sources, id]);
|
|
851
|
+
return { text: `added ${url} as a ${result.format} source.`, miss: false };
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function handleInterval(ctx, minutes) {
|
|
855
|
+
ctx.config.pollMinutes = clampPollMinutes(minutes);
|
|
856
|
+
return { text: `poll interval set to ${ctx.config.pollMinutes} minute${ctx.config.pollMinutes === 1 ? "" : "s"}.`, miss: false };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** parseNewsRequest -> the matching engine call -> a rendered text block.
|
|
860
|
+
* Every surface renders through this one function, so wording stays
|
|
861
|
+
* identical everywhere it appears. */
|
|
862
|
+
export async function newsTurn(line, ctx) {
|
|
863
|
+
const req = parseNewsRequest(line);
|
|
864
|
+
if (!req) return null;
|
|
865
|
+
|
|
866
|
+
if (req.kind === "show") {
|
|
867
|
+
const feed = await buildFeed(ctx);
|
|
868
|
+
return { text: renderFeedText(feed, req.focus), miss: false, goal: "surface the news feed built over this graph" };
|
|
869
|
+
}
|
|
870
|
+
if (req.kind === "poll") {
|
|
871
|
+
if (!ctx.config.sources.length) return { text: "no sources enabled — nothing to poll.", miss: true };
|
|
872
|
+
return renderPollResult(await pollNewsSources(ctx));
|
|
873
|
+
}
|
|
874
|
+
if (req.kind === "rank") return { text: renderRankText(ctx), miss: false };
|
|
875
|
+
if (req.kind === "enrich") return renderEnrichResult(await enrichTopTerms(ctx));
|
|
876
|
+
if (req.kind === "sources") return { text: renderSourcesText(ctx), miss: false };
|
|
877
|
+
if (req.kind === "add") return handleAddSource(ctx, req.url);
|
|
878
|
+
if (req.kind === "interval") return handleInterval(ctx, req.minutes);
|
|
879
|
+
return { text: NEWS_USAGE, miss: true };
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// ---------------------------------------------------------------------------
|
|
883
|
+
// metrics (10.2, the section 16 rig's six numbers)
|
|
884
|
+
// ---------------------------------------------------------------------------
|
|
885
|
+
|
|
886
|
+
/** The rig row: grounding rate (strict and optimistic, two separate
|
|
887
|
+
* columns, never merged), facts added, terms resolved and derivations, from
|
|
888
|
+
* two cycle accumulators — pure, no clock read here. */
|
|
889
|
+
export function cycleMetrics(before, after, { source } = {}) {
|
|
890
|
+
const sentences = (after.sentences || 0) - (before.sentences || 0);
|
|
891
|
+
const recognized = (after.recognized || 0) - (before.recognized || 0);
|
|
892
|
+
const optimisticCount = (after.optimisticCount || 0) - (before.optimisticCount || 0);
|
|
893
|
+
const factsAdded = (after.factsAdded || 0) - (before.factsAdded || 0);
|
|
894
|
+
const termsResolved = (after.termsResolved || 0) - (before.termsResolved || 0);
|
|
895
|
+
const derived = (after.derived || 0) - (before.derived || 0);
|
|
896
|
+
return {
|
|
897
|
+
at: after.at ?? before.at ?? "",
|
|
898
|
+
sourceId: source ?? "",
|
|
899
|
+
sentences,
|
|
900
|
+
groundedRateStrict: sentences > 0 ? recognized / sentences : 0,
|
|
901
|
+
groundedRateOptimistic: sentences > 0 ? (recognized + optimisticCount) / sentences : 0,
|
|
902
|
+
factsAdded,
|
|
903
|
+
termsResolved,
|
|
904
|
+
derived,
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// ---------------------------------------------------------------------------
|
|
909
|
+
// a fresh, empty state — a small companion to news-store.mjs's persisted
|
|
910
|
+
// shape, for a surface (or a test) starting a session with nothing yet.
|
|
911
|
+
// ---------------------------------------------------------------------------
|
|
912
|
+
|
|
913
|
+
export function createNewsState() {
|
|
914
|
+
return {
|
|
915
|
+
items: [], ledger: ledgerPayload(createTermLedger()), health: [], requestLog: [], metrics: [],
|
|
916
|
+
lastPollAt: "", lastEnrichAt: "",
|
|
917
|
+
};
|
|
918
|
+
}
|