mnemo-engine 0.19.1

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>mnemo inspect</title>
<style>
  :root {
    --bg: #ffffff; --fg: #1d1d1f; --muted: #6e6e73; --line: #e3e3e8;
    --panel: #f6f6f8; --accent: #2f5fd0; --tag: #eef1fb; --warn: #9a5b00;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #161618; --fg: #ececf0; --muted: #9a9aa2; --line: #2e2e33;
      --panel: #1f1f23; --accent: #8aa8ff; --tag: #262a3a; --warn: #f0b45a;
    }
  }
  * { box-sizing: border-box; }
  body {
    margin: 0; background: var(--bg); color: var(--fg);
    font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }
  header {
    display: flex; flex-wrap: wrap; align-items: center; gap: 12px;
    padding: 12px 20px; border-bottom: 1px solid var(--line);
  }
  header h1 { font-size: 16px; margin: 0; font-weight: 600; }
  header .file { color: var(--muted); font-family: ui-monospace, Menlo, monospace; font-size: 12px; overflow-wrap: anywhere; }
  header .spacer { flex: 1; }
  nav { display: flex; gap: 4px; padding: 8px 20px; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
  nav button, .btn {
    border: 1px solid transparent; background: none; color: var(--fg);
    padding: 6px 12px; border-radius: 6px; cursor: pointer; font: inherit;
  }
  nav button.on { background: var(--panel); border-color: var(--line); font-weight: 600; }
  .btn { border-color: var(--line); background: var(--panel); }
  main { padding: 16px 20px 40px; max-width: 1100px; }
  .filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; align-items: center; }
  input, select {
    font: inherit; color: var(--fg); background: var(--bg);
    border: 1px solid var(--line); border-radius: 6px; padding: 5px 8px;
  }
  input[type=search] { min-width: 240px; flex: 1; }
  .count { color: var(--muted); margin: 0 0 8px; }
  .card { border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; margin-bottom: 8px; }
  .card.old { opacity: 0.65; }
  .meta { display: flex; flex-wrap: wrap; gap: 6px; color: var(--muted); font-size: 12px; margin-bottom: 4px; }
  .tag { background: var(--tag); border-radius: 4px; padding: 0 6px; color: var(--fg); }
  .mono { font-family: ui-monospace, Menlo, monospace; font-size: 12px; }
  .content { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; font: inherit; }
  details { margin-top: 4px; }
  summary { cursor: pointer; color: var(--muted); font-size: 12px; }
  pre.json, pre.essence {
    background: var(--panel); border-radius: 6px; padding: 10px; overflow: auto;
    white-space: pre-wrap; overflow-wrap: anywhere; font: 12px/1.5 ui-monospace, Menlo, monospace; margin: 6px 0;
  }
  table { border-collapse: collapse; width: 100%; }
  td, th { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
  th { color: var(--muted); font-weight: 500; width: 220px; }
  .layout { display: grid; grid-template-columns: minmax(200px, 280px) 1fr; gap: 16px; }
  @media (max-width: 700px) { .layout { grid-template-columns: 1fr; } }
  .list button {
    display: block; width: 100%; text-align: left; border: 1px solid var(--line); background: var(--bg);
    color: var(--fg); border-radius: 6px; padding: 8px 10px; margin-bottom: 6px; cursor: pointer; font: inherit;
  }
  .list button.on { border-color: var(--accent); }
  .list small { color: var(--muted); display: block; }
  .error { color: var(--warn); }
  .empty { color: var(--muted); }
  .turn { border-left: 3px solid var(--line); padding: 4px 10px; margin: 6px 0; }
  .turn b { font-weight: 600; }
  h2 { font-size: 15px; margin: 18px 0 8px; }
  table.data th { width: auto; }
  table.data tr.click { cursor: pointer; }
  table.data tr.click:hover td, table.data tr.on td { background: var(--panel); }
  .wrap { overflow-x: auto; }
</style>
</head>
<body>
<header>
  <h1>mnemo inspect</h1>
  <span class="file" id="file"></span>
  <span class="spacer"></span>
  <span class="count" id="loaded" style="margin:0"></span>
  <button class="btn" id="reload" title="Read the file again (one passphrase derivation)">Reload</button>
</header>
<nav id="tabs">
  <button data-view="memories" class="on">Memories</button>
  <button data-view="keys">Keyed history</button>
  <button data-view="threads">Threads</button>
  <button data-view="findings">Findings</button>
  <button data-view="tasks">Tasks</button>
  <button data-view="snapshots">Snapshots</button>
  <button data-view="about">About</button>
</nav>
<main id="main"></main>
<script>
"use strict";
// The printed link carries a one-time code, not the token. The page takes it
// out of the address bar and exchanges it once for the session token, which
// it keeps for this tab only. The server refuses the code after that, so the
// copy in the browser's history (and in `--open`'s forwarding page) is dead.
const TOKEN_KEY = "mnemo-inspect-token";
let TOKEN = "";
function storedToken() {
  try { return sessionStorage.getItem(TOKEN_KEY) || ""; } catch (e) { return ""; }
}
async function session() {
  const code = new URLSearchParams(location.search).get("c");
  if (!code) return { token: storedToken() };
  // The tab in the hash (`#findings`) stays; only the code goes.
  history.replaceState(null, "", location.pathname + location.hash);
  // A page the browser renders ahead of time waits until it's shown, so a
  // prerender that's thrown away doesn't use up the link.
  if (document.prerendering) {
    await new Promise(r => document.addEventListener("prerenderingchange", r, { once: true }));
  }
  const r = await fetch("/api/session?" + new URLSearchParams({ c: code }).toString())
    .catch(() => { throw new Error(STOPPED); });
  if (!r.ok) return { token: storedToken(), used: true };
  const { token } = await r.json();
  try { sessionStorage.setItem(TOKEN_KEY, token); } catch (e) {}
  return { token };
}
const main = document.getElementById("main");
let view = "memories";
const state = { q: "", type: "", agent: "", keyed: "", thread: "", key: null, threadId: null,
  fStatus: "", fCategory: "", fPriority: "", findingId: null, tStatus: "", taskSlug: null,
  dFrom: "", dTo: "", tDate: "created" };

// v0.19.0: one date range for every tab, From and To inclusive, in the
// viewer's local time. The server filters (`since`, `until`, unix seconds).
function dayStart(v) { const [y, m, d] = v.split("-").map(Number); return Math.floor(new Date(y, m - 1, d).getTime() / 1000); }
function dayEnd(v) { const [y, m, d] = v.split("-").map(Number); return Math.floor(new Date(y, m - 1, d + 1).getTime() / 1000) - 1; }
function withRange(params) {
  if (state.dFrom) params.since = dayStart(state.dFrom);
  if (state.dTo) params.until = dayEnd(state.dTo);
  return params;
}
function dateInputs() {
  const input = (key, label) => {
    const i = el("input", { type: "date", title: label, "aria-label": label });
    i.value = state[key];
    i.addEventListener("change", e => { state[key] = e.target.value; state.findingId = null; state.taskSlug = null; render(); });
    return i;
  };
  return [el("span", { class: "count", style: "margin:0" }, "From"), input("dFrom", "From (inclusive)"),
    el("span", { class: "count", style: "margin:0" }, "to"), input("dTo", "To (inclusive)")];
}
const ranged = () => Boolean(state.dFrom || state.dTo);

// RB-004.5 item 4: once the server has stopped (`--idle-timeout`, or
// Ctrl-C), a request can't connect; say that instead of the browser's text.
const STOPPED = "The inspector has stopped (after --idle-timeout without use, or Ctrl-C), " +
  "so this page can't read the file any more. Run `mnemo inspect <file>` again for a new link.";
function api(path, params) {
  const u = new URLSearchParams(params || {});
  u.set("t", TOKEN);
  return fetch(path + "?" + u.toString()).catch(() => { throw new Error(STOPPED); }).then(async r => {
    const body = await r.json().catch(() => ({ error: r.statusText }));
    if (!r.ok) throw new Error(body.error || r.statusText);
    return body;
  });
}
function el(tag, attrs, ...kids) {
  const e = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs || {})) {
    if (k === "class") e.className = v;
    else if (k.startsWith("on")) e.addEventListener(k.slice(2), v);
    else e.setAttribute(k, v);
  }
  for (const k of kids.flat()) if (k != null) e.append(k instanceof Node ? k : String(k));
  return e;
}
function when(secs) {
  if (secs == null) return "—";
  return new Date(secs * 1000).toISOString().replace(".000Z", "Z").replace("T", " ");
}
function bytes(n) {
  if (n < 1024) return n + " B";
  if (n < 1048576) return (n / 1024).toFixed(1) + " KiB";
  return (n / 1048576).toFixed(1) + " MiB";
}
function fail(e) { main.replaceChildren(el("p", { class: "error" }, String(e.message || e))); }

