memoryking 0.1.0__py3-none-any.whl

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.
Files changed (179) hide show
  1. memoryking/__init__.py +3 -0
  2. memoryking/__main__.py +1328 -0
  3. memoryking/adapters/__init__.py +1 -0
  4. memoryking/adapters/adapter_state.py +242 -0
  5. memoryking/adapters/anchor_schema.sql +7 -0
  6. memoryking/adapters/atlas.py +441 -0
  7. memoryking/adapters/browser_commands.py +125 -0
  8. memoryking/adapters/dashboard.py +510 -0
  9. memoryking/adapters/dense_search.py +86 -0
  10. memoryking/adapters/egress_policy.py +244 -0
  11. memoryking/adapters/egress_schema.sql +13 -0
  12. memoryking/adapters/embedding.schema.json +302 -0
  13. memoryking/adapters/embedding_store.py +469 -0
  14. memoryking/adapters/execution.py +369 -0
  15. memoryking/adapters/experience.py +423 -0
  16. memoryking/adapters/experience.schema.json +1508 -0
  17. memoryking/adapters/experience_records.py +239 -0
  18. memoryking/adapters/experience_schema.sql +23 -0
  19. memoryking/adapters/handoff.py +494 -0
  20. memoryking/adapters/handoff.schema.json +299 -0
  21. memoryking/adapters/handoff_schema.sql +17 -0
  22. memoryking/adapters/index_schema.sql +11 -0
  23. memoryking/adapters/inference.py +454 -0
  24. memoryking/adapters/inference.schema.json +541 -0
  25. memoryking/adapters/inspection.py +1128 -0
  26. memoryking/adapters/inspection.schema.json +568 -0
  27. memoryking/adapters/knowledge.schema.json +633 -0
  28. memoryking/adapters/knowledge_schema.sql +37 -0
  29. memoryking/adapters/knowledge_store.py +800 -0
  30. memoryking/adapters/legacy_snapshot.py +358 -0
  31. memoryking/adapters/legacy_tables.py +49 -0
  32. memoryking/adapters/local_contract.py +45 -0
  33. memoryking/adapters/local_embeddings.py +189 -0
  34. memoryking/adapters/local_files.py +242 -0
  35. memoryking/adapters/local_ipc.py +258 -0
  36. memoryking/adapters/local_schema.sql +44 -0
  37. memoryking/adapters/local_store.py +632 -0
  38. memoryking/adapters/local_wire.schema.json +7672 -0
  39. memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
  40. memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
  41. memoryking/adapters/optional_schema.sql +43 -0
  42. memoryking/adapters/plan_dashboard.py +51 -0
  43. memoryking/adapters/plans.py +253 -0
  44. memoryking/adapters/postgres_admin.py +300 -0
  45. memoryking/adapters/postgres_anchor_schema.sql +9 -0
  46. memoryking/adapters/postgres_counter.sql +14 -0
  47. memoryking/adapters/postgres_egress_schema.sql +15 -0
  48. memoryking/adapters/postgres_experience_schema.sql +39 -0
  49. memoryking/adapters/postgres_index_schema.sql +7 -0
  50. memoryking/adapters/postgres_optional_schema.sql +71 -0
  51. memoryking/adapters/postgres_pool.py +77 -0
  52. memoryking/adapters/postgres_recovery.py +525 -0
  53. memoryking/adapters/postgres_schema.sql +365 -0
  54. memoryking/adapters/postgres_sql.py +102 -0
  55. memoryking/adapters/postgres_store.py +428 -0
  56. memoryking/adapters/postgres_summary_schema.sql +12 -0
  57. memoryking/adapters/postgres_trust_schema.sql +20 -0
  58. memoryking/adapters/processing.schema.json +471 -0
  59. memoryking/adapters/processing_store.py +346 -0
  60. memoryking/adapters/projects.py +83 -0
  61. memoryking/adapters/proposals.py +238 -0
  62. memoryking/adapters/ranking.py +315 -0
  63. memoryking/adapters/repository.schema.json +664 -0
  64. memoryking/adapters/repository_git.py +264 -0
  65. memoryking/adapters/repository_schema.sql +25 -0
  66. memoryking/adapters/repository_store.py +960 -0
  67. memoryking/adapters/retrieval.py +1285 -0
  68. memoryking/adapters/retrieval.schema.json +553 -0
  69. memoryking/adapters/retrieval_schema.sql +10 -0
  70. memoryking/adapters/shared_control.py +40 -0
  71. memoryking/adapters/shared_dashboard.py +636 -0
  72. memoryking/adapters/shared_gateway.py +63 -0
  73. memoryking/adapters/shared_http.py +216 -0
  74. memoryking/adapters/shared_mcp.py +159 -0
  75. memoryking/adapters/shared_service.py +124 -0
  76. memoryking/adapters/stdio.py +193 -0
  77. memoryking/adapters/stdio.tools.json +6776 -0
  78. memoryking/adapters/summary_schema.sql +10 -0
  79. memoryking/adapters/team.py +253 -0
  80. memoryking/adapters/timeline.py +80 -0
  81. memoryking/adapters/token_count.py +55 -0
  82. memoryking/adapters/tokenizers/LICENSE +21 -0
  83. memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
  84. memoryking/adapters/trust.py +123 -0
  85. memoryking/adapters/trust_schema.sql +13 -0
  86. memoryking/adapters/web/app.css +1251 -0
  87. memoryking/adapters/web/app.js +907 -0
  88. memoryking/adapters/web/brand.js +44 -0
  89. memoryking/adapters/web/crown-mono.svg +1 -0
  90. memoryking/adapters/web/crown.svg +8 -0
  91. memoryking/adapters/web/elephant.png +0 -0
  92. memoryking/adapters/web/favicon.svg +8 -0
  93. memoryking/adapters/web/graph-layout.js +52 -0
  94. memoryking/adapters/web/graph-worker.js +10 -0
  95. memoryking/adapters/web/graph.js +570 -0
  96. memoryking/adapters/web/index.html +208 -0
  97. memoryking/adapters/web/observatory.js +1208 -0
  98. memoryking/adapters/web/team.js +151 -0
  99. memoryking/adapters/web/wordmark.svg +1 -0
  100. memoryking/adapters/working.py +971 -0
  101. memoryking/adapters/working.schema.json +1717 -0
  102. memoryking/adapters/working_schema.sql +24 -0
  103. memoryking/application/__init__.py +1 -0
  104. memoryking/application/conformance.py +50 -0
  105. memoryking/application/legacy_import.py +337 -0
  106. memoryking/application/local_port.py +9 -0
  107. memoryking/application/storage.py +117 -0
  108. memoryking/application/store_core.py +1292 -0
  109. memoryking/backups.py +131 -0
  110. memoryking/contracts/__init__.py +6 -0
  111. memoryking/contracts/__main__.py +20 -0
  112. memoryking/contracts/canonical.py +88 -0
  113. memoryking/contracts/embedding.schema.json +302 -0
  114. memoryking/contracts/embedding_generated.py +65 -0
  115. memoryking/contracts/experience.schema.json +1508 -0
  116. memoryking/contracts/experience_generated.py +239 -0
  117. memoryking/contracts/generated.py +122 -0
  118. memoryking/contracts/handoff.schema.json +299 -0
  119. memoryking/contracts/handoff_generated.py +69 -0
  120. memoryking/contracts/inference.schema.json +541 -0
  121. memoryking/contracts/inference_generated.py +106 -0
  122. memoryking/contracts/processing.schema.json +471 -0
  123. memoryking/contracts/processing_generated.py +82 -0
  124. memoryking/contracts/py.typed +0 -0
  125. memoryking/contracts/repository.schema.json +664 -0
  126. memoryking/contracts/repository_generated.py +144 -0
  127. memoryking/contracts/retrieval.schema.json +553 -0
  128. memoryking/contracts/retrieval_generated.py +110 -0
  129. memoryking/contracts/schema.json +696 -0
  130. memoryking/contracts/validation.py +92 -0
  131. memoryking/contracts/working.schema.json +1717 -0
  132. memoryking/contracts/working_generated.py +291 -0
  133. memoryking/domain/__init__.py +1 -0
  134. memoryking/domain/anchors.py +97 -0
  135. memoryking/domain/briefing.py +108 -0
  136. memoryking/domain/briefing_text.py +222 -0
  137. memoryking/domain/checkpoint.py +118 -0
  138. memoryking/domain/compression.py +64 -0
  139. memoryking/domain/delta.py +129 -0
  140. memoryking/domain/embeddings.py +90 -0
  141. memoryking/domain/hints.py +465 -0
  142. memoryking/domain/http_status.py +45 -0
  143. memoryking/domain/learning.py +62 -0
  144. memoryking/domain/local.py +65 -0
  145. memoryking/domain/plans.py +140 -0
  146. memoryking/domain/repository.py +118 -0
  147. memoryking/domain/selectors.py +356 -0
  148. memoryking/domain/summary.py +88 -0
  149. memoryking/domain/usage.py +163 -0
  150. memoryking/embedding_loop.py +98 -0
  151. memoryking/embedding_worker.py +131 -0
  152. memoryking/harness.py +882 -0
  153. memoryking/harness_context.py +376 -0
  154. memoryking/hooks.py +171 -0
  155. memoryking/host_hooks.py +454 -0
  156. memoryking/lean.py +352 -0
  157. memoryking/memory_tool.py +776 -0
  158. memoryking/migration.py +194 -0
  159. memoryking/model_install.py +78 -0
  160. memoryking/observability.py +101 -0
  161. memoryking/observability_metrics.py +100 -0
  162. memoryking/profiles.py +150 -0
  163. memoryking/providers.py +330 -0
  164. memoryking/py.typed +0 -0
  165. memoryking/pytest_plugin.py +69 -0
  166. memoryking/reference_agent.py +152 -0
  167. memoryking/repository_worker.py +57 -0
  168. memoryking/resume_adapter.py +154 -0
  169. memoryking/sdk.py +302 -0
  170. memoryking/shared.py +301 -0
  171. memoryking/shared_sdk.py +101 -0
  172. memoryking/vault.py +176 -0
  173. memoryking-0.1.0.dist-info/METADATA +157 -0
  174. memoryking-0.1.0.dist-info/RECORD +179 -0
  175. memoryking-0.1.0.dist-info/WHEEL +5 -0
  176. memoryking-0.1.0.dist-info/entry_points.txt +7 -0
  177. memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
  178. memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
  179. memoryking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,907 @@
