@polycode-projects/the-mechanical-code-talker 5.0.25 → 5.0.27

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.
Files changed (36) hide show
  1. package/README.md +74 -11
  2. package/bin/tmct.mjs +81 -0
  3. package/package.json +6 -1
  4. package/src/adapters/corpus/courtesy.mjs +91 -28
  5. package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
  6. package/src/adapters/corpus/news-sources.mjs +436 -0
  7. package/src/adapters/corpus/research-source.mjs +16 -3
  8. package/src/adapters/corpus/wiktionary-live.mjs +158 -0
  9. package/src/adapters/news-store.mjs +87 -0
  10. package/src/adapters/toml-config.mjs +18 -0
  11. package/src/domain/ask.mjs +19 -6
  12. package/src/domain/choice-question.mjs +275 -0
  13. package/src/domain/cli-verbs.mjs +20 -0
  14. package/src/domain/codegraph.mjs +8 -1
  15. package/src/domain/dialogue-acts.mjs +1 -0
  16. package/src/domain/el-classify.mjs +569 -0
  17. package/src/domain/fact-phrase.mjs +70 -0
  18. package/src/domain/feed-normalize.mjs +224 -0
  19. package/src/domain/grammar/ace.mjs +223 -7
  20. package/src/domain/grammar/lexicon-core.json +2 -0
  21. package/src/domain/memory/trust.mjs +15 -0
  22. package/src/domain/news-feed.mjs +219 -0
  23. package/src/domain/reasoning-config.mjs +56 -0
  24. package/src/domain/sprite-animation.mjs +20 -2
  25. package/src/domain/tableau.mjs +1225 -0
  26. package/src/domain/term-ledger.mjs +118 -0
  27. package/src/services/chat.mjs +523 -20
  28. package/src/services/extract-facts.mjs +91 -1
  29. package/src/services/index.mjs +12 -0
  30. package/src/services/init.mjs +33 -0
  31. package/src/services/news-viz.mjs +489 -0
  32. package/src/services/news.mjs +918 -0
  33. package/src/services/sprite-catalog-viz.mjs +148 -78
  34. package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
  35. package/src/surfaces/web/news-browser-entry.mjs +384 -0
  36. package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