function memoryCard(m) {
  const tags = [el("span", { class: "tag" }, m.type), el("span", {}, "agent " + m.agent)];
  if (m.key) tags.push(el("span", { class: "tag mono" }, "key " + m.key));
  if (m.thread) tags.push(el("span", { class: "tag mono" }, "thread " + m.thread));
  if (m.kind) tags.push(el("span", { class: "tag" }, m.kind));
  if (m.private) tags.push(el("span", { class: "tag" }, "private"));
  if (m.superseded_by) tags.push(el("span", {}, "superseded " + when(m.invalid_at)));
  if (m.score != null) tags.push(el("span", {}, "score " + m.score.toFixed(2)));
  tags.push(el("span", {}, when(m.created_at)), el("span", {}, "importance " + m.importance));
  return el("div", { class: "card" + (m.superseded_by ? " old" : "") },
    el("div", { class: "meta" }, tags),
    el("pre", { class: "content" }, m.content),
    el("details", {}, el("summary", {}, el("span", { class: "mono" }, m.id)),
      el("pre", { class: "json" }, JSON.stringify(m.metadata, null, 2))));
}

async function showMemories() {
  const params = withRange({ limit: 200 });
  for (const k of ["q", "type", "agent", "keyed", "thread"]) if (state[k]) params[k] = state[k];
  const [data, threads] = await Promise.all([api("/api/memories", params), api("/api/threads")]);
  const sel = (name, opts) => {
    const s = el("select", { onchange: e => { state[name] = e.target.value; render(); } },
      opts.map(([v, label]) => { const o = el("option", { value: v }, label); if (state[name] === v) o.selected = true; return o; }));
    return s;
  };
  const search = el("input", { type: "search", placeholder: "Keyword search (BM25)", value: state.q });
  search.addEventListener("keydown", e => { if (e.key === "Enter") { state.q = search.value.trim(); render(); } });
  const filters = el("div", { class: "filters" },
    search,
    sel("type", [["", "All types"], ["semantic", "semantic"], ["episodic", "episodic"], ["procedural", "procedural"], ["working", "working"]]),
    sel("agent", [["", "All agents"], ...data.agents.map(a => [a, a])]),
    sel("keyed", [["", "Keyed or not"], ["yes", "Keyed"], ["no", "Not keyed"]]),
    sel("thread", [["", "Any thread"], ...threads.threads.map(t => [t.id, t.id])]),
    ...dateInputs());
  const shown = data.memories.length;
  const note = shown < data.total ? `showing ${shown} of ${data.total}` : `${data.total} ${data.total === 1 ? "memory" : "memories"}`;
  main.replaceChildren(filters,
    el("p", { class: "count" }, note + (state.q ? `, best match first` : "") + ". Thread turns are under Threads."),
    ...(data.memories.length ? data.memories.map(memoryCard) : [el("p", { class: "empty" }, "Nothing matches.")]));
  if (state.q) search.focus();
}

