opencode-self-improvement 0.14.27 → 0.15.0

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
@@ -90,6 +90,7 @@ What is established, from tests and fixtures (no live store involved):
90
90
 
91
91
  - **The trigger events are ones the host actually emits.** Capture subscribes to `session.execution.succeeded` and `session.execution.interrupted`, the two turn-end events present in a recording of the desktop service (`test/fixtures/host-events.jsonl`). `session.idle`, `session.status` and `session.execution.failed` are *declared* by the host but absent from that recording, so they deliberately do not trigger capture; `test/event-fidelity.test.ts` refuses a trigger that is only declared. An earlier revision subscribed to `session.idle` and stayed silent for days with no signal — reading a declared event as an emitted one is the failure that fixture exists to prevent.
92
92
  - **The path runs under simulated host traffic** — unit tests hand the plugin the recorded envelopes and assert a candidate lands through the write gate, including conservation (a near-duplicate collapses at the gate instead of writing a second row): `test/capture.test.ts`, `test/capture-compaction.test.ts`. No terminal e2e scenario covers the trigger, so the simulated envelope is the strongest evidence that exists — and fabricating the envelope is exactly what passed while this feature was dead.
93
+ - **Identity triggers have their own recording check.** `test/event-fidelity.test.ts` checks `IDENTITY_EVENT_TYPES` against the original 2.1.4 recording plus `test/fixtures/host-session-move.json`, a normalized one-frame extract from a separate 2.2.2 move capture. The extract must declare nonempty provenance and its retained envelopes must round-trip through the lockfile-pinned `@opencode/schema` 2.0.32 decoder. These checks reject missing metadata and malformed envelopes; they do not authenticate the capture. The identity replay uses the plugin subscription, but live plugin rebinding remains unverified. The recording version is distinct from the CI host pin (2.0.26).
93
94
 
94
95
  What is not established:
95
96
 
