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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  });
@@ -148,3 +148,42 @@ export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch }
148
148
  },
149
149
  };
150
150
  }
151
+
152
+ function retryOnceOnUnavailable(fn) {
153
+ return async (...args) => {
154
+ try {
155
+ return await fn(...args);
156
+ } catch (err) {
157
+ if (!(err instanceof BackendUnavailable)) throw err;
158
+ return fn(...args);
159
+ }
160
+ };
161
+ }
162
+
163
+ /** Wraps a row backend so every method retries once on `BackendUnavailable`
164
+ * — a network-level failure, never `BackendRejected`, which a retry cannot
165
+ * fix. Every method here is safe to repeat: reads are read-only,
166
+ * `putRows`/`deleteRows` are upserts/keyed-deletes the service already
167
+ * documents as per-row atomic (a repeat just upserts or re-marks the same
168
+ * rows), and `deleteAll` already carries its own retry. The one race this
169
+ * covers: a consumer whose memory binds a large read-only seed as its base
170
+ * overlay (`wrapRowBackend`'s `basePayload`) does one CPU-heavy row
171
+ * projection the first time that session's memory is read — long enough,
172
+ * in a same-process test double, to occasionally land the very next
173
+ * network call on a socket the server had already begun tearing down.
174
+ * Real deployments (browser ↔ a separate Lambda-backed service) don't
175
+ * share an event loop with the store, so this is a same-process artifact,
176
+ * not a form of casual unreliability to paper over broadly — hence one
177
+ * retry, not a backoff loop. */
178
+ export function withOneRetryOnUnavailable(rowBackend) {
179
+ const wrapped = {
180
+ ...rowBackend,
181
+ readRows: retryOnceOnUnavailable(rowBackend.readRows),
182
+ putRows: retryOnceOnUnavailable(rowBackend.putRows),
183
+ deleteRows: retryOnceOnUnavailable(rowBackend.deleteRows),
184
+ readMeta: retryOnceOnUnavailable(rowBackend.readMeta),
185
+ putMeta: retryOnceOnUnavailable(rowBackend.putMeta),
186
+ };
187
+ if (typeof rowBackend.readRowsByTerm === "function") wrapped.readRowsByTerm = retryOnceOnUnavailable(rowBackend.readRowsByTerm);
188
+ return wrapped;
189
+ }
@@ -17,7 +17,8 @@
17
17
  // never published — only the hosted demo site's public/ledger.html links to
18
18
  // it, as an optional sibling script the page degrades honestly without.
19
19
  import { vocabExampleHint } from "../../services/chat.mjs";
20
- import { createInMemoryStore, normFactTerm, applySeedPayload, loadMemory, readFactRows } from "../../adapters/memory/core.mjs";
20
+ import { createInMemoryStore, normFactTerm, applySeedPayload, loadMemory, readFactRows, wrapRowBackend } from "../../adapters/memory/core.mjs";
21
+ import { createHttpRowBackend, withOneRetryOnUnavailable } from "./http-row-backend.mjs";
21
22
  import { splitSentencesPreservingPaths } from "../../services/sentences.mjs";
22
23
  import { parseEntities } from "../../domain/codegraph.mjs";
23
24
  import { memoryFactGraphPayload } from "../../domain/memory-facts.mjs";
@@ -45,14 +46,35 @@ import { graphAsk, enginePlan } from "./engine-surface.mjs";
45
46
  * traverses those facts while a code-structure question still refuses honestly.
46
47
  *
47
48
  * ledger-viz.mjs's own inline script calls computeLedgerDataFromPayload
48
- * (re-exported below) on `memoryDir.payload` after a turn whose record shows
49
- * a successful write (`via: "assert"` or `via: "retract"`, `miss: false`) to
50
- * re-derive the page's rows/terms/edges/stats and re-mount the same view a
51
- * fresh page load would have rendered — a plain query never re-derives.
49
+ * (re-exported below) on the session's current payload after a turn whose
50
+ * record shows a successful write (`via: "assert"` or `via: "retract"`,
51
+ * `miss: false`) to re-derive the page's rows/terms/edges/stats and re-mount
52
+ * the same view a fresh page load would have rendered — a plain query never
53
+ * re-derives.
54
+ *
55
+ * `awsSessionKey` (optional): the page's AWS-mode backend choice, the same
56
+ * seam chat-browser-entry.mjs's own createChatSession takes — given, the
57
+ * session's memory binds to `createHttpRowBackend({apiBase: "/", sessionKey:
58
+ * awsSessionKey, fetchImpl})` wrapped with `seedPayload` as its read-only
59
+ * seed overlay; omitted, memory stays the plain in-memory store. `fetchImpl`
60
+ * (optional) overrides the ambient `fetch` the row backend calls through —
61
+ * a test points it at a running row-service double.
52
62
  */
53
- export function createLedgerSession({ seedPayload = null, vocabSeeded = false } = {}) {
54
- const memoryDir = createInMemoryStore();
55
- applySeedPayload(memoryDir, seedPayload);
63
+ export function createLedgerSession({
64
+ seedPayload = null, vocabSeeded = false, awsSessionKey = null,
65
+ fetchImpl = (...args) => globalThis.fetch(...args),
66
+ } = {}) {
67
+ // onOversizedRow: "drop" — see chat-browser-entry.mjs's own createChatSession
68
+ // for why: a real corpus seed's high-fan-out mgx:statedBy group is already
69
+ // over the row cap before this session teaches anything, and a session's
70
+ // own new fact adding one more edge to it can't fit one wire row either.
71
+ // The read side (core.mjs) always keeps every seed row regardless, so
72
+ // nothing about the seed itself is lossy — only that one property's
73
+ // cross-fact edge index stays as unwritable as the seed's own copy of it.
74
+ const memoryDir = awsSessionKey
75
+ ? wrapRowBackend(withOneRetryOnUnavailable(createHttpRowBackend({ apiBase: "/", sessionKey: awsSessionKey, fetchImpl })), { basePayload: seedPayload, onOversizedRow: "drop" })
76
+ : createInMemoryStore();
77
+ if (!awsSessionKey) applySeedPayload(memoryDir, seedPayload);
56
78
 
57
79
  const codeGraph = parseEntities({ individuals: [], objectProperties: [] });
58
80