async function showKeys() {
  const keys = await api("/api/keys");
  if (!keys.length) { main.replaceChildren(el("p", { class: "empty" }, "No keyed facts in this file.")); return; }
  const pick = keys.find(k => state.key && k.key === state.key.key && k.owner === state.key.owner) || keys[0];
  state.key = { key: pick.key, owner: pick.owner };
  const hist = await api("/api/history", { key: pick.key, owner: pick.owner });
  const list = el("div", { class: "list" }, keys.map(k =>
    el("button", { class: k === pick ? "on" : "", onclick: () => { state.key = { key: k.key, owner: k.owner }; render(); } },
      el("span", { class: "mono" }, k.key),
      el("small", {}, (k.owner ? "agent " + k.owner : "shared") + ` · ${k.versions} version${k.versions === 1 ? "" : "s"}`))));
  const chain = hist.versions.map((v, i) => el("div", { class: "card" + (v.current ? "" : " old") },
    el("div", { class: "meta" },
      el("span", { class: "tag" }, v.current ? "current" : `version ${i + 1}`),
      el("span", {}, "written " + when(v.created_at)),
      v.current ? null : el("span", {}, "stopped being current " + when(v.invalid_at))),
    el("pre", { class: "content" }, v.content),
    el("div", { class: "meta mono" }, v.id)));
  main.replaceChildren(el("div", { class: "layout" }, list,
    el("div", {}, el("p", { class: "count" }, "Oldest to newest. A new version supersedes the old one; nothing is erased."), chain)));
}

