@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.
package/README.md CHANGED
@@ -103,6 +103,18 @@ Teach it a fact in plain English and it mints a node. Ask it a question and
103
103
  it answers from what it was seeded with, what you taught it, and what it can
104
104
  derive by rule from both. Every answer is either grounded or an honest miss.
105
105
 
106
+ ## Host it yourself
107
+
108
+ tmct is a library first. You can embed it as a backend, running the engine
109
+ server-side over your own fact store (DynamoDB, SQLite, in-memory, or a
110
+ custom backend that passes the published conformance kit). Load corpus data from your own sources using the shipped
111
+ `tmct corpus` CLI verb; the reference bands (WordNet, ConceptNet, Wikidata)
112
+ are built in-tree. The deployed demos at tmct.polycode.co.uk show this
113
+ architecture end to end: the chat and ledger pages run the engine in-page
114
+ locally, while the news page is a thin client that calls server-side turn
115
+ and feed endpoints — both run on the same tmct library backend and session
116
+ table. Choose the architecture that fits your use case.
117
+
106
118
  ## Repository layout
107
119
 
108
120
  | directory | contains |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "6.0.2",
3
+ "version": "6.0.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -796,7 +796,13 @@ async function readRowPayload(handle) {
796
796
  if (!handle.cachedPayload) {
797
797
  const empty = emptyMemory();
798
798
  const stored = await collectRows(handle.impl.readRows());
799
- handle.baseRows = payloadToRows(handle.basePayload || empty);
799
+ // "keep": the base overlay's own rows never reach the wire (persistRowPayload
800
+ // excludes every seed key from every write via seedOnlyKeys below), so the
801
+ // per-row byte cap that protects a real backend's real item-size limit has
802
+ // nothing to protect here — capping it would silently drop a real corpus
803
+ // band's own high-fan-out property (one edge per fact is normal, not a
804
+ // pathology) and break every read that depends on it.
805
+ handle.baseRows = payloadToRows(handle.basePayload || empty, { onOversizedRow: "keep" });
800
806
  handle.storedRows = stored.filter((row) => row?.rowClass !== BOOKKEEPING_ROW_CLASS);
801
807
  handle.cachedPayload = rowsToPayload(overlayRows(handle.baseRows, handle.storedRows), {
802
808
  meta: {
@@ -109,14 +109,20 @@ function ordAssigner(priorRows) {
109
109
  };
110
110
  }
111
111
 
112
- /** Refuse or drop an oversized row. The default posture throws: one fact that
113
- * big is an extraction pathology and the turn should fail loudly, naming the
114
- * provenance that produced it. A consumer whose turn is itself the last resort
115
- * passes `onOversizedRow: "drop"` instead, and the turn completes with
116
- * everything else persisted. */
112
+ /** Refuse, drop, or keep an oversized row. The default posture throws: one
113
+ * fact that big is an extraction pathology and the turn should fail loudly,
114
+ * naming the provenance that produced it. A consumer whose turn is itself
115
+ * the last resort passes `onOversizedRow: "drop"` instead, and the turn
116
+ * completes with everything else persisted. `"keep"` is for rows that will
117
+ * never actually reach the wire — a read-only seed overlay's own projection
118
+ * (core.mjs's `readRowPayload`), never a caller-facing choice: the cap
119
+ * protects a real backend's real per-item limit, which does not apply to a
120
+ * base payload `persistRowPayload` already excludes from every write
121
+ * (`seedOnlyKeys`). Silent — an oversized seed row is not a pathology, it's
122
+ * what a real corpus band's own high-fan-out property looks like. */
117
123
  function admitRow(row, provenance, { onOversizedRow, log }) {
118
124
  const bytes = rowJsonBytes(row);
119
- if (bytes <= MAX_ROW_BYTES) return true;
125
+ if (bytes <= MAX_ROW_BYTES || onOversizedRow === "keep") return true;
120
126
  const where = provenance ? ` (provenance: ${provenance})` : "";
121
127
  const detail = `${row.rowClass} row ${row.rowKey} serializes to ${bytes} bytes, over the ${MAX_ROW_BYTES}-byte cap${where}`;
122
128
  if (onOversizedRow === "drop") {
@@ -127,16 +133,18 @@ function admitRow(row, provenance, { onOversizedRow, log }) {
127
133
  }
128
134
 
129
135
  const warnToConsole = (message) => console.warn(message);
136
+ const OVERSIZED_ROW_POSTURES = new Set(["throw", "drop", "keep"]);
130
137
 
131
138
  /** Project a memory payload into wire rows.
132
139
  *
133
140
  * `priorRows` are the rows this payload was last projected as; pass them and
134
141
  * every unchanged row comes back byte-identical, so `diffRows` writes only
135
- * what actually moved. `onOversizedRow` is "throw" (default) or "drop", and
136
- * `log` takes the drop notices. */
142
+ * what actually moved. `onOversizedRow` is "throw" (default), "drop", or
143
+ * "keep" (rows that never reach the wire — see `admitRow`), and `log` takes
144
+ * the drop notices. */
137
145
  export function payloadToRows(payload, { priorRows = null, onOversizedRow = "throw", log = warnToConsole } = {}) {
138
- if (onOversizedRow !== "throw" && onOversizedRow !== "drop") {
139
- throw new TypeError(`onOversizedRow must be "throw" or "drop", got ${JSON.stringify(onOversizedRow)}`);
146
+ if (!OVERSIZED_ROW_POSTURES.has(onOversizedRow)) {
147
+ throw new TypeError(`onOversizedRow must be "throw", "drop", or "keep", got ${JSON.stringify(onOversizedRow)}`);
140
148
  }
141
149
  const ordFor = ordAssigner(priorRows);
142
150
  const posture = { onOversizedRow, log };
@@ -96,15 +96,17 @@ async function fetchMergedEntities(config) {
96
96
 
97
97
  /** Fetch the entities payload through the provider seam. With a registered provider, its
98
98
  * result is returned as-is (uncached); a non-object result is a clean ToolError. Default:
99
- * read + parse the local graph artifact, cached per file. A missing artifact (ENOENT)
99
+ * read + parse the local graph artifact, cached per file. A missing artifact (ENOENT), or
100
+ * no config/graphFile at all (a graph-less caller — nothing was ever configured to read),
100
101
  * returns the bootstrap payload, uncached, so a freshly written file is picked up next
101
102
  * fetch. When `config.graphFiles` names more than one file, delegates to
102
103
  * fetchMergedEntities instead. */
103
104
  export async function fetchEntities(config) {
105
+ const cfg = config || {};
104
106
  if (provider) {
105
107
  let payload;
106
108
  try {
107
- payload = await provider(config);
109
+ payload = await provider(cfg);
108
110
  } catch (e) {
109
111
  if (e instanceof ToolError) throw e;
110
112
  throw new ToolError(`graph provider failed (${e?.message || e})`);
@@ -114,25 +116,26 @@ export async function fetchEntities(config) {
114
116
  }
115
117
  return payload;
116
118
  }
117
- if (Array.isArray(config.graphFiles) && config.graphFiles.length > 1) {
118
- return fetchMergedEntities(config);
119
+ if (Array.isArray(cfg.graphFiles) && cfg.graphFiles.length > 1) {
120
+ return fetchMergedEntities(cfg);
119
121
  }
120
- if (cache && cache.file === config.graphFile) return cache.payload;
122
+ if (!cfg.graphFile) return emptyEntities();
123
+ if (cache && cache.file === cfg.graphFile) return cache.payload;
121
124
  let text;
122
125
  try {
123
- text = await readFile(config.graphFile, "utf8");
126
+ text = await readFile(cfg.graphFile, "utf8");
124
127
  } catch (e) {
125
128
  if (e?.code === "ENOENT") return emptyEntities();
126
129
  throw new ToolError(
127
- `cannot read graph artifact at ${config.graphFile} (${e?.code || e?.message || e})`,
130
+ `cannot read graph artifact at ${cfg.graphFile} (${e?.code || e?.message || e})`,
128
131
  );
129
132
  }
130
133
  let payload;
131
134
  try {
132
135
  payload = JSON.parse(text);
133
136
  } catch {
134
- throw new ToolError(`graph artifact ${config.graphFile} is not valid JSON`);
137
+ throw new ToolError(`graph artifact ${cfg.graphFile} is not valid JSON`);
135
138
  }
136
- cache = { file: config.graphFile, payload };
139
+ cache = { file: cfg.graphFile, payload };
137
140
  return payload;
138
141
  }
@@ -366,6 +366,35 @@ export function inviteParamsFrom(search) {
366
366
  return { offer: offer, world: params.get("world") || "", worldName: params.get("name") || "" };
367
367
  }
368
368
 
369
+ /**
370
+ * The page's backend mode from its own query string: "aws" when
371
+ * `backend=aws` is present, "local" for anything else — absent, empty, or
372
+ * any other value, silently. Mode is a boot choice (the slider rewrites the
373
+ * URL and reloads rather than switching a live session), so this is the one
374
+ * place either mode is ever decided.
375
+ *
376
+ * Self-contained (no outer refs), `.toString()`-splice safe.
377
+ */
378
+ export function resolveBackendMode(search) {
379
+ return new URLSearchParams(String(search || "")).get("backend") === "aws" ? "aws" : "local";
380
+ }
381
+
382
+ /**
383
+ * The current page address with its `backend` query parameter rewritten to
384
+ * match `mode` — "aws" written explicitly, anything else removed rather than
385
+ * written out as "local", so a plain reload never carries a redundant param.
386
+ * Every other query parameter and the hash survive untouched, so a slider
387
+ * flip never drops an invite the address was already carrying.
388
+ *
389
+ * Self-contained (no outer refs), `.toString()`-splice safe.
390
+ */
391
+ export function backendModeUrl(pageUrl, mode) {
392
+ const url = new URL(String(pageUrl));
393
+ if (mode === "aws") url.searchParams.set("backend", "aws");
394
+ else url.searchParams.delete("backend");
395
+ return url.toString();
396
+ }
397
+
369
398
  /**
370
399
  * The boot statusline while the big assets stream in — "loading the engine…
371
400
  * X MB / Y MB", aggregated across every asset currently downloading. `parts`
@@ -561,13 +590,18 @@ ${THEME_TOKENS_CSS}
561
590
  only) has no radio of its own — every radio clears when that mode is
562
591
  active, and the statusline names it instead. */
563
592
  .composer-wiki { max-width: 720px; margin: 0 auto; padding: 0 1.1rem .4rem; display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); }
564
- fieldset.wikiMode { border: none; margin: 0; padding: 0; display: inline-flex; align-items: center; gap: .7rem; }
565
- fieldset.wikiMode legend { padding: 0; margin-right: .15rem; font: inherit; color: inherit; }
566
- fieldset.wikiMode label { display: inline-flex; align-items: center; gap: .28rem; cursor: pointer; white-space: nowrap; }
567
- fieldset.wikiMode input[type="radio"] { margin: 0; accent-color: var(--corpus); }
593
+ fieldset.wikiMode, fieldset.backendMode { border: none; margin: 0; padding: 0; display: inline-flex; align-items: center; gap: .7rem; }
594
+ fieldset.wikiMode legend, fieldset.backendMode legend { padding: 0; margin-right: .15rem; font: inherit; color: inherit; }
595
+ fieldset.wikiMode label, fieldset.backendMode label { display: inline-flex; align-items: center; gap: .28rem; cursor: pointer; white-space: nowrap; }
596
+ fieldset.wikiMode input[type="radio"], fieldset.backendMode input[type="radio"] { margin: 0; accent-color: var(--corpus); }
568
597
  .synthRow { display: inline-flex; align-items: center; gap: .5rem; white-space: nowrap; }
569
598
  .synthRow input[type="range"] { width: 88px; accent-color: var(--corpus); }
570
599
 
600
+ /* the backend row, above the wiki row: local (this browser, IndexedDB) or
601
+ AWS (an anonymous server-side session) — a boot choice, so picking one
602
+ reloads the page rather than switching a live session. */
603
+ .composer-backend { max-width: 720px; margin: 0 auto; padding: .5rem 1.1rem 0; display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); }
604
+
571
605
  /* the research row: type a topic, and the page asks "research <topic>"
572
606
  then ticks "research next" turns through the queue — play/pause rides
573
607
  the shared viz-ticker verbs. Same quiet mono idiom as the wiki row. */
@@ -751,6 +785,13 @@ ${shareOverlayHtml({ withTape: true })}
751
785
  placeholder="loading the engine…" aria-label="Ask tmct something" disabled>
752
786
  <button type="submit" id="composerSend" aria-label="Send" disabled>&#8594;</button>
753
787
  </div>
788
+ <div class="composer-backend">
789
+ <fieldset class="backendMode" id="backendMode" title="local: everything you teach stays in this browser only (IndexedDB), never sent anywhere. AWS: the same engine, but taught facts save to an anonymous server-side session that expires after seven days, restored on reload. Switching reloads the page — a session is never moved between modes.">
790
+ <legend>backend</legend>
791
+ <label><input type="radio" name="backendMode" id="backendLocal" value="local" checked> local</label>
792
+ <label><input type="radio" name="backendMode" id="backendAws" value="aws"> AWS</label>
793
+ </fieldset>
794
+ </div>
754
795
  <div class="composer-wiki">
755
796
  <fieldset class="wikiMode" id="wikiMode" title="Off by default. &quot;when I don't know&quot;: a question nothing local can answer also asks en.wikipedia.org — two small requests per lookup, cited (CC BY-SA). &quot;always&quot;: every grounded answer also gets a cited Wikipedia read-out. Type /wiki supplement for that same read-out on grounded answers only, without switching this to always.">
756
797
  <legend>ask wikipedia</legend>
@@ -812,6 +853,8 @@ ${shareOverlayHtml({ withTape: true })}
812
853
  const nodeInitials = ${nodeInitials.toString()};
813
854
  const inviteLinkFor = ${inviteLinkFor.toString()};
814
855
  const inviteParamsFrom = ${inviteParamsFrom.toString()};
856
+ const resolveBackendMode = ${resolveBackendMode.toString()};
857
+ const backendModeUrl = ${backendModeUrl.toString()};
815
858
  const tapeClock = ${tapeClock.toString()};
816
859
  const relativeWhen = ${relativeWhen.toString()};
817
860
  const shareStepStates = ${shareStepStates.toString()};
@@ -844,6 +887,19 @@ ${shareOverlayHtml({ withTape: true })}
844
887
  const synthSliderEl = el("synthSlider");
845
888
  const synthValueEl = el("synthValue");
846
889
 
890
+ // The backend mode is a boot choice, decided once from the URL this page
891
+ // was loaded with — never switched under a live session. The radios only
892
+ // ever reflect that choice and, on a change, rewrite the URL and reload;
893
+ // they never flip the running session's own store.
894
+ const backendModeFieldset = el("backendMode");
895
+ const backendModeRadios = Array.prototype.slice.call(backendModeFieldset.querySelectorAll('input[type="radio"]'));
896
+ const backendMode = resolveBackendMode(location.search);
897
+ for (const radio of backendModeRadios) radio.checked = radio.value === backendMode;
898
+ backendModeFieldset.addEventListener("change", function () {
899
+ const chosen = backendModeRadios.find((r) => r.checked);
900
+ location.href = backendModeUrl(location.href, chosen ? chosen.value : "local");
901
+ });
902
+
847
903
  // The wikipedia mode: "off" | "miss" (the radio's own value for what the
848
904
  // session calls plain true, a rescue on a clean miss) | "always". "supplement"
849
905
  // (typed /wiki supplement only) never lands here — a turn that sets it
@@ -889,6 +945,25 @@ ${shareOverlayHtml({ withTape: true })}
889
945
  try { localStorage.setItem(SYNTH_BUDGET_KEY, String(n)); } catch { /* private mode — this visit still works */ }
890
946
  }
891
947
 
948
+ // AWS mode's one local item: a session pointer, never facts (§2's own
949
+ // wording — the copy the stats panel shows repeats it). Read once at boot;
950
+ // minted fresh whenever none is stored yet, or after a purge discards one.
951
+ const AWS_SESSION_KEY = "tmct.chat.sessionKey";
952
+ function readAwsSessionKey() {
953
+ try { return localStorage.getItem(AWS_SESSION_KEY) || null; } catch { return null; }
954
+ }
955
+ function writeAwsSessionKey(key) {
956
+ try { localStorage.setItem(AWS_SESSION_KEY, key); } catch { /* private mode — this visit still works, just not restorable */ }
957
+ }
958
+ function discardAwsSessionKey() {
959
+ try { localStorage.removeItem(AWS_SESSION_KEY); } catch { /* already effectively gone this visit */ }
960
+ }
961
+ function mintAwsSessionKey() {
962
+ const key = crypto.randomUUID();
963
+ writeAwsSessionKey(key);
964
+ return key;
965
+ }
966
+
892
967
  function scrollToEnd() {
893
968
  messagesEl.parentElement.scrollTop = messagesEl.parentElement.scrollHeight;
894
969
  }
@@ -1126,6 +1201,7 @@ ${shareOverlayHtml({ withTape: true })}
1126
1201
  synthesisBudget: readSynthBudget(),
1127
1202
  onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
1128
1203
  digestStructures: DIGEST_STRUCTURES,
1204
+ awsSessionKey: (backendMode === "aws" && !persistenceUnavailable) ? awsSessionKey : undefined,
1129
1205
  });
1130
1206
  }
1131
1207
 
@@ -1164,6 +1240,11 @@ ${shareOverlayHtml({ withTape: true })}
1164
1240
  let restoredCount = 0;
1165
1241
  let siteVersion = "dev";
1166
1242
  let lastStatsTotal = null;
1243
+ // AWS mode's own state: the minted/restored session pointer, and whether
1244
+ // the row service ever answered this visit. Local mode never touches
1245
+ // either — persist (IndexedDB) stays that mode's own persistence.
1246
+ let awsSessionKey = null;
1247
+ let persistenceUnavailable = false;
1167
1248
  window.tmctChatLastSave = null;
1168
1249
  window.tmct.lastSave = null;
1169
1250
 
@@ -1193,7 +1274,15 @@ ${shareOverlayHtml({ withTape: true })}
1193
1274
  async function forgetEverything() {
1194
1275
  clearTimeout(saveTimer);
1195
1276
  saveTimer = null;
1196
- if (persist) await persist.clear();
1277
+ if (backendMode === "aws" && !persistenceUnavailable) {
1278
+ if (window.tmct.session && window.tmct.page.discardAwsSession) {
1279
+ try { await window.tmct.page.discardAwsSession(window.tmct.session.memoryDir); }
1280
+ catch { /* best effort — the old session still expires on its own within seven days */ }
1281
+ }
1282
+ awsSessionKey = mintAwsSessionKey();
1283
+ } else if (persist) {
1284
+ await persist.clear();
1285
+ }
1197
1286
  restoredCount = 0;
1198
1287
  // The room holds the OLD session's store, so it can't outlive the swap —
1199
1288
  // it would keep merging peers' facts into a store nothing reads any more.
@@ -1201,7 +1290,10 @@ ${shareOverlayHtml({ withTape: true })}
1201
1290
  dropRoom();
1202
1291
  await newSession();
1203
1292
  const stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
1204
- addSystemLine("forgot everything taught on this device \\u2014 back to the fresh seed (" + statsSummaryLine(stats, bandLabelFor) + ").");
1293
+ const note = backendMode === "aws" && !persistenceUnavailable
1294
+ ? "forgot everything taught this session \\u2014 back to the fresh seed under a new anonymous session ("
1295
+ : "forgot everything taught on this device \\u2014 back to the fresh seed (";
1296
+ addSystemLine(note + statsSummaryLine(stats, bandLabelFor) + ").");
1205
1297
  await renderStatsPanel(stats);
1206
1298
  }
1207
1299
 
@@ -1225,10 +1317,15 @@ ${shareOverlayHtml({ withTape: true })}
1225
1317
  }
1226
1318
  lastStatsTotal = Number(stats.total || 0);
1227
1319
  renderFactPill();
1320
+ const awsPersisting = backendMode === "aws" && !persistenceUnavailable;
1228
1321
  renderStatsPanelInto(statsPanelEl, stats, {
1229
1322
  bandLabel: bandLabelFor,
1230
- onForget: persist ? forgetEverything : null,
1231
- persistNote: "taught facts are kept best-effort on this device (IndexedDB), never sent anywhere.",
1323
+ onForget: (awsPersisting || persist) ? forgetEverything : null,
1324
+ persistNote: backendMode === "aws"
1325
+ ? (persistenceUnavailable
1326
+ ? "the row service wasn't reachable this visit \\u2014 taught facts are not being saved anywhere."
1327
+ : "taught facts are stored server-side against an anonymous session that expires after seven days.")
1328
+ : "taught facts are kept best-effort on this device (IndexedDB), never sent anywhere.",
1232
1329
  });
1233
1330
  }
1234
1331
 
@@ -1649,14 +1746,23 @@ ${shareOverlayHtml({ withTape: true })}
1649
1746
  // first visit. Harder than "forget everything", which only swaps the live
1650
1747
  // session — this trusts nothing in memory and re-fetches the seed asset.
1651
1748
  //
1652
- // Both stores go, not just the payload: what you taught lives in IndexedDB,
1653
- // and the seed asset itself lives in the service worker's Cache Storage. A
1654
- // reset that cleared only the first would re-seed straight back out of a
1655
- // cached copy of an older seed, which is exactly what it promises not to do.
1749
+ // Both stores go, not just the payload: what you taught lives in IndexedDB
1750
+ // (local mode) or the row service (AWS mode), and the seed asset itself
1751
+ // lives in the service worker's Cache Storage. A reset that cleared only
1752
+ // the first would re-seed straight back out of a cached copy of an older
1753
+ // seed, which is exactly what it promises not to do. In AWS mode the reset
1754
+ // also discards the stored session pointer, so the reload it triggers
1755
+ // mints a fresh one — the same "back to a first visit" promise, kept on
1756
+ // the server side too.
1656
1757
  el("reinitStore").addEventListener("click", async () => {
1657
1758
  clearTimeout(saveTimer);
1658
1759
  saveTimer = null;
1659
1760
  if (persist) await persist.clear();
1761
+ if (backendMode === "aws" && !persistenceUnavailable && window.tmct.session && window.tmct.page.discardAwsSession) {
1762
+ try { await window.tmct.page.discardAwsSession(window.tmct.session.memoryDir); }
1763
+ catch { /* best effort — TTL still reclaims it within seven days */ }
1764
+ discardAwsSessionKey();
1765
+ }
1660
1766
  await clearSiteAssetCaches();
1661
1767
  window.location.reload();
1662
1768
  });
@@ -2410,36 +2516,93 @@ ${shareOverlayHtml({ withTape: true })}
2410
2516
  await Promise.all([fetchSeed(), tryLoadWink(), fetchSiteVersion().then((v) => { siteVersion = v; })]);
2411
2517
  progressActive = false;
2412
2518
  window.tmct.page.registerReferencePackProvider(fetchPackProvider);
2413
- if (window.tmct.page.openPersistedStore) {
2414
- persist = window.tmct.page.openPersistedStore({ storeKey: "chat", stamp: siteVersion + ":" + seedFacts + ":" + SEED_STAMP });
2415
- }
2416
- const savedRecord = persist ? await persist.load() : null;
2417
2519
  const initialMode = readWikiMode();
2418
2520
  setWikiModeRadios(initialMode);
2419
2521
  writeWikiMode(initialMode); // settles a legacy-key migration under the new key immediately, not only on the next radio change
2420
2522
  synthSliderEl.value = String(readSynthBudget());
2421
2523
  synthValueEl.textContent = synthSliderEl.value;
2422
- if (savedRecord && savedRecord.payload) {
2524
+
2525
+ // AWS mode boots straight into the row service under the stored (or
2526
+ // freshly minted) session pointer — no separate consent step, unlike
2527
+ // news.html's start press, since this page's engine is in-page either
2528
+ // way and the mode was already chosen before this script ran. Local
2529
+ // mode keeps its own IndexedDB restore path, byte-identical to before.
2530
+ let savedRecord = null;
2531
+ if (backendMode === "aws") {
2532
+ awsSessionKey = readAwsSessionKey() || mintAwsSessionKey();
2423
2533
  await window.tmct.open({
2424
- seedPayload: savedRecord.payload,
2425
- vocabSeeded: true,
2534
+ seedPayload: cloneSeed(),
2535
+ vocabSeeded: Boolean(seedPayload),
2426
2536
  liveReference: liveReferenceForMode(initialMode),
2427
2537
  synthesisBudget: readSynthBudget(),
2428
2538
  onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
2429
2539
  digestStructures: DIGEST_STRUCTURES,
2540
+ awsSessionKey: awsSessionKey,
2430
2541
  });
2431
2542
  } else {
2432
- await newSession();
2543
+ if (window.tmct.page.openPersistedStore) {
2544
+ persist = window.tmct.page.openPersistedStore({ storeKey: "chat", stamp: siteVersion + ":" + seedFacts + ":" + SEED_STAMP });
2545
+ }
2546
+ savedRecord = persist ? await persist.load() : null;
2547
+ if (savedRecord && savedRecord.payload) {
2548
+ await window.tmct.open({
2549
+ seedPayload: savedRecord.payload,
2550
+ vocabSeeded: true,
2551
+ liveReference: liveReferenceForMode(initialMode),
2552
+ synthesisBudget: readSynthBudget(),
2553
+ onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
2554
+ digestStructures: DIGEST_STRUCTURES,
2555
+ });
2556
+ } else {
2557
+ await newSession();
2558
+ }
2433
2559
  }
2434
2560
  // The session now holds whatever the seed brought, so the phase settles
2435
2561
  // here rather than when the bytes landed: "ready" means queryable.
2436
2562
  if (window.tmct.seed.state !== "failed") setSeedPhase("ready");
2437
- const stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2438
- if (savedRecord) restoredCount = stats.taught.length;
2439
- const restoredNote = savedRecord
2440
- ? " Restored " + restoredCount + " taught fact" + (restoredCount === 1 ? "" : "s")
2441
- + " from your last visit \\u2014 state kept best-effort on this device."
2442
- : "";
2563
+
2564
+ // AWS mode's first real read: an unreachable row service surfaces here,
2565
+ // before "ready" is ever said, and the page falls through to running
2566
+ // this visit unpersisted rather than failing to boot — the best-effort
2567
+ // row every page keeps (§2's own wording): the engine is in-page, so a
2568
+ // service outage never blocks the page, it only costs this visit's save.
2569
+ let stats;
2570
+ if (backendMode === "aws") {
2571
+ try {
2572
+ stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2573
+ } catch {
2574
+ persistenceUnavailable = true;
2575
+ await window.tmct.open({
2576
+ seedPayload: cloneSeed(),
2577
+ vocabSeeded: Boolean(seedPayload),
2578
+ liveReference: liveReferenceForMode(initialMode),
2579
+ synthesisBudget: readSynthBudget(),
2580
+ onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
2581
+ digestStructures: DIGEST_STRUCTURES,
2582
+ });
2583
+ stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2584
+ }
2585
+ } else {
2586
+ stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2587
+ }
2588
+
2589
+ if (backendMode === "aws" && !persistenceUnavailable) restoredCount = stats.taught.length;
2590
+ else if (savedRecord) restoredCount = stats.taught.length;
2591
+
2592
+ let restoredNote;
2593
+ if (backendMode === "aws") {
2594
+ restoredNote = persistenceUnavailable
2595
+ ? " This visit couldn't reach the row service \\u2014 running unpersisted; nothing taught will be saved."
2596
+ : (restoredCount
2597
+ ? " Restored " + restoredCount + " taught fact" + (restoredCount === 1 ? "" : "s")
2598
+ + " from your last visit \\u2014 kept server-side against this anonymous session."
2599
+ : "");
2600
+ } else {
2601
+ restoredNote = savedRecord
2602
+ ? " Restored " + restoredCount + " taught fact" + (restoredCount === 1 ? "" : "s")
2603
+ + " from your last visit \\u2014 state kept best-effort on this device."
2604
+ : "";
2605
+ }
2443
2606
  addSystemLine("tmct \\u2014 the real engine, running in this page \\u2014 " + statsSummaryLine(stats, bandLabelFor)
2444
2607
  + "." + restoredNote + " Ask it something, or teach it a fact of your own.");
2445
2608
  await renderStatsPanel(stats);
@@ -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
  }