@@ -0,0 +1,384 @@
1
+ // news-browser-entry.mjs — the esbuild entry for news.html's engine
2
+ // (public/news-browser.bundle.js, built by scripts/build-news-bundle.mjs).
3
+ //
4
+ // news.html is the scheduled-ingestion demo: one in-memory Backend-B store,
5
+ // seeded from chat-seed.json exactly as chat.html and research.html are,
6
+ // that then grows through the news capability (src/services/news.mjs) —
7
+ // polling contemporary sources, ranking what does not ground, walking
8
+ // knowledge-base sources to close the gap, and building the fact-churn feed —
9
+ // all over the SAME library contract the CLI's `tmct news` verb runs.
10
+ //
11
+ // The one rule every method below honours: NOTHING here calls a fetcher
12
+ // before `start()` (or a returning visit's own `start()` replay) is called.
13
+ // `poll()`/`enrich()` are consent-gated the same way; `addSource()` performs
14
+ // its own one-off preflight fetch because pasting a URL and pressing "add" is
15
+ // itself the explicit action authorising that one request; `replayFixture()`
16
+ // never touches the network at all — it re-runs the exact ingest pipeline
17
+ // over an already-downloaded fixture body.
18
+ //
19
+ // The start-consent PREFERENCE (which localStorage key, and whether to persist
20
+ // at all) is a page concern, not this session's — the same split
21
+ // chat-page-viz.mjs's own WIKI_MODE_KEY draws between the page's own storage
22
+ // and chat-browser-entry.mjs's pure session. `prefs` here defaults to a real
23
+ // localStorage-backed store when one exists (so a caller doing nothing extra
24
+ // still gets persistence), and is fully injectable for tests, which never
25
+ // touch a real browser storage API.
26
+ //
27
+ // Gitignored, Pages-demo-site-only output — scripts/build-demo-site.mjs will
28
+ // build it fresh on every deploy once news.html joins DEMO_PAGES (a later
29
+ // round), never committed, the same posture every sibling *-browser-entry.mjs
30
+ // documents for its own output.
31
+
32
+ import { createInMemoryStore, applySeedPayload, loadMemory, readFactRows, appendFacts, removeFacts, normFactTerm, normFactPredicate } from "../../adapters/memory/core.mjs";
33
+ import { factIdFor } from "../../domain/hash.mjs";
34
+ import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
35
+ import { ingestText } from "../../services/extract-facts.mjs";
36
+ import {
37
+ resolveNewsConfig, createNewsState, pollNewsSources, enrichTopTerms, buildFeed,
38
+ ingestUploadedFactRows, isVocabGroundedTerm,
39
+ } from "../../services/news.mjs";
40
+ import { rankedTerms, ledgerFromPayload, bumpTerms, ledgerPayload } from "../../domain/term-ledger.mjs";
41
+ import {
42
+ newsSourceRecords, normalizeNewsSourceIds, createNewsFetcher, preflightNewsUrl, registerNewsSource,
43
+ } from "../../adapters/corpus/news-sources.mjs";
44
+ import { detectFeedFormat, parseFeed, normalizeFeedItems, stripMarkup } from "../../domain/feed-normalize.mjs";
45
+ import { DEFAULT_MIN_INTERVAL_MS } from "../../adapters/corpus/courtesy.mjs";
46
+ import { getResearchProvider } from "../../adapters/corpus/wikipedia-live.mjs";
47
+ import { registerWinkModel } from "../../adapters/wink-model.mjs";
48
+ import { openPersistedStore } from "./idb-persist.mjs";
49
+ import { publishTmctSurface } from "./tmct-surface.mjs";
50
+
51
+ /** The localStorage key the shipped page persists start-consent under —
52
+ * exported so the page's own inline script and a test can both name it
53
+ * without retyping the string. */
54
+ export const NEWS_START_PREF_KEY = "tmct.news.started";
55
+
56
+ function localStoragePrefStore() {
57
+ return {
58
+ get(key) { try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; } },
59
+ set(key, value) { try { globalThis.localStorage?.setItem(key, value); } catch { /* private mode — this visit still works */ } },
60
+ remove(key) { try { globalThis.localStorage?.removeItem(key); } catch { /* already gone */ } },
61
+ };
62
+ }
63
+
64
+ /** An in-memory stand-in for localStorage, used when no real one exists
65
+ * (every Node test, and any browser context with storage denied). */
66
+ function memoryPrefStore() {
67
+ const map = new Map();
68
+ return {
69
+ get: (key) => (map.has(key) ? map.get(key) : null),
70
+ set: (key, value) => { map.set(key, value); },
71
+ remove: (key) => { map.delete(key); },
72
+ };
73
+ }
74
+
75
+ function resolveNowMs() {
76
+ return Date.now();
77
+ }
78
+
79
+ function isoNow() {
80
+ return new Date().toISOString();
81
+ }
82
+
83
+ const POLL_FLOOR_MINUTES = 5;
84
+
85
+ function clampPollMinutesLocal(n) {
86
+ const v = Number(n);
87
+ if (!Number.isFinite(v)) return POLL_FLOOR_MINUTES;
88
+ const floored = Math.max(0, Math.floor(v));
89
+ return floored === 0 ? 0 : Math.max(POLL_FLOOR_MINUTES, floored);
90
+ }
91
+
92
+ /** The wikimedia-feed body shape (`{ news: [...] }` or `{ mostread: {
93
+ * articles: [...] } }`) turned into the same raw-item shape
94
+ * createNewsFetcher's own network path builds — the pure half of that
95
+ * adapter's private fetchWikimediaFeed, restated here because a fixture
96
+ * replay never calls the network wrapper that owns it. Kept intentionally
97
+ * small: only the mapping a fixture-replay demo button needs, never the
98
+ * courtesy-gated fetch itself. */
99
+ function wikimediaFixtureRawItems(body) {
100
+ const articles = Array.isArray(body?.news)
101
+ ? body.news.flatMap((story) => (Array.isArray(story?.links) ? story.links : []))
102
+ : Array.isArray(body?.mostread?.articles)
103
+ ? body.mostread.articles
104
+ : [];
105
+ return articles.map((a) => ({
106
+ guid: a?.wikibase_item || a?.normalizedtitle || a?.title || "",
107
+ title: stripMarkup(a?.normalizedtitle || a?.displaytitle || a?.title || ""),
108
+ url: a?.content_urls?.desktop?.page || "",
109
+ summary: stripMarkup(a?.extract || ""),
110
+ publishedAt: "",
111
+ }));
112
+ }
113
+
114
+ /** A fixture body's raw items, for whichever wire shape the demo buttons
115
+ * ship: `format` names it explicitly so this never has to guess. */
116
+ function fixtureRawItems(format, body) {
117
+ if (format === "wikimedia-feed") return wikimediaFixtureRawItems(body);
118
+ return parseFeed(body, { format });
119
+ }
120
+
121
+ /**
122
+ * The graph-growing session over the real news capability (news.mjs), pure
123
+ * except for the fetches `start()`/`poll()`/`enrich()`/`addSource()`
124
+ * themselves trigger — every one of them consent-gated, `addSource()` by its
125
+ * own one-off preflight rather than the poll cycle's consent.
126
+ *
127
+ * Returns `{ memoryDir, phase, consented, metrics, nextPollAt, config,
128
+ * requestLog, health, start, poll, enrich, buildFeed, rank, addSource,
129
+ * setInterval, ingestText, ingestFile, replayFixture, revokeConsent,
130
+ * destroy }`.
131
+ */
132
+ export function createNewsSession({
133
+ seedPayload = null, vocabSeeded = false, fetchImpl = null, now = isoNow,
134
+ prefs = null, prefKey = NEWS_START_PREF_KEY,
135
+ } = {}) {
136
+ const memoryDir = createInMemoryStore();
137
+ applySeedPayload(memoryDir, seedPayload);
138
+
139
+ const store = { loadMemory, readFactRows, appendFacts, removeFacts };
140
+ const cache = { rows: null };
141
+ let lexicon = loadLexicon();
142
+ let config = resolveNewsConfig();
143
+ const state = createNewsState();
144
+ const doFetch = fetchImpl || ((...args) => globalThis.fetch(...args));
145
+
146
+ const prefStore = prefs || (typeof globalThis !== "undefined" && globalThis.localStorage ? localStoragePrefStore() : memoryPrefStore());
147
+ let consented = prefStore.get(prefKey) === "on";
148
+
149
+ let phase = "seeded"; // the page-level "seeding" state (S0) precedes this session existing at all
150
+ let timer = null;
151
+ const bootMs = resolveNowMs();
152
+ const metrics = { timeToFirstArticleMs: null, timeToFirstCompletePollMs: null };
153
+ let nextPollAt = "";
154
+
155
+ const validators = new Map();
156
+ const fetchersById = new Map();
157
+ function rebuildFetchers() {
158
+ fetchersById.clear();
159
+ for (const id of normalizeNewsSourceIds(config.sources)) {
160
+ const record = newsSourceRecords().find((r) => r.id === id);
161
+ if (!record) continue;
162
+ fetchersById.set(id, createNewsFetcher(record, { fetchImpl: doFetch, validators, now }));
163
+ }
164
+ }
165
+ rebuildFetchers();
166
+
167
+ const providers = {
168
+ newsFetchers: fetchersById,
169
+ getResearchProvider: ({ source } = {}) => getResearchProvider({ source }),
170
+ preflightNewsUrl: (url) => preflightNewsUrl(url, { fetchImpl: doFetch }),
171
+ };
172
+
173
+ function ctx() {
174
+ return { memoryDir, store, cache, lexicon, config, state, providers, now };
175
+ }
176
+
177
+ function clearTimer() {
178
+ if (timer !== null) { clearTimeout(timer); timer = null; }
179
+ nextPollAt = "";
180
+ }
181
+
182
+ function armTimer() {
183
+ clearTimer();
184
+ if (!consented || !config.pollMinutes) return;
185
+ const delayMs = config.pollMinutes * 60000;
186
+ nextPollAt = new Date(resolveNowMs() + delayMs).toISOString();
187
+ timer = setTimeout(() => { runPollCycle().then(runEnrichCycle).catch(() => {}); }, delayMs);
188
+ }
189
+
190
+ async function noteFirstArticle() {
191
+ if (metrics.timeToFirstArticleMs !== null) return;
192
+ const feed = await buildFeed(ctx());
193
+ if (feed.items.length) metrics.timeToFirstArticleMs = resolveNowMs() - bootMs;
194
+ }
195
+
196
+ async function runPollCycle() {
197
+ phase = "polling";
198
+ const result = await pollNewsSources(ctx());
199
+ if (metrics.timeToFirstCompletePollMs === null) metrics.timeToFirstCompletePollMs = resolveNowMs() - bootMs;
200
+ phase = "grounding";
201
+ await noteFirstArticle();
202
+ return result;
203
+ }
204
+
205
+ async function runEnrichCycle() {
206
+ phase = "enriching";
207
+ const result = await enrichTopTerms(ctx());
208
+ phase = "idle";
209
+ armTimer();
210
+ return result;
211
+ }
212
+
213
+ return {
214
+ memoryDir,
215
+ get phase() { return phase; },
216
+ get consented() { return consented; },
217
+ get metrics() { return { ...metrics }; },
218
+ get nextPollAt() { return nextPollAt; },
219
+ get config() { return { ...config }; },
220
+ get requestLog() { return state.requestLog; },
221
+ get health() { return state.health; },
222
+
223
+ /** First run: records the start-consent preference. Every run (first or
224
+ * a returning visit's own replay): one poll cycle, then one enrich
225
+ * cycle, then the timer arms for the next one — "poll on load" for a
226
+ * returning visit is exactly this same call. */
227
+ async start() {
228
+ consented = true;
229
+ prefStore.set(prefKey, "on");
230
+ const pollResult = await runPollCycle();
231
+ const enrichResult = await runEnrichCycle();
232
+ return { poll: pollResult, enrich: enrichResult };
233
+ },
234
+
235
+ /** A manual "poll now" — still consent-gated: never fires before
236
+ * start() has run at least once this session. */
237
+ async poll() {
238
+ if (!consented) return { fetched: 0, newItems: 0, failures: 0, evicted: 0, facts: 0, derived: 0, sources: [] };
239
+ return runPollCycle();
240
+ },
241
+
242
+ /** A manual "enrich now" — same consent gate as poll(). */
243
+ async enrich() {
244
+ if (!consented) return { enriched: [], missed: [], facts: 0, derived: 0 };
245
+ return runEnrichCycle();
246
+ },
247
+
248
+ async buildFeed() { return buildFeed(ctx()); },
249
+
250
+ /** The fact rows behind a set of ids — a feed item's own `factIds`,
251
+ * expanded so the page's `<details>` fact list can show each one as a
252
+ * sentence and, nested under it, the raw triple record. */
253
+ async factRows(ids) {
254
+ const wanted = new Set(ids || []);
255
+ if (!wanted.size) return [];
256
+ const memory = await store.loadMemory(memoryDir);
257
+ return store.readFactRows(memory).filter((r) => wanted.has(r.id));
258
+ },
259
+
260
+ async rank({ limit = 20 } = {}) {
261
+ const nowVal = typeof now === "function" ? now() : now;
262
+ const ledger = ledgerFromPayload(state.ledger);
263
+ return rankedTerms(ledger, { limit, now: nowVal, ttlMs: config.negativeCacheTtlHours * 3600000 });
264
+ },
265
+
266
+ /** Add-by-URL: its own one-off preflight fetch, independent of the poll
267
+ * cycle's start()-gated consent — pasting a URL and pressing "add" IS
268
+ * the explicit action authorising that one request. */
269
+ async addSource(url) {
270
+ const result = await preflightNewsUrl(url, { fetchImpl: doFetch });
271
+ if (!result.ok) return { ok: false, reason: result.reason };
272
+ const id = `custom:${normFactTerm(url)}`;
273
+ registerNewsSource({
274
+ id, name: url, kind: "contemporary", format: result.format, url, homepage: url,
275
+ licence: "unknown", browserVerified: "", minIntervalMs: DEFAULT_MIN_INTERVAL_MS, enabledByDefault: false,
276
+ });
277
+ config.sources = normalizeNewsSourceIds([...config.sources, id]);
278
+ rebuildFetchers();
279
+ return { ok: true, id, format: result.format };
280
+ },
281
+
282
+ /** Re-arms the poll timer at `minutes`, clamped to the same floor the
283
+ * service config enforces (0 disarms). */
284
+ setInterval(minutes) {
285
+ config.pollMinutes = clampPollMinutesLocal(minutes);
286
+ armTimer();
287
+ return config.pollMinutes;
288
+ },
289
+
290
+ /** The teach panel's free-text path: prose ingested under this upload's
291
+ * own teach tag, the same tier a typed teach turn earns. */
292
+ async ingestText(text, { fileLabel = "free-text" } = {}) {
293
+ const nowVal = typeof now === "function" ? now() : now;
294
+ const sourceTag = `teach:upload:${fileLabel}@${nowVal}`;
295
+ const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon });
296
+ cache.rows = null;
297
+ return { facts: result.extracted.length + result.optimistic.length, sentences: result.sentences };
298
+ },
299
+
300
+ /** One uploaded file, routed by its own kind: `.txt`/`.md` prose through
301
+ * the same free-text path as ingestText; `.json` (a lexicon-core-shaped
302
+ * extra vocabulary) widens this session's own lexicon so later
303
+ * grounding can resolve terms it could not before; `.jsonl` (fact rows)
304
+ * through ingestUploadedFactRows's validate-and-downgrade before they
305
+ * land, so an uploaded row can never claim trust it did not earn. */
306
+ async ingestFile({ name, text, kind } = {}) {
307
+ const nowVal = typeof now === "function" ? now() : now;
308
+ const resolvedKind = kind || (/\.jsonl$/i.test(name || "") ? "jsonl" : /\.json$/i.test(name || "") ? "json" : "prose");
309
+ if (resolvedKind === "prose") {
310
+ return this.ingestText(text, { fileLabel: name || "upload" });
311
+ }
312
+ if (resolvedKind === "json") {
313
+ let extra;
314
+ try { extra = JSON.parse(text); } catch { return { facts: 0, vocabAdded: 0, error: "not valid JSON" }; }
315
+ lexicon = loadLexicon(extra);
316
+ return { facts: 0, vocabAdded: (extra?.nouns ? Object.keys(extra.nouns).length : 0), error: null };
317
+ }
318
+ // jsonl: one fact row per non-empty line.
319
+ const rows = [];
320
+ for (const line of String(text || "").split("\n")) {
321
+ const trimmed = line.trim();
322
+ if (!trimmed) continue;
323
+ try { rows.push(JSON.parse(trimmed)); } catch { /* an unparseable line is skipped, never thrown */ }
324
+ }
325
+ const downgraded = ingestUploadedFactRows(rows, { fileLabel: name || "upload", now: nowVal })
326
+ .filter((r) => r.subject && r.predicate && r.object);
327
+ if (downgraded.length) { await appendFacts(memoryDir, downgraded); cache.rows = null; }
328
+ return { facts: downgraded.length, vocabAdded: 0, error: null };
329
+ },
330
+
331
+ /** Replays a committed fixture's raw wire body through the exact live
332
+ * parse -> ingest pipeline, under `news-fixture:<sourceId>@<itemId>`
333
+ * provenance (the corpus-tier demo path) rather than `news:` — never a
334
+ * network call, so it works with the network fully blocked. */
335
+ async replayFixture(sourceId, { format, body } = {}) {
336
+ const nowVal = typeof now === "function" ? now() : now;
337
+ const raw = fixtureRawItems(format, body);
338
+ const items = normalizeFeedItems(sourceId, raw, { now: nowVal });
339
+ let factsTotal = 0;
340
+ for (const snapshot of items) {
341
+ const text = [snapshot.title, snapshot.summary].filter(Boolean).join(". ");
342
+ const sourceTag = `news-fixture:${sourceId}@${snapshot.id}`;
343
+ const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon });
344
+ const allFacts = [...result.extracted, ...result.optimistic];
345
+ snapshot.factIds = allFacts.map((f) => factIdFor(normFactTerm(f.subject), normFactPredicate(f.predicate), normFactTerm(f.object)));
346
+ factsTotal += allFacts.length;
347
+
348
+ const vocabGroundedByTerm = new Map();
349
+ for (const term of result.ungroundedCounts.keys()) vocabGroundedByTerm.set(term, isVocabGroundedTerm(lexicon, term));
350
+ const ledger = ledgerFromPayload(state.ledger);
351
+ bumpTerms(ledger, result.ungroundedCounts, snapshot.id, nowVal, vocabGroundedByTerm);
352
+ state.ledger = ledgerPayload(ledger);
353
+ }
354
+ if (factsTotal) cache.rows = null;
355
+ const existingIds = new Set(state.items.map((s) => s.id));
356
+ state.items = [...state.items, ...items.filter((s) => !existingIds.has(s.id))];
357
+ await noteFirstArticle();
358
+ return { items: items.length, facts: factsTotal };
359
+ },
360
+
361
+ /** Clears the start-consent preference and stops the timer — the next
362
+ * load of this page reads back as first-visit, exactly as if start()
363
+ * had never been pressed. */
364
+ revokeConsent() {
365
+ consented = false;
366
+ prefStore.remove(prefKey);
367
+ clearTimer();
368
+ phase = "seeded";
369
+ },
370
+
371
+ /** Stops the poll timer without touching consent — a test's own
372
+ * teardown, and a page's own unload hook. */
373
+ destroy() { clearTimer(); },
374
+ };
375
+ }
376
+
377
+ publishTmctSurface({
378
+ open: createNewsSession,
379
+ page: {
380
+ NEWS_START_PREF_KEY,
381
+ registerWinkModel, openPersistedStore, normFactTerm,
382
+ newsSourceRecords, detectFeedFormat,
383
+ },
384
+ });
@@ -32,8 +32,8 @@ import { createInMemoryStore, appendFacts, normFactTerm, loadMemory, readFactRow
32
32
  import { extractSceneItems, splitSceneBackdrop } from "../../domain/scene-compose.mjs";
33
33
  import { randomSceneSentence, sceneVocabulary } from "../../domain/scene-random.mjs";
34
34
  import {
35
- isMovingSwatchLabel, movingCounterpartLabel, nextFocusMode, frameAtTick,
36
- focusModeFrames, oscillateWalkStep, walkFrameLabelCandidates,
35
+ isMovingSwatchLabel, movingCounterpartLabel, nextFocusMode, initialCardAnimation,
36
+ cardAnimationClick, frameAtTick, focusModeFrames, oscillateWalkStep, walkFrameLabelCandidates,
37
37
  } from "../../domain/sprite-animation.mjs";
38
38
  import { parseEntities } from "../../domain/codegraph.mjs";
39
39
  import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
@@ -103,8 +103,8 @@ publishTmctSurface({
103
103
  // functions the page splices as text, published here for any caller that
104
104
  // reaches the machinery through the bundle instead.
105
105
  spriteAnimation: {
106
- isMovingSwatchLabel, movingCounterpartLabel, nextFocusMode, frameAtTick,
107
- focusModeFrames, oscillateWalkStep, walkFrameLabelCandidates,
106
+ isMovingSwatchLabel, movingCounterpartLabel, nextFocusMode, initialCardAnimation,
107
+ cardAnimationClick, frameAtTick, focusModeFrames, oscillateWalkStep, walkFrameLabelCandidates,
108
108
  },
109
109
  },
110
110
  });