@polycode-projects/the-mechanical-code-talker 6.0.2 → 6.0.4

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.
@@ -540,6 +540,34 @@ function sparkCaptionHtml(stats) {
540
540
  : "cumulative facts, teach order";
541
541
  }
542
542
 
543
+ /**
544
+ * The page's backend mode from its own query string: "aws" when
545
+ * `backend=aws` is present, "local" for anything else — absent, empty, or
546
+ * any other value, silently. Mode is a boot choice (the slider rewrites the
547
+ * URL and reloads rather than switching a live session), so this is the one
548
+ * place either mode is ever decided.
549
+ *
550
+ * Self-contained (no outer refs), `.toString()`-splice safe.
551
+ */
552
+ export function resolveBackendMode(search) {
553
+ return new URLSearchParams(String(search || "")).get("backend") === "aws" ? "aws" : "local";
554
+ }
555
+
556
+ /**
557
+ * The current page address with its `backend` query parameter rewritten to
558
+ * match `mode` — "aws" written explicitly, anything else removed rather than
559
+ * written out as "local", so a plain reload never carries a redundant param.
560
+ * Every other query parameter and the hash survive untouched.
561
+ *
562
+ * Self-contained (no outer refs), `.toString()`-splice safe.
563
+ */
564
+ export function backendModeUrl(pageUrl, mode) {
565
+ const url = new URL(String(pageUrl));
566
+ if (mode === "aws") url.searchParams.set("backend", "aws");
567
+ else url.searchParams.delete("backend");
568
+ return url.toString();
569
+ }
570
+
543
571
  /** One complete, self-contained document: the ledger, segment rail,
544
572
  * worth-a-look panel, breadcrumb/search, two-hop minimap, and (when the
545
573
  * memory-ask bundle is present) the ask-the-graph chat dock, all over the
@@ -585,7 +613,15 @@ export function renderLedgerHtml({ rows, terms, edges, focus, contradictions, wo
585
613
  // session store, so they appear only where that bundle is offered — the
586
614
  // demo site, never the CLI's self-contained tmct viz page.
587
615
  const ingestHtml = ledgerBundleAvailable
588
- ? `<div class="docktools">
616
+ ? `<div class="backendrow" title="local: everything taught here lives in this browser tab only, and nothing survives a reload. AWS: taught facts save to an anonymous server-side session that expires after seven days, and reload where you left off. Switching reloads the page — a session is never moved between modes.">
617
+ <fieldset class="backendMode" id="backendMode">
618
+ <legend class="mono">backend</legend>
619
+ <label><input type="radio" name="backendMode" id="backendLocal" value="local" checked> local</label>
620
+ <label><input type="radio" name="backendMode" id="backendAws" value="aws"> AWS</label>
621
+ </fieldset>
622
+ <p class="backendnote mono" id="backendNote"></p>
623
+ </div>
624
+ <div class="docktools">
589
625
  <button type="button" id="ingestToggle" class="dockbtn">ingest text&hellip;</button>
590
626
  <button type="button" id="exportFacts" class="dockbtn">export facts</button>
591
627
  </div>
@@ -764,6 +800,15 @@ ${DASH_DARK_CHROME_CSS}
764
800
  .chatask input { flex: 1; font-family: ${MONO_STACK}; font-size: .78rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .32rem .6rem; min-width: 0; }
765
801
  .chatask input:disabled { opacity: .6; }
766
802
  .chatnote { font-family: ${MONO_STACK}; font-size: .72rem; color: var(--muted); margin: 0; }
803
+ /* local (this tab only) or AWS (an anonymous server-side session) — a boot
804
+ choice, so picking one reloads the page rather than switching a live
805
+ session. backendNote states whichever mode's promise is actually live. */
806
+ .backendrow { display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; margin-bottom: .55rem; }
807
+ fieldset.backendMode { border: none; margin: 0; padding: 0; display: inline-flex; align-items: center; gap: .5rem; font-size: .68rem; color: var(--muted); }
808
+ fieldset.backendMode legend { padding: 0; margin-right: .1rem; }
809
+ fieldset.backendMode label { display: inline-flex; align-items: center; gap: .22rem; cursor: pointer; white-space: nowrap; font-size: .72rem; }
810
+ fieldset.backendMode input[type="radio"] { margin: 0; accent-color: var(--corpus); }
811
+ .backendnote { font-size: .68rem; color: var(--muted); margin: 0; }
767
812
  .docktools { display: flex; gap: .5rem; margin-top: .55rem; }
768
813
  .dockbtn { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); border: 1px solid var(--line); border-radius: 6px; padding: .22rem .6rem; background: var(--bg); cursor: pointer; }
769
814
  .dockbtn:hover { color: var(--ink); border-color: var(--ink); }
