opencode-self-improvement 0.14.28 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -247,6 +247,14 @@ Every imported row re-enters through the same four gates as `memory_remember` (t
247
247
  | `skipped` | malformed line; never reached the gates |
248
248
  | `downgraded` | imported as settled because its `status:"open"` could not be vouched for |
249
249
 
250
+ Import and auto-capture also scan incoming prose for a small set of instruction-override, role-header, and download/execute patterns. Matching rows still face every write gate; a promoted match is tagged `quarantine` and withheld from recall, prompt/frontier injection, compaction anchors, contextual pull, scope/type listings, consolidation proposals, and decay. Decay previews do not quote these rows, and applied decay leaves them in the human review queue. The import reply counts quarantined promotions, gate evidence records pattern identifiers without copying the matched prose, and `/memory-report` lists review IDs for the caller's repository.
251
+
252
+ Review the full row in the memory viewer's **quarantined** filter. **Release quarantine** requires a reason, snapshots the pre-release row, and removes the quarantine flag and known scanner-reason tags; unrelated user labels such as `quarantine:custom`, repository ownership, row identity, blocklist, and supersession remain intact. Missing and already-released rows produce distinct, audited no-op outcomes. Existing prompt blocks refresh before the next delivery or status report when a row becomes quarantined or is released. Undoing a release can restore the quarantine flag.
253
+
254
+ This is a heuristic review queue, not a complete prompt-injection detector: legitimate documentation or quoted code can match. Markdown-bold role headers and download-then-`&&`-execute forms are recognized, but alternate role delimiters such as `[INST]` / `<<SYS>>`, base64-to-shell pipelines, paraphrased instructions, and indirect execution can evade it. Direct `memory_remember` and human viewer edits are explicit writes and are not automatically scanned: a session with that tool still has a prose channel, mitigated by the existing framing and provenance rather than quarantine. Those defenses still apply to released rows.
255
+
256
+ Existing stores are not rescanned. A byte-identical import that collapses into an existing row does not retroactively tag that row. Export preserves quarantined rows and their tags to avoid data loss; an exported released row can be quarantined again when re-import promotes it on another machine.
257
+
250
258
  An open row is exempt from reference grounding, so that status is honored only for files carrying an export header. Even with a header: an open row claiming `repo:"global"` is downgraded, and imported `repo` / `repoPath` stamps are kept only when they match the importing session's current repo — foreign stamps are dropped and the row is stamped for the importing repo. Re-running the same import in the same repo is a no-op.
251
259
 
252
260
  ## Surfaces
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.28",
3
+ "version": "0.15.1",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
package/src/gates.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // canonical-graph correctness, GATE-2 stale-ref scan + supersession, GATE-3
3
3
  // dedup, GATE-4 promotion/block. Every step emits an ordered evidence line.
4
4
  import { join } from "node:path";
5
+ import { isQuarantined, quarantineReasons } from "./quarantine.ts";
5
6
  import { memoryRoot, canonicalFile } from "./config.ts";
6
7
  import { bracketList, parseLine, readLines } from "./logfmt.ts";
7
8
  import {
@@ -346,6 +347,8 @@ export async function runWriteGate(
346
347
  scope: candidate.scope,
347
348
  type: candidate.type,
348
349
  ch,
350
+ quarantined: isQuarantined(candidate) || undefined,
351
+ quarantine_patterns: isQuarantined(candidate) ? bracketList(quarantineReasons(candidate)) : undefined,
349
352
  });
350
353
 
351
354
  const scopeMems = candidate.scope
@@ -813,6 +816,8 @@ export async function runWriteGate(
813
816
  snapshot: snapshot[0] ?? "-",
814
817
  trusted: ctx.trusted ? true : undefined,
815
818
  grounded_by: groundedByEngagement ? "engagement" : undefined,
819
+ quarantined: isQuarantined(candidate) || undefined,
820
+ quarantine_patterns: isQuarantined(candidate) ? bracketList(quarantineReasons(candidate)) : undefined,
816
821
  chain,
817
822
  });
