opencode-self-improvement 0.15.18 → 0.15.19

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 (93) hide show
  1. package/README.md +4 -0
  2. package/package.json +4 -2
  3. package/src/capture/candidates.ts +17 -6
  4. package/src/capture/lag.ts +6 -2
  5. package/src/capture/prompt.ts +1 -1
  6. package/src/capture/runtime.ts +85 -21
  7. package/src/capture/session-model.ts +2 -1
  8. package/src/capture/transcript.ts +10 -4
  9. package/src/capture/triggers.ts +48 -14
  10. package/src/command/ensure.ts +6 -1
  11. package/src/consolidate/propose.ts +47 -17
  12. package/src/consolidate/render.ts +3 -1
  13. package/src/core/cmp-ts.ts +2 -2
  14. package/src/core/config/budgets.ts +0 -1
  15. package/src/core/config/paths.ts +2 -3
  16. package/src/core/hooks.ts +8 -3
  17. package/src/core/host.ts +8 -3
  18. package/src/core/logfmt/format.ts +20 -5
  19. package/src/core/logfmt/publish.ts +21 -4
  20. package/src/core/lru.ts +20 -20
  21. package/src/core/permissions.ts +21 -5
  22. package/src/core/runtime.ts +7 -3
  23. package/src/core/state.ts +12 -2
  24. package/src/core/time.ts +0 -1
  25. package/src/core/tokenize.ts +16 -5
  26. package/src/core/types.ts +8 -1
  27. package/src/events.ts +74 -18
  28. package/src/evidence/record.ts +29 -9
  29. package/src/gate/gate.ts +208 -64
  30. package/src/gate/resolver.ts +105 -20
  31. package/src/hits/ledger.ts +35 -10
  32. package/src/identity/host-events.ts +35 -11
  33. package/src/identity/repokey.ts +27 -9
  34. package/src/identity/session-context.ts +39 -8
  35. package/src/index.ts +108 -42
  36. package/src/init/detect.ts +62 -12
  37. package/src/init/run.ts +50 -11
  38. package/src/inject/anchor.ts +11 -5
  39. package/src/inject/attribution.ts +29 -6
  40. package/src/inject/budget.ts +9 -2
  41. package/src/inject/digest.ts +16 -8
  42. package/src/inject/epochs.ts +43 -15
  43. package/src/inject/pull.ts +11 -5
  44. package/src/inject/version.ts +10 -5
  45. package/src/portable/decay.ts +20 -9
  46. package/src/portable/export.ts +30 -10
  47. package/src/portable/import.ts +43 -12
  48. package/src/recall/relevant.ts +11 -5
  49. package/src/recall/score.ts +5 -3
  50. package/src/status/format.ts +8 -2
  51. package/src/status/metrics.ts +22 -6
  52. package/src/status/payload.ts +7 -2
  53. package/src/status/report.ts +63 -18
  54. package/src/status/write.ts +21 -7
  55. package/src/store/blocklist.ts +16 -4
  56. package/src/store/containment.ts +27 -8
  57. package/src/store/files/append.ts +57 -37
  58. package/src/store/files/deletions.ts +5 -2
  59. package/src/store/files/load.ts +37 -11
  60. package/src/store/files/prune.ts +18 -5
  61. package/src/store/files/snapshots.ts +6 -2
  62. package/src/store/files/supersede.ts +32 -12
  63. package/src/store/files/target.ts +4 -1
  64. package/src/store/lock.ts +10 -2
  65. package/src/store/model/visibility.ts +26 -6
  66. package/src/store/prune.ts +1 -1
  67. package/src/store/quarantine/quarantine.ts +36 -9
  68. package/src/store/quarantine/release.ts +9 -3
  69. package/src/store/secrets.ts +4 -2
  70. package/src/store/tombstones/rejection.ts +21 -5
  71. package/src/store/tombstones/tombstone.ts +48 -11
  72. package/src/store/undo.ts +43 -18
  73. package/src/tools/consolidate.ts +18 -8
  74. package/src/tools/decay.ts +37 -9
  75. package/src/tools/deps.ts +10 -2
  76. package/src/tools/evidence.ts +7 -4
  77. package/src/tools/export.ts +10 -4
  78. package/src/tools/forget.ts +15 -5
  79. package/src/tools/import.ts +16 -5
  80. package/src/tools/init.ts +13 -4
  81. package/src/tools/list.ts +12 -6
  82. package/src/tools/merge-review.ts +52 -20
  83. package/src/tools/recall.ts +17 -9
  84. package/src/tools/registry.ts +4 -1
  85. package/src/tools/remember.ts +21 -7
  86. package/src/tools/schema.ts +55 -18
  87. package/src/tools/status-tool.ts +29 -11
  88. package/src/tools/undo.ts +23 -8
  89. package/src/tools/update.ts +116 -40
  90. package/src/tui/panel.tsx +119 -30
  91. package/src/viewer/mutate.ts +57 -20
  92. package/src/viewer/rejections.ts +1 -1
  93. package/src/viewer/server.ts +88 -28