@@ -847,6 +892,8 @@ ${ledgerBundleAvailable ? `<script src="./ledger-browser.bundle.js"></script>` :
847
892
  if ("serviceWorker" in navigator) navigator.serviceWorker.register("./tmct-sw.js").catch(() => {});
848
893
  const DAY = 86400000;
849
894
  const facetCounts = ${facetCounts.toString()};
895
+ const resolveBackendMode = ${resolveBackendMode.toString()};
896
+ const backendModeUrl = ${backendModeUrl.toString()};
850
897
  const el = (id) => document.getElementById(id);
851
898
  const esc = ${escapeHtml.toString()};
852
899
  // Aliased so the dashboard/sparkline builders below (toString-embedded
@@ -1167,6 +1214,44 @@ ${ledgerBundleAvailable ? `<script src="./ledger-browser.bundle.js"></script>` :
1167
1214
  return d;
1168
1215
  };
1169
1216
 
1217
+ // The backend mode is a boot choice, decided once from the URL this page
1218
+ // was loaded with — never switched under a live session. The radios only
1219
+ // ever reflect that choice and, on a change, rewrite the URL and reload.
1220
+ const backendModeFieldset = el("backendMode");
1221
+ const backendModeRadios = Array.prototype.slice.call(backendModeFieldset.querySelectorAll('input[type="radio"]'));
1222
+ const backendMode = resolveBackendMode(location.search);
1223
+ for (const radio of backendModeRadios) radio.checked = radio.value === backendMode;
1224
+ backendModeFieldset.addEventListener("change", function () {
1225
+ const chosen = backendModeRadios.find((r) => r.checked);
1226
+ location.href = backendModeUrl(location.href, chosen ? chosen.value : "local");
1227
+ });
1228
+ const backendNoteEl = el("backendNote");
1229
+ backendNoteEl.textContent = backendMode === "aws"
1230
+ ? "taught facts save to an anonymous server-side session that expires after seven days."
1231
+ : "taught facts stay in this browser tab only, and are lost on reload.";
1232
+
1233
+ // AWS mode's one local item: a session pointer, never facts. Resolved
1234
+ // once, eagerly, so the FIRST dock turn (not just a later one) already
1235
+ // knows whether to bind the session's memory to the row service.
1236
+ const AWS_SESSION_KEY = "tmct.ledger.sessionKey";
1237
+ function mintAwsSessionKey() {
1238
+ const key = crypto.randomUUID();
1239
+ try { localStorage.setItem(AWS_SESSION_KEY, key); } catch { /* private mode — this visit still works, just not restorable */ }
1240
+ return key;
1241
+ }
1242
+ let awsSessionKey = null;
1243
+ if (backendMode === "aws") {
1244
+ let stored = null;
1245
+ try { stored = localStorage.getItem(AWS_SESSION_KEY); } catch { stored = null; }
1246
+ awsSessionKey = stored || mintAwsSessionKey();
1247
+ }
1248
+
1249
+ // A row-backed session's memory has no .payload of its own (the
1250
+ // in-memory store's shape) — its current state lives in .cachedPayload,
1251
+ // kept fresh in place after every turn. .impl is present on a row
1252
+ // handle alone, so it doubles as the branch test.
1253
+ const payloadOf = (memoryDir) => (memoryDir.impl ? memoryDir.cachedPayload : memoryDir.payload);
1254
+
1170
1255
  let session = null;
1171
1256
  // Serializes every engine-touching call through this one dock — the same
1172
1257
  // posture plan-viz.mjs's own chat-assert dock takes with its withLock,
@@ -1204,11 +1289,11 @@ ${ledgerBundleAvailable ? `<script src="./ledger-browser.bundle.js"></script>` :
1204
1289
  async function ensureSession() {
1205
1290
  if (session) return session;
1206
1291
  await tryLoadWink();
1207
- session = await tmct.open({ seedPayload: PAYLOAD });
1292
+ session = await tmct.open({ seedPayload: PAYLOAD, awsSessionKey: awsSessionKey || undefined });
1208
1293
  // From here the live store is the source of truth for the digest, so a
1209
1294
  // digest of a term taught this session reads its fresh facts — the store
1210
1295
  // grows in place, so this one closure stays current.
1211
- getLivePayload = () => session.memoryDir.payload;
1296
+ getLivePayload = () => payloadOf(session.memoryDir);
1212
1297
  return session;
1213
1298
  }
1214
1299
 
@@ -1230,7 +1315,7 @@ ${ledgerBundleAvailable ? `<script src="./ledger-browser.bundle.js"></script>` :
1230
1315
  pending.className = "a" + (taught ? " taught" : (record && record.miss ? " miss" : ""));
1231
1316
  pending.innerHTML = taught ? '<span class="tag">taught</span>' + body : body;
1232
1317
  if (taught) {
1233
- const fresh = tmct.page.computeLedgerDataFromPayload(live.memoryDir.payload, {});
1318
+ const fresh = tmct.page.computeLedgerDataFromPayload(payloadOf(live.memoryDir), {});
1234
1319
  applyLedgerData(fresh);
1235
1320
  } else if (!(record && record.miss)) {
1236
1321
  // Only a genuine answer (never a miss) tries to resolve a
@@ -1298,7 +1383,7 @@ ${ledgerBundleAvailable ? `<script src="./ledger-browser.bundle.js"></script>` :
1298
1383
  const r = await tmct.turn(sentence);
1299
1384
  if (r.record && r.record.miss === false && r.record.via === "assert") grounded += 1;
1300
1385
  }
1301
- const fresh = tmct.page.computeLedgerDataFromPayload(s.memoryDir.payload, {});
1386
+ const fresh = tmct.page.computeLedgerDataFromPayload(payloadOf(s.memoryDir), {});
1302
1387
  applyLedgerData(fresh);
1303
1388
  const skipped = sentences.length - grounded;
1304
1389
  statusEl.textContent = countLabel(sentences.length, "sentence")
@@ -1373,7 +1458,7 @@ ${ledgerBundleAvailable ? `<script src="./ledger-browser.bundle.js"></script>` :
1373
1458
  researchQueue = result.research;
1374
1459
  renderResearchControls();
1375
1460
  if (!missed) {
1376
- const fresh = tmct.page.computeLedgerDataFromPayload(live.memoryDir.payload, {});
1461
+ const fresh = tmct.page.computeLedgerDataFromPayload(payloadOf(live.memoryDir), {});
1377
1462
  applyLedgerData(fresh);
1378
1463
  }
1379
1464
  }
@@ -164,8 +164,9 @@ export async function loadSeedPayload(fetcher, url, seedQuery, onProgress) {
164
164
  * opts.onForget when set, renders a "forget everything" button wired
165
165
  * to this callback; omitted, no button renders (a page
166
166
  * with no persistence to forget).
167
- * opts.persistNote when set (and onForget is set), a short note under the
168
- * forget button naming where the state lives.
167
+ * opts.persistNote when set, a short note naming where taught state
168
+ * lives (or that it isn't being saved), with or
169
+ * without the forget button above it.
169
170
  */
170
171
  export function renderStatsPanelInto(panelEl, stats, opts) {
171
172
  const { bandLabel, taughtHint, onForget = null, persistNote = null } = opts;
@@ -222,12 +223,15 @@ export function renderStatsPanelInto(panelEl, stats, opts) {
222
223
  forget.title = "clear what this device has saved and restart from the fresh seed";
223
224
  forget.addEventListener("click", onForget);
224
225
  panelEl.appendChild(forget);
225
- if (persistNote) {
226
- const note = document.createElement("p");
227
- note.className = "persist-note";
228
- note.textContent = persistNote;
229
- panelEl.appendChild(note);
230
- }
226
+ }
227
+ // The note stands on its own: a visit with nothing to forget (an
228
+ // unreachable service, an unpersisted mode) is exactly when the reader
229
+ // most needs to be told where taught facts are (not) going.
230
+ if (persistNote) {
231
+ const note = document.createElement("p");
232
+ note.className = "persist-note";
233
+ note.textContent = persistNote;
234
+ panelEl.appendChild(note);
231
235
  }
232
236
  }
233
237
 
@@ -122,6 +122,7 @@ ${THEME_TOKENS_CSS}
122
122
  @keyframes pulse { 0%, 100% { opacity: .25; } 50% { opacity: 1; } }
123
123
  @media (prefers-reduced-motion: reduce) { .btn[aria-busy="true"]::after { animation: none; opacity: .7; } }
124
124
  select { font-family: ${MONO_STACK}; font-size: .72rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .3rem .55rem; }
125
+ .fuzzytoggle { display: inline-flex; align-items: center; gap: .35rem; font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); cursor: pointer; }
125
126
  .sources { display: flex; flex-direction: column; gap: .3rem; margin: .6rem 0; }
126
127
  .sources h2 { margin: .6rem 0 .1rem; }
127
128
  .sourcegroup { display: flex; flex-direction: column; gap: .3rem; }
@@ -160,15 +161,34 @@ ${THEME_TOKENS_CSS}
160
161
  .teach { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: .7rem .85rem; margin-bottom: 1rem; }
161
162
  .teach textarea { width: 100%; box-sizing: border-box; min-height: 90px; font-family: ${MONO_STACK}; font-size: .76rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .5rem .6rem; }
162
163
  .teach .teachrow { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; align-items: center; }
164
+ .chat { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: .7rem .85rem; margin-bottom: 1rem; }
165
+ .chatlog { display: flex; flex-direction: column; gap: .5rem; max-height: 40vh; overflow-y: auto; margin: .5rem 0; padding-right: .25rem; }
166
+ .chatlog:empty::after { content: "ask the graph what it knows, or teach it something new"; color: var(--muted); font-size: .8rem; }
167
+ .chatturn { display: flex; flex-direction: column; gap: .2rem; }
168
+ .chatbubble { border: 1px solid var(--line); border-radius: 6px; padding: .4rem .6rem; font-size: .84rem; max-width: 42rem; white-space: pre-wrap; }
169
+ .chatturn.you { align-items: flex-end; }
170
+ .chatturn.you .chatbubble { background: var(--bg); }
171
+ .chatturn.graph .chatbubble { background: var(--bg); }
172
+ .chatturn.error .chatbubble { border-color: var(--alert); color: var(--alert); background: var(--alert-soft); }
173
+ .chatlearned { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); }
174
+ .chatlearned ul { margin: .15rem 0 0; padding-left: 1.1rem; }
175
+ .chattrace summary { font-family: ${MONO_STACK}; font-size: .64rem; color: var(--muted); cursor: pointer; }
176
+ .chattrace pre { font-family: ${MONO_STACK}; font-size: .64rem; color: var(--muted); white-space: pre-wrap; margin: .3rem 0 0; }
177
+ .chatform { display: flex; gap: .4rem; }
178
+ .chatform input[type="text"] { flex: 1; font: inherit; font-family: ${MONO_STACK}; font-size: .8rem; background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: .4rem .6rem; }
179
+ .chatform input[disabled] { opacity: .55; }
163
180
  .pagelog { font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); max-height: 140px; overflow-y: auto; border-top: 1px solid var(--line); padding-top: .4rem; }
164
181
  `;
165
182
 
166
183
  /** `renderNewsHtml({ title })` — one self-contained document: the dashboard,
167
184
  * the controls row (start/poll, enrich now, stop & forget), the source
168
- * panel, the request log, the feed, and the teach panel. Everything below
169
- * the teach panel is left unclaimed for the chat area this page will grow
170
- * next — an empty `#chatMount` section, not a placeholder for engine work
171
- * of its own. */
185
+ * panel, the request log, the feed, the teach panel, and the chat area.
186
+ * The chat area is the turn endpoint's page consumer: one input, one send,
187
+ * one transcript, over the same session UUID the feed already holds. A
188
+ * reply's text and any citation or trace text land through `textContent`/
189
+ * `createTextNode` only, never through markup built from a string — this
190
+ * page's answer text is the one thing on it never HTML-escaped-then-
191
+ * interpolated, because it never needs to be. */
172
192
  export function renderNewsHtml({ title = DEFAULT_TITLE } = {}) {
173
193
  return `<!doctype html>
174
194
  <html lang="en">
@@ -209,6 +229,7 @@ ${NEWS_STYLE}
209
229
  <div class="controls" id="controls">
210
230
  <button type="button" class="btn primary" id="newsStart">start polling live sources</button>
211
231
  <button type="button" class="btn" id="enrichNow">enrich now</button>
232
+ <label class="fuzzytoggle" for="fuzzyToggle"><input type="checkbox" id="fuzzyToggle" checked> fuzzy corpus match</label>
212
233
  <button type="button" class="btn ghost" id="stopForget">stop &amp; forget</button>
213
234
  <span class="mono" id="controlsStatus" aria-live="polite"></span>
214
235
  </div>
@@ -252,7 +273,16 @@ ${NEWS_STYLE}
252
273
  </div>
253
274
  </section>
254
275
 
255
- <section id="chatMount" aria-label="Chat"></section>
276
+ <section id="chatMount" aria-label="Chat">
277
+ <h2 class="tile-label">chat with the graph</h2>
278
+ <div class="chat">
279
+ <div class="chatlog" id="chatLog" aria-live="polite"></div>
280
+ <form class="chatform" id="chatForm">
281
+ <input type="text" id="chatInput" autocomplete="off" placeholder="press start above to chat with the graph" aria-label="Message to the graph" disabled>
282
+ <button type="submit" class="btn primary" id="chatSend" disabled>send</button>
283
+ </form>
284
+ </div>
285
+ </section>
256
286
 
257
287
  <div class="pagelog" id="pageLog" aria-live="polite"></div>
258
288
  </main>
@@ -274,6 +304,11 @@ ${NEWS_STYLE}
274
304
 
275
305
  const EMPTY_FEED = { items: [], rankedTerms: [], stats: { graphSize: 0, factsFromNews: 0 }, sourceStatus: [], requestLog: [], builtAt: null };
276
306
 
307
+ // Set once boot() opens the session; read by setUnavailable/
308
+ // updateChatAvailability below, which both live outside boot()'s own
309
+ // closure and never call the network themselves.
310
+ let session = null;
311
+
277
312
  function appendLog(text) {
278
313
  const line = document.createElement("div");
279
314
  line.textContent = text;
@@ -314,6 +349,81 @@ ${NEWS_STYLE}
314
349
  ["newsStart", "enrichNow", "stopForget", "teachIngest", "teachBrowse"].forEach(function (id) {
315
350
  el(id).disabled = isUnavailable;
316
351
  });
352
+ updateChatAvailability();
353
+ }
354
+
355
+ // Chat joins the same disabled-together posture as every other
356
+ // network-facing control once the service goes unreachable, and carries
357
+ // its OWN gate besides: it stays disabled until the visitor has pressed
358
+ // start at least once, the one control on this page that waits for that
359
+ // specific press rather than minting its own session on first use.
360
+ function updateChatAvailability() {
361
+ const blocked = !session || !session.consented || session.unavailable;
362
+ el("chatInput").disabled = blocked;
363
+ el("chatSend").disabled = blocked;
364
+ el("chatInput").placeholder = (session && session.consented)
365
+ ? "ask or teach the graph a fact"
366
+ : "press start above to chat with the graph";
367
+ }
368
+
369
+ /** One chat-log row: ".chatturn <kind>" wrapping one ".chatbubble" whose
370
+ * text lands through textContent alone — never HTML built from a
371
+ * string, matching the answer-text posture no other text on this page
372
+ * needs, since a chat reply is the one string here nobody has read or
373
+ * sanitised before it arrives. */
374
+ function chatBubble(kind, text) {
375
+ const row = document.createElement("div");
376
+ row.className = "chatturn " + kind;
377
+ const bubble = document.createElement("div");
378
+ bubble.className = "chatbubble";
379
+ bubble.textContent = text;
380
+ row.appendChild(bubble);
381
+ return row;
382
+ }
383
+
384
+ function appendChatTurn(kind, text) {
385
+ const row = chatBubble(kind, text);
386
+ el("chatLog").appendChild(row);
387
+ el("chatLog").scrollTop = el("chatLog").scrollHeight;
388
+ return row;
389
+ }
390
+
391
+ /** The graph's own turn, plus what it touched: result.citations (already
392
+ * phrase-layer English, from session.turn()) as a plain list under the
393
+ * reply, and result.narration as a collapsible trace — the same
394
+ * disclosure shape a fact card's own "what the graph already knew"
395
+ * details block uses. Both are optional; a plain answer with no writes
396
+ * and no trace text renders as just the one bubble. Says nothing about
397
+ * the feed either way — a taught fact reaches it at the next
398
+ * materialization, whenever that runs. */
399
+ function appendChatReply(result) {
400
+ const row = chatBubble("graph", result.reply);
401
+ if (result.citations && result.citations.length) {
402
+ const learned = document.createElement("div");
403
+ learned.className = "chatlearned";
404
+ learned.appendChild(document.createTextNode("learned this turn:"));
405
+ const list = document.createElement("ul");
406
+ for (const line of result.citations) {
407
+ const li = document.createElement("li");
408
+ li.textContent = line;
409
+ list.appendChild(li);
410
+ }
411
+ learned.appendChild(list);
412
+ row.appendChild(learned);
413
+ }
414
+ if (result.narration) {
415
+ const trace = document.createElement("details");
416
+ trace.className = "chattrace";
417
+ const summary = document.createElement("summary");
418
+ summary.textContent = "trace";
419
+ const pre = document.createElement("pre");
420
+ pre.textContent = result.narration;
421
+ trace.appendChild(summary);
422
+ trace.appendChild(pre);
423
+ row.appendChild(trace);
424
+ }
425
+ el("chatLog").appendChild(row);
426
+ el("chatLog").scrollTop = el("chatLog").scrollHeight;
317
427
  }
318
428
 
319
429
  function renderRequestLog(feed) {
@@ -328,6 +438,7 @@ ${NEWS_STYLE}
328
438
 
329
439
  function renderSourcesPanel(feed) {
330
440
  const byId = new Map((feed.sourceStatus || []).map(function (h) { return [h.sourceId, h]; }));
441
+ const nowMs = Date.now();
331
442
  document.querySelectorAll("[data-source-id]").forEach(function (row) {
332
443
  const health = byId.get(row.getAttribute("data-source-id"));
333
444
  const statusEl = row.querySelector("[data-source-status]");
@@ -335,6 +446,12 @@ ${NEWS_STYLE}
335
446
  if (health) {
336
447
  if (health.autoDisabled) text = "auto-disabled";
337
448
  else if (health.browserBlocked) text = "source does not permit browser access";
449
+ // A source can be skipped without being auto-disabled yet — one or
450
+ // two failures back off for a while rather than giving up on it —
451
+ // and that reads as nothing without its own note; left to fall
452
+ // through to lastStatus, a merely-cooling-down source would show
453
+ // "failed" forever, which understates what actually happened.
454
+ else if (health.backoffUntil && Date.parse(health.backoffUntil) > nowMs) text = "skipped — backing off";
338
455
  else if (health.lastStatus) text = health.lastStatus;
339
456
  }
340
457
  statusEl.textContent = text;
@@ -345,6 +462,27 @@ ${NEWS_STYLE}
345
462
  }));
346
463
  }
347
464
 
465
+ // Live progress during a running cycle, read off the marker each button
466
+ // press reports through its own onCycle callback — a poll cycle's own
467
+ // per-source entries as they land, or "polling…" for a roster member the
468
+ // marker hasn't reached yet. renderSourcesPanel overwrites all of this the
469
+ // moment the press's own promise resolves with the finished feed; this is
470
+ // only what a visitor sees while it's still running.
471
+ function renderCycleProgress(marker) {
472
+ if (!marker) return;
473
+ const perSource = marker.sources || {};
474
+ document.querySelectorAll("[data-source-id]").forEach(function (row) {
475
+ if (row.classList.contains("kb")) return;
476
+ const id = row.getAttribute("data-source-id");
477
+ const statusEl = row.querySelector("[data-source-status]");
478
+ if (Object.prototype.hasOwnProperty.call(perSource, id)) {
479
+ statusEl.textContent = perSource[id].status;
480
+ } else if (marker.state === "running" && marker.kind === "poll") {
481
+ statusEl.textContent = "polling…";
482
+ }
483
+ });
484
+ }
485
+
348
486
  function cardHtml(item) {
349
487
  const factLines = item.factLines || [];
350
488
  const factsHtml = factLines.map(function (line) { return '<div class="factrow">' + esc(line) + '</div>'; }).join("");
@@ -472,11 +610,21 @@ ${NEWS_STYLE}
472
610
  }
473
611
 
474
612
  async function boot() {
475
- const session = await window.tmct.open({});
613
+ session = await window.tmct.open({});
476
614
  window.tmct.news = { phase: "seeded" };
477
615
 
616
+ // The standing refresh loop lives inside the session, started already —
617
+ // this just subscribes to it. A cycle another tab (or a reload-surviving
618
+ // trigger) finishes reaches this page the same way a press's own cycle
619
+ // does, without this page having asked for anything.
620
+ session.onFeedUpdate(function (feed) {
621
+ renderAll(feed);
622
+ appendLog("the feed updated in the background");
623
+ });
624
+
478
625
  const startBtn = el("newsStart");
479
626
  startBtn.textContent = session.consented ? "poll now" : "start polling live sources";
627
+ updateChatAvailability(); // a restored, already-consented session unlocks chat right away
480
628
 
481
629
  function markBusy(button, label) {
482
630
  button.dataset.idleLabel = button.textContent;
@@ -515,12 +663,13 @@ ${NEWS_STYLE}
515
663
  startBtn.addEventListener("click", function () {
516
664
  emptyFeedText = DEFAULT_EMPTY_FEED_TEXT;
517
665
  const ids = [].slice.call(document.querySelectorAll("[data-source-toggle]:checked")).map(function (b) { return b.value; });
518
- runPress(startBtn, "polling…", function () { return session.consented ? "poll now" : "start polling live sources"; }, function () { return session.start(ids); })
666
+ runPress(startBtn, "polling…", function () { return session.consented ? "poll now" : "start polling live sources"; }, function () { return session.start(ids, { onCycle: renderCycleProgress }); })
519
667
  .catch(function () {});
520
668
  });
521
669
 
522
670
  el("enrichNow").addEventListener("click", function () {
523
- runPress(el("enrichNow"), "enriching…", function () { return "enrich now"; }, function () { return session.enrich(); })
671
+ const fuzzy = el("fuzzyToggle").checked;
672
+ runPress(el("enrichNow"), "enriching…", function () { return "enrich now"; }, function () { return session.enrich({ fuzzy: fuzzy, onCycle: renderCycleProgress }); })
524
673
  .catch(function () {});
525
674
  });
526
675
 
@@ -567,14 +716,40 @@ ${NEWS_STYLE}
567
716
  const graphSizeBefore = Number((el("tileGraphSize").querySelector("[data-value]") || {}).textContent) || 0;
568
717
  await runPress(btn, "ingesting…", function () { return "ingest"; }, async function () {
569
718
  const feed = looksLikeFactRows(text)
570
- ? await session.ingestRows(window.tmct.page.parseJsonlRows(text))
571
- : await session.ingestText(text);
719
+ ? await session.ingestRows(window.tmct.page.parseJsonlRows(text), { onCycle: renderCycleProgress })
720
+ : await session.ingestText(text, { onCycle: renderCycleProgress });
572
721
  const added = Math.max(0, (feed.stats.graphSize || 0) - graphSizeBefore);
573
722
  el("teachStatus").textContent = added + " fact(s) added to the graph";
574
723
  return feed;
575
724
  }).catch(function (err) { el("teachStatus").textContent = err.message || String(err); });
576
725
  });
577
726
 
727
+ el("chatForm").addEventListener("submit", async function (ev) {
728
+ ev.preventDefault();
729
+ const input = el("chatInput");
730
+ const text = input.value.trim();
731
+ if (!text || input.disabled) return;
732
+ appendChatTurn("you", text);
733
+ input.value = "";
734
+ const sendBtn = el("chatSend");
735
+ input.disabled = true;
736
+ sendBtn.disabled = true;
737
+ sendBtn.setAttribute("aria-busy", "true");
738
+ try {
739
+ const fuzzy = el("fuzzyToggle").checked;
740
+ const result = await session.turn(text, { fuzzy: fuzzy });
741
+ setUnavailable(false);
742
+ appendChatReply(result);
743
+ } catch (err) {
744
+ appendChatTurn("error", err && err.message ? err.message : String(err));
745
+ if (session.unavailable) setUnavailable(true);
746
+ } finally {
747
+ sendBtn.removeAttribute("aria-busy");
748
+ updateChatAvailability();
749
+ input.focus();
750
+ }
751
+ });
752
+
578
753
  if (session.sessionKey) {
579
754
  try {
580
755
  const feed = await session.fetchFeed();
@@ -38,7 +38,8 @@
38
38
  // (see that module's header), so the call is harmless either way, never
39
39
  // a load error and never a behavior change on the Node side.
40
40
  import { vocabExampleHint } from "../../services/chat.mjs";
41
- import { createInMemoryStore, normFactTerm, loadMemory, readFactRows, applySeedPayload } from "../../adapters/memory/core.mjs";
41
+ import { createInMemoryStore, normFactTerm, loadMemory, readFactRows, applySeedPayload, wrapRowBackend, isRowHandle } from "../../adapters/memory/core.mjs";
42
+ import { createHttpRowBackend, withOneRetryOnUnavailable } from "./http-row-backend.mjs";
42
43
  import { splitSentencesPreservingPaths } from "../../services/sentences.mjs";
43
44
  import { parseEntities } from "../../domain/codegraph.mjs";
44
45
  import { memoryFactGraphPayload } from "../../domain/memory-facts.mjs";
@@ -90,6 +91,16 @@ import { graphAsk, enginePlan } from "./engine-surface.mjs";
90
91
  * is module-scope, last write wins, and every session created after this one
91
92
  * shares it.
92
93
  *
94
+ * `awsSessionKey` (optional): the page's AWS-mode backend choice. Given, the
95
+ * session's memory binds to `createHttpRowBackend({apiBase: "/", sessionKey:
96
+ * awsSessionKey, fetchImpl})` wrapped with `seedPayload` as its read-only
97
+ * seed overlay (§3.1's basePayload — the seed is never written back to the
98
+ * service; only what a turn actually teaches lands as rows). Omitted (the
99
+ * default), memory stays the plain in-memory store it always was, seeded the
100
+ * same way. `fetchImpl` (optional) overrides the ambient `fetch` the row
101
+ * backend calls through — a page never passes it; a test points it at a
102
+ * running row-service double instead.
103
+ *
93
104
  * Returns { memoryDir, sessionId, graph, codeGraph, refreshGraph, turn }.
94
105
  * `turn(line)` resolves to { answer, end, record, plan } and threads
95
106
  * focus/last/planState between calls exactly as the CLI session does.
@@ -141,10 +152,27 @@ function newsProvidersFor(config) {
141
152
  };
142
153
  }
143
154
 
144
- export function createChatSession({ seedPayload = null, vocabSeeded = false, liveReference = false, onLiveLookup = null, synthesisBudget = 12, digestStructures = null } = {}) {
155
+ export function createChatSession({
156
+ seedPayload = null, vocabSeeded = false, liveReference = false, onLiveLookup = null,
157
+ synthesisBudget = 12, digestStructures = null, awsSessionKey = null,
158
+ fetchImpl = (...args) => globalThis.fetch(...args),
159
+ } = {}) {
145
160
  setDigestStructures(digestStructures || []);
146
- const memoryDir = createInMemoryStore();
147
- applySeedPayload(memoryDir, seedPayload);
161
+ // onOversizedRow: "drop" — a WRITE-side posture only (core.mjs's own
162
+ // read-side base projection always keeps every seed row regardless, so the
163
+ // seed itself is never lossy). A real corpus seed's own high-fan-out
164
+ // property (mgx:statedBy: one edge per fact) is already over the row cap
165
+ // before this session ever teaches anything; a session's own new fact adds
166
+ // one more edge to that same, already-uncapped group, which can never fit
167
+ // one wire row either way. Dropping that one write is the visitor's own
168
+ // "turn is itself the last resort" case the option exists for: the fact
169
+ // itself still writes and answers correctly (it is its own separate row),
170
+ // only that property's cross-fact edge index stays exactly as unwritable
171
+ // as the seed's own copy of it already was.
172
+ const memoryDir = awsSessionKey
173
+ ? wrapRowBackend(withOneRetryOnUnavailable(createHttpRowBackend({ apiBase: "/", sessionKey: awsSessionKey, fetchImpl })), { basePayload: seedPayload, onOversizedRow: "drop" })
174
+ : createInMemoryStore();
175
+ if (!awsSessionKey) applySeedPayload(memoryDir, seedPayload);
148
176
 
149
177
  // A known-empty code graph: code-structure questions get the same honest
150
178
  // no-code-graph answer an un-pointed CLI session gives, never a crash. The
@@ -235,6 +263,15 @@ export async function researchedFactRows(memoryDir) {
235
263
  .map((row) => ({ subject: row.subject, predicate: row.predicate, object: row.object }));
236
264
  }
237
265
 
266
+ /** The AWS-mode "forget everything"/"reset to seed" seam: marks every row
267
+ * and meta entry this session's row backend holds absent server-side. A
268
+ * no-op for a local (in-memory) session — there is nothing server-side to
269
+ * discard, so a page can call this unconditionally on its own memoryDir
270
+ * without first checking which mode it opened in. */
271
+ export async function discardAwsSession(memoryDir) {
272
+ if (isRowHandle(memoryDir)) await memoryDir.impl.deleteAll();
273
+ }
274
+
238
275
  // The page reaches the engine through the one shared surface: `tmct.open()`
239
276
  // opens this session, `tmct.turn()` runs the dock, `tmct.ask()` puts a
240
277
  // question to the session's own graph. What stays on `tmct.page` is what has
@@ -253,7 +290,7 @@ publishTmctSurface({
253
290
  page: {
254
291
  registerWinkModel, registerReferencePackProvider, registerLiveReferenceProvider,
255
292
  registerResearchProvider, registerNewsProvider, normFactTerm, vocabExampleHint, memoryStats,
256
- openPersistedStore, exportFactsJsonl, researchedFactRows,
293
+ openPersistedStore, exportFactsJsonl, researchedFactRows, discardAwsSession,
257
294
  splitSentences: splitSentencesPreservingPaths,
258
295
  },
259
296
  });
@@ -14,11 +14,23 @@ import {
14
14
  } from "../../adapters/memory/row-backend.mjs";
15
15
 
16
16
  const SESSION_HEADER = "x-tmct-session";
17
+ const PAYLOAD_HASH_HEADER = "x-amz-content-sha256";
17
18
 
18
19
  function trimTrailingSlash(value) {
19
20
  return value.endsWith("/") ? value.slice(0, -1) : value;
20
21
  }
21
22
 
23
+ /** Hex SHA-256 of `text`, via Web Crypto (available as `globalThis.crypto.subtle`
24
+ * in both browsers and node >= 20, so this needs no node-only import and
25
+ * stays safe to bundle for the page). Every body-carrying `/api/*` request
26
+ * needs this as `x-amz-content-sha256`: Lambda URLs behind OAC 403 at the
27
+ * URL auth layer, before the handler ever runs, if a body-carrying request
28
+ * arrives without it. */
29
+ export async function sha256Hex(text) {
30
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
31
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
32
+ }
33
+
22
34
  /** Reads whatever text the response carries, for the error's own message
23
35
  * only. The class decision uses the status code alone (the service's own
24
36
  * §3.8 mapping), so a consumer never has to parse a body to know whether a
@@ -94,7 +106,12 @@ export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch }
94
106
  }
95
107
 
96
108
  async function mutate(path, { method, body }, { retryOn5xx = false } = {}) {
97
- const init = { method, headers: jsonHeaders, body: JSON.stringify(body) };
109
+ const serializedBody = JSON.stringify(body);
110
+ const init = {
111
+ method,
112
+ headers: { ...jsonHeaders, [PAYLOAD_HASH_HEADER]: await sha256Hex(serializedBody) },
113
+ body: serializedBody,
114
+ };
98
115
  const response = retryOn5xx
99
116
  ? await fetchWithOneRetryOn5xx(fetchImpl, `${base}${path}`, init, "could not reach the row service")
100
117
  : await runFetch(fetchImpl, `${base}${path}`, init, "could not reach the row service");
@@ -148,3 +165,42 @@ export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch }
148
165
  },
149
166
  };
150
167
  }
168
+
169
+ function retryOnceOnUnavailable(fn) {
170
+ return async (...args) => {
171
+ try {
172
+ return await fn(...args);
173
+ } catch (err) {
174
+ if (!(err instanceof BackendUnavailable)) throw err;
175
+ return fn(...args);
176
+ }
177
+ };
178
+ }
179
+
180
+ /** Wraps a row backend so every method retries once on `BackendUnavailable`
181
+ * — a network-level failure, never `BackendRejected`, which a retry cannot
182
+ * fix. Every method here is safe to repeat: reads are read-only,
183
+ * `putRows`/`deleteRows` are upserts/keyed-deletes the service already
184
+ * documents as per-row atomic (a repeat just upserts or re-marks the same
185
+ * rows), and `deleteAll` already carries its own retry. The one race this
186
+ * covers: a consumer whose memory binds a large read-only seed as its base
187
+ * overlay (`wrapRowBackend`'s `basePayload`) does one CPU-heavy row
188
+ * projection the first time that session's memory is read — long enough,
189
+ * in a same-process test double, to occasionally land the very next
190
+ * network call on a socket the server had already begun tearing down.
191
+ * Real deployments (browser ↔ a separate Lambda-backed service) don't
192
+ * share an event loop with the store, so this is a same-process artifact,
193
+ * not a form of casual unreliability to paper over broadly — hence one
194
+ * retry, not a backoff loop. */
195
+ export function withOneRetryOnUnavailable(rowBackend) {
196
+ const wrapped = {
197
+ ...rowBackend,
198
+ readRows: retryOnceOnUnavailable(rowBackend.readRows),
199
+ putRows: retryOnceOnUnavailable(rowBackend.putRows),
200
+ deleteRows: retryOnceOnUnavailable(rowBackend.deleteRows),
201
+ readMeta: retryOnceOnUnavailable(rowBackend.readMeta),
202
+ putMeta: retryOnceOnUnavailable(rowBackend.putMeta),
203
+ };
204
+ if (typeof rowBackend.readRowsByTerm === "function") wrapped.readRowsByTerm = retryOnceOnUnavailable(rowBackend.readRowsByTerm);
205
+ return wrapped;
206
+ }