818
823
  } catch (err) {
package/src/index.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  clearSuperseded,
15
15
  evidenceVisibleTo,
16
16
  isActive,
17
+ isInjectable,
17
18
  isVisibleTo,
18
19
  loadAll,
19
20
  malformedCount,
@@ -27,6 +28,7 @@ import {
27
28
  } from "./memory.ts";
28
29
  import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gates.ts";
29
30
  import { withStoreLock } from "./lock.ts";
31
+ import { isQuarantined, quarantineCandidate, quarantineReasons } from "./quarantine.ts";
30
32
  import { pruneMemory } from "./prune.ts";
31
33
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
32
34
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
@@ -465,7 +467,7 @@ const impl = {
465
467
  async execute(args, context): Promise<{ content: string }> {
466
468
  const { sid } = toolIds(context);
467
469
  const reader = readerFromSid(sid);
468
- const all = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
470
+ const all = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
469
471
  const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
470
472
  const ledger = await readLedger();
471
473
  const use = ledger.byRow;
@@ -512,7 +514,7 @@ const impl = {
512
514
  async execute(args, context): Promise<{ content: string }> {
513
515
  const { sid, call } = toolIds(context);
514
516
  const reader = readerFromSid(sid);
515
- let results = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
517
+ let results = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
516
518
  if (!results.length) return { content: "No memories found" };
517
519
  const total = results.length;
518
520
  if (args.scope) results = results.filter((m) => m.scope.includes(args.scope!));
@@ -889,7 +891,7 @@ const impl = {
889
891
  async execute(_args, context): Promise<{ content: string }> {
890
892
  const { sid } = toolIds(context);
891
893
  const reader = readerFromSid(sid);
892
- const mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
894
+ const mems = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
893
895
  if (!mems.length) return { content: "No memories found" };
894
896
  const scopes = new Map<string, number>();
895
897
  const types = new Map<string, number>();
@@ -1156,6 +1158,7 @@ const impl = {
1156
1158
  content:
1157
1159
  `Imported ${args.file}: ${t.promoted} promoted, ${t.collapsed} duplicates collapsed, ` +
1158
1160
  `${t.blocked} blocked by the gate, ${t.skipped} malformed lines skipped.` +
1161
+ (t.quarantined ? ` ${t.quarantined} promoted ${t.quarantined === 1 ? "row" : "rows"} quarantined: withheld from recall/injection until human release in the viewer.` : "") +
1159
1162
  (t.downgraded
1160
1163
  ? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
1161
1164
  : "") +
@@ -1252,6 +1255,8 @@ const impl = {
1252
1255
  async execute(_args, context): Promise<{ content: string }> {
1253
1256
  // In-process truth: the live epoch + ledger, fresher than any file.
1254
1257
  const sid = toolIds(context).sid;
1258
+ const reportReader = readerFromSid(sid);
1259
+ if (sid !== "?") await sessions.refresh(sid);
1255
1260
  const status = sid === "?" ? null : await sessions.buildPayload(sid);
1256
1261
  const all = await loadAll();
1257
1262
  const act = all.filter(isActive);
@@ -1275,7 +1280,10 @@ const impl = {
1275
1280
  store.rowsPerDay = rowsPerDay(act) ?? undefined;
1276
1281
  store.captureLag = captureLag(await captureLagLines());
1277
1282
  return {
1278
- content: renderMemoryReport({ status, store, blocked: await blockedRecent(6) }),
1283
+ content: renderMemoryReport({ status, store, blocked: await blockedRecent(6),
1284
+ quarantined: act.filter((m) => isVisibleTo(m, reportReader) && isQuarantined(m))
1285
+ .map((m) => ({ ts: m.ts, patterns: quarantineReasons(m) })),
1286
+ }),
1279
1287
  };
1280
1288
  },
1281
1289
  }));
@@ -1572,13 +1580,13 @@ const impl = {
1572
1580
  let outcome: Awaited<ReturnType<typeof runWriteGate>>;
1573
1581
  try {
1574
1582
  outcome = await runWriteGate(
1575
- {
1583
+ quarantineCandidate({
1576
1584
  ...c,
1577
1585
  tags:
1578
1586
  trigger === "compaction"
1579
1587
  ? ["auto-capture", CAPTURE_COMPACT_TAG]
1580
1588
  : ["auto-capture"],
1581
- },
1589
+ }),
1582
1590
  { ...captureGate, durable },
1583
1591
  );
1584
1592
  } catch (err) {
package/src/inject.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // session context hook's system parts. Contextual pull appends relevant memory
4
4
  // to grep/glob/read results. Evidence is never injected.
5
5
  import { createHash } from "node:crypto";
6
- import { isActive, loadAll, readerFromSid, visibleTo, type Memory } from "./memory.ts";
6
+ import { isInjectable, loadAll, readerFromSid, visibleTo, type Memory } from "./memory.ts";
7
7
  import { record } from "./evidence.ts";
8
8
  import { dateStr, frontierBudget, injectBudget } from "./config.ts";
9
9
  import { bracketList } from "./logfmt.ts";
@@ -116,7 +116,7 @@ const LONG_QUERY_TOKENS = 3;
116
116
  // matcher.
117
117
  //
118
118
  // Superseded rows are dropped HERE, not only by the callers. Every model-facing
119
- // sink already passes isActive() rows, but a scorer that can be handed a raw
119
+ // sink already passes isInjectable() rows, but a scorer that can be handed a raw
120
120
  // loadAll() result must not be the one place a retired memory leaks back into
121
121
  // an injected block (#43 item 1: forbidden hits). The drop also keeps a
122
122
  // retired row from diluting the document frequencies the ranking depends on.
@@ -126,7 +126,7 @@ export function scoreMemories(
126
126
  limit: number,
127
127
  use?: UseSignals,
128
128
  ): Memory[] {
129
- const live = mems.filter((m) => !m.superseded_by);
129
+ const live = mems.filter(isInjectable);
130
130
  const query = new Set(words(term).filter((t) => !QUERY_STOPWORDS.has(t)));
131
131
  if (!query.size) return [];
132
132
  const needShared = query.size >= LONG_QUERY_TOKENS ? 2 : 1;
@@ -286,7 +286,7 @@ export async function systemDigest(
286
286
  // Repo-scoped: model-facing reads see the CALLER's repo + global rows, via
287
287
  // the sid carried on this flow's input (#127) — never a global re-read
288
288
  // after the loadAll await.
289
- const mems = opts.rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
289
+ const mems = (opts.rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
290
290
  if (!mems.length) return;
291
291
  // CACHE-STABLE BY CONSTRUCTION (issue #162): this line carries no row count
292
292
  // and no latest-ts. Both change on every promoted write, and the digest rides
@@ -349,7 +349,7 @@ export async function selectRelevant(
349
349
  if (!text) return { block: "", selected: [] };
350
350
  // Repo-scoped: model-facing reads see the caller's repo + global rows
351
351
  // (their session when one was threaded, #127).
352
- const mems = rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
352
+ const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
353
353
  const top = scoreMemories(text, mems, limit, use);
354
354
  if (!top.length) return { block: "", selected: [] };
355
355
  return {
@@ -379,7 +379,7 @@ export function injectedRows(block: string, candidates: Memory[]): Memory[] {
379
379
  // loadAll() already had to read and parse for the request.
380
380
  export async function storeVersion(rows?: Memory[], sid?: string): Promise<string> {
381
381
  // Repo-scoped: model-facing reads see the caller's repo + global rows.
382
- const mems = rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
382
+ const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
383
383
  if (!mems.length) return "0:";
384
384
  let max = "";
385
385
  const hash = createHash("sha256");
@@ -424,7 +424,7 @@ const ANCHOR_BUDGET = 2500;
424
424
 
425
425
  export async function compactionAnchor(limit = 12, sid?: string): Promise<string> {
426
426
  // Repo-scoped: model-facing reads see the caller's repo + global rows.
427
- const mems = visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
427
+ const mems = visibleTo((await loadAll()).filter(isInjectable), readerFromSid(sid));
428
428
  if (!mems.length) return "";
429
429
  const byNewest = (a: Memory, b: Memory) => cmpTs(b.ts, a.ts);
430
430
  const open = mems
@@ -456,7 +456,7 @@ export async function contextualPull(
456
456
  if (!term) return [];
457
457
  // Repo-scoped: model-facing reads see the CALLER's repo + global rows —
458
458
  // the pull's own sessionID, resolved before the store read (#127).
459
- const mems = visibleTo((await loadAll()).filter(isActive), readerFromSid(input.sessionID));
459
+ const mems = visibleTo((await loadAll()).filter(isInjectable), readerFromSid(input.sessionID));
460
460
  const top = scoreMemories(term, mems, 3, use);
461
461
  if (!top.length) return [];
462
462
  // Held to the injection budget too: three long rows were ~12 KB per call.
@@ -1,6 +1,6 @@
1
1
  // Per-setup injection epochs. Host event parsing and identity binding stay in
2
2
  // index.ts; this module owns frozen bytes, refresh decisions, and their status.
3
- import { isActive, isVisibleTo, loadAll, malformedCount, readerFromSid, type Memory } from "./memory.ts";
3
+ import { isInjectable, isActive, isVisibleTo, loadAll, malformedCount, readerFromSid, type Memory } from "./memory.ts";
4
4
  import { SESSION_CAP, SessionLru } from "./sessions.ts";
5
5
  import { record } from "./evidence.ts";
6
6
  import {
@@ -142,7 +142,7 @@ export function createInjectionEpochs({
142
142
  // session's repo into this one's system prompt.
143
143
  const injectableRows = async (sid?: string): Promise<Memory[]> => {
144
144
  const reader = readerFromSid(sid);
145
- return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
145
+ return (await loadAll()).filter((m) => isInjectable(m) && isVisibleTo(m, reader));
146
146
  };
147
147
  // Render the COMPLETE memory section for one request: the standing digest,
148
148
  // the open-thread frontier and the convergence line (all from systemDigest),
@@ -307,6 +307,7 @@ export function createInjectionEpochs({
307
307
  epoch.delete(sid);
308
308
  latestPrompt.delete(sid);
309
309
  },
310
+ refresh: refreshEpoch,
310
311
  buildPayload,
311
312
  flushStatus,
312
313
  };
package/src/memory.ts CHANGED
@@ -23,6 +23,7 @@ import { blockedTs } from "./blocklist.ts";
23
23
  import { tombstoneMany } from "./tombstones.ts";
24
24
  import { containsSecret, redactSecrets } from "./secrets.ts";
25
25
  import { flattenMemoryText } from "./sanitize.ts";
26
+ import { isQuarantined, QUARANTINE_TAG, quarantineReasons } from "./quarantine.ts";
26
27
 
27
28
  export type MemoryStatus = "open" | "settled";
28
29
 
@@ -686,6 +687,29 @@ export function isActive(m: Memory): boolean {
686
687
  return !m.superseded_by;
687
688
  }
688
689
 
690
+ // Quarantine remains durable and reviewable; only model-facing reads withhold it.
691
+ export function isInjectable(m: Memory): boolean {
692
+ return isActive(m) && !isQuarantined(m);
693
+ }
694
+
695
+ // Human viewer action only. Preserve identity, origin, and all non-quarantine
696
+ // metadata; stampRow snapshots and atomically publishes under the store lock.
697
+ export async function releaseQuarantine(ts: string): Promise<"released" | "not_found" | "not_quarantined"> {
698
+ for (const file of await memoryFiles()) {
699
+ const result = await stampRow(file, ts, (fields) => {
700
+ const tags = typeof fields.tags === "string" ? fields.tags.split(",") : [];
701
+ if (!tags.includes(QUARANTINE_TAG)) return null;
702
+ const scanTags = new Set([QUARANTINE_TAG, ...quarantineReasons({ tags }).map((id) => `quarantine:${id}`)]);
703
+ const kept = tags.filter((tag) => !scanTags.has(tag));
704
+ if (kept.length) fields.tags = kept.join(",");
705
+ else delete fields.tags;
706
+ return formatLine(fields);
707
+ });
708
+ if (result !== null) return result ? "released" : "not_quarantined";
709
+ }
710
+ return "not_found";
711
+ }
712
+
689
713
  // --- repo visibility ---------------------------------------------------------
690
714
  // A READER is an immutable caller identity, resolved once at the entry of a
691
715
  // flow (a hook, a tool call, a viewer route) and carried through every await
package/src/portable.ts CHANGED
@@ -9,8 +9,10 @@ import { mkdir, open, readFile } from "node:fs/promises";
9
9
  import { dirname, join } from "node:path";
10
10
  import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
11
11
  import { resolveContained } from "./containment.ts";
12
+ import { isQuarantined, quarantineCandidate } from "./quarantine.ts";
12
13
  import {
13
14
  isActive,
15
+ isInjectable,
14
16
  isVisibleTo,
15
17
  loadAll,
16
18
  readerFromSid,
@@ -189,6 +191,7 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
189
191
 
190
192
  export interface ImportTally {
191
193
  promoted: number;
194
+ quarantined?: number;
192
195
  collapsed: number;
193
196
  blocked: number;
194
197
  skipped: number;
@@ -256,7 +259,7 @@ function parseRow(line: string): WriteCandidate | null {
256
259
  // machine. Unstamped rows stay global.
257
260
  if (typeof r.repo === "string" && r.repo) c.repo = r.repo;
258
261
  if (typeof r.repoPath === "string" && r.repoPath) c.repoPath = r.repoPath;
259
- return c;
262
+ return quarantineCandidate(c);
260
263
  }
261
264
 
262
265
  // Read a JSONL export and run every valid row through `gate`. The CALLER owns
@@ -350,6 +353,7 @@ export async function importMemories(
350
353
  const outcome = await gate(c);
351
354
  if (outcome.action === "promoted") {
352
355
  tally.promoted++;
356
+ if (isQuarantined(c)) tally.quarantined = (tally.quarantined ?? 0) + 1;
353
357
  if (outcome.evidenceError !== undefined) {
354
358
  tally.unaudited++;
355
359
  tally.auditError ??= outcome.evidenceError;
@@ -370,6 +374,6 @@ export async function findStaleOpen(days: number, sid?: string): Promise<Memory[
370
374
  return (await loadAll())
371
375
  // Decay is repo-scoped: running it here must not retire
372
376
  // another repo's open threads.
373
- .filter((m) => isActive(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
377
+ .filter((m) => isInjectable(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
374
378
  .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
375
379
  }
@@ -0,0 +1,31 @@
1
+ // Heuristic review queue for untrusted capture/import prose, not a guarantee
2
+ // against prompt injection. Matches are identifiers only; never audit the text.
3
+ export const QUARANTINE_TAG = "quarantine";
4
+ const PATTERNS: readonly [string, RegExp][] = [
5
+ ["instruction_override", /\b(?:ignore|disregard|override)\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions|rules|prompts)\b/i],
6
+ ["role_header", /(?:^|\n)[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?(?:system|developer|assistant)[ \t]*:/i],
7
+ ["role_delimiter", /<\|(?:im_start|start_header_id)\|>|<\/?(?:system|developer|assistant)>|\[(?:system|developer|assistant)\]/i],
8
+ ["download_execute", /\b(?:curl|wget)\b[^\r\n|]{0,2048}(?:\||&&)\s*(?:sh|bash|zsh|powershell|pwsh)\b/i],
9
+ ["dynamic_execute", /(?<![$\w.])(?:eval|exec)\s*\(|\b(?:Invoke-Expression|iex)\s+/i],
10
+ ];
11
+
12
+ export function quarantinePatterns(content: string): string[] {
13
+ return PATTERNS.filter(([, pattern]) => pattern.test(content)).map(([id]) => id);
14
+ }
15
+
16
+ export function isQuarantined(row: { tags?: string[] }): boolean {
17
+ return row.tags?.includes(QUARANTINE_TAG) === true;
18
+ }
19
+
20
+ export function quarantineReasons(row: { tags?: string[] }): string[] {
21
+ return PATTERNS.map(([id]) => id).filter((id) => row.tags?.includes(`quarantine:${id}`));
22
+ }
23
+
24
+ export function quarantineCandidate<T extends { content: string; tags?: string[] }>(candidate: T): T {
25
+ const hits = quarantinePatterns(candidate.content);
26
+ if (!hits.length) return candidate;
27
+ return {
28
+ ...candidate,
29
+ tags: [...new Set([...(candidate.tags ?? []), QUARANTINE_TAG, ...hits.map((id) => `quarantine:${id}`)])],
30
+ };
31
+ }
package/src/schema.ts CHANGED
@@ -200,6 +200,7 @@ export const EditBody = z.object({
200
200
  export const DeleteBody = z.object({ ts: isoTs, reason: z.string() });
201
201
  export const BlockBody = z.object({ ts: isoTs, reason: z.string() });
202
202
  export const UnblockBody = z.object({ ts: isoTs });
203
+ export const ReleaseQuarantineBody = z.object({ ts: isoTs, reason: z.string().trim().min(1) });
203
204
  // #35: lift a value-keyed rejection. `ch` is the 12-hex content hash the gate's
204
205
  // block hint names, and the same identifier a `dedup_rejected` evidence line
205
206
  // carries — so a human can act on either without reading the store by hand.
package/src/status.ts CHANGED
@@ -465,9 +465,17 @@ export function renderMemoryReport(input: {
465
465
  status: StatusPayload | null;
466
466
  store: StoreCounts;
467
467
  blocked: BlockedRow[];
468
+ quarantined?: { ts: string; patterns: string[] }[];
468
469
  }): string {
469
470
  const { status, store, blocked } = input;
470
471
  const out: string[] = ["MEMORY STATUS", ""];
472
+ if (input.quarantined?.length) {
473
+ out.push("QUARANTINE", ` ${input.quarantined.length} rows withheld from recall and injection; review/release in the memory viewer.`);
474
+ for (const row of input.quarantined.slice(0, 20)) {
475
+ out.push(` ${row.ts} ${row.patterns.join(", ") || "marked for review"}`);
476
+ }
477
+ out.push("");
478
+ }
471
479
 
472
480
  if (!status) {
473
481
  out.push(
@@ -18,6 +18,7 @@ import {
18
18
  loadAll,
19
19
  markSuperseded,
20
20
  snapshotFiles,
21
+ releaseQuarantine,
21
22
  type Memory,
22
23
  } from "../memory.ts";
23
24
 
@@ -194,6 +195,21 @@ async function audit(
194
195
  );
195
196
  }
196
197
 
198
+ export async function releaseQuarantinedMemory(ts: string, reason: string): Promise<{ released: boolean; reason?: "not_found" | "not_quarantined"; auditError?: string }> {
199
+ // Layered with ReleaseQuarantineBody's trim/min check. Neither layer alone
200
+ // is pinned by the route rejection test; direct callers still need this one.
201
+ requireReason(reason);
202
+ const outcome = await releaseQuarantine(ts);
203
+ const result = outcome === "released" ? { released: true } : { released: false, reason: outcome };
204
+ try {
205
+ await record(result.released ? "quarantine_released" : "quarantine_release_noop", { mem: ts, reason, outcome, source: "viewer" }, false);
206
+ return result;
207
+ } catch {
208
+ // Release is already durable; an audit failure must not pretend otherwise.
209
+ return { ...result, auditError: `${result.released ? "Release succeeded" : `No release applied (${outcome})`}, but its audit line could not be recorded.` };
210
+ }
211
+ }
212
+
197
213
  // Blocking is a human rejection, so it tombstones the VALUE as well as hiding
198
214
  // the row (#35): without that, re-ingesting the source stores the same content
199
215
  // again under a fresh `ts` and the block silently stops protecting anything.
@@ -101,6 +101,7 @@
101
101
  <option value="active">active</option>
102
102
  <option value="all">all (incl. superseded)</option>
103
103
  <option value="superseded">superseded</option>
104
+ <option value="quarantined">quarantined (review required)</option>
104
105
  <option value="blocked">blocked</option>
105
106
  <option value="deleted">deleted</option>
106
107
  <option value="rejected">rejected values</option>
@@ -189,6 +190,7 @@ function currentList() {
189
190
  if (fus === "deleted") return { list: DATA.deleted, kind: "deleted" };
190
191
  if (fus === "rejected") return { list: DATA.rejections, kind: "rejected" };
191
192
  if (fus === "superseded") return { list: DATA.memories.filter((m) => m.superseded_by), kind: "superseded" };
193
+ if (fus === "quarantined") return { list: DATA.memories.filter((m) => m.quarantined && !m.superseded_by), kind: "quarantined" };
192
194
  if (fus === "all") return { list: DATA.memories, kind: "all" };
193
195
  return { list: DATA.memories.filter((m) => !m.superseded_by), kind: "active" };
194
196
  }
@@ -223,7 +225,7 @@ function render() {
223
225
 
224
226
  $("rows").innerHTML = rows.map((m) => {
225
227
  const status = kind === "blocked" ? "blocked" : kind === "deleted" ? "deleted"
226
- : m.superseded_by ? "superseded" : "active";
228
+ : m.superseded_by ? "superseded" : m.quarantined ? "quarantined" : "active";
227
229
  const stBadge = status === "superseded" ? badge("status-superseded", "superseded \u2192 " + m.superseded_by.slice(0,8))
228
230
  : badge("status-" + status, status);
229
231
  const actions = kind === "blocked"
@@ -232,7 +234,8 @@ function render() {
232
234
  ? `<button class="btn warn" data-action="restore-deleted" data-ts="${esc(m.ts)}" data-type="${esc(m.type)}" data-scope="${esc(m.scope)}" data-content="${esc(m.content)}" data-repo="${esc(m.repo ?? "")}" data-repo-path="${esc(m.repoPath ?? "")}" title="Re-add this deleted entry to memory">restore</button>`
233
235
  : `<button class="btn" data-action="edit" data-ts="${esc(m.ts)}" title="Edit: snapshot, supersede this entry, append the replacement">edit</button>
234
236
  <button class="btn danger" data-action="delete" data-ts="${esc(m.ts)}" title="Delete: snapshot the file, then remove this entry (audited)">delete</button>
235
- <button class="btn danger" data-action="block" data-ts="${esc(m.ts)}" title="Block (poison): keep on disk but hide from recall/inject">block</button>`;
237
+ <button class="btn danger" data-action="block" data-ts="${esc(m.ts)}" title="Block (poison): keep on disk but hide from recall/inject">block</button>
238
+ ${m.quarantined && !m.superseded_by ? `<button class="btn warn" data-action="release-quarantine" data-ts="${esc(m.ts)}" title="Approve this content for recall and injection">release quarantine</button>` : ""}`;
236
239
  return `<tr>
237
240
  <td class="ts">${tsCell(m.ts)}</td>
238
241
  <td>${badge("type", m.type)}</td>
@@ -327,6 +330,22 @@ async function unblock(ts) {
327
330
  } catch (e) { toast(String(e.message), true); }
328
331
  }
329
332
 
333
+ function releaseQuarantine(ts) {
334
+ const m = DATA.memories.find((x) => x.ts === ts);
335
+ askModal(
336
+ `Release quarantined memory ${ts.slice(0, 19)}?`,
337
+ `This content matched ${m?.quarantinePatterns?.join(", ") || "a review flag"}. Review the row before approving it for recall and prompt injection. Blocking and supersession still apply.`,
338
+ "Release",
339
+ async (reason) => {
340
+ try {
341
+ const result = await api("/api/release-quarantine", { ts, reason });
342
+ toast(result.auditError || (result.released ? "quarantine released" : result.reason === "not_found" ? "memory row not found; nothing released" : "row is already outside quarantine; nothing changed"), !!result.auditError || result.reason === "not_found");
343
+ await refresh();
344
+ } catch (e) { toast(String(e.message), true); }
345
+ },
346
+ );
347
+ }
348
+
330
349
  // The human-only escape hatch for #35. No confirmation prompt asking "why": the
331
350
  // operator already owns the store, and a rejection they are lifting is by
332
351
  // definition one they no longer agree with.
@@ -369,6 +388,7 @@ $("rows").addEventListener("click", (e) => {
369
388
  else if (action === "delete") del(ts);
370
389
  else if (action === "block") block(ts);
371
390
  else if (action === "unblock") unblock(ts);
391
+ else if (action === "release-quarantine") releaseQuarantine(ts);
372
392
  else if (action === "un-reject") unreject(btn.dataset.ch);
373
393
  else if (action === "restore-deleted") {
374
394
  const { type, scope, content, repo, repoPath } = btn.dataset;
@@ -8,12 +8,14 @@ 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 } from "../schema.ts";
11
+ import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody, ReleaseQuarantineBody } from "../schema.ts";
12
12
  import { deletionsFile, memoryRoot, snapshotDir } from "../config.ts";
13
13
  import { blockedEntries } from "../blocklist.ts";
14
14
  import { listSnapshots, restoreSnapshot } from "../undo.ts";
15
15
  import { appendMemory, loadAll, memoryFiles } from "../memory.ts";
16
16
  import { parseLine, readLines } from "../logfmt.ts";
17
+ import { releaseQuarantinedMemory } from "./mutate.ts";
18
+ import { isQuarantined, quarantineReasons } from "../quarantine.ts";
17
19
  import { deleteMemory, editMemory, blockMemory, unblockMemory, unrejectMemory, type MutationResult } from "./mutate.ts";
18
20
  import { tombstones } from "../tombstones.ts";
19
21
 
@@ -209,6 +211,8 @@ async function loaded(): Promise<Record<string, unknown>> {
209
211
  content: m.content,
210
212
  issue: m.issue,
211
213
  tags: m.tags,
214
+ quarantined: isQuarantined(m),
215
+ quarantinePatterns: quarantineReasons(m),
212
216
  superseded_by: m.superseded_by,
213
217
  reason: m.reason,
214
218
  // The viewer is the explicit ADMIN read surface (header comment): it
@@ -242,6 +246,10 @@ async function route(req: Request, url: URL): Promise<Response> {
242
246
  if (url.pathname === "/api/delete") return parseWith(DeleteBody, body, deleteRoute);
243
247
  if (url.pathname === "/api/block") return parseWith(BlockBody, body, blockRoute);
244
248
  if (url.pathname === "/api/unblock") return parseWith(UnblockBody, body, unblockRoute);
249
+ if (url.pathname === "/api/release-quarantine") {
250
+ return parseWith(ReleaseQuarantineBody, body, async ({ ts, reason }) =>
251
+ json(await releaseQuarantinedMemory(ts, reason)));
252
+ }
245
253
  if (url.pathname === "/api/unreject") return parseWith(UnrejectBody, body, unrejectRoute);
246
254
  if (url.pathname === "/api/restore-entry") return parseWith(RestoreEntryBody, body, restoreEntryRoute);
247
255
  // /api/restore is deliberately NOT schema-parsed here: its name check is