package/src/tui/panel.tsx CHANGED
@@ -14,10 +14,15 @@ import { Plugin, usePlugin } from "@opencode/plugin/tui";
14
14
  import type { PanelInput } from "@opencode/plugin/tui/context";
15
15
  import { evidenceDir, memoryRoot } from "../core/config/paths.ts";
16
16
  import { fmtBytes, fmtMs } from "../status/format.ts";
17
- import { cacheHealth, cacheRate, type CacheHealth } from "../status/format.ts"
18
- import { ledgerIsYoung } from "../status/metrics.ts"
19
- import { type BlockedRow, type StatusPayload } from "../status/payload.ts"
20
- import { attributionLines, cacheLines, contextLines, windowLines } from "../status/report.ts"
17
+ import { cacheHealth, cacheRate, type CacheHealth } from "../status/format.ts";
18
+ import { ledgerIsYoung } from "../status/metrics.ts";
19
+ import { type BlockedRow, type StatusPayload } from "../status/payload.ts";
20
+ import {
21
+ attributionLines,
22
+ cacheLines,
23
+ contextLines,
24
+ windowLines,
25
+ } from "../status/report.ts";
21
26
  import { blockedRecent, readStatus, statusDir } from "../status/write.ts";
22
27
 
23
28
  const PANEL = "self-improvement.memory";