async function showThreads() {
  const data = await api("/api/threads");
  const project = data.project_essence
    ? [el("h2", {}, "Project essence"), el("pre", { class: "essence" }, data.project_essence)] : [];
  if (!data.threads.length) {
    main.replaceChildren(...project, el("p", { class: "empty" }, "No threads in this file."));
    return;
  }
  const id = data.threads.some(t => t.id === state.threadId) ? state.threadId : data.threads[0].id;
  state.threadId = id;
  const t = await api("/api/thread", { id });
  const turnsBox = el("div", {});
  const loadTurns = el("button", { class: "btn", onclick: async () => {
    loadTurns.disabled = true;
    try {
      const full = await api("/api/thread", { id, turns: "1" });
      turnsBox.replaceChildren(...full.turns.map(x => el("div", { class: "turn" },
        el("div", { class: "meta" }, el("b", {}, x.role), x.timestamp != null ? el("span", {}, when(x.timestamp)) : null, el("span", { class: "mono" }, x.turn_id)),
        el("pre", { class: "content" }, x.content))));
      loadTurns.remove();
    } catch (e) { turnsBox.replaceChildren(el("p", { class: "error" }, e.message)); }
  } }, `Show the ${t.turn_count} archived turn${t.turn_count === 1 ? "" : "s"}`);
  const list = el("div", { class: "list" }, data.threads.map(x =>
    el("button", { class: x.id === id ? "on" : "", onclick: () => { state.threadId = x.id; render(); } },
      el("span", { class: "mono" }, x.id),
      el("small", {}, `${x.turns} turn${x.turns === 1 ? "" : "s"} · ${x.essence_items} essence item${x.essence_items === 1 ? "" : "s"}`))));
  main.replaceChildren(el("div", { class: "layout" }, list, el("div", {},
    el("h2", { style: "margin-top:0" }, "Essence"),
    t.essence ? el("pre", { class: "essence" }, t.essence) : el("p", { class: "empty" }, "No essence for this thread."),
    el("h2", {}, "Turn archive"), t.turn_count ? loadTurns : el("p", { class: "empty" }, "No turns."), turnsBox,
    ...project)));
}

// v0.18.1 (INSPECT-COORD): review findings and tasks, read-only. Everything
// from the brain goes in as text (el() appends strings as text nodes), never
// as HTML.
function choose(key, label, values) {
  return el("select", { onchange: e => { state[key] = e.target.value; state.findingId = null; state.taskSlug = null; render(); } },
    [["", label], ...values.map(v => [v, v])].map(([v, l]) => {
      const o = el("option", { value: v }, l); if (state[key] === v) o.selected = true; return o;
    }));
}
function countsLine(data, noun) {
  const parts = data.counts.map(c => `${c.count} ${c.status}`).join(", ");
  return el("p", { class: "count" }, `${parts} (${data.total} ${noun}${data.total === 1 ? "" : "s"})`);
}
function historyTable(h) {
  if (!h || !h.length) return el("p", { class: "empty" }, "No status changes yet.");
  return el("div", { class: "wrap" }, el("table", { class: "data" },
    el("tr", {}, ["When", "From", "To", "By", "Note"].map(x => el("th", {}, x))),
    h.map(x => el("tr", {},
      el("td", {}, when(x.at)), el("td", {}, x.from ?? "—"), el("td", {}, x.to ?? "—"), el("td", {}, x.by ?? "—"),
      el("td", {}, el("pre", { class: "content" }, x.note ?? (x.reclaimed_from ? "reclaimed from " + x.reclaimed_from : "")))))));
}
function findingDetail(f) {
  const rows = [
    ["Status", f.status + (f.private ? " (private until verified)" : "")],
    ["Category, priority", `${f.category}, ${f.priority}`],
    ["Added", `${when(f.created_at)} by ${f.author || "—"}`],
  ];
  if (f.triage != null) rows.push(["Triage", el("div", {}, el("pre", { class: "content" }, f.triage), el("small", {}, "by " + (f.triaged_by || "—")))]);
  if (f.verified_ref != null) rows.push(["Verified", `against ${f.verified_ref} by ${f.verified_by || "—"}`]);
  if (f.refs.length) rows.push(["Refs", el("div", {}, f.refs.map(r => el("div", { class: "mono" }, r)))]);
  return el("div", { class: "card" },
    el("div", { class: "meta" }, el("span", { class: "tag mono" }, f.id), el("span", { class: "mono" }, f.record_id)),
    el("pre", { class: "content" }, el("b", {}, f.title)),
    f.body ? el("pre", { class: "content" }, f.body) : null,
    el("table", {}, rows.map(([k, v]) => el("tr", {}, el("th", {}, k), el("td", {}, v)))),
    el("h2", {}, "Status history"), historyTable(f.history));
}
async function showFindings() {
  const params = withRange({});
  if (state.fStatus) params.status = state.fStatus;
  if (state.fCategory) params.category = state.fCategory;
  if (state.fPriority) params.priority = state.fPriority;
  const data = await api("/api/findings", params);
  if (!data.total && !ranged()) {
    main.replaceChildren(el("p", { class: "empty" }, "No review findings in this file. A Reviewer adds them with `mnemo finding add`."));
    return;
  }
  const filters = el("div", { class: "filters" },
    choose("fStatus", "Any status", data.statuses),
    choose("fCategory", "Any category", data.categories),
    choose("fPriority", "Any priority", data.priorities),
    ...dateInputs());
  const pick = data.findings.find(f => f.id === state.findingId);
  const table = data.findings.length ? el("div", { class: "wrap" }, el("table", { class: "data" },
    el("tr", {}, ["Id", "Category", "Priority", "Status", "Title", "Author", "Last change"].map(x => el("th", {}, x))),
    data.findings.map(f => el("tr", { class: "click" + (f === pick ? " on" : ""),
        onclick: () => { state.findingId = f.id === state.findingId ? null : f.id; render(); } },
      el("td", { class: "mono" }, f.id), el("td", {}, f.category), el("td", {}, f.priority), el("td", {}, f.status),
      el("td", {}, f.title, f.private ? [" ", el("span", { class: "tag" }, "private until verified")] : null),
      el("td", {}, f.author || "—"), el("td", {}, when(f.updated_at))))))
    : el("p", { class: "empty" }, ranged() && !data.total ? "Nothing in this date range." : "Nothing matches.");
  main.replaceChildren(countsLine(data, "finding"), filters,
    el("p", { class: "count" }, "Ordered by id. Click one for its body, triage, refs and history."),
    ...(pick ? [findingDetail(pick)] : []), table);
}
function taskDetail(t) {
  const rows = [
    ["Status", t.status + (t.pre_approved ? " (pre-approved)" : "")],
    ["For", t.role || "anyone"],
    ["Owner", t.owner || "—"],
    ["Added", `${when(t.created_at)} by ${t.creator || "—"}`],
  ];
  if (t.after.length) rows.push(["After", t.after.join(", ")]);
  if (t.refs && t.refs.length) rows.push(["Refs", el("div", {}, t.refs.map(r => el("div", { class: "mono" }, r)))]);
  return el("div", { class: "card" },
    el("div", { class: "meta" }, el("span", { class: "tag mono" }, t.slug), el("span", { class: "mono" }, t.record_id)),
    el("pre", { class: "content" }, el("b", {}, t.title)),
    t.body ? el("pre", { class: "content" }, t.body) : null,
    el("table", {}, rows.map(([k, v]) => el("tr", {}, el("th", {}, k), el("td", {}, v)))),
    el("h2", {}, "Status history"), historyTable(t.history));
}
async function showTasks() {
  const params = withRange({ date: state.tDate });
  if (state.tStatus) params.status = state.tStatus;
  const data = await api("/api/tasks", params);
  if (!data.total && !ranged()) {
    main.replaceChildren(el("p", { class: "empty" }, "No tasks in this file. They're added with `mnemo task add`."));
    return;
  }
  const pick = data.tasks.find(t => t.slug === state.taskSlug);
  const table = data.tasks.length ? el("div", { class: "wrap" }, el("table", { class: "data" },
    el("tr", {}, ["Task", "Title", "Status", "Owner", "For", "After", "Last change"].map(x => el("th", {}, x))),
    data.tasks.map(t => el("tr", { class: "click" + (t === pick ? " on" : ""),
        onclick: () => { state.taskSlug = t.slug === state.taskSlug ? null : t.slug; render(); } },
      el("td", { class: "mono" }, t.slug), el("td", {}, t.title), el("td", {}, t.status), el("td", {}, t.owner || "—"),
      el("td", {}, t.role || "anyone"), el("td", { class: "mono" }, t.after.join(", ") || "—"), el("td", {}, when(t.updated_at))))))
    : el("p", { class: "empty" }, ranged() && !data.total ? "Nothing in this date range." : "Nothing matches.");
  const byDate = el("select", { "aria-label": "Date of", onchange: e => { state.tDate = e.target.value; render(); } },
    [["created", "Added"], ["updated", "Last change"]].map(([v, l]) => {
      const o = el("option", { value: v }, l); if (state.tDate === v) o.selected = true; return o;
    }));
  main.replaceChildren(countsLine(data, "task"),
    el("div", { class: "filters" }, choose("tStatus", "Any status", data.statuses), byDate, ...dateInputs()),
    el("p", { class: "count" }, "In the order they were added. Click one for its body and history."),
    ...(pick ? [taskDetail(pick)] : []), table);
}

async function showSnapshots() {
  const s = await api("/api/snapshots");
  const rows = [
    ["Restore points retained", s.retained],
    ["Oldest restorable", when(s.oldest_restorable_at)],
    ["Kept from reuse (pinned)", bytes(s.pinned_bytes)],
  ];
  main.replaceChildren(
    el("table", {}, rows.map(([k, v]) => el("tr", {}, el("th", {}, k), el("td", {}, v)))),
    el("p", { class: "count" }, "These are the snapshots the file holds now; under heavy churn the retention cap can keep fewer than its policy. `mnemo restore` rolls back to one."),
    el("h2", {}, "Snapshots, newest first"),
    el("table", {}, el("tr", {}, el("th", {}, "Transaction"), el("th", {}, "Committed"), el("th", {}, "Memories")),
      s.list.slice().reverse().map(x => el("tr", {}, el("td", { class: "mono" }, x.txn_id), el("td", {}, when(x.created_at)), el("td", {}, x.memory_count)))));
}

async function showAbout() {
  const a = await api("/api/about");
  const fmtEmb = e => `${e.name} (${e.dimensions} dims, normalize ${e.normalize})`;
  const emb = a.embedder ? fmtEmb(a.embedder)
    : a.manifest_embedder && a.manifest_embedder.name ? fmtEmb(a.manifest_embedder) + ", from the manifest (no identity recorded yet)"
    : "none recorded yet";
  const rows = [
    ["Format", "v" + a.format_version + (a.format_version < 9 ? " (read-only; mnemo compact converts it to v9)" : "")],
    ["Recall mode", a.recall_mode],
    ["Embedder", emb],
    ["Dimensions", a.dimensions],
    ["Memories", `${a.memories} live, ${a.tombstoned} tombstoned`],
    ["Threads / keyed facts", `${a.threads} / ${a.keys}`],
    ["Findings / tasks", `${a.findings} / ${a.tasks}`],
    ["Agents", a.agents.join(", ") || "—"],
    ["File size", bytes(a.file_bytes)],
    ["Vector column", bytes(a.vector_column_bytes)],
    ["ANN index", a.has_index ? "yes" : "no"],
    ["WAL region", a.wal_pages + " pages"],
    ["Result cache", `${a.cache.entries} entries, ${bytes(a.cache.bytes)}`],
    ["Created", when(a.created_at)],
  ];
  main.replaceChildren(el("table", {}, rows.map(([k, v]) => el("tr", {}, el("th", {}, k), el("td", {}, v)))),
    el("h2", {}, "Onboarding (mnemo about)"),
    ...(a.onboarding.length ? a.onboarding.map(o => el("div", { class: "card" },
      el("div", { class: "meta" }, o.topic ? el("span", { class: "tag" }, o.topic) : null, el("span", { class: "mono" }, o.id)),
      el("pre", { class: "content" }, o.content))) : [el("p", { class: "empty" }, "No onboarding memories.")]));
}

const views = { memories: showMemories, keys: showKeys, threads: showThreads, findings: showFindings,
  tasks: showTasks, snapshots: showSnapshots, about: showAbout };
function render() { views[view]().catch(fail); }
async function header() {
  try {
    const a = await api("/api/about");
    document.getElementById("file").textContent = a.path + " · v" + a.format_version + " · read-only";
    document.getElementById("loaded").textContent = "read " + when(a.loaded_at);
  } catch (e) { fail(e); }
}
function selectTab(name) {
  // RB-015.2: own keys only, so `#__proto__` or `#toString` opens no tab.
  if (!Object.hasOwn(views, name)) return false;
  view = name;
  for (const x of document.querySelectorAll("#tabs button")) x.classList.toggle("on", x.dataset.view === name);
  return true;
}
document.getElementById("tabs").addEventListener("click", e => {
  const b = e.target.closest("button"); if (!b) return;
  // v0.19.0: the tab is in the address (`#findings`), so a link can open it.
  if (selectTab(b.dataset.view)) history.replaceState(null, "", location.pathname + "#" + view);
  render();
});
document.getElementById("reload").addEventListener("click", async () => {
  const btn = document.getElementById("reload");
  btn.disabled = true; btn.textContent = "Reading…";
  try { await api("/api/reload"); await header(); render(); }
  catch (e) { document.getElementById("loaded").textContent = "reload failed: " + e.message; }
  finally { btn.disabled = false; btn.textContent = "Reload"; }
});
session().then(s => {
  TOKEN = s.token;
  selectTab(location.hash.slice(1));
  if (TOKEN) { header(); render(); return; }
  main.replaceChildren(el("p", { class: "error" }, s.used
    ? "This link has already been used. Each link `mnemo inspect` prints opens one tab; run it again for a new one."
    : "This tab has no access. Open the link that `mnemo inspect` printed."));
}, fail);
</script>
</body>
</html>