@@ -246,6 +247,14 @@ Every imported row re-enters through the same four gates as `memory_remember` (t
246
247
  | `skipped` | malformed line; never reached the gates |
247
248
  | `downgraded` | imported as settled because its `status:"open"` could not be vouched for |
248
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
+
249
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.
250
259
 
251
260
  ## Surfaces
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.27",
3
+ "version": "0.15.0",
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/host.ts CHANGED
@@ -23,14 +23,18 @@ export interface SessionIdentity {
23
23
  directory?: string;
24
24
  }
25
25
 
26
+ // Shared with the recording-backed fidelity checks. Adding a trigger requires
27
+ // both a protocol declaration and an observation from a live host.
28
+ export const IDENTITY_EVENT_TYPES: readonly string[] = Object.freeze([
29
+ "session.created",
30
+ "session.execution.started",
31
+ "session.moved",
32
+ ]);
33
+
26
34
  /** A directory-less identity still lets the caller resolve the session row. */
27
35
  export function sessionIdentityEvent(raw: unknown): SessionIdentity | undefined {
28
36
  const event = fields(raw);
29
- if (
30
- event.type !== "session.created" &&
31
- event.type !== "session.execution.started" &&
32
- event.type !== "session.moved"
33
- ) return undefined;
37
+ if (typeof event.type !== "string" || !IDENTITY_EVENT_TYPES.includes(event.type)) return undefined;
34
38
  const data = fields(event.data ?? event.properties);
35
39
  const info = fields(data.info ?? data);
36
40
  const sessionID = info.sessionID ?? data.sessionID;
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";
@@ -220,6 +222,8 @@ export function resetCaptureCooldowns(): void {
220
222
  // test/event-fidelity.test.ts requires every trigger to appear in both that
221
223
  // recording and the installed @opencode/schema manifest: a declared event
222
224
  // alone is insufficient evidence that the host emits it (#78, #136).
225
+ // Identity triggers have a separate observed check in that test, combining
226
+ // this recording with the 2.2.2 move extract in host-session-move.json (#176).
223
227
  export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
224
228
 
225
229
  /** Every event type the capture subscription reacts to (fidelity-tested). */
@@ -463,7 +467,7 @@ const impl = {
463
467
  async execute(args, context): Promise<{ content: string }> {
464
468
  const { sid } = toolIds(context);
465
469
  const reader = readerFromSid(sid);
466
- const all = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
470
+ const all = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
467
471
  const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
468
472
  const ledger = await readLedger();
469
473
  const use = ledger.byRow;
@@ -510,7 +514,7 @@ const impl = {
510
514
  async execute(args, context): Promise<{ content: string }> {
511
515
  const { sid, call } = toolIds(context);
512
516
  const reader = readerFromSid(sid);
513
- let results = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
517
+ let results = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
514
518
  if (!results.length) return { content: "No memories found" };
515
519
  const total = results.length;
516
520
  if (args.scope) results = results.filter((m) => m.scope.includes(args.scope!));
@@ -887,7 +891,7 @@ const impl = {
887
891
  async execute(_args, context): Promise<{ content: string }> {
888
892
  const { sid } = toolIds(context);
889
893
  const reader = readerFromSid(sid);
890
- const mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
894
+ const mems = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
891
895
  if (!mems.length) return { content: "No memories found" };
892
896
  const scopes = new Map<string, number>();
893
897
  const types = new Map<string, number>();
@@ -1154,6 +1158,7 @@ const impl = {
1154
1158
  content:
1155
1159
  `Imported ${args.file}: ${t.promoted} promoted, ${t.collapsed} duplicates collapsed, ` +
1156
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.` : "") +
1157
1162
  (t.downgraded
1158
1163
  ? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
1159
1164
  : "") +
@@ -1250,6 +1255,8 @@ const impl = {
1250
1255
  async execute(_args, context): Promise<{ content: string }> {
1251
1256
  // In-process truth: the live epoch + ledger, fresher than any file.
1252
1257
  const sid = toolIds(context).sid;
1258
+ const reportReader = readerFromSid(sid);
1259
+ if (sid !== "?") await sessions.refresh(sid);
1253
1260
  const status = sid === "?" ? null : await sessions.buildPayload(sid);
1254
1261
  const all = await loadAll();
1255
1262
  const act = all.filter(isActive);
@@ -1273,7 +1280,10 @@ const impl = {
1273
1280
  store.rowsPerDay = rowsPerDay(act) ?? undefined;
1274
1281
  store.captureLag = captureLag(await captureLagLines());
1275
1282
  return {
1276
- 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
+ }),
1277
1287
  };
1278
1288
  },
1279
1289
  }));
@@ -1570,13 +1580,13 @@ const impl = {
1570
1580
  let outcome: Awaited<ReturnType<typeof runWriteGate>>;
1571
1581
  try {
1572
1582
  outcome = await runWriteGate(
1573
- {
1583
+ quarantineCandidate({
1574
1584
  ...c,
1575
1585
  tags:
1576
1586
  trigger === "compaction"
1577
1587
  ? ["auto-capture", CAPTURE_COMPACT_TAG]
1578
1588
  : ["auto-capture"],
1579
- },
1589
+ }),
1580
1590
  { ...captureGate, durable },
1581
1591
  );
1582
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;
@@ -1,18 +1,21 @@
1
1
  // Memory Viewer server. Bundled with the plugin: run `bun memory-view` (or
2
2
  // `bun run src/viewer/server.ts`) from the repo root and open the printed URL.
3
- // Binds 127.0.0.1 only — the memory store is local, personal data. All reads go
3
+ // Defaults to 127.0.0.1 — the memory store is local, personal data. All reads go
4
4
  // through the same loadAll() used by recall/inject (so blocked entries are
5
5
  // hidden), and all mutations are non-destructive (snapshot + audit + supersede).
6
6
  // I2: serves only file data; never writes into any repo.
7
7
  import { basename, join } from "node:path";
8
+ import { isIP } from "node:net";
8
9
  import { serve, type Server } from "bun";
9
10
  import { z, type ZodTypeAny } from "zod";
10
- import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody } from "../schema.ts";
11
+ import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody, ReleaseQuarantineBody } from "../schema.ts";
11
12
  import { deletionsFile, memoryRoot, snapshotDir } from "../config.ts";
12
13
  import { blockedEntries } from "../blocklist.ts";
13
14
  import { listSnapshots, restoreSnapshot } from "../undo.ts";
14
15
  import { appendMemory, loadAll, memoryFiles } from "../memory.ts";
15
16
  import { parseLine, readLines } from "../logfmt.ts";
17
+ import { releaseQuarantinedMemory } from "./mutate.ts";
18
+ import { isQuarantined, quarantineReasons } from "../quarantine.ts";
16
19
  import { deleteMemory, editMemory, blockMemory, unblockMemory, unrejectMemory, type MutationResult } from "./mutate.ts";
17
20
  import { tombstones } from "../tombstones.ts";
18
21
 
@@ -59,6 +62,18 @@ function allowedHostnames(): Set<string> {
59
62
  return new Set(names);
60
63
  }
61
64
 
65
+ function isLoopbackHostname(name: string): boolean {
66
+ // allowedHostnames supplies trimmed, lower-cased names (IPv6 bracketed).
67
+ const host = name.replace(/^\[|\]$/g, "");
68
+ if (host === "localhost") return true;
69
+ if (isIP(host) === 4) return host.startsWith("127.");
70
+ // Closed spellings only: URL parsing throws on IPv6 zone ids. Ambiguous
71
+ // aliases (including abbreviated IPv4) conservatively trigger the warning.
72
+ return host === "::1" || host === "0:0:0:0:0:0:0:1";
73
+ }
74
+
75
+ 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.";
76
+
62
77
  function rejectRequest(req: Request, url: URL, port: number): Response | null {
63
78
  if (!allowedHostnames().has(url.hostname) || (url.port || "80") !== String(port)) {
64
79
  return error("unexpected Host header", 403);
@@ -171,6 +186,10 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
171
186
  },
172
187
  });
173
188
  const bound = server.port ?? port;
189
+ // Warn after binding; wildcard binds (0.0.0.0 and ::) are non-loopback too.
190
+ if ([...allowedHostnames()].some((host) => !isLoopbackHostname(host))) {
191
+ console.warn(EXPOSURE_WARNING);
192
+ }
174
193
  return { server, url: `http://${HOST}:${bound}/` };
175
194
  }
176
195
 
@@ -192,6 +211,8 @@ async function loaded(): Promise<Record<string, unknown>> {
192
211
  content: m.content,
193
212
  issue: m.issue,
194
213
  tags: m.tags,
214
+ quarantined: isQuarantined(m),
215
+ quarantinePatterns: quarantineReasons(m),
195
216
  superseded_by: m.superseded_by,
196
217
  reason: m.reason,
197
218
  // The viewer is the explicit ADMIN read surface (header comment): it
@@ -225,6 +246,10 @@ async function route(req: Request, url: URL): Promise<Response> {
225
246
  if (url.pathname === "/api/delete") return parseWith(DeleteBody, body, deleteRoute);
226
247
  if (url.pathname === "/api/block") return parseWith(BlockBody, body, blockRoute);
227
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
+ }
228
253
  if (url.pathname === "/api/unreject") return parseWith(UnrejectBody, body, unrejectRoute);
229
254
  if (url.pathname === "/api/restore-entry") return parseWith(RestoreEntryBody, body, restoreEntryRoute);
230
255
  // /api/restore is deliberately NOT schema-parsed here: its name check is
@@ -325,6 +350,6 @@ async function restoreRoute(body: Record<string, unknown>): Promise<Response> {
325
350
 
326
351
  if (import.meta.main) {
327
352
  startViewer(PORT).then(({ url }) => {
328
- console.log(`\nMemory Viewer: ${url}\n(127.0.0.1 only; snapshot+audit are mandatory on every edit/delete)`);
353
+ console.log(`\nMemory Viewer: ${url}\n(snapshot+audit are mandatory on every edit/delete)`);
329
354
  });
330
355
  }