1
+ import { Observatory } from "./observatory.js";
2
+ import { installEmblem } from "./brand.js";
3
+ import { Team } from "./team.js";
4
+ const CAPACITY_LABELS = {
5
+ jobs: ["Pending jobs", "Drained by the service between requests"],
6
+ rendered_artifacts: ["Retained briefings", "Oldest evicted first at the cap"],
7
+ rendered_bytes: ["Retained bytes", "Artifact bodies held for replay"],
8
+ operation_intents: ["Open operations", "Released when an operation resolves"],
9
+ processing_usage: ["Usage attempts", "Pruned after 30 days"],
10
+ };
11
+ function renderComparison(before, after, beforeId, afterId) {
12
+ // What changed between two briefings: references added, dropped or kept,
13
+ // status, and token cost. Diagnostics carry references, not content.
14
+ const box = el("div", "", "comparison");
15
+ box.append(el("h4", "Compared with the previous briefing"));
16
+ box.append(el("p", `${beforeId} → ${afterId}`, "caption"));
17
+ const refs = (d) => new Map((d.selected ?? []).map((s) => [s.reference, s]));
18
+ const was = refs(before), now = refs(after);
19
+ const added = [...now.keys()].filter((r) => !was.has(r));
20
+ const dropped = [...was.keys()].filter((r) => !now.has(r));
21
+ const kept = [...now.keys()].filter((r) => was.has(r));
22
+ const facts = el("ul");
23
+ facts.append(el("li", `Status ${label(before.status)} → ${label(after.status)}`), el("li", `Tokens ${String(before.usage?.output_tokens ?? "?")} → ${String(after.usage?.output_tokens ?? "?")} (budget ${String(after.usage?.max_output_tokens ?? "?")})`), el("li", `${kept.length} references kept · ${added.length} added · ${dropped.length} dropped`));
24
+ box.append(facts);
25
+ for (const [title, list, source] of [
26
+ ["Added", added, now],
27
+ ["Dropped", dropped, was],
28
+ ]) {
29
+ if (!list.length)
30
+ continue;
31
+ box.append(el("h5", title));
32
+ const ul = el("ul");
33
+ for (const reference of list) {
34
+ const entry = source.get(reference);
35
+ ul.append(el("li", `${reference} · ${label(entry?.authority ?? "")} · ${label(entry?.reason ?? "")}`));
36
+ }
37
+ box.append(ul);
38
+ }
39
+ const beforeOmissions = (before.omissions ?? []).join(", ") || "none";
40
+ const afterOmissions = (after.omissions ?? []).join(", ") || "none";
41
+ if (beforeOmissions !== afterOmissions)
42
+ box.append(el("p", `Omissions ${beforeOmissions} → ${afterOmissions}`, "caption"));
43
+ return box;
44
+ }
45
+ const PROJECT_KEY = "memoryking.project";
46
+ let projectsLoadedFor = -1;
47
+ function rememberedProject() {
48
+ const linked = /^#project=([A-Za-z0-9_%\-]{1,96})$/.exec(location.hash);
49
+ if (linked)
50
+ return decodeURIComponent(linked[1]);
51
+ try {
52
+ return localStorage.getItem(PROJECT_KEY) ?? "";
53
+ }
54
+ catch {
55
+ return "";
56
+ }
57
+ }
58
+ function rememberProject(project) {
59
+ try {
60
+ localStorage.setItem(PROJECT_KEY, project);
61
+ }
62
+ catch {
63
+ /* per-viewer convenience only */
64
+ }
65
+ }
66
+ async function loadProjects() {
67
+ if (!snapshot || projectsLoadedFor === generation)
68
+ return;
69
+ projectsLoadedFor = generation;
70
+ const context = generation;
71
+ let items = [];
72
+ try {
73
+ items = (await api("/api/projects")).items;
74
+ }
75
+ catch {
76
+ projectsLoadedFor = -1;
77
+ return;
78
+ }
79
+ if (!snapshot || context !== generation)
80
+ return;
81
+ const remembered = rememberedProject();
82
+ renderProjects(items, remembered);
83
+ for (const id of ["execution-project", "receipt-project", "team-project"]) {
84
+ const select = get(id);
85
+ const current = select.value || remembered;
86
+ select.replaceChildren();
87
+ if (!items.length) {
88
+ const empty = el("option", "No readable projects yet");
89
+ empty.value = "";
90
+ empty.disabled = true;
91
+ empty.selected = true;
92
+ select.append(empty);
93
+ continue;
94
+ }
95
+ for (const item of items) {
96
+ const option = el("option", `${item.project} · ${item.observations} memories · ${item.tasks} tasks · ${item.receipts} receipts`);
97
+ option.value = item.project;
98
+ select.append(option);
99
+ }
100
+ select.value = items.some((i) => i.project === current)
101
+ ? current
102
+ : items[0].project;
103
+ }
104
+ }
105
+ /** One card per readable project; opening one selects it in every view. */
106
+ function renderProjects(items, current) {
107
+ const grid = get("project-grid");
108
+ grid.replaceChildren();
109
+ get("projects-state").textContent = items.length
110
+ ? `${items.length} readable`
111
+ : "None readable";
112
+ for (const item of items) {
113
+ const card = el("button", "", "project-card" + (item.project === current ? " selected" : ""));
114
+ card.type = "button";
115
+ card.append(el("strong", item.project), el("small", `${item.observations} memories · ${item.claims} claims · ${item.tasks} tasks · ${item.receipts} receipts`), el("small", item.last_activity_ms
116
+ ? "last activity " + new Date(item.last_activity_ms).toLocaleString()
117
+ : "no recorded activity"));
118
+ card.onclick = () => openProject(item.project);
119
+ grid.append(card);
120
+ }
121
+ }
122
+ /** Follow a project in every view, from a card or a #project= link. */
123
+ function openProject(project) {
124
+ rememberProject(project);
125
+ for (const id of ["execution-project", "receipt-project", "team-project"]) {
126
+ const select = get(id);
127
+ if (Array.from(select.options).some((o) => o.value === project))
128
+ select.value = project;
129
+ }
130
+ for (const card of get("project-grid").querySelectorAll(".project-card"))
131
+ card.classList.toggle("selected", (card.querySelector("strong")?.textContent ?? "") === project);
132
+ history.replaceState(null, "", "#project=" + encodeURIComponent(project));
133
+ get("execution-form").requestSubmit();
134
+ get("execution-panel").scrollIntoView();
135
+ }
136
+ function renderCapacity(capacity) {
137
+ const list = get("capacity-list");
138
+ list.replaceChildren();
139
+ const entries = Object.entries(capacity ?? {});
140
+ const warnings = entries.filter(([, v]) => v.warning).length;
141
+ get("capacity-state").textContent = entries.length
142
+ ? warnings
143
+ ? `${warnings} near limit`
144
+ : "Within limits"
145
+ : "Not reported";
146
+ for (const [name, value] of entries) {
147
+ const [title, note] = CAPACITY_LABELS[name] ?? [name, ""];
148
+ const item = el("div", "", value.warning ? "capacity-item warning" : "capacity-item");
149
+ item.append(el("p", title, "eyebrow"));
150
+ const shown = name === "rendered_bytes"
151
+ ? `${(value.used / 1048576).toFixed(1)} / ${Math.round(value.limit / 1048576)} MiB`
152
+ : `${value.used.toLocaleString()} / ${value.limit.toLocaleString()}`;
153
+ item.append(el("strong", shown));
154
+ const meter = el("div", "", "capacity-meter");
155
+ const fill = el("span");
156
+ fill.style.width = `${Math.min(100, (100 * value.used) / Math.max(1, value.limit))}%`;
157
+ meter.append(fill);
158
+ item.append(meter);
159
+ item.append(el("p", note));
160
+ list.append(item);
161
+ }
162
+ }
163
+ const get = (id) => document.getElementById(id);
164
+ function el(tag, text = "", cls = "") {
165
+ const node = document.createElement(tag);
166
+ node.textContent = text;
167
+ node.className = cls;
168
+ return node;
169
+ }
170
+ function label(value) {
171
+ return value.replaceAll("_", " ");
172
+ }
173
+ let snapshot = null;
174
+ let pendingReceipt = null;
175
+ /** Jump from a graph node to one of the receipts that used it, in Retrieval history. */
176
+ function openReceipt(project, receipt) {
177
+ const select = get("receipt-project");
178
+ if (!Array.from(select.options).some((o) => o.value === project)) {
179
+ get("receipt-notice").textContent =
180
+ "That project is not in your readable list; reload the project picker.";
181
+ return;
182
+ }
183
+ select.value = project;
184
+ rememberProject(project);
185
+ pendingReceipt = receipt;
186
+ get("retrieval-lab").scrollIntoView();
187
+ get("receipt-form").requestSubmit();
188
+ }
189
+ const observatory = new Observatory(get("observatory"), api, () => snapshot
190
+ ? {
191
+ csrf: snapshot.csrf,
192
+ tenant: snapshot.tenant,
193
+ principal: snapshot.principal,
194
+ incarnation: snapshot.incarnation,
195
+ authorization_epoch: snapshot.authorization_epoch,
196
+ }
197
+ : null, openReceipt);
198
+ const team = new Team(get("team-output"), {
199
+ api,
200
+ csrf: () => snapshot?.csrf ?? null,
201
+ signedOut: (message) => {
202
+ clear(message);
203
+ },
204
+ });
205
+ get("team-nav").onclick = () => get("team").scrollIntoView();
206
+ get("team-project").addEventListener("change", () => {
207
+ rememberProject(get("team-project").value);
208
+ team.clear();
209
+ });
210
+ get("team-form").addEventListener("submit", (event) => {
211
+ event.preventDefault();
212
+ if (!snapshot)
213
+ return;
214
+ void team.load(get("team-project").value);
215
+ });
216
+ installEmblem(get("emblem-reveal"));
217
+ get("atlas-nav").onclick = () => get("observatory").scrollIntoView();
218
+ let paused = false;
219
+ let busy = false;
220
+ let loggedOut = false;
221
+ let generation = 0;
222
+ let receiptGeneration = 0;
223
+ let receiptExpires = 0;
224
+ let liveStream = null;
225
+ let streamFallback = false;
226
+ let streamSequence = 0;
227
+ function stopStream() {
228
+ liveStream?.close();
229
+ liveStream = null;
230
+ streamSequence = 0;
231
+ }
232
+ function startStream() {
233
+ if (!snapshot?.streaming ||
234
+ liveStream ||
235
+ streamFallback ||
236
+ paused ||
237
+ loggedOut ||
238
+ document.hidden)
239
+ return;
240
+ const ticket = generation;
241
+ const source = new EventSource("/api/events");
242
+ liveStream = source;
243
+ const reset = () => {
244
+ if (ticket !== generation || source !== liveStream)
245
+ return;
246
+ generation++;
247
+ streamFallback = true;
248
+ clear("Live connection changed. Checking current permission with polling.");
249
+ if (!loggedOut && !document.hidden)
250
+ void refresh();
251
+ };
252
+ for (const kind of ["snapshot", "resync"]) {
253
+ source.addEventListener(kind, (event) => {
254
+ if (ticket !== generation || source !== liveStream || paused || !snapshot)
255
+ return;
256
+ try {
257
+ const value = JSON.parse(event.data);
258
+ if (value.schema_version !== 1 ||
259
+ value.tenant !== snapshot.tenant ||
260
+ value.principal !== snapshot.principal ||
261
+ value.incarnation !== snapshot.incarnation ||
262
+ value.authorization_epoch !== snapshot.authorization_epoch) {
263
+ reset();
264
+ return;
265
+ }
266
+ if (kind === "resync") {
267
+ observatory.clear();
268
+ clearReceipts();
269
+ clearExecution("Rebuilding the current authorized snapshot after a stream gap.");
270
+ streamSequence = 0;
271
+ }
272
+ const sequence = value.stream_sequence ?? 0;
273
+ if (sequence <= streamSequence)
274
+ return;
275
+ streamSequence = sequence;
276
+ snapshot = value;
277
+ render();
278
+ void refreshExecution();
279
+ }
280
+ catch {
281
+ reset();
282
+ }
283
+ });
284
+ }
285
+ source.addEventListener("heartbeat", (event) => {
286
+ if (ticket !== generation || source !== liveStream || paused || !snapshot)
287
+ return;
288
+ try {
289
+ const value = JSON.parse(event.data);
290
+ snapshot.fresh_until_ms = value.fresh_until_ms;
291
+ }
292
+ catch {
293
+ reset();
294
+ }
295
+ });
296
+ source.addEventListener("context-reset", reset);
297
+ source.onerror = reset;
298
+ }
299
+ function clearReceipts() {
300
+ receiptGeneration++;
301
+ receiptExpires = 0;
302
+ get("receipt-list").replaceChildren();
303
+ get("receipt-detail").replaceChildren();
304
+ }
305
+ function clear(message) {
306
+ observatory.clear();
307
+ team.clear();
308
+ get("team-project").selectedIndex = -1;
309
+ get("project-grid").replaceChildren();
310
+ stopStream();
311
+ clearExecution();
312
+ get("execution-project").selectedIndex = -1;
313
+ clearReceipts();
314
+ get("receipt-project").selectedIndex = -1;
315
+ get("receipt-notice").textContent = "Sign in to inspect retained receipts.";
316
+ snapshot = null;
317
+ get("content").hidden = true;
318
+ get("provenance").textContent = "";
319
+ get("notice").textContent = message;
320
+ get("login").hidden = false;
321
+ for (const id of ["pause", "refresh", "logout"])
322
+ get(id).hidden = true;
323
+ get("freshness").textContent = "Session required";
324
+ }
325
+ async function api(path, data) {
326
+ const response = await fetch(path, {
327
+ method: data === undefined ? "GET" : "POST",
328
+ credentials: "same-origin",
329
+ cache: "no-store",
330
+ redirect: "error",
331
+ headers: data === undefined ? {} : { "Content-Type": "application/json" },
332
+ body: data === undefined ? undefined : JSON.stringify(data),
333
+ signal: AbortSignal.timeout(7000),
334
+ });
335
+ const value = await response.json();
336
+ if (!response.ok)
337
+ throw new Error(typeof value.error === "string" ? value.error : "Request failed");
338
+ return value;
339
+ }
340
+ function render() {
341
+ if (!snapshot)
342
+ return;
343
+ get("login").hidden = true;
344
+ get("content").hidden = false;
345
+ get("notice").textContent = "";
346
+ if (get("receipt-notice").textContent ===
347
+ "Sign in to inspect retained receipts.")
348
+ get("receipt-notice").textContent =
349
+ "Choose a project to inspect retained receipts. No model usage is inferred.";
350
+ for (const id of ["pause", "refresh", "logout"])
351
+ get(id).hidden = false;
352
+ get("freshness").textContent = paused
353
+ ? "Updates paused · snapshot ages normally"
354
+ : snapshot.streaming && !streamFallback
355
+ ? "Current snapshot · live updates and 5s polling"
356
+ : "Current snapshot · polled every 5s";
357
+ renderCapacity(snapshot.capacity);
358
+ void loadProjects();
359
+ get("provenance").textContent =
360
+ `${snapshot.tenant} / ${snapshot.principal} · history ${snapshot.incarnation} · observed ${new Date(snapshot.observed_ms).toLocaleString()}`;
361
+ }
362
+ async function refresh() {
363
+ if (busy || loggedOut)
364
+ return;
365
+ busy = true;
366
+ const ticket = generation;
367
+ try {
368
+ const value = (await api("/api/snapshot"));
369
+ if (ticket !== generation)
370
+ return;
371
+ if (value.schema_version !== 1)
372
+ throw new Error("Snapshot unavailable");
373
+ if (snapshot &&
374
+ (snapshot.incarnation !== value.incarnation ||
375
+ snapshot.principal !== value.principal ||
376
+ snapshot.tenant !== value.tenant ||
377
+ snapshot.authorization_epoch !== value.authorization_epoch)) {
378
+ clear("Authorization context changed.");
379
+ }
380
+ snapshot = value;
381
+ render();
382
+ startStream();
383
+ void refreshExecution();
384
+ }
385
+ catch (error) {
386
+ if (ticket === generation)
387
+ clear("Session or source unavailable. " +
388
+ (error instanceof Error ? label(error.message) : ""));
389
+ }
390
+ finally {
391
+ busy = false;
392
+ }
393
+ }
394
+ get("login-form").addEventListener("submit", async (event) => {
395
+ event.preventDefault();
396
+ generation++;
397
+ loggedOut = false;
398
+ stopStream();
399
+ streamFallback = false;
400
+ try {
401
+ await api("/api/bootstrap", { code: get("code").value });
402
+ get("code").value = "";
403
+ await refresh();
404
+ }
405
+ catch (error) {
406
+ clear(error instanceof Error ? label(error.message) : "Sign-in failed");
407
+ }
408
+ });
409
+ get("logout").addEventListener("click", async () => {
410
+ const csrf = snapshot?.csrf;
411
+ generation++;
412
+ loggedOut = true;
413
+ clear("Signed out.");
414
+ try {
415
+ await api("/api/logout", { csrf });
416
+ }
417
+ catch {
418
+ get("notice").textContent =
419
+ "Local view cleared. Session termination was not confirmed; it expires within 15 minutes.";
420
+ }
421
+ });
422
+ get("refresh").addEventListener("click", () => void refresh());
423
+ // `memoryking dashboard open` hands the one-use code over in the URL fragment, which
424
+ // never reaches the server; it is consumed and removed from the address bar at once.
425
+ const fragmentCode = /^#code=([A-Za-z0-9_\\-]{16,128})$/.exec(location.hash);
426
+ if (fragmentCode) {
427
+ history.replaceState(null, "", location.pathname);
428
+ get("code").value = fragmentCode[1];
429
+ get("login-form").requestSubmit();
430
+ }
431
+ get("overview").addEventListener("click", () => window.scrollTo({ top: 0 }));
432
+ get("retrieval-nav").addEventListener("click", () => get("retrieval-lab").scrollIntoView());
433
+ get("receipt-project").addEventListener("change", () => {
434
+ rememberProject(get("receipt-project").value);
435
+ clearReceipts();
436
+ });
437
+ get("receipt-form").addEventListener("submit", async (event) => {
438
+ event.preventDefault();
439
+ clearReceipts();
440
+ if (!snapshot)
441
+ return;
442
+ const ticket = receiptGeneration;
443
+ const context = generation;
444
+ const project = get("receipt-project").value;
445
+ get("receipt-notice").textContent = "Checking current access…";
446
+ try {
447
+ const result = await api("/api/receipts/" + encodeURIComponent(project));
448
+ if (!snapshot || ticket !== receiptGeneration || context !== generation)
449
+ return;
450
+ receiptExpires = Date.now() + 15000;
451
+ const items = result.items;
452
+ get("receipt-notice").textContent = items.length
453
+ ? `${items.length} retained receipts · snapshot clears after 15 seconds`
454
+ : "No currently available receipts for this owner and project.";
455
+ for (const item of items) {
456
+ const button = el("button", "", "receipt-row");
457
+ button.dataset.receipt = item.receipt;
458
+ button.append(el("strong", label(item.status)), el("small", `${item.usage.output_tokens ?? "Unknown"} tokens · ${item.usage.counting ?? "not counted"} · cache ${item.cache}`), el("small", new Date(item.created_ms).toLocaleString()));
459
+ button.addEventListener("click", async () => {
460
+ try {
461
+ const detail = await api("/api/receipt/" +
462
+ encodeURIComponent(project) +
463
+ "/" +
464
+ encodeURIComponent(item.receipt));
465
+ if (!snapshot ||
466
+ ticket !== receiptGeneration ||
467
+ context !== generation)
468
+ return;
469
+ receiptExpires = Date.now() + 15000;
470
+ const diag = detail.diagnostics;
471
+ const panel = get("receipt-detail");
472
+ const meter = el("meter");
473
+ meter.max = diag.usage.max_output_tokens || 1;
474
+ meter.value = diag.usage.output_tokens || 0;
475
+ meter.hidden = typeof diag.usage.output_tokens !== "number";
476
+ if (diag.status === "budget_insufficient")
477
+ meter.className = "budget-failed";
478
+ meter.setAttribute("aria-label", "Serialized token budget used");
479
+ panel.replaceChildren(el("div", "Response details", "eyebrow"), el("h3", label(diag.status)), el("p", `${diag.usage.output_tokens ?? "Unknown"} / ${diag.usage.max_output_tokens ?? "not applicable"} tokens · ${diag.usage.counting ?? "not counted for this artifact"}`), meter, el("p", `${diag.usage.serialized_bytes} serialized bytes · Provider usage: ${diag.usage.provider_usage}`));
480
+ if (diag.status === "budget_insufficient") {
481
+ panel.prepend(el("p", `No briefing fits. Minimum essential budget: ${diag.minimum_required_tokens ?? "not computable"} tokens. The displayed count measures only the failure response.`, "integrity"));
482
+ }
483
+ if (diag.coverage)
484
+ panel.append(el("p", `Channels: lexical ${diag.coverage.lexical}; dense ${diag.coverage.dense}. Optional coverage: ${label(diag.coverage.optional)}.`, "caption"));
485
+ for (const stage of diag.trace ?? []) {
486
+ const row = el("div", "", "trace-stage");
487
+ row.append(el("strong", label(String(stage.stage))));
488
+ const facts = el("div", "", "trace-facts");
489
+ for (const [key, value] of Object.entries(stage)) {
490
+ if (key === "stage")
491
+ continue;
492
+ facts.append(el("span", key === "duration_ms"
493
+ ? `Duration: ${value} ms`
494
+ : `${label(key)}: ${typeof value === "string" ? label(value) : String(value)}`));
495
+ }
496
+ row.append(facts);
497
+ panel.append(row);
498
+ }
499
+ const list = el("ul");
500
+ for (const selected of diag.selected ?? [])
501
+ list.append(el("li", `${label(selected.authority)} · ${label(selected.reason)} · ${selected.reference}`));
502
+ panel.append(list, el("p", `Omissions: ${(diag.omissions ?? []).join(", ") || "none recorded"}`, "caption"), el("code", "SHA-256 " + String(detail.rendered_hash)), el("p", "Inspecting this receipt does not execute anything. Exact replay rechecks permission on retained bytes; rerun compiles a new artifact from explicit inputs. Neither calls a model.", "caption"));
503
+ const compare = el("button", "Compare with previous briefing");
504
+ compare.type = "button";
505
+ compare.addEventListener("click", async () => {
506
+ // The list is newest first, so the previous briefing is the next entry.
507
+ const previous = items[items.indexOf(item) + 1];
508
+ if (!previous) {
509
+ compare.replaceWith(el("p", "No earlier receipt to compare with.", "caption"));
510
+ return;
511
+ }
512
+ try {
513
+ const before = await api("/api/receipt/" +
514
+ encodeURIComponent(project) +
515
+ "/" +
516
+ encodeURIComponent(previous.receipt));
517
+ if (!snapshot ||
518
+ ticket !== receiptGeneration ||
519
+ context !== generation)
520
+ return;
521
+ compare.replaceWith(renderComparison(before.diagnostics, diag, previous.receipt, item.receipt));
522
+ }
523
+ catch (error) {
524
+ compare.replaceWith(el("p", "Comparison unavailable: " +
525
+ (error instanceof Error
526
+ ? label(error.message)
527
+ : "request failed"), "caption"));
528
+ }
529
+ });
530
+ panel.append(compare);
531
+ const replay = el("button", "Exact retained replay"), rerun = el("button", "Rerun retrieval with these inputs"), inputs = el("textarea"), output = el("pre");
532
+ inputs.setAttribute("aria-label", "New briefing inputs JSON");
533
+ inputs.rows = 8;
534
+ inputs.value = JSON.stringify({
535
+ project,
536
+ query: "inspect current evidence",
537
+ bindings: [{}],
538
+ max_output_tokens: 6000,
539
+ tokenizer: "cl100k_base",
540
+ }, null, 2);
541
+ const invoke = async (action) => {
542
+ if (!snapshot ||
543
+ ticket !== receiptGeneration ||
544
+ context !== generation)
545
+ return;
546
+ replay.disabled = rerun.disabled = true;
547
+ try {
548
+ const result = await api("/api/command", {
549
+ csrf: snapshot.csrf,
550
+ operation: "retrieval",
551
+ command: {
552
+ version: 1,
553
+ incarnation: snapshot.incarnation,
554
+ action,
555
+ args: action === "replay"
556
+ ? { project, receipt: item.receipt }
557
+ : {
558
+ project,
559
+ predecessor: item.receipt,
560
+ brief: JSON.parse(inputs.value),
561
+ },
562
+ },
563
+ });
564
+ if (!snapshot ||
565
+ ticket !== receiptGeneration ||
566
+ context !== generation)
567
+ return;
568
+ output.textContent =
569
+ (action === "replay"
570
+ ? "Exact retained artifact (displayed as formatted JSON)."
571
+ : "New retrieval artifact linked to the selected predecessor; results may differ.") +
572
+ "\n" +
573
+ JSON.stringify(result, null, 2);
574
+ // Never extend the displayed snapshot's original lifetime.
575
+ }
576
+ catch (error) {
577
+ if (ticket !== receiptGeneration || context !== generation)
578
+ return;
579
+ output.textContent = `Unavailable: ${error instanceof Error ? error.message : "request failed"}. Reload before another attempt.`;
580
+ }
581
+ finally {
582
+ replay.disabled = rerun.disabled = false;
583
+ }
584
+ };
585
+ replay.onclick = () => void invoke("replay");
586
+ rerun.onclick = () => void invoke("rerun");
587
+ const rerunBox = el("details");
588
+ rerunBox.append(el("summary", "New retrieval inputs (no model call)"), inputs, rerun);
589
+ panel.append(replay, rerunBox, output);
590
+ }
591
+ catch {
592
+ clearReceipts();
593
+ get("receipt-notice").textContent =
594
+ "Receipt unavailable under current permissions. Reload to check again.";
595
+ }
596
+ });
597
+ get("receipt-list").append(button);
598
+ }
599
+ if (pendingReceipt) {
600
+ const wanted = pendingReceipt;
601
+ pendingReceipt = null;
602
+ const row = get("receipt-list").querySelector(`[data-receipt="${CSS.escape(wanted)}"]`);
603
+ if (row)
604
+ row.click();
605
+ else
606
+ get("receipt-notice").textContent +=
607
+ " · the cited receipt is no longer retained for this account";
608
+ }
609
+ }
610
+ catch {
611
+ if (ticket !== receiptGeneration || context !== generation)
612
+ return;
613
+ clearReceipts();
614
+ get("receipt-notice").textContent =
615
+ "Receipts unavailable. Check the project and current session.";
616
+ }
617
+ });
618
+ get("pause").addEventListener("click", () => {
619
+ paused = !paused;
620
+ get("pause").textContent = paused ? "Resume updates" : "Pause updates";
621
+ get("freshness").textContent = paused
622
+ ? "Updates paused · snapshot ages normally"
623
+ : "Refreshing";
624
+ if (paused)
625
+ stopStream();
626
+ if (!paused)
627
+ void refresh();
628
+ });
629
+ get("theme").addEventListener("click", () => document.body.classList.toggle("light"));
630
+ setInterval(() => {
631
+ observatory.tick();
632
+ if (executionExpires && Date.now() >= executionExpires) {
633
+ clearExecution("Task snapshot expired. Reconnect to check current permissions.");
634
+ }
635
+ if (receiptExpires && Date.now() >= receiptExpires) {
636
+ clearReceipts();
637
+ get("receipt-notice").textContent =
638
+ "Receipt snapshot expired. Load again to recheck permissions.";
639
+ }
640
+ if (snapshot && Date.now() > snapshot.fresh_until_ms) {
641
+ clear("Snapshot expired. Refresh checks current authorization before displaying content.");
642
+ get("refresh").hidden = false;
643
+ }
644
+ }, 250);
645
+ setInterval(() => {
646
+ if (!paused && !document.hidden)
647
+ void refresh();
648
+ }, 5000);
649
+ document.addEventListener("visibilitychange", () => {
650
+ if (document.hidden) {
651
+ generation++;
652
+ clear("View cleared while hidden. Reconnecting checks current permission.");
653
+ }
654
+ else if (!loggedOut)
655
+ void refresh();
656
+ });
657
+ let selectedPlan = "";
658
+ let planCursor = null;
659
+ function planAction(text, action) {
660
+ const button = el("button", text);
661
+ button.type = "button";
662
+ button.addEventListener("click", () => {
663
+ if (!snapshot || Date.now() >= executionExpires)
664
+ return;
665
+ executionGeneration++;
666
+ get("execution-plans").replaceChildren(el("p", "Loading current plan view…"));
667
+ action();
668
+ void refreshExecution();
669
+ });
670
+ return button;
671
+ }
672
+ function planMeter(p, title) {
673
+ const box = el("div", "", "structured-plan-progress");
674
+ const meter = el("progress");
675
+ meter.max = Math.max(1, p.total);
676
+ meter.value = p.completed;
677
+ meter.setAttribute("aria-label", `${title}: ${p.completed} of ${p.total} steps completed`);
678
+ box.append(el("strong", p.total
679
+ ? `${p.work_percent}% · ${p.completed} of ${p.total} steps completed`
680
+ : "No steps defined"), meter, el("p", `${p.doing} in progress · ${p.todo} to do · ${p.blocked} blocked · ${p.skipped} skipped · ${p.unknown} need verification`));
681
+ if (p.skipped)
682
+ box.append(el("p", `${p.resolved} resolved including skipped work. Skipped steps do not count as completed.`));
683
+ return box;
684
+ }
685
+ function renderPlans(value) {
686
+ const root = get("execution-plans");
687
+ root.replaceChildren();
688
+ const detail = value.detail;
689
+ const items = detail ? [{ ...detail, ...detail.plan }] : (value.plans ?? []);
690
+ if (detail || planCursor)
691
+ root.append(planAction("Back to plans", () => {
692
+ selectedPlan = "";
693
+ planCursor = null;
694
+ }));
695
+ if (!items.length)
696
+ root.append(el("p", "No structured plans on this page."));
697
+ for (const p of items) {
698
+ const card = el("article", "", "task-card structured-plan");
699
+ card.append(el("h3", p.title), el("p", p.objective), el("p", `${p.status} · Revision ${p.revision} · Updated ${new Date(p.updated_ms).toLocaleString()}`, "eyebrow"), planMeter(p.progress, p.title));
700
+ if (!p.history_complete)
701
+ card.append(el("p", "Incomplete history: affected completion requires verification."));
702
+ if (!detail)
703
+ card.append(planAction("View plan", () => {
704
+ selectedPlan = p.id;
705
+ planCursor = null;
706
+ }));
707
+ else {
708
+ if (detail.plan.context)
709
+ card.append(el("p", detail.plan.context));
710
+ for (const phase of p.progress.phases) {
711
+ const box = el("details", "", "plan-phase");
712
+ box.dataset.task = `plan-${p.id}-${phase.id}`;
713
+ const summary = el("summary", `${phase.id} · ${phase.title} · ${phase.progress.completed}/${phase.progress.total} completed`);
714
+ box.append(summary, planMeter(phase.progress, phase.title));
715
+ for (const step of detail.plan.steps.filter((s) => s.phase === phase.id)) {
716
+ const row = el("section", "", "plan-step");
717
+ row.append(el("h4", step.description), el("p", `${step.id} · ${step.status}`));
718
+ if (step.depends_on.length)
719
+ row.append(el("p", `Depends on: ${step.depends_on.join(", ")}`));
720
+ if (step.notes)
721
+ row.append(el("p", step.notes));
722
+ if (step.decision)
723
+ row.append(el("p", `Scope decision: ${step.decision}`));
724
+ if (step.reported_status !== step.status)
725
+ row.append(el("p", `Reported ${step.reported_status}; current evidence requires verification.`));
726
+ for (const e of step.evidence)
727
+ row.append(el("code", `${e.kind}: ${e.id}`, "source-evidence"));
728
+ box.append(row);
729
+ }
730
+ card.append(box);
731
+ }
732
+ if (detail.plan.closure_note)
733
+ card.append(el("h4", "Closure"), el("p", detail.plan.closure_note));
734
+ for (const e of detail.plan.lessons)
735
+ card.append(el("code", `Lesson ${e.kind}: ${e.id}`, "source-evidence"));
736
+ }
737
+ root.append(card);
738
+ }
739
+ if (value.cursor)
740
+ root.append(planAction("More plans", () => {
741
+ planCursor = value.cursor ?? null;
742
+ }));
743
+ }
744
+ let executionProject = "";
745
+ let executionGeneration = 0;
746
+ let executionExpires = 0;
747
+ let executionBusy = false;
748
+ function clearExecution(message = "Enter a project to load its tasks.") {
749
+ executionGeneration++;
750
+ executionExpires = 0;
751
+ executionProject = "";
752
+ get("execution-tasks").replaceChildren();
753
+ get("execution-plans").replaceChildren();
754
+ selectedPlan = "";
755
+ planCursor = null;
756
+ get("execution-events").replaceChildren();
757
+ get("execution-provenance").textContent = "";
758
+ get("execution-notice").textContent = message;
759
+ }
760
+ function renderExecution(value) {
761
+ const tasks = get("execution-tasks");
762
+ tasks.replaceChildren();
763
+ get("execution-notice").textContent = value.tasks.length
764
+ ? `${value.tasks.length} task record${value.tasks.length === 1 ? "" : "s"} · refreshed every 5s while updates run`
765
+ : "No tasks in the current project view.";
766
+ for (const task of value.tasks) {
767
+ if (task.plan_id)
768
+ continue;
769
+ const card = el("article", "", "task-card");
770
+ card.append(el("div", `Saved by ${task.writer} · Task ${task.task}${task.run ? ` · Run ${task.run}` : ""}`, "eyebrow"), el("h3", task.objective));
771
+ if (task.summary) {
772
+ card.append(el("p", "Where this left off", "eyebrow"), el("p", task.summary.text, "task-summary"), el("p", `Summary ${label(task.summary.method)} by ${task.summary.author} · ${new Date(task.summary.created_ms).toLocaleString()} · the checkpoint is the record`, "caption"));
773
+ }
774
+ card.append(el("p", task.current_state));
775
+ const p = task.progress;
776
+ const summary = `${p.passed} passed · ${p.pending} pending · ${p.failed} failed · ${p.unknown} unknown · ${p.waived} waived / ${p.total} criteria`;
777
+ const bar = el("div", "", "criteria-bar");
778
+ bar.setAttribute("role", "img");
779
+ bar.setAttribute("aria-label", summary);
780
+ for (const c of task.criteria) {
781
+ const segment = el("span", "", "criterion-segment " + c.effective);
782
+ segment.title = c.id + ": " + c.effective;
783
+ segment.setAttribute("aria-hidden", "true");
784
+ bar.append(segment);
785
+ }
786
+ card.append(bar, el("p", summary, "criterion-summary"), el("p", `Weighted: ${p.weighted.passed} passed / ${p.weighted.total} declared units; ${p.weighted.waived} waived, ${p.weighted.unknown} unknown. Missing weights default to 1.`, "caption"));
787
+ if (p.scope_changed)
788
+ card.append(el("p", `Scope changed since previous checkpoint: ${p.previous_total} → ${p.total} criteria.`, "integrity"));
789
+ if (p.reopened)
790
+ card.append(el("p", `${p.reopened} previously passed criteria reopened since previous checkpoint.`, "integrity"));
791
+ if (!p.history_complete)
792
+ card.append(el("p", "Definition history is incomplete; passed claims remain unknown.", "integrity"));
793
+ const heartbeat = task.heartbeat;
794
+ card.append(el("p", heartbeat.status === "recent"
795
+ ? `Heartbeat observed ${new Date(heartbeat.recorded_ms).toLocaleTimeString()} · reported ${label(heartbeat.activity ?? "unknown")}`
796
+ : `Heartbeat ${heartbeat.status} · current liveness unknown`, "heartbeat " + heartbeat.status));
797
+ if (task.blockers.length) {
798
+ const blockers = el("ul", "", "blocker-list");
799
+ for (const b of task.blockers)
800
+ blockers.append(el("li", `${b.text} · owner: ${b.owner ?? "unassigned"}`));
801
+ card.append(el("h4", "Reported blockers"), blockers);
802
+ }
803
+ const details = el("details");
804
+ details.dataset.task = task.task + "/" + (task.run ?? "task");
805
+ details.append(el("summary", "Inspect criteria, evidence and source"));
806
+ for (const c of task.criteria) {
807
+ const row = el("div", "", "criterion-row");
808
+ row.append(el("strong", `${c.id} · ${c.effective}`), el("p", c.text));
809
+ if (c.reported !== c.effective)
810
+ row.append(el("p", `Producer reported ${c.reported}; current evidence or definition checks prevent credit.`, "integrity"));
811
+ if (c.reverification_required)
812
+ row.append(el("p", "Reverification required: changed definition with reused proof, or incomplete history.", "caption"));
813
+ for (const e of c.evidence)
814
+ row.append(el("code", `${e.kind}: ${e.id}`));
815
+ if (c.decision)
816
+ row.append(el("p", `Waiver decision: ${c.decision}`, "caption"));
817
+ details.append(row);
818
+ }
819
+ for (const v of task.verification)
820
+ details.append(el("p", `${v.name}: ${label(v.result)} · ${v.environment} · revision ${v.target_revision ?? "unspecified"}`, "caption"));
821
+ for (const op of task.operations)
822
+ details.append(el("p", `${op.id}: ${label(op.state)}${op.reconciliation_required ? " · reconciliation required" : ""}`, "caption"));
823
+ for (const gap of task.capture_gaps)
824
+ details.append(el("p", "Capture gap: " + gap, "integrity"));
825
+ details.append(el("p", `Checkpoint ${task.checkpoint} · revision ${task.revision} · writer ${task.writer} · position ${task.source_position}`, "caption"), el("code", "Body SHA-256 " + task.body_hash), el("code", "Criterion scope " + p.scope_hash), el("p", "Display text is bounded. Use full resume for complete task state. Repository freshness must be inspected against the current snapshot.", "caption"));
826
+ card.append(details);
827
+ tasks.append(card);
828
+ }
829
+ const events = get("execution-events");
830
+ events.replaceChildren();
831
+ for (const event of value.events) {
832
+ const row = el("li");
833
+ row.append(el("strong", label(event.kind)), el("p", `${event.task} · ${event.actor}`, "caption"), el("p", `Recorded ${new Date(event.recorded_ms).toLocaleString()}`, "caption"), el("p", `Observed ${new Date(event.observed_ms).toLocaleString()} · position ${event.source_position}`, "caption"));
834
+ events.append(row);
835
+ }
836
+ if (!value.events.length)
837
+ events.append(el("li", "No linked activity records visible."));
838
+ get("execution-provenance").textContent =
839
+ `${value.project} · ${value.tenant} / ${value.principal} · history ${value.incarnation} · observed ${new Date(value.observed_ms).toLocaleString()}. Bounded view: up to 8 visible tasks from 64 recent streams, 32 events from 128 candidates, 128 prior checkpoints per stream. No hidden totals, private reasoning, cost or ETA.`;
840
+ }
841
+ async function refreshExecution() {
842
+ if (!snapshot || !executionProject || executionBusy)
843
+ return;
844
+ executionBusy = true;
845
+ const ticket = executionGeneration, context = generation, project = executionProject;
846
+ const started = Date.now();
847
+ try {
848
+ const value = (await api("/api/execution/" + encodeURIComponent(project)));
849
+ const plans = (await api("/api/plans/" +
850
+ encodeURIComponent(project) +
851
+ (selectedPlan
852
+ ? "/" + encodeURIComponent(selectedPlan)
853
+ : planCursor
854
+ ? "?cursor=" + encodeURIComponent(planCursor)
855
+ : "")));
856
+ if (ticket !== executionGeneration || context !== generation || !snapshot)
857
+ return;
858
+ if (plans.schema_version !== 1 ||
859
+ plans.project !== project ||
860
+ plans.tenant !== snapshot.tenant ||
861
+ plans.principal !== snapshot.principal ||
862
+ plans.incarnation !== snapshot.incarnation ||
863
+ value.schema_version !== 1 ||
864
+ value.status !== "available" ||
865
+ value.project !== project ||
866
+ value.incarnation !== snapshot.incarnation ||
867
+ value.tenant !== snapshot.tenant ||
868
+ value.principal !== snapshot.principal ||
869
+ Date.now() >= started + 15000)
870
+ throw new Error("Current task authorization or evidence unavailable");
871
+ executionExpires = Math.min(started + 15000, value.fresh_until_ms, plans.fresh_until_ms);
872
+ if (Date.now() >= executionExpires)
873
+ throw new Error("Snapshot expired");
874
+ // Preserve disclosure state and keyboard position across observational polling.
875
+ const open = new Set(Array.from(get("execution-panel").querySelectorAll("details[open]"), (d) => d.dataset.task));
876
+ const focused = document.activeElement?.closest("details")?.dataset.task;
877
+ renderExecution(value);
878
+ renderPlans(plans);
879
+ for (const d of get("execution-panel").querySelectorAll("details")) {
880
+ d.open = open.has(d.dataset.task);
881
+ if (focused === d.dataset.task)
882
+ d.querySelector("summary")?.focus({ preventScroll: true });
883
+ }
884
+ }
885
+ catch {
886
+ if (ticket === executionGeneration && context === generation)
887
+ clearExecution("Task data unavailable. Reconnect to recheck project access and current evidence.");
888
+ }
889
+ finally {
890
+ executionBusy = false;
891
+ }
892
+ }
893
+ get("execution-nav").addEventListener("click", () => get("execution-panel").scrollIntoView());
894
+ get("execution-project").addEventListener("change", () => {
895
+ rememberProject(get("execution-project").value);
896
+ clearExecution();
897
+ });
898
+ get("execution-form").addEventListener("submit", (event) => {
899
+ event.preventDefault();
900
+ clearExecution();
901
+ if (!snapshot)
902
+ return;
903
+ executionProject = get("execution-project").value;
904
+ get("execution-notice").textContent = "Checking current task access…";
905
+ void refreshExecution();
906
+ });
907
+ void refresh();