@polycode-projects/the-mechanical-code-talker 5.0.34 → 5.0.36

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.
@@ -9,12 +9,13 @@
9
9
  // all over the SAME library contract the CLI's `tmct news` verb runs.
10
10
  //
11
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.
12
+ // until the visitor presses something. `start()` (or a returning visit's own
13
+ // `start()` replay) is the press that also arms the recurring timer;
14
+ // `poll()`/`pollOnce()`/`enrich()`/`addSource()` each run one round of
15
+ // requests on their own press and schedule nothing, the same reasoning that
16
+ // lets pasting a URL and pressing "add" authorise its own preflight;
17
+ // `replayFixture()` never touches the network at all — it re-runs the exact
18
+ // ingest pipeline over an already-downloaded fixture body.
18
19
  //
19
20
  // The start-consent PREFERENCE (which localStorage key, and whether to persist
20
21
  // at all) is a page concern, not this session's — the same split
@@ -36,7 +37,7 @@ import { ingestText, setIngestYield } from "../../services/extract-facts.mjs";
36
37
  import { isNewsProvenance } from "../../domain/news-feed.mjs";
37
38
  import {
38
39
  resolveNewsConfig, createNewsState, pollNewsSources, enrichTopTerms, buildFeed,
39
- ingestUploadedFactRows, isVocabGroundedTerm,
40
+ ingestUploadedFactRows, isVocabGroundedTerm, filterRankedTermEntries,
40
41
  } from "../../services/news.mjs";
41
42
  import { rankedTerms, ledgerFromPayload, bumpTerms, ledgerPayload } from "../../domain/term-ledger.mjs";