@@ -54,7 +59,8 @@ export default Plugin.define({
54
59
  // Dot colors: theme semantic colors when the host provides them, stable
55
60
  // hex fallbacks otherwise. Resolved once per setup.
56
61
  const th = context.theme as unknown as Record<string, any>;
57
- const col = (v: unknown, fallback: string): string => (typeof v === "string" ? v : fallback);
62
+ const col = (v: unknown, fallback: string): string =>
63
+ typeof v === "string" ? v : fallback;
58
64
  const DOT: Record<CacheHealth, string> = {
59
65
  green: col(th.success, "#4ade80"),
60
66
  recent: col(th.warning, "#fbbf24"),
@@ -128,9 +134,12 @@ export default Plugin.define({
128
134
  }
129
135
  };
130
136
  const ensureWatchers = () => {
131
- if (!rootWatcher) rootWatcher = attach(() => watch(memoryRoot(), scheduleRefresh));
132
- if (!dirWatcher) dirWatcher = attach(() => watch(statusDir(), scheduleRefresh));
133
- if (!evWatcher) evWatcher = attach(() => watch(evidenceDir(), scheduleRefresh));
137
+ if (!rootWatcher)
138
+ rootWatcher = attach(() => watch(memoryRoot(), scheduleRefresh));
139
+ if (!dirWatcher)
140
+ dirWatcher = attach(() => watch(statusDir(), scheduleRefresh));
141
+ if (!evWatcher)
142
+ evWatcher = attach(() => watch(evidenceDir(), scheduleRefresh));
134
143
  };
135
144
  ensureWatchers();
136
145
  const timer = setInterval(() => {
@@ -163,7 +172,11 @@ export default Plugin.define({
163
172
  append: "home.footer.status",
164
173
  render: () => {
165
174
  const s = status();
166
- return <text fg={context.theme.text.base}>{s ? `mem ${s.store.active}` : "mem -"}</text>;
175
+ return (
176
+ <text fg={context.theme.text.base}>
177
+ {s ? `mem ${s.store.active}` : "mem -"}
178
+ </text>
179
+ );
167
180
  },
168
181
  });
169
182
 
@@ -172,7 +185,12 @@ export default Plugin.define({
172
185
  append: "session.panel",
173
186
  render: (panel) => (
174
187
  <Show when={panel.name === PANEL}>
175
- <MemoryPanel panel={panel} refresh={refresh} status={status()} blocked={blocked()} />
188
+ <MemoryPanel
189
+ panel={panel}
190
+ refresh={refresh}
191
+ status={status()}
192
+ blocked={blocked()}
193
+ />
176
194
  </Show>
177
195
  ),
178
196
  });
@@ -193,7 +211,10 @@ export default Plugin.define({
193
211
  slash: { name: "memory" },
194
212
  run: () => {
195
213
  if (!context.ui.panel.open(PANEL)) {
196
- context.ui.toast.show({ message: "the memory panel needs an open session", variant: "info" });
214
+ context.ui.toast.show({
215
+ message: "the memory panel needs an open session",
216
+ variant: "info",
217
+ });
197
218
  }
198
219
  },
199
220
  },
@@ -230,7 +251,12 @@ function MemoryPanel(props: {
230
251
  bind: "r",
231
252
  run: () => void props.refresh(props.panel.sessionID),
232
253
  },
233
- { id: "self-improvement.memory.fullscreen", title: "Fullscreen", bind: "f", run: props.panel.toggleFullscreen },
254
+ {
255
+ id: "self-improvement.memory.fullscreen",
256
+ title: "Fullscreen",
257
+ bind: "f",
258
+ run: props.panel.toggleFullscreen,
259
+ },
234
260
  ],
235
261
  }));
236
262
 
@@ -245,19 +271,43 @@ function MemoryPanel(props: {
245
271
  <Section t="CONTEXT" />
246
272
  <Show
247
273
  when={s()}
248
- fallback={<text fg={context.theme.text.base}> no epoch yet — nothing injected (fresh server, or no prompt scored)</text>}
274
+ fallback={
275
+ <text fg={context.theme.text.base}>
276
+ {
277
+ " no epoch yet — nothing injected (fresh server, or no prompt scored)"
278
+ }
279
+ </text>
280
+ }
249
281
  >
250
- <For each={contextLines(s()!)}>{(line) => <text fg={context.theme.text.base}>{line}</text>}</For>
282
+ <For each={contextLines(s()!)}>
283
+ {(line) => <text fg={context.theme.text.base}>{line}</text>}
284
+ </For>
251
285
  </Show>
252
286
 
253
287
  <Section t="CACHE" />
254
- <Show when={s()} fallback={<text fg={context.theme.text.base}> nothing to report before the first epoch</text>}>
255
- <For each={cacheLines(s()!)}>{(line) => <text fg={context.theme.text.base}>{line}</text>}</For>
288
+ <Show
289
+ when={s()}
290
+ fallback={
291
+ <text fg={context.theme.text.base}>
292
+ {" nothing to report before the first epoch"}
293
+ </text>
294
+ }
295
+ >
296
+ <For each={cacheLines(s()!)}>
297
+ {(line) => <text fg={context.theme.text.base}>{line}</text>}
298
+ </For>
256
299
  </Show>
257
300
 
258
301
  <Section t="CONTEXT WINDOW — is memory bloating your context?" />
259
- <Show when={s()} fallback={<text fg={context.theme.text.base}> nothing injected yet</text>}>
260
- <For each={windowLines(s()!)}>{(line) => <text fg={context.theme.text.base}>{line}</text>}</For>
302
+ <Show
303
+ when={s()}
304
+ fallback={
305
+ <text fg={context.theme.text.base}>{" nothing injected yet"}</text>
306
+ }
307
+ >
308
+ <For each={windowLines(s()!)}>
309
+ {(line) => <text fg={context.theme.text.base}>{line}</text>}
310
+ </For>
261
311
  </Show>
262
312
 
263
313
  <Section t="INJECTED BLOCK (VERBATIM)" />
@@ -266,41 +316,78 @@ function MemoryPanel(props: {
266
316
  when={s()!.block}
267
317
  fallback={
268
318
  <text fg={context.theme.text.base}>
269
- {" abstained — your prompt shares no content vocabulary with any memory, so nothing was injected (by design)"}
319
+ {
320
+ " abstained — your prompt shares no content vocabulary with any memory, so nothing was injected (by design)"
321
+ }
270
322
  </text>
271
323
  }
272
324
  >
273
- <For each={s()!.block.split("\n")}>{(line) => <text fg={context.theme.text.base}>{" " + line}</text>}</For>
325
+ <For each={s()!.block.split("\n")}>
326
+ {(line) => <text fg={context.theme.text.base}>{" " + line}</text>}
327
+ </For>
274
328
  </Show>
275
329
  </Show>
276
330
 
277
331
  <Section t="MEMORY ATTRIBUTION — answered from memory vs re-reading files" />
278
- <Show when={s()} fallback={<text fg={context.theme.text.base}> nothing injected yet</text>}>
279
- <For each={attributionLines(s()!)}>{(line) => <text fg={context.theme.text.base}>{line}</text>}</For>
332
+ <Show
333
+ when={s()}
334
+ fallback={
335
+ <text fg={context.theme.text.base}>{" nothing injected yet"}</text>
336
+ }
337
+ >
338
+ <For each={attributionLines(s()!)}>
339
+ {(line) => <text fg={context.theme.text.base}>{line}</text>}
340
+ </For>
280
341
  </Show>
281
342
 
282
343
  <Section t="RECENT BLOCKED WRITES" />
283
- <Show when={props.blocked.length} fallback={<text fg={context.theme.text.base}> (none today or yesterday)</text>}>
344
+ <Show
345
+ when={props.blocked.length}
346
+ fallback={
347
+ <text fg={context.theme.text.base}>
348
+ {" (none today or yesterday)"}
349
+ </text>
350
+ }
351
+ >
284
352
  <For each={props.blocked}>
285
- {(b) => <text fg={context.theme.text.base}>{" " + b.ts.slice(11, 19) + " " + b.reason + " " + b.sid}</text>}
353
+ {(b) => (
354
+ <text fg={context.theme.text.base}>
355
+ {" " + b.ts.slice(11, 19) + " " + b.reason + " " + b.sid}
356
+ </text>
357
+ )}
286
358
  </For>
287
359
  </Show>
288
360
 
289
361
  <Section t="STORE" />
290
362
  <Show when={s()}>
291
363
  <text fg={context.theme.text.base}>
292
- {" " + (s()?.store.active ?? 0) + " active · " + (s()?.store.superseded ?? 0) + " superseded · " +
293
- (s()?.store.open ?? 0) + " open · " + (s()?.store.scopes ?? 0) + " scopes" +
294
- ((s()?.store.malformed ?? 0) > 0 ? " · " + s()!.store.malformed + " malformed (skipped)" : "") +
364
+ {" " +
365
+ (s()?.store.active ?? 0) +
366
+ " active · " +
367
+ (s()?.store.superseded ?? 0) +
368
+ " superseded · " +
369
+ (s()?.store.open ?? 0) +
370
+ " open · " +
371
+ (s()?.store.scopes ?? 0) +
372
+ " scopes" +
373
+ ((s()?.store.malformed ?? 0) > 0
374
+ ? " · " + s()!.store.malformed + " malformed (skipped)"
375
+ : "") +
295
376
  ((s()?.store.neverRetrieved ?? 0) > 0
296
377
  ? " · " +
297
378
  s()!.store.neverRetrieved +
298
379
  (ledgerIsYoung(s()!.store.ledgerSince)
299
- ? " never retrieved (ledger since " + (s()!.store.ledgerSince?.slice(0, 10) ?? "no lines") + ")"
380
+ ? " never retrieved (ledger since " +
381
+ (s()!.store.ledgerSince?.slice(0, 10) ?? "no lines") +
382
+ ")"
300
383
  : " never retrieved (30d)")
301
384
  : "") +
302
385
  ((s()?.store.bytes ?? 0) > 0
303
- ? " · " + fmtBytes(s()!.store.bytes!) + " · " + s()!.store.bytesPerRow + " B/row"
386
+ ? " · " +
387
+ fmtBytes(s()!.store.bytes!) +
388
+ " · " +
389
+ s()!.store.bytesPerRow +
390
+ " B/row"
304
391
  : "") +
305
392
  ((s()?.store.captureLag?.n ?? 0) > 0
306
393
  ? " · capture p50 " + fmtMs(s()!.store.captureLag!.p50)
@@ -308,7 +395,9 @@ function MemoryPanel(props: {
308
395
  </text>
309
396
  </Show>
310
397
 
311
- <text fg={context.theme.text.base}>{"\n r refresh · f fullscreen · esc close"}</text>
398
+ <text fg={context.theme.text.base}>
399
+ {"\n r refresh · f fullscreen · esc close"}
400
+ </text>
312
401
  </box>
313
402
  );
314
403
  }
@@ -11,15 +11,19 @@ import { addBlock, removeBlock } from "../store/blocklist.ts";
11
11
  import { record, chainId, contentHash } from "../evidence/record.ts";
12
12
  import { removeTombstone, tombstone } from "../store/tombstones/tombstone.ts";
13
13
  import { redactSecrets } from "../store/secrets.ts";
14
- import { formatLine, parseLine } from "../core/logfmt/format.ts"
15
- import { appendLog, fileIdentity, writeAtomic } from "../core/logfmt/publish.ts"
14
+ import { formatLine, parseLine } from "../core/logfmt/format.ts";
15
+ import {
16
+ appendLog,
17
+ fileIdentity,
18
+ writeAtomic,
19
+ } from "../core/logfmt/publish.ts";
16
20
  import { readLines } from "../core/logfmt/read.ts";
17
21
  import { withStoreLock, LOCK_WRITE } from "../store/lock.ts";
18
- import { appendMemory } from "../store/files/append.ts"
19
- import { loadAll } from "../store/files/load.ts"
20
- import { snapshotFiles } from "../store/files/snapshots.ts"
21
- import { markSuperseded } from "../store/files/supersede.ts"
22
- import { type Memory } from "../store/model/memory.ts"
22
+ import { appendMemory } from "../store/files/append.ts";
23
+ import { loadAll } from "../store/files/load.ts";
24
+ import { snapshotFiles } from "../store/files/snapshots.ts";
25
+ import { markSuperseded } from "../store/files/supersede.ts";
26
+ import { type Memory } from "../store/model/memory.ts";
23
27
  import { releaseQuarantine } from "../store/quarantine/release.ts";
24
28
  import { assertViewerWriteAllowed } from "./rejections.ts";
25
29
 
@@ -97,12 +101,18 @@ export async function editMemory(input: EditInput): Promise<MutationResult> {
97
101
  });
98
102
  const retired: string[] = [];
99
103
  try {
100
- await markSuperseded(input.ts, {
101
- superseded_by: newTs,
102
- reason: "human_edit",
103
- }, retired);
104
+ await markSuperseded(
105
+ input.ts,
106
+ {
107
+ superseded_by: newTs,
108
+ reason: "human_edit",
109
+ },
110
+ retired,
111
+ );
104
112
  } catch (err) {
105
- throw new Error(`viewer edit PARTIAL: replacement ${newTs} IS on disk; original ${input.ts} ${retired.includes(input.ts) ? "IS retired" : "was NOT retired by this edit"}. Stopped: ${String(err)}. Inspect the rows or use memory_undo before retrying.`);
113
+ throw new Error(
114
+ `viewer edit PARTIAL: replacement ${newTs} IS on disk; original ${input.ts} ${retired.includes(input.ts) ? "IS retired" : "was NOT retired by this edit"}. Stopped: ${String(err)}. Inspect the rows or use memory_undo before retrying.`,
115
+ );
106
116
  }
107
117
  await audit("edited", target, input.ts, newTs, input.reason);
108
118
  await record("viewer_edit", {
@@ -126,7 +136,9 @@ export async function editMemory(input: EditInput): Promise<MutationResult> {
126
136
  }
127
137
 
128
138
  // Non-destructive delete: snapshot the pre-state, remove the entry, audit.
129
- export async function deleteMemory(input: DeleteInput): Promise<MutationResult> {
139
+ export async function deleteMemory(
140
+ input: DeleteInput,
141
+ ): Promise<MutationResult> {
130
142
  requireReason(input.reason);
131
143
  const chain = chainId();
132
144
  const target = await findMemory(input.ts);
@@ -143,9 +155,14 @@ export async function deleteMemory(input: DeleteInput): Promise<MutationResult>
143
155
  const f = parseLine(l);
144
156
  return !(f && f.ts === input.ts);
145
157
  });
146
- if (kept.length === lines.length) throw new Error(`memory line not found: ${input.ts}`);
158
+ if (kept.length === lines.length)
159
+ throw new Error(`memory line not found: ${input.ts}`);
147
160
  snapshot = await snapshotFiles([target.file]);
148
- await writeAtomic(target.file, kept.join("\n") + (kept.length ? "\n" : ""), since);
161
+ await writeAtomic(
162
+ target.file,
163
+ kept.join("\n") + (kept.length ? "\n" : ""),
164
+ since,
165
+ );
149
166
  },
150
167
  LOCK_WRITE,
151
168
  );
@@ -199,18 +216,35 @@ async function audit(
199
216
  );
200
217
  }
201
218
 
202
- export async function releaseQuarantinedMemory(ts: string, reason: string): Promise<{ released: boolean; reason?: "not_found" | "not_quarantined"; auditError?: string }> {
219
+ export async function releaseQuarantinedMemory(
220
+ ts: string,
221
+ reason: string,
222
+ ): Promise<{
223
+ released: boolean;
224
+ reason?: "not_found" | "not_quarantined";
225
+ auditError?: string;
226
+ }> {
203
227
  // Layered with ReleaseQuarantineBody's trim/min check. Neither layer alone
204
228
  // is pinned by the route rejection test; direct callers still need this one.
205
229
  requireReason(reason);
206
230
  const outcome = await releaseQuarantine(ts);
207
- const result = outcome === "released" ? { released: true } : { released: false, reason: outcome };
231
+ const result =
232
+ outcome === "released"
233
+ ? { released: true }
234
+ : { released: false, reason: outcome };
208
235
  try {
209
- await record(result.released ? "quarantine_released" : "quarantine_release_noop", { mem: ts, reason, outcome, source: "viewer" }, false);
236
+ await record(
237
+ result.released ? "quarantine_released" : "quarantine_release_noop",
238
+ { mem: ts, reason, outcome, source: "viewer" },
239
+ false,
240
+ );
210
241
  return result;
211
242
  } catch {
212
243
  // Release is already durable; an audit failure must not pretend otherwise.
213
- return { ...result, auditError: `${result.released ? "Release succeeded" : `No release applied (${outcome})`}, but its audit line could not be recorded.` };
244
+ return {
245
+ ...result,
246
+ auditError: `${result.released ? "Release succeeded" : `No release applied (${outcome})`}, but its audit line could not be recorded.`,
247
+ };
214
248
  }
215
249
  }
216
250
 
@@ -220,7 +254,10 @@ export async function releaseQuarantinedMemory(ts: string, reason: string): Prom
220
254
  // Order matters — the block is what the operator asked for and lands first; a
221
255
  // failure to tombstone leaves the row hidden (no data loss) rather than the
222
256
  // reverse (row visible, rejection half-applied).
223
- export async function blockMemory(input: { ts: string; reason: string }): Promise<string> {
257
+ export async function blockMemory(input: {
258
+ ts: string;
259
+ reason: string;
260
+ }): Promise<string> {
224
261
  requireReason(input.reason);
225
262
  const mem = await findMemory(input.ts);
226
263
  await addBlock(input.ts, input.reason);
@@ -10,6 +10,6 @@ export async function assertViewerWriteAllowed(content: string): Promise<void> {
10
10
  if (!rejection) return;
11
11
  throw new Error(
12
12
  `viewer write blocked: previously_rejected (${rejection.kind}; hash ${rejection.tombstone.ch}). ` +
13
- "Nothing was stored. Use Rejections → un-reject in the viewer to explicitly lift that rejection before retrying.",
13
+ "Nothing was stored. Use Rejections → un-reject in the viewer to explicitly lift that rejection before retrying.",
14
14
  );
15
15
  }
@@ -8,17 +8,39 @@ import { basename, join } from "node:path";
8
8
  import { isIP } from "node:net";
9
9
  import { serve, type Server } from "bun";
10
10
  import { z, type ZodTypeAny } from "zod";
11
- import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody, ReleaseQuarantineBody } from "../tools/schema.ts";
12
- import { deletionsFile, memoryRoot, snapshotDir } from "../core/config/paths.ts";
11
+ import {
12
+ BlockBody,
13
+ DeleteBody,
14
+ EditBody,
15
+ RestoreEntryBody,
16
+ UnblockBody,
17
+ UnrejectBody,
18
+ ReleaseQuarantineBody,
19
+ } from "../tools/schema.ts";
20
+ import {
21
+ deletionsFile,
22
+ memoryRoot,
23
+ snapshotDir,
24
+ } from "../core/config/paths.ts";
13
25
  import { blockedEntries } from "../store/blocklist.ts";
14
26
  import { listSnapshots, restoreSnapshot } from "../store/undo.ts";
15
- import { appendMemory } from "../store/files/append.ts"
27
+ import { appendMemory } from "../store/files/append.ts";
16
28
  import { loadAll, memoryFiles } from "../store/files/load.ts";
17
- import { parseLine } from "../core/logfmt/format.ts"
29
+ import { parseLine } from "../core/logfmt/format.ts";
18
30
  import { readLines } from "../core/logfmt/read.ts";
19
31
  import { releaseQuarantinedMemory } from "./mutate.ts";
20
- import { isQuarantined, quarantineReasons } from "../store/quarantine/quarantine.ts";
21
- import { deleteMemory, editMemory, blockMemory, unblockMemory, unrejectMemory, type MutationResult } from "./mutate.ts";
32
+ import {
33
+ isQuarantined,
34
+ quarantineReasons,
35
+ } from "../store/quarantine/quarantine.ts";
36
+ import {
37
+ deleteMemory,
38
+ editMemory,
39
+ blockMemory,
40
+ unblockMemory,
41
+ unrejectMemory,
42
+ type MutationResult,
43
+ } from "./mutate.ts";
22
44
  import { tombstones } from "../store/tombstones/tombstone.ts";
23
45
  import { assertViewerWriteAllowed } from "./rejections.ts";
24
46
 
@@ -75,17 +97,26 @@ function isLoopbackHostname(name: string): boolean {
75
97
  return host === "::1" || host === "0:0:0:0:0:0:0:1";
76
98
  }
77
99
 
78
- const EXPOSURE_WARNING = "[memory-viewer] WARNING: non-loopback hosts are allowed. The viewer serves private memory over plain HTTP without authentication; anyone who can reach it with an allowed Host can read or modify the store. Use only on a network you trust.";
100
+ const EXPOSURE_WARNING =
101
+ "[memory-viewer] WARNING: non-loopback hosts are allowed. The viewer serves private memory over plain HTTP without authentication; anyone who can reach it with an allowed Host can read or modify the store. Use only on a network you trust.";
79
102
 
80
103
  function rejectRequest(req: Request, url: URL, port: number): Response | null {
81
- if (!allowedHostnames().has(url.hostname) || (url.port || "80") !== String(port)) {
104
+ if (
105
+ !allowedHostnames().has(url.hostname) ||
106
+ (url.port || "80") !== String(port)
107
+ ) {
82
108
  return error("unexpected Host header", 403);
83
109
  }
84
110
  if (req.method === "GET" || req.method === "HEAD") return null;
85
111
  const origin = req.headers.get("origin");
86
- if (origin !== null && origin !== url.origin) return error("cross-origin request refused", 403);
87
- const type = (req.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
88
- if (type !== "application/json") return error("content-type must be application/json", 415);
112
+ if (origin !== null && origin !== url.origin)
113
+ return error("cross-origin request refused", 403);
114
+ const type = (req.headers.get("content-type") ?? "")
115
+ .split(";")[0]
116
+ .trim()
117
+ .toLowerCase();
118
+ if (type !== "application/json")
119
+ return error("content-type must be application/json", 415);
89
120
  return null;
90
121
  }
91
122
 
@@ -115,7 +146,9 @@ async function deletedRows(): Promise<Row[]> {
115
146
  content: String(f.content ?? ""),
116
147
  reason: String(f.reason ?? ""),
117
148
  ...(typeof f.repo === "string" && f.repo ? { repo: f.repo } : {}),
118
- ...(typeof f.repoPath === "string" && f.repoPath ? { repoPath: f.repoPath } : {}),
149
+ ...(typeof f.repoPath === "string" && f.repoPath
150
+ ? { repoPath: f.repoPath }
151
+ : {}),
119
152
  }));
120
153
  }
121
154
 
@@ -176,7 +209,10 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
176
209
  if (rejected) return rejected;
177
210
  if (url.pathname === "/") {
178
211
  return new Response(page, {
179
- headers: { ...SECURITY_HEADERS, "content-type": "text/html; charset=utf-8" },
212
+ headers: {
213
+ ...SECURITY_HEADERS,
214
+ "content-type": "text/html; charset=utf-8",
215
+ },
180
216
  });
181
217
  }
182
218
  if (req.method === "GET" && url.pathname === "/api/data") {
@@ -185,7 +221,9 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
185
221
  () => error("failed to load memory data"),
186
222
  );
187
223
  }
188
- return route(req, url).catch((e) => error(e instanceof Error ? e.message : String(e)));
224
+ return route(req, url).catch((e) =>
225
+ error(e instanceof Error ? e.message : String(e)),
226
+ );
189
227
  },
190
228
  });
191
229
  const bound = server.port ?? port;
@@ -245,20 +283,28 @@ async function loaded(): Promise<Record<string, unknown>> {
245
283
  async function route(req: Request, url: URL): Promise<Response> {
246
284
  if (req.method === "POST") {
247
285
  const body: unknown = await req.json().catch(() => ({}));
248
- if (url.pathname === "/api/edit") return parseWith(EditBody, body, editRoute);
249
- if (url.pathname === "/api/delete") return parseWith(DeleteBody, body, deleteRoute);
250
- if (url.pathname === "/api/block") return parseWith(BlockBody, body, blockRoute);
251
- if (url.pathname === "/api/unblock") return parseWith(UnblockBody, body, unblockRoute);
286
+ if (url.pathname === "/api/edit")
287
+ return parseWith(EditBody, body, editRoute);
288
+ if (url.pathname === "/api/delete")
289
+ return parseWith(DeleteBody, body, deleteRoute);
290
+ if (url.pathname === "/api/block")
291
+ return parseWith(BlockBody, body, blockRoute);
292
+ if (url.pathname === "/api/unblock")
293
+ return parseWith(UnblockBody, body, unblockRoute);
252
294
  if (url.pathname === "/api/release-quarantine") {
253
295
  return parseWith(ReleaseQuarantineBody, body, async ({ ts, reason }) =>
254
- json(await releaseQuarantinedMemory(ts, reason)));
296
+ json(await releaseQuarantinedMemory(ts, reason)),
297
+ );
255
298
  }
256
- if (url.pathname === "/api/unreject") return parseWith(UnrejectBody, body, unrejectRoute);
257
- if (url.pathname === "/api/restore-entry") return parseWith(RestoreEntryBody, body, restoreEntryRoute);
299
+ if (url.pathname === "/api/unreject")
300
+ return parseWith(UnrejectBody, body, unrejectRoute);
301
+ if (url.pathname === "/api/restore-entry")
302
+ return parseWith(RestoreEntryBody, body, restoreEntryRoute);
258
303
  // /api/restore is deliberately NOT schema-parsed here: its name check is
259
304
  // basename + pinned-grammar CONTAINMENT, not a shape gate,
260
305
  // and its regression tests pin that behavior.
261
- if (url.pathname === "/api/restore") return restoreRoute(body as Record<string, unknown>);
306
+ if (url.pathname === "/api/restore")
307
+ return restoreRoute(body as Record<string, unknown>);
262
308
  }
263
309
  return json({ error: "not found" }, 404);
264
310
  }
@@ -296,7 +342,9 @@ async function editRoute(body: z.infer<typeof EditBody>): Promise<Response> {
296
342
  return json(r);
297
343
  }
298
344
 
299
- async function deleteRoute(body: z.infer<typeof DeleteBody>): Promise<Response> {
345
+ async function deleteRoute(
346
+ body: z.infer<typeof DeleteBody>,
347
+ ): Promise<Response> {
300
348
  return json(await deleteMemory({ ts: body.ts, reason: body.reason }));
301
349
  }
302
350
 
@@ -304,18 +352,24 @@ async function blockRoute(body: z.infer<typeof BlockBody>): Promise<Response> {
304
352
  return json({ ts: await blockMemory(body) });
305
353
  }
306
354
 
307
- async function unblockRoute(body: z.infer<typeof UnblockBody>): Promise<Response> {
355
+ async function unblockRoute(
356
+ body: z.infer<typeof UnblockBody>,
357
+ ): Promise<Response> {
308
358
  return json({ unblocked: await unblockMemory(body.ts) });
309
359
  }
310
360
 
311
361
  // The only way a rejection is ever lifted (#35). Human-only: the plugin exposes
312
362
  // no tool for this, so a session whose write was refused cannot clear the
313
363
  // refusal and re-submit the rejected value.
314
- async function unrejectRoute(body: z.infer<typeof UnrejectBody>): Promise<Response> {
364
+ async function unrejectRoute(
365
+ body: z.infer<typeof UnrejectBody>,
366
+ ): Promise<Response> {
315
367
  return json({ unrejected: await unrejectMemory(body.ch) });
316
368
  }
317
369
 
318
- async function restoreEntryRoute(body: z.infer<typeof RestoreEntryBody>): Promise<Response> {
370
+ async function restoreEntryRoute(
371
+ body: z.infer<typeof RestoreEntryBody>,
372
+ ): Promise<Response> {
319
373
  await assertViewerWriteAllowed(body.content);
320
374
  // Origin survives the restore round trip (#129): when the audit line carried
321
375
  // a repo stamp, the restored row carries it again — the viewer's own missing
@@ -344,7 +398,11 @@ async function restoreRoute(body: Record<string, unknown>): Promise<Response> {
344
398
  // dropped rows can be recovered from is taken by restoreSnapshot itself,
345
399
  // under the store lock — snapshotting here instead would miss anything
346
400
  // another session appended between this call and the rollback.
347
- const res = await restoreSnapshot(join(snapshotDir(), name), memoryRoot(), "force");
401
+ const res = await restoreSnapshot(
402
+ join(snapshotDir(), name),
403
+ memoryRoot(),
404
+ "force",
405
+ );
348
406
  return json({
349
407
  restored: res.target,
350
408
  safety: res.safety ?? null,
@@ -354,6 +412,8 @@ async function restoreRoute(body: Record<string, unknown>): Promise<Response> {
354
412
 
355
413
  if (import.meta.main) {
356
414
  startViewer(PORT).then(({ url }) => {
357
- console.log(`\nMemory Viewer: ${url}\n(snapshot+audit are mandatory on every edit/delete)`);
415
+ console.log(
416
+ `\nMemory Viewer: ${url}\n(snapshot+audit are mandatory on every edit/delete)`,
417
+ );
358
418
  });
359
419
  }