42
43
  import {
@@ -121,14 +122,13 @@ function fixtureRawItems(format, body) {
121
122
 
122
123
  /**
123
124
  * The graph-growing session over the real news capability (news.mjs), pure
124
- * except for the fetches `start()`/`poll()`/`enrich()`/`addSource()`
125
- * themselves trigger — every one of them consent-gated, `addSource()` by its
126
- * own one-off preflight rather than the poll cycle's consent.
125
+ * except for the fetches `start()`/`poll()`/`pollOnce()`/`enrich()`/
126
+ * `addSource()` themselves trigger — each one a press the visitor made.
127
127
  *
128
- * Returns `{ memoryDir, phase, consented, metrics, nextPollAt, config,
129
- * requestLog, health, start, poll, enrich, buildFeed, stats, rank, addSource,
130
- * setInterval, ingestText, ingestFile, replayFixture, revokeConsent,
131
- * destroy }`.
128
+ * Returns `{ memoryDir, phase, consented, busy, metrics, nextPollAt, config,
129
+ * requestLog, health, start, poll, pollOnce, stopPolling, enrich, buildFeed,
130
+ * stats, rank, addSource, setInterval, ingestText, ingestFile, replayFixture,
131
+ * revokeConsent, destroy }`.
132
132
  */
133
133
  export function createNewsSession({
134
134
  seedPayload = null, vocabSeeded = false, fetchImpl = null, now = isoNow,
@@ -176,6 +176,17 @@ export function createNewsSession({
176
176
 
177
177
  let phase = "seeded"; // the page-level "seeding" state (S0) precedes this session existing at all
178
178
  let timer = null;
179
+ // Set by revokeConsent, cleared by the next action that puts content back.
180
+ // While it holds, buildFeed answers with nothing rather than falling back to
181
+ // the seed graph: a visitor who pressed "stop & forget" asked for an empty
182
+ // feed, and seed-derived cards in its place read as articles that survived
183
+ // the purge.
184
+ let forgotten = false;
185
+ // Raised by stopPolling(), lowered when the next cycle starts. The ingest
186
+ // loops read it at their own awaited yield points, so a stop lands between
187
+ // whole articles and never half-way through folding one.
188
+ let stopRequested = false;
189
+ let cycleRunning = false;
179
190
  const bootMs = resolveNowMs();
180
191
  const metrics = { timeToFirstArticleMs: null, timeToFirstCompletePollMs: null };
181
192
  let nextPollAt = "";
@@ -199,7 +210,7 @@ export function createNewsSession({
199
210
  };
200
211
 
201
212
  function ctx() {
202
- return { memoryDir, store, cache, lexicon, config, state, providers, now };
213
+ return { memoryDir, store, cache, lexicon, config, state, providers, now, shouldAbort: () => stopRequested };
203
214
  }
204
215
 
205
216
  function clearTimer() {
@@ -212,7 +223,7 @@ export function createNewsSession({
212
223
  if (!consented || !config.pollMinutes) return;
213
224
  const delayMs = config.pollMinutes * 60000;
214
225
  nextPollAt = new Date(resolveNowMs() + delayMs).toISOString();
215
- timer = setTimeout(() => { runPollCycle().then(runEnrichCycle).catch(() => {}); }, delayMs);
226
+ timer = setTimeout(() => { runCycle({ armNext: true }).catch(() => {}); }, delayMs);
216
227
  }
217
228
 
218
229
  async function noteFirstArticle() {
@@ -222,6 +233,8 @@ export function createNewsSession({
222
233
  }
223
234
 
224
235
  async function runPollCycle() {
236
+ forgotten = false;
237
+ cycleRunning = true;
225
238
  phase = "polling";
226
239
  const result = await pollNewsSources(ctx());
227
240
  // The cycle's ingest writes through core appendFact directly, never the
@@ -234,16 +247,35 @@ export function createNewsSession({
234
247
  return result;
235
248
  }
236
249
 
237
- async function runEnrichCycle() {
250
+ async function runEnrichCycle({ armNext = true } = {}) {
251
+ forgotten = false;
252
+ cycleRunning = true;
238
253
  phase = "enriching";
239
254
  const result = await enrichTopTerms(ctx());
240
255
  foldedRows = null;
241
256
  cache.rows = null;
242
257
  phase = "idle";
243
- armTimer();
258
+ cycleRunning = false;
259
+ if (armNext) armTimer();
244
260
  return result;
245
261
  }
246
262
 
263
+ /** One poll-then-enrich pass, with the stop flag lowered first so a cycle
264
+ * the visitor asked for is never cancelled by an older stop. `armNext`
265
+ * false runs the pass without scheduling another — what "poll once"
266
+ * means. */
267
+ async function runCycle({ armNext } = {}) {
268
+ stopRequested = false;
269
+ try {
270
+ const poll = await runPollCycle();
271
+ const enrich = await runEnrichCycle({ armNext });
272
+ return { poll, enrich };
273
+ } finally {
274
+ cycleRunning = false;
275
+ stopRequested = false;
276
+ }
277
+ }
278
+
247
279
  return {
248
280
  memoryDir,
249
281
  get phase() { return phase; },
@@ -261,25 +293,51 @@ export function createNewsSession({
261
293
  async start() {
262
294
  consented = true;
263
295
  prefStore.set(prefKey, "on");
264
- const pollResult = await runPollCycle();
265
- const enrichResult = await runEnrichCycle();
266
- return { poll: pollResult, enrich: enrichResult };
296
+ return runCycle({ armNext: true });
267
297
  },
268
298
 
269
- /** A manual "poll now" — still consent-gated: never fires before
270
- * start() has run at least once this session. */
299
+ /** One poll cycle, now, on its own: the click IS the authorisation for
300
+ * that one round of requests, the same way addSource's own preflight
301
+ * is. It never records the start preference and never schedules
302
+ * another, so "poll once" really does mean once. */
271
303
  async poll() {
272
- if (!consented) return { fetched: 0, newItems: 0, failures: 0, evicted: 0, facts: 0, derived: 0, sources: [] };
273
- return runPollCycle();
304
+ stopRequested = false;
305
+ try {
306
+ return await runPollCycle();
307
+ } finally {
308
+ cycleRunning = false;
309
+ stopRequested = false;
310
+ }
274
311
  },
275
312
 
276
- /** A manual "enrich now" — same consent gate as poll(). */
313
+ /** One poll-then-enrich pass on demand, scheduling nothing after it. */
314
+ async pollOnce() {
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. */
277
320
  async enrich() {
278
- if (!consented) return { enriched: [], missed: [], facts: 0, derived: 0 };
279
- return runEnrichCycle();
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 };
280
332
  },
281
333
 
282
- async buildFeed() { return buildFeed(ctx()); },
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
+ },
283
341
 
284
342
  /** The two whole-graph counts the dashboard shows: every fact the store
285
343
  * holds, and the subset a news, fixture-replay or research ingest
@@ -303,10 +361,17 @@ export function createNewsSession({
303
361
  return store.readFactRows(memory).filter((r) => wanted.has(r.id));
304
362
  },
305
363
 
364
+ // filterRankedTermEntries can shrink the ledger's own limited slice, so
365
+ // this asks for more than the display wants and trims afterward — the
366
+ // panel's own count stays full even when a class term or a bare
367
+ // quantity filters out.
306
368
  async rank({ limit = 20 } = {}) {
307
369
  const nowVal = typeof now === "function" ? now() : now;
308
370
  const ledger = ledgerFromPayload(state.ledger);
309
- return rankedTerms(ledger, { limit, now: nowVal, ttlMs: config.negativeCacheTtlHours * 3600000 });
371
+ const raw = rankedTerms(ledger, { limit: limit * 4, now: nowVal, ttlMs: config.negativeCacheTtlHours * 3600000 });
372
+ const memory = await store.loadMemory(memoryDir);
373
+ const rows = store.readFactRows(memory);
374
+ return filterRankedTermEntries(rows, raw).slice(0, limit);
310
375
  },
311
376
 
312
377
  /** Add-by-URL: its own one-off preflight fetch, independent of the poll
@@ -349,6 +414,7 @@ export function createNewsSession({
349
414
  /** The teach panel's free-text path: prose ingested under this upload's
350
415
  * own teach tag, the same tier a typed teach turn earns. */
351
416
  async ingestText(text, { fileLabel = "free-text" } = {}) {
417
+ forgotten = false;
352
418
  const nowVal = typeof now === "function" ? now() : now;
353
419
  const sourceTag = `teach:upload:${fileLabel}@${nowVal}`;
354
420
  const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon, observedAt: nowVal });
@@ -364,6 +430,7 @@ export function createNewsSession({
364
430
  * through ingestUploadedFactRows's validate-and-downgrade before they
365
431
  * land, so an uploaded row can never claim trust it did not earn. */
366
432
  async ingestFile({ name, text, kind } = {}) {
433
+ forgotten = false;
367
434
  const nowVal = typeof now === "function" ? now() : now;
368
435
  const resolvedKind = kind || (/\.jsonl$/i.test(name || "") ? "jsonl" : /\.json$/i.test(name || "") ? "json" : "prose");
369
436
  if (resolvedKind === "prose") {
@@ -394,6 +461,7 @@ export function createNewsSession({
394
461
  * provenance (the corpus-tier demo path) rather than `news:` — never a
395
462
  * network call, so it works with the network fully blocked. */
396
463
  async replayFixture(sourceId, { format, body } = {}) {
464
+ forgotten = false;
397
465
  const nowVal = typeof now === "function" ? now() : now;
398
466
  const raw = fixtureRawItems(format, body);
399
467
  const items = normalizeFeedItems(sourceId, raw, { now: nowVal });
@@ -420,19 +488,46 @@ export function createNewsSession({
420
488
  return { items: items.length, facts: factsTotal };
421
489
  },
422
490
 
423
- /** Clears the start-consent preference and stops the timer — the next
424
- * load of this page reads back as first-visit, exactly as if start()
425
- * had never been pressed. */
426
- revokeConsent() {
491
+ /** Forgets everything this session gathered: the start-consent
492
+ * preference, the poll timer, every article snapshot, the term ledger,
493
+ * the health and request logs, and every fact a news, fixture-replay or
494
+ * enrichment ingest wrote into the graph. The next load of this page
495
+ * reads back as first-visit, and the feed here and now is empty — a
496
+ * visitor who pressed this asked for the articles to go, not just the
497
+ * preference. The seed graph itself is untouched. */
498
+ async revokeConsent() {
427
499
  consented = false;
500
+ forgotten = true;
501
+ stopRequested = true;
428
502
  prefStore.remove(prefKey);
429
503
  clearTimer();
430
504
  phase = "seeded";
505
+
506
+ const nowVal = typeof now === "function" ? now() : now;
507
+ const memory = await store.loadMemory(memoryDir);
508
+ const newsFactIds = store.readFactRows(memory)
509
+ .filter((row) => isNewsProvenance(row.provenance))
510
+ .map((row) => row.id);
511
+ if (newsFactIds.length) await store.removeFacts(memoryDir, newsFactIds, { retractedAt: nowVal });
512
+
513
+ const fresh = createNewsState();
514
+ state.items = fresh.items;
515
+ state.ledger = fresh.ledger;
516
+ state.health = fresh.health;
517
+ state.requestLog = fresh.requestLog;
518
+ state.metrics = fresh.metrics;
519
+ state.lastPollAt = "";
520
+ state.lastEnrichAt = "";
521
+ metrics.timeToFirstArticleMs = null;
522
+ metrics.timeToFirstCompletePollMs = null;
523
+ cache.rows = null;
524
+ foldedRows = null;
525
+ return { factsRemoved: newsFactIds.length };
431
526
  },
432
527
 
433
- /** Stops the poll timer without touching consent — a test's own
434
- * teardown, and a page's own unload hook. */
435
- destroy() { clearTimer(); },
528
+ /** Stops the poll timer and any running cycle without touching consent —
529
+ * a test's own teardown, and a page's own unload hook. */
530
+ destroy() { stopRequested = true; clearTimer(); },
436
531
  };
437
532
  }
438
533