opencode-self-improvement 0.14.23 → 0.14.25

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.23",
3
+ "version": "0.14.25",
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
@@ -14,11 +14,12 @@ import {
14
14
  type SupersedeFields,
15
15
  } from "./memory.ts";
16
16
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
17
- import { noteAuthored } from "./state.ts";
17
+ import { getCurrent, noteAuthored } from "./state.ts";
18
18
  import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
19
19
  import { flattenMemoryText } from "./sanitize.ts";
20
20
  import { containsSecret, redactSecrets } from "./secrets.ts";
21
- import { readerForSession } from "./memory.ts";
21
+ import { readerFromSid, UnresolvedWriterError, type Reader } from "./memory.ts";
22
+ import { writeTarget, type WriteTarget } from "./repokey.ts";
22
23
  import {
23
24
  displayCall,
24
25
  extractCallForms,
@@ -29,6 +30,8 @@ import {
29
30
  type DriftInfo,
30
31
  type LazyTree,
31
32
  } from "./resolver.ts";
33
+ import { STOPWORDS, jaccard, rawTokens, tokens } from "./tokenize.ts";
34
+ import { probeRejection } from "./tombstones.ts";
32
35
 
33
36
  export interface WriteCandidate {
34
37
  type: string;
@@ -69,6 +72,11 @@ export const auditCaveat = (outcome: GateOutcome): string =>
69
72
 
70
73
  export interface GateContext {
71
74
  liveRoot: string;
75
+ // Capture authority before awaiting locks, model calls, or gate evidence.
76
+ // Named callers read their repo; named-unbound callers read global-only;
77
+ // absent/"?" callers capture ambient authority at entry (not after awaits).
78
+ reader?: Reader;
79
+ writeAt?: WriteTarget;
72
80
  evidenceCalls: string[];
73
81
  // Total before the telemetry window was selected. Legacy/direct callers
74
82
  // may still supply their complete list; the writer bounds that too.
@@ -125,44 +133,9 @@ export type GateOutcome =
125
133
  | (GateOutcomeFields & { action: "blocked"; reason: string })
126
134
  | (GateOutcomeFields & { action: "collapsed" });
127
135
 
128
- const STOPWORDS = new Set([
129
- "use",
130
- "using",
131
- "the",
132
- "a",
133
- "an",
134
- "in",
135
- "of",
136
- "to",
137
- "with",
138
- "on",
139
- "and",
140
- "or",
141
- "for",
142
- "is",
143
- "are",
144
- ]);
145
-
146
- function tokens(text: string): string[] {
147
- return text
148
- .toLowerCase()
149
- .split(/[^a-z0-9_.]+/)
150
- .filter((t) => t.length > 0);
151
- }
152
-
153
- // Case-preserving tokens, for reporting asserted values back to the user.
154
- function rawTokens(text: string): string[] {
155
- return text.split(/[^A-Za-z0-9_.]+/).filter(Boolean);
156
- }
157
-
158
- function jaccard(a: string[], b: string[]): number {
159
- const sa = new Set(a);
160
- const sb = new Set(b);
161
- let inter = 0;
162
- for (const t of sa) if (sb.has(t)) inter++;
163
- const union = sa.size + sb.size - inter;
164
- return union === 0 ? 0 : inter / union;
165
- }
136
+ // STOPWORDS, tokens, rawTokens and jaccard now live in tokenize.ts so the
137
+ // rejection sketch (#35) scores similarity with the same definition GATE-3
138
+ // uses. Imported below; behavior is byte-identical to the local copies.
166
139
 
167
140
  // GATE-3 similarity floors. OVERLAP_FLOOR: reworded near-duplicates of any
168
141
  // type are merge-review candidates. CONFLICT_OVERLAP_FLOOR: decisions and
@@ -274,6 +247,8 @@ export async function runWriteGate(
274
247
  candidate: WriteCandidate,
275
248
  ctx: GateContext,
276
249
  ): Promise<GateOutcome> {
250
+ const reader = ctx.reader ?? readerFromSid(ctx.sessionID);
251
+ const writeAt = ctx.writeAt ?? writeTarget(ctx.sessionID ?? getCurrent().sid);
277
252
  const chain = chainId();
278
253
  // Gate audit lines thread the session: runWriteGate awaits (analysis, the
279
254
  // locked append), and another session's dispatch can move the ambient
@@ -379,13 +354,7 @@ export async function runWriteGate(
379
354
  const scopeMems = candidate.scope
380
355
  ? await loadScope(
381
356
  candidate.scope,
382
- // Dedup/stale reads partition on the WRITE's session, captured at
383
- // flow entry — not the ambient current after this await (#127). An
384
- // unknown "?" (or absent) caller is the readerFromSid AMBIENT case,
385
- // exactly as before: readerForSession is for named sessions only.
386
- ctx.sessionID !== undefined && ctx.sessionID !== "?"
387
- ? readerForSession(ctx.sessionID)
388
- : undefined,
357
+ reader,
389
358
  )
390
359
  : [];
391
360
  // One tree index per write, shared by gate1 and every gate2 stale scan.
@@ -549,6 +518,19 @@ export async function runWriteGate(
549
518
  }
550
519
 
551
520
  // ---- GATE-3: no dupes ----------------------------------------------------
521
+ // #35: a value a human rejected stays rejected. This is the "have we already
522
+ // seen this" gate, and it is the only place a rejection can be enforced
523
+ // before a write becomes durable — but unlike every other check here, it is
524
+ // keyed on the VALUE, not on row identity. The blocklist keys on `ts` and
525
+ // prune deletes the row outright, so re-ingesting the original source (the
526
+ // same transcript through auto-capture, the same export through
527
+ // memory_import) stores a rejected fact again with a fresh `ts`, as if it had
528
+ // never been turned down.
529
+ //
530
+ // Computed here, enforced at GATE-4, so the ordered evidence chain
531
+ // (gate_start → gate1 → gate2 → dedup_*) stays intact for every verdict.
532
+ const probe = await probeRejection(candidate.content);
533
+ const rejection = probe.rejection;
552
534
  const conflictProne = candidate.type === "decision" || candidate.type === "preference";
553
535
  const active = scopeMems.filter((m) => !m.superseded_by);
554
536
  // Exact duplicates are detected against the full scope (a drift-superseded
@@ -618,7 +600,36 @@ export async function runWriteGate(
618
600
  overlapScore = Math.round(rival.score * 100) / 100;
619
601
  }
620
602
 
621
- if (collapseMatch) {
603
+ // A declined near-match, recorded so the guard is falsifiable in the field:
604
+ // without this line "it never over-blocks a correction" is a claim with no
605
+ // evidence either way, and this is exactly the kind of judgement that needs
606
+ // counting where it happens. Only reached when nothing refused the write.
607
+ if (!rejection && probe.vetoed) {
608
+ await rec("rejection_vetoed", {
609
+ gate: 3,
610
+ survivors: scopeMems.length,
611
+ match_ch: probe.vetoed.tombstone.ch,
612
+ score: probe.vetoed.score,
613
+ differs: probe.vetoed.differs,
614
+ action: "allow_different_fact",
615
+ chain,
616
+ });
617
+ }
618
+
619
+ if (rejection) {
620
+ // The prior rejection's own hash, never the prose: the atlas step-10
621
+ // inversion is a deletion log that reproduces what it deleted.
622
+ await rec("dedup_rejected", {
623
+ gate: 3,
624
+ survivors: scopeMems.length,
625
+ match_ch: rejection.tombstone.ch,
626
+ match_kind: rejection.kind,
627
+ ...(rejection.kind === "near" ? { score: rejection.score } : {}),
628
+ rejected_at: rejection.tombstone.rejected_at,
629
+ action: "refuse_previously_rejected",
630
+ chain,
631
+ });
632
+ } else if (collapseMatch) {
622
633
  await rec("dedup_collapse", {
623
634
  gate: 3,
624
635
  survivors: scopeMems.length,
@@ -668,7 +679,38 @@ export async function runWriteGate(
668
679
  let blockReason: string | undefined;
669
680
  let blockFlags: string[] = [];
670
681
  let hint: string | undefined;
671
- if (g1.candidateStale) {
682
+ if (rejection) {
683
+ // First in the chain: every other reason here is a heuristic about the
684
+ // write's shape, and a human already made a decision about this value.
685
+ blockReason = "previously_rejected";
686
+ blockFlags =
687
+ rejection.kind === "exact"
688
+ ? [`ch=${rejection.tombstone.ch}`, "exact"]
689
+ : [`ch=${rejection.tombstone.ch}`, `score=${rejection.score}`, "near_match"];
690
+ const when = rejection.tombstone.rejected_at.slice(0, 10) || "an earlier session";
691
+ // Scrubbed here as well as on the way in and on the way out of tombstones():
692
+ // this string goes to the model, and the hint is built from a field a human
693
+ // typed. If the row already came through clean this is a no-op — deleting it
694
+ // changes nothing observable today, which is deliberate: the guarantee lives
695
+ // on the read path (it covers every consumer, the viewer included), and this
696
+ // is the seam where the value becomes a model-facing sentence.
697
+ const why = redactSecrets(rejection.tombstone.reason) || "no reason recorded";
698
+ const tch = rejection.tombstone.ch;
699
+ // The escape-hatch tail is shared by BOTH kinds. An earlier draft put it
700
+ // only on the near-match branch, which left the COMMON case — a byte-exact
701
+ // replay — reported as a dead end with no way to lift it.
702
+ const lift =
703
+ `If this is genuinely a different fact, state it in clearly different terms; ` +
704
+ `if the earlier rejection was wrong, a human can lift it in the viewer ` +
705
+ `(Rejections → un-reject, hash ${tch}) — there is deliberately no tool that ` +
706
+ `lifts a rejection, so a blocked write cannot be re-submitted by the session ` +
707
+ `it was refused.`;
708
+ hint =
709
+ (rejection.kind === "exact"
710
+ ? `This exact content was rejected on ${when} (reason: ${why}; hash ${tch}). Nothing was stored. `
711
+ : `Content ${rejection.score} similar to a value rejected on ${when} (reason: ${why}; ` +
712
+ `hash ${tch}) — the same statement reworded counts as the rejected value. Nothing was stored. `) + lift;
713
+ } else if (g1.candidateStale) {
672
714
  blockReason = "drift_ref_stale_incoming";
673
715
  blockFlags = ["incoming_embeds_pre_drift_ref"];
674
716
  } else if (g1.missingPaths.length && !planningObject) {
@@ -740,7 +782,15 @@ export async function runWriteGate(
740
782
  const snapshot = await snapshotFiles([join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`)]);
741
783
  // The write carries the CALLER's session, not whatever current says after
742
784
  // the gate's own awaits - capture's stamp must follow the captured session.
743
- const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
785
+ if (candidate.repo === undefined && !writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
786
+ // A captured unscoped ambient writer deliberately publishes repo=global.
787
+ // Leaving repo undefined would make appendMemory resolve ambient ownership
788
+ // again after awaits. This changes the old unstamped shape: exports now keep
789
+ // this row global on import instead of adopting the importing repository.
790
+ const owner = candidate.repo === undefined && writeAt.ok
791
+ ? { repo: writeAt.scope?.key ?? "global", repoPath: writeAt.scope?.path }
792
+ : {};
793
+ const ts = await appendMemory({ ...candidate, ...owner, sessionID: ctx.sessionID });
744
794
  // #165: remember who made this row, so the writing session is not billed a
745
795
  // prompt-cache bust to be shown its own thought. Only promoted writes are
746
796
  // attributed — a blocked candidate created nothing.
package/src/index.ts CHANGED
@@ -296,6 +296,8 @@ const impl = {
296
296
  const bound = sid ?? getCurrent().sid;
297
297
  return {
298
298
  sessionID: sid,
299
+ reader: readerFromSid(sid),
300
+ writeAt: writeTarget(bound),
299
301
  // NOTE (re-review): this one lookup is intentionally NON-firm — a
300
302
  // provisional binding may supply the gate's verification TREE. The
301
303
  // tree is where a referenced file is checked to exist, not who the
@@ -687,7 +689,7 @@ const impl = {
687
689
  repo: requested.repo,
688
690
  repoPath: target.repo ? target.repoPath : undefined,
689
691
  },
690
- { ...gateContext(sid), supersedesTs: target.ts, durable: gateDurable },
692
+ { ...gateContext(sid), reader, supersedesTs: target.ts, durable: gateDurable },
691
693
  );
692
694
  if (outcome.action === "promoted" && outcome.ts && target) {
693
695
  mutated = true;
@@ -1137,13 +1139,14 @@ const impl = {
1137
1139
  await bindSessionIdentity(sid);
1138
1140
  const ownerless = ownerlessWriter(sid);
1139
1141
  if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
1142
+ const importGate = gateContext(sid);
1140
1143
  try {
1141
1144
  const t = await importMemories(
1142
1145
  args.file,
1143
1146
  (c) =>
1144
1147
  runWriteGate(
1145
1148
  { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
1146
- gateContext(sid),
1149
+ importGate,
1147
1150
  ),
1148
1151
  sid,
1149
1152
  );
@@ -1529,6 +1532,7 @@ const impl = {
1529
1532
  await record("auto_capture_refused", { session: sid, trigger }, true, sid);
1530
1533
  return;
1531
1534
  }
1535
+ const captureGate = gateContext(sid);
1532
1536
  let transcript = seeded;
1533
1537
  let msgs = seededMsgs;
1534
1538
  if (transcript.length < 200) {
@@ -1561,7 +1565,7 @@ const impl = {
1561
1565
  ? ["auto-capture", CAPTURE_COMPACT_TAG]
1562
1566
  : ["auto-capture"],
1563
1567
  },
1564
- gateContext(sid),
1568
+ captureGate,
1565
1569
  );
1566
1570
  await record(
1567
1571
  trigger === "compaction"
package/src/init.ts CHANGED
@@ -8,10 +8,11 @@
8
8
  import { basename, join } from "node:path";
9
9
  import { existsSync } from "node:fs";
10
10
  import { cbmBin } from "./config.ts";
11
- import { isVisibleTo, loadAll, markSuperseded, readerFromSid } from "./memory.ts";
11
+ import { isVisibleTo, loadAll, markSuperseded, readerFromSid, type Reader } from "./memory.ts";
12
12
  import { runWriteGate, type GateContext } from "./gates.ts";
13
13
  import { record } from "./evidence.ts";
14
14
  import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
+ import { writeTarget } from "./repokey.ts";
15
16
  import { getCurrent } from "./state.ts";
16
17
 
17
18
  export interface ScriptRecord {
@@ -190,13 +191,12 @@ export interface InitStamp {
190
191
  head: string;
191
192
  }
192
193
 
193
- export async function initStamp(scope: string, sid?: string): Promise<InitStamp | null> {
194
+ export async function initStamp(scope: string, sid?: string, reader: Reader = readerFromSid(sid)): Promise<InitStamp | null> {
194
195
  // Scope is a basename, so two different repos can share one
195
196
  // ("api" next to "api", a fork beside its upstream). Visibility filtering
196
197
  // makes each repo see only its own stamp — basename collisions no longer
197
198
  // alias init state between repos. The reader comes from the CALLER's
198
199
  // session, not from the global current after this await (#127).
199
- const reader = readerFromSid(sid);
200
200
  const mems = (await loadAll()).filter((m) => !m.superseded_by && isVisibleTo(m, reader));
201
201
  for (const m of mems) {
202
202
  if (m.type !== "context" || m.scope !== scope) continue;
@@ -208,6 +208,8 @@ export async function initStamp(scope: string, sid?: string): Promise<InitStamp
208
208
  }
209
209
 
210
210
  export async function runInit(args: InitArgs): Promise<InitSummary> {
211
+ const reader = readerFromSid(args.sessionID);
212
+ const writeAt = writeTarget(args.sessionID ?? getCurrent().sid);
211
213
  const root = await gitRootOf(args.liveRoot);
212
214
  const scope = basename(root) || basename(args.liveRoot);
213
215
  const head = await gitHead(root);
@@ -216,6 +218,8 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
216
218
 
217
219
  const gateCtx: GateContext = {
218
220
  liveRoot: root,
221
+ reader,
222
+ writeAt,
219
223
  ...writeEvidence(args.sessionID ?? getCurrent().sid),
220
224
  hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
221
225
  // Stamps land on the caller's session even though runInit awaits git
@@ -224,7 +228,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
224
228
  trusted: true,
225
229
  };
226
230
 
227
- const prior = await initStamp(scope, args.sessionID);
231
+ const prior = await initStamp(scope, args.sessionID, reader);
228
232
  if (prior && !force && prior.head === head) {
229
233
  await record("init_skip", { scope, head, since: prior.ts }, false);
230
234
  return {
package/src/memory.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  } from "./logfmt.ts";
21
21
  import { withStoreLock, LOCK_WRITE } from "./lock.ts";
22
22
  import { blockedTs } from "./blocklist.ts";
23
+ import { tombstoneMany } from "./tombstones.ts";
23
24
  import { containsSecret, redactSecrets } from "./secrets.ts";
24
25
  import { flattenMemoryText } from "./sanitize.ts";
25
26
 
@@ -96,6 +97,9 @@ const RESERVED = new Set([
96
97
  "deleted.logfmt",
97
98
  "canonical.logfmt",
98
99
  "blocklist.logfmt",
100
+ // Value-keyed rejection tombstones (#35). Hashes only, never prose — and it
101
+ // must never be ingested as a row, exported, or restored by undo.
102
+ "rejected.logfmt",
99
103
  // The use ledger (src/hits.ts): telemetry, not memory. A hit line must never
100
104
  // be able to become a row — or to be superseded, exported, or injected.
101
105
  HITS_FILENAME,
@@ -651,6 +655,24 @@ export async function prune(
651
655
  LOCK_WRITE,
652
656
  );
653
657
  }
658
+ // #35: tombstone every forgotten VALUE, keyed on content rather than on the
659
+ // row's `ts`, so replaying the source cannot store the fact again.
660
+ //
661
+ // ONE batched call, not one per row: `memory_forget` deletes by scope+type and
662
+ // routinely removes hundreds of rows, and the per-row form issued a store-lock
663
+ // create/unlink pair plus a full re-read of the tombstone file for each one.
664
+ // Done AFTER the per-file locks are released as well — appending inside the
665
+ // loop would nest a second store lock (day file, then rejected.logfmt) inside
666
+ // the first, and one consistent order across the codebase is what keeps the
667
+ // lock manager from having to reason about nesting at all.
668
+ await tombstoneMany(
669
+ deleted.map((d) => ({
670
+ content: d.memory.content,
671
+ scope: d.memory.scope,
672
+ type: d.memory.type,
673
+ })),
674
+ { reason, source: "forget" },
675
+ );
654
676
  return { deleted, snapshot };
655
677
  }
656
678
 
package/src/portable.ts CHANGED
@@ -288,6 +288,10 @@ export async function importMemories(
288
288
  // the ambient current.
289
289
  sessionID?: string,
290
290
  ): Promise<ImportTally> {
291
+ // Capture the importing owner before file I/O: later session moves must not
292
+ // re-home rows partway through the import (#183). Resolve with the writer
293
+ // rule so an unresolved named session never borrows the ambient repo (#152).
294
+ const writeAt = writeTarget(sessionID ?? getCurrent().sid);
291
295
  const target = await resolveContained(path, memoryRoot(), {
292
296
  label: "memory_import file",
293
297
  // Deliberately no mention of the operator escape hatch: this string goes
@@ -307,12 +311,8 @@ export async function importMemories(
307
311
  throw err;
308
312
  }
309
313
  const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
310
- // #152: the importing session's repository is resolved BEFORE the first row,
311
- // through the writer rule rather than the ambient one. An unresolved named
312
- // session has no write target, and half a file re-stamped into whatever
313
- // workspace happened to set up last is worse than none — so this throws
314
- // before a single row is gated, not partway through the tally.
315
- const writeAt = writeTarget(sessionID ?? getCurrent().sid);
314
+ // Preserve file-validation error precedence, but reject an unresolved owner
315
+ // before gating any row. Resolution happened at entry, not at this await.
316
316
  if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
317
317
  const currentScope = writeAt.scope;
318
318
  let allowFrontier = false;
package/src/schema.ts CHANGED
@@ -200,6 +200,10 @@ 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
+ // #35: lift a value-keyed rejection. `ch` is the 12-hex content hash the gate's
204
+ // block hint names, and the same identifier a `dedup_rejected` evidence line
205
+ // carries — so a human can act on either without reading the store by hand.
206
+ export const UnrejectBody = z.object({ ch: z.string().regex(/^[0-9a-f]{12}$/) });
203
207
  // Strict fields by intent: String(body.x ?? "") coercion once let unvalidated
204
208
  // POSTs append rows with empty type/scope/content.
205
209
  // repo/repoPath (#129): the origin stamp of the DELETED row, replayed from the
@@ -0,0 +1,208 @@
1
+ // The tokenizer moved out of gates.ts verbatim so the rejection-sketch
2
+ // (tombstones.ts) scores similarity with EXACTLY the same notion of a "token"
3
+ // the write gates use. One definition on purpose: if the two ever disagreed, a
4
+ // near-match could be claimed in one place and denied in the other, and the
5
+ // reason a write was refused would stop being reproducible.
6
+ //
7
+ // Deliberately its own module rather than exported from gates.ts, because
8
+ // gates.ts now depends on tombstones.ts — a shared leaf keeps that one-way.
9
+
10
+ // Filler words that carry no claim. Used where a score must not be diluted by
11
+ // prose glue (delta-token selection in gates.ts; the rejection sketch in
12
+ // tombstones.ts, which filters them so a stopword-heavy rewording of a rejected
13
+ // value still matches it). NOT used by tokens() itself: GATE-3's rivalry floors
14
+ // have always scored on the unfiltered token set, and this move preserves that.
15
+ export const STOPWORDS: ReadonlySet<string> = new Set([
16
+ "use",
17
+ "using",
18
+ "the",
19
+ "a",
20
+ "an",
21
+ "in",
22
+ "of",
23
+ "to",
24
+ "with",
25
+ "on",
26
+ "and",
27
+ "or",
28
+ "for",
29
+ "is",
30
+ "are",
31
+ ]);
32
+
33
+ export function tokens(text: string): string[] {
34
+ return text
35
+ .toLowerCase()
36
+ .split(/[^a-z0-9_.]+/)
37
+ .filter((t) => t.length > 0);
38
+ }
39
+
40
+ // Case-preserving tokens, for reporting asserted values back to the user.
41
+ export function rawTokens(text: string): string[] {
42
+ return text.split(/[^A-Za-z0-9_.]+/).filter(Boolean);
43
+ }
44
+
45
+ export function jaccard(a: string[], b: string[]): number {
46
+ const sa = new Set(a);
47
+ const sb = new Set(b);
48
+ let inter = 0;
49
+ for (const t of sa) if (sb.has(t)) inter++;
50
+ const union = sa.size + sb.size - inter;
51
+ return union === 0 ? 0 : inter / union;
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // The two things token overlap cannot see (#35 review).
56
+ //
57
+ // The rejection sketch decides "same statement reworded" from shared tokens, and
58
+ // for the two shapes below that judgement is wrong in the same direction — it
59
+ // scores a CORRECTION higher than a rewording:
60
+ //
61
+ // "retains audit records for 30 days" -> "…for 90 days" sketch 0.800
62
+ // "must enable anonymous access" -> "…must disable …" sketch 0.778
63
+ // (a genuine rewording measures 0.500-0.615)
64
+ //
65
+ // So the sketch alone can never separate them: the pairs above are not lower
66
+ // scoring, they are different. What separates them is that a load-bearing VALUE
67
+ // moved, so the two value dimensions are extracted here and the tombstone keeps
68
+ // one per row. Both are word-level and closed-vocabulary on purpose: this is not
69
+ // an attempt to understand a claim, only to notice when the words that carry its
70
+ // number or its sign are not the same words.
71
+ // ---------------------------------------------------------------------------
72
+
73
+ /** Every token carrying a digit, deduped and sorted: the quantities, versions,
74
+ * ids and durations a statement asserts ("30", "3.19", "9ae0998"). A change
75
+ * here is a different fact, not a rephrasing. */
76
+ export function numericTokens(text: string): string[] {
77
+ return [...new Set(tokens(text).filter((t) => /\d/.test(t)))].sort();
78
+ }
79
+
80
+ export const POL_POS = "pos";
81
+ export const POL_NEG = "neg";
82
+
83
+ // Antonym stems whose opposition is unambiguous: flipping one turns the statement
84
+ // into a different fact. Deliberately no open-ended stemming and no generic
85
+ // comparatives ("more"/"less") or particles ("on"/"off") — those appear in
86
+ // ordinary prose, and a spurious sign is the expensive error: it releases a value
87
+ // a human rejected. (A sign that is merely ABSENT leaves the sketch to decide,
88
+ // which is the shipped behaviour.)
89
+ const POLARITY: ReadonlyMap<string, string> = new Map<string, string>(
90
+ [
91
+ ["enable enables enabled enabling", "disable disables disabled disabling"],
92
+ ["allow allows allowed allowing", "deny denies denied denying disallow disallows disallowed"],
93
+ [
94
+ "permit permits permitted permitting",
95
+ "refuse refuses refused refusing forbid forbids forbidden prohibit prohibits prohibited prohibiting",
96
+ ],
97
+ ["accept accepts accepted accepting", "reject rejects rejected rejecting"],
98
+ ["include includes included including", "exclude excludes excluded excluding"],
99
+ ["add adds added adding", "remove removes removed removing"],
100
+ ["start starts started starting begin begins began beginning", "stop stops stopped stopping halt halts halted halting cease ceases ceased ceasing"],
101
+ ["require requires required requiring", "waive waives waived waiving exempt exempts exempted exempting"],
102
+ ["keep keeps kept keeping", "drop drops dropped dropping"],
103
+ ["true", "false"],
104
+ ["always", "never"],
105
+ ].flatMap(([pos, neg]) => [
106
+ ...pos.split(" ").map((w) => [w, POL_POS] as [string, string]),
107
+ ...neg.split(" ").map((w) => [w, POL_NEG] as [string, string]),
108
+ ]),
109
+ );
110
+
111
+ // Words that reverse the claim word after them. `tokens()` splits apostrophes
112
+ // away, so "doesn't" arrives as "doesn" + "t" and the contraction stem is the
113
+ // token to match. "never" is both a negator and a NEG term in its own right.
114
+ const NEGATORS: ReadonlySet<string> = new Set([
115
+ "not",
116
+ "no",
117
+ "never",
118
+ "without",
119
+ "cannot",
120
+ "nor",
121
+ "none",
122
+ "doesn",
123
+ "didn",
124
+ "don",
125
+ "isn",
126
+ "aren",
127
+ "wasn",
128
+ "weren",
129
+ "shouldn",
130
+ "wouldn",
131
+ "couldn",
132
+ "hasn",
133
+ "haven",
134
+ "hadn",
135
+ "mustn",
136
+ "wont",
137
+ ]);
138
+
139
+ // Copula/auxiliaries keep a negation alive across them: "must not be enabled" is
140
+ // still a prohibition. Any other word ends the window.
141
+ const NEGATION_SPAN: ReadonlySet<string> = new Set([
142
+ "be",
143
+ "been",
144
+ "being",
145
+ "is",
146
+ "are",
147
+ "am",
148
+ "was",
149
+ "were",
150
+ "do",
151
+ "does",
152
+ "did",
153
+ "to",
154
+ ]);
155
+
156
+ /**
157
+ * The set of polarity signs a statement asserts, deduped and sorted, so `["pos"]`
158
+ * means it asserts something permitted/active/affirmative, `["neg"]` the opposite,
159
+ * `["neg","pos"]` both, and `[]` that it asserts neither.
160
+ *
161
+ * Signs carry NO word identity, and that is what makes the signature safe to use
162
+ * as a veto: "enable", "allow" and "permit" all reduce to `pos`, so restating a
163
+ * rejected instruction with a synonym is still the same claim, while
164
+ * enable↔disable cannot be mistaken for one. "not enable" reduces to `neg` and so
165
+ * matches a rejected "disable" — a reversal expressed differently is still the
166
+ * rejected reversal, not a correction of it.
167
+ *
168
+ * The domain is two values, which is why recording it in a durable log gives
169
+ * nothing back about the prose.
170
+ */
171
+ export function polaritySigns(text: string): string[] {
172
+ const signs = new Set<string>();
173
+ let negated = false;
174
+ // A negator that is itself a table term — "never" asserts a prohibition AND
175
+ // negates what follows — holds its own sign BACK. If something in its span
176
+ // consumes the negation, that flipped predicate is its whole contribution:
177
+ // counting the word too would make "must never disable" assert a prohibition
178
+ // and a permission at once, so it would stop matching the "must enable" claim
179
+ // it restates. Nothing consumed it ("the job never runs"), and the word's own
180
+ // ban is all there is.
181
+ let held: string | undefined;
182
+ for (const t of tokens(text)) {
183
+ const sign = POLARITY.get(t);
184
+ if (NEGATORS.has(t)) {
185
+ if (held) signs.add(held);
186
+ negated = true;
187
+ held = sign;
188
+ continue;
189
+ }
190
+ if (sign) {
191
+ signs.add(negated ? (sign === POL_POS ? POL_NEG : POL_POS) : sign);
192
+ negated = false;
193
+ held = undefined;
194
+ continue;
195
+ }
196
+ // A copula keeps the negation alive across it ("must not be enabled"); any
197
+ // other word closes the span, releasing a held dual-role negator as its own
198
+ // sign.
199
+ if (!NEGATION_SPAN.has(t)) {
200
+ if (held) signs.add(held);
201
+ negated = false;
202
+ held = undefined;
203
+ }
204
+ }
205
+ if (held) signs.add(held);
206
+ return [...signs].sort();
207
+ }
208
+
@@ -0,0 +1,455 @@
1
+ // Value-keyed rejection tombstones (#35).
2
+ //
3
+ // The blocklist keys on `ts` — ROW identity. memory_forget/prune deletes the
4
+ // row outright. Neither survives re-ingestion: replay the original source (a
5
+ // transcript, a doc, an export) and the rejected fact is stored again with a
6
+ // fresh `ts` as if it had never been turned down. Something has to be keyed on
7
+ // the VALUE, which is step 6 of the Agent Memory Atlas deletion-durability
8
+ // sequence and the most-repeated gap in the field.
9
+ //
10
+ // Hashes only, never values (atlas step-10 inversion: a deletion log that
11
+ // reproduces the deleted secret is a compliance problem). Fields per line:
12
+ //
13
+ // ch sha1(content)[0:12] — the same hash the gates already emit on
14
+ // gate_start / write_promoted, so a rejection is searchable with the
15
+ // identifiers telemetry already carries.
16
+ // sig a bottom-k sketch of the content's token hashes (see sketchOf).
17
+ // Supports near-match WITHOUT storing the prose.
18
+ // num hashes of the numeric tokens the statement asserted, and
19
+ // pol the polarity signs it asserted ("pos"/"neg").
20
+ // The value signatures that keep a CORRECTION from being refused as the
21
+ // rejected fact — see the note on {@link differsIn}. `pol` is a label from
22
+ // a two-value vocabulary and `num` is a hash, so neither gives the deleted
23
+ // number or verb back.
24
+ //
25
+ // The near-match is what closes the rewording hole: "use Express for the HTTP
26
+ // layer" and "the HTTP layer uses Express" are different bytes, so `ch` alone
27
+ // lets the second one through after a human rejected the first. The sketch is
28
+ // computed from the token set, so an order-only rewording scores 1.0.
29
+ //
30
+ // Why a hashed-token sketch rather than the token list: it is one-way per
31
+ // token and carries no ordering, so the file cannot be read back as prose. It
32
+ // is strictly less revealing than deletions.logfmt, which stores the full text
33
+ // of every forgotten row verbatim (memory.ts logDeletion).
34
+ //
35
+ // Scope is deliberately GLOBAL, matching the file's location at the memory
36
+ // root: a rejection is a statement about a value in this store, not about a
37
+ // repository. The cost is that repo A's rejection also declines repo B's
38
+ // byte-identical write; that is the honest reading of "this value was rejected
39
+ // here", and a false positive is liftable by a HUMAN in the viewer.
40
+ //
41
+ // Not snapshotted. snapshotFiles() walks memoryFiles(), which excludes every
42
+ // RESERVED name, so `memory_undo` cannot resurrect a tombstone any more than
43
+ // it can resurrect a blocklist entry — and conversely cannot erase one.
44
+ import { readFile } from "node:fs/promises";
45
+ import { createHash } from "node:crypto";
46
+ import { join } from "node:path";
47
+ import { contentHash } from "./evidence.ts";
48
+ import { memoryRoot } from "./config.ts";
49
+ import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
50
+ import { withStoreLock, LOCK_WRITE } from "./lock.ts";
51
+ import { redactSecrets } from "./secrets.ts";
52
+ import { STOPWORDS, tokens, numericTokens, polaritySigns } from "./tokenize.ts";
53
+
54
+ const REJECTED_FILENAME = "rejected.logfmt";
55
+
56
+ /** How many lowest token-hashes the sketch keeps. */
57
+ const SKETCH_SIZE = 64;
58
+
59
+ /** Per-token hash width. 8 hex chars keeps the sketch compact and collisions
60
+ * irrelevant at this store's size (a collision merges two tokens, which only
61
+ * ever makes a near-match score marginally HIGHER than the truth — so the
62
+ * floors below are the conservative direction only up to ~1e-9 of inputs). */
63
+ const TOKEN_HASH_CHARS = 8;
64
+
65
+ /** Near-match floors. A sketch whose token count is at or below SKETCH_SIZE is
66
+ * the token set itself, so Jaccard here is EXACT, not an estimate — which is
67
+ * every real memory in practice. Beyond SKETCH_SIZE it is the standard
68
+ * bottom-k estimator.
69
+ *
70
+ * Calibrated, not guessed — measured with this sketch on store-shaped prose
71
+ * (12-token memories):
72
+ *
73
+ * rewordings of the SAME claim ......... 0.500 – 0.615
74
+ * same topic, DIFFERENT claim .......... 0.059 – 0.235
75
+ * unrelated ............................ 0.000
76
+ *
77
+ * 0.40 sits in the middle of that gap with ~0.17 of margin on both sides. It
78
+ * is also in family with the repo's existing calibration: GATE-3 uses 0.9 for
79
+ * "reworded duplicate of a live row" and 0.3 for a decision/preference
80
+ * CONFLICT, so this is the conflict-style band applied to a rejection.
81
+ *
82
+ * The floor is NOT the whole decision. Corrections score HIGHER than rewordings
83
+ * — a changed number or a flipped polarity shares almost every token with what
84
+ * it replaces (0.800 and 0.778 measured) — so the band above cannot separate
85
+ * them and the value signatures in {@link differsIn} vetoes instead. Read the
86
+ * floor as "worth a second look at the values", not as a verdict on its own.
87
+ *
88
+ * NEAR_MIN_SHARED exists because a three-token content can hit a high Jaccard
89
+ * against unrelated prose on shared filler alone; below this many shared
90
+ * tokens nothing is a near-match at all, and short content is refused only on
91
+ * an exact match.
92
+ */
93
+ export const NEAR_FLOOR = 0.4;
94
+ const NEAR_MIN_SHARED = 6;
95
+
96
+ export interface Tombstone {
97
+ ch: string;
98
+ /** Rejection reason as the human gave it, scrubbed of recognized credentials
99
+ * on the way in AND on the way out (it is the one free-prose field here, and
100
+ * the one copied into a model-facing hint). */
101
+ reason: string;
102
+ /** What recorded it: `forget` (memory_forget/prune) or `block` (viewer). */
103
+ source: string;
104
+ rejected_at: string;
105
+ /** Origin metadata for the hint. Matching never consults these. */
106
+ scope?: string;
107
+ type?: string;
108
+ sig: string[];
109
+ /** Hashes of the numbers the rejected statement asserted. `undefined` means
110
+ * the row was written before value tracking existed, which is NOT the same
111
+ * thing as `[]` (tracked, and it asserted none) — see {@link differsIn}. */
112
+ num?: string[];
113
+ /** Polarity signs the rejected statement asserted ("pos"/"neg"). Same
114
+ * present/absent rule as `num`. */
115
+ pol?: string[];
116
+ }
117
+
118
+ export type Rejection =
119
+ | { kind: "exact"; tombstone: Tombstone }
120
+ | { kind: "near"; tombstone: Tombstone; score: number; shared: number };
121
+
122
+ /** The dimension on which a strong sketch match is nonetheless a different fact. */
123
+ export type ValueDifference = "numeric_value" | "polarity";
124
+
125
+ /** A sketch match over the floor that was NOT treated as the rejected value. */
126
+ export interface VetoedMatch {
127
+ tombstone: Tombstone;
128
+ score: number;
129
+ shared: number;
130
+ differs: ValueDifference;
131
+ }
132
+
133
+ export interface RejectionProbe {
134
+ rejection?: Rejection;
135
+ /** Set only when there is no rejection AND something over the floor was
136
+ * declined. Nothing is enforced from it — it exists so the guard is visible
137
+ * in the field, where "the mechanism never over-blocks" would otherwise be a
138
+ * claim with no evidence either way. */
139
+ vetoed?: VetoedMatch;
140
+ }
141
+
142
+ export function rejectedFile(): string {
143
+ return join(memoryRoot(), REJECTED_FILENAME);
144
+ }
145
+
146
+ function tokenHash(token: string): string {
147
+ return createHash("sha1").update(token).digest("hex").slice(0, TOKEN_HASH_CHARS);
148
+ }
149
+
150
+ /** The GATE-3 token set minus the filler words, so the sketch is a set of
151
+ * claims rather than a set of prose. Splitting is `tokens()` from tokenize.ts,
152
+ * shared with gates.ts so both score the same way. */
153
+ function baseTokens(content: string): string[] {
154
+ return tokens(content).filter((t) => !STOPWORDS.has(t));
155
+ }
156
+
157
+ /**
158
+ * The content's token set, as sorted hashes, kept to the SKETCH_SIZE lowest.
159
+ *
160
+ * Hashing uses NO secret salt on purpose: the sketch has to be comparable
161
+ * across processes and across machines (an exported store must still decline
162
+ * what this store rejected), and a salt stored beside the file protects
163
+ * nothing the file itself does not already give up.
164
+ *
165
+ * Tokens are lowercase alphanumeric runs with the GATE-3 stopword list
166
+ * removed (gates.ts STOPWORDS is not exported, and duplicating the handful of
167
+ * words here is cheaper than widening that module's surface for one import).
168
+ */
169
+ export function sketchOf(content: string): string[] {
170
+ const tokens = new Set<string>();
171
+ for (const raw of baseTokens(content)) {
172
+ tokens.add(tokenHash(raw));
173
+ }
174
+ // Fixed-width lowercase hex sorts lexicographically in numeric order, so
175
+ // "lowest 64" is simply the first 64 after a sort.
176
+ return [...tokens].sort().slice(0, SKETCH_SIZE);
177
+ }
178
+
179
+ /** What the content asserts on the two value dimensions a sketch cannot see:
180
+ * the numbers it names and the polarity it takes. Stored per tombstone so the
181
+ * comparison needs no prose. */
182
+ interface ValueSig {
183
+ num: string[];
184
+ pol: string[];
185
+ }
186
+
187
+ export function valueSigOf(content: string): ValueSig {
188
+ return {
189
+ num: [...new Set(numericTokens(content).map(tokenHash))].sort(),
190
+ pol: polaritySigns(content),
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Does a strong sketch match differ from the rejected value on a VALUE, rather
196
+ * than restating it?
197
+ *
198
+ * Token overlap cannot answer this, because a correction is not a lower-scoring
199
+ * rewording — it is a higher-scoring one. Measured against a rejected "retains
200
+ * audit records for 30 days before cleanup":
201
+ *
202
+ * the same statement with 90 days ............ 0.800 (different fact)
203
+ * the same statement with "disable" .......... 0.778 (different fact)
204
+ * honest rewordings of the same claim ........ 0.500 – 0.615
205
+ *
206
+ * So no floor separates them: raising it to 0.85 to release the corrections would
207
+ * release nothing in between, and the corrections are the shape humans actually
208
+ * write. What separates them is that a load-bearing value moved, and only the
209
+ * tombstone's own record of what was ASSERTED can show it.
210
+ *
211
+ * A dimension has moved only when EACH side asserts something the other does not:
212
+ * - Extension is not disagreement. "{30}" vs "{30, 2}" still asserts 30 days, so
213
+ * a revision number, a count or a date appended to the rejected sentence stays
214
+ * the rejected claim.
215
+ * - Nor is something merely going missing. "{30, 90}" vs "{30}" only drops an
216
+ * assertion, and if dropping counted, deleting "30 days" from a rejected
217
+ * sentence would be enough to smuggle it back in.
218
+ * - A row written before value tracking existed records nothing, so the
219
+ * near-match decides exactly as it shipped (every row from here on carries
220
+ * both signatures, so that degradation does not grow).
221
+ */
222
+ function differsIn(a: ValueSig, b: ValueSig): ValueDifference | undefined {
223
+ if (moved(a.num, b.num)) return "numeric_value";
224
+ if (moved(a.pol, b.pol)) return "polarity";
225
+ return undefined;
226
+ }
227
+
228
+ /** True when each side names an element the other does not. An empty side answers
229
+ * false, which is the "no evidence on this dimension" case above. */
230
+ function moved(a: string[], b: string[]): boolean {
231
+ const sa = new Set(a);
232
+ const sb = new Set(b);
233
+ return a.some((x) => !sb.has(x)) && b.some((y) => !sa.has(y));
234
+ }
235
+
236
+
237
+ /**
238
+ * The tombstone set, cached against the file's change token.
239
+ *
240
+ * `findRejection` runs on EVERY gated write, so without this each write pays a
241
+ * full read of every rejection ever recorded — a cost this mechanism introduced
242
+ * into the hot path, and one that shows up badly on Windows, where the CI runner
243
+ * is slow enough for it to matter. `fileIdentity` is the repo's own change token
244
+ * (any append, rewrite or replacement changes it, "absent" means no file yet),
245
+ * so the cache is keyed on evidence rather than on a clock: a human lifting a
246
+ * rejection in the viewer process is seen by the next write in this one. A TTL
247
+ * would have been wrong here — it would keep refusing a value for the length of
248
+ * the TTL after the human said otherwise.
249
+ */
250
+ let cache: { at: string; rows: Tombstone[] } | null = null;
251
+
252
+ /** Drop the cached tombstone set. Exposed for tests and for the write paths,
253
+ * which invalidate after touching the file so a same-process re-read cannot
254
+ * serve a pre-write snapshot. */
255
+ export function resetTombstoneCache(): void {
256
+ cache = null;
257
+ }
258
+
259
+ export async function tombstones(): Promise<Tombstone[]> {
260
+ const file = rejectedFile();
261
+ const identity = await fileIdentity(file);
262
+ if (cache && cache.at === identity) return cache.rows;
263
+ const lines = await readLines(file);
264
+ const out: Tombstone[] = [];
265
+ for (const line of lines) {
266
+ const f = parseLine(line);
267
+ if (!f || typeof f.ch !== "string") continue;
268
+ out.push({
269
+ ch: f.ch,
270
+ // Scrubbed again on the way OUT, deliberately: the write boundary below
271
+ // keeps new rows clean, but a reason already on disk — written by an older
272
+ // build, or hand-edited — is what feeds both the refusal hint and the
273
+ // viewer's Rejections panel. This is the single read path for both.
274
+ reason: redactSecrets(typeof f.reason === "string" ? f.reason : ""),
275
+ source: typeof f.source === "string" ? f.source : "unknown",
276
+ rejected_at: typeof f.rejected_at === "string" ? f.rejected_at : "",
277
+ scope: typeof f.scope === "string" ? f.scope : undefined,
278
+ type: typeof f.type === "string" ? f.type : undefined,
279
+ sig: typeof f.sig === "string" ? f.sig.split(".").filter(Boolean) : [],
280
+ // Present-but-empty ("num=") means tracked with nothing asserted; absent
281
+ // means the row predates value tracking. differsIn treats them apart.
282
+ num: typeof f.num === "string" ? f.num.split(".").filter(Boolean) : undefined,
283
+ pol: typeof f.pol === "string" ? f.pol.split(".").filter(Boolean) : undefined,
284
+ });
285
+ }
286
+ cache = { at: identity, rows: out };
287
+ return out;
288
+ }
289
+
290
+ /**
291
+ * Record that a human rejected a batch of values.
292
+ *
293
+ * ONE read of the existing set, ONE lock, ONE append for the whole batch. This
294
+ * is not a micro-optimisation: the per-value version did a lock create/unlink
295
+ * pair plus a full read per row, and `memory_forget` deletes by scope+type, so a
296
+ * bulk forget issued hundreds of lock cycles while other sessions were writing.
297
+ * The heavy concurrent scenario on the Windows runner failed 2/2 with that shape
298
+ * (run 41112466339) and never on main; src/lock.ts gives up waiting after 5s and
299
+ * proceeds UNLOCKED, which is precisely how a row gets lost behind a long
300
+ * read-modify-write. Whether the batch is sufficient there is the open question
301
+ * this commit's CI run answers; the cost it removes is real either way.
302
+ *
303
+ * Still idempotent by `ch`, and de-duplicated WITHIN the batch too, so a forget
304
+ * that removes fifty rows carrying the same content records one tombstone.
305
+ * The read-then-write is not a compare-and-set: two processes rejecting the same
306
+ * NEW value at the same instant can both append. The value ends up tombstoned
307
+ * either way and no third party's line is lost, because every writer of this
308
+ * file takes the same lock and the append is O_APPEND.
309
+ */
310
+ export async function tombstoneMany(
311
+ entries: Array<{ content: string; scope?: string; type?: string }>,
312
+ opts: { reason: string; source: string },
313
+ ): Promise<{ recorded: number; chs: string[] }> {
314
+ if (entries.length === 0) return { recorded: 0, chs: [] };
315
+ const known = new Set((await tombstones()).map((t) => t.ch));
316
+ const at = new Date().toISOString();
317
+ // An audit reason is human prose (prune passes the caller's straight through),
318
+ // and this is the boundary where it becomes durable — the same rule the
319
+ // deletion audit and the evidence log apply (#128). Scrubbing here rather than
320
+ // at each call site is what keeps a future caller from forgetting to.
321
+ const reason = redactSecrets(opts.reason);
322
+ const fresh: string[] = [];
323
+ const chs: string[] = [];
324
+ for (const e of entries) {
325
+ const ch = contentHash(e.content);
326
+ chs.push(ch);
327
+ if (known.has(ch)) continue;
328
+ known.add(ch);
329
+ const values = valueSigOf(e.content);
330
+ fresh.push(
331
+ formatLine({
332
+ ch,
333
+ reason,
334
+ source: opts.source,
335
+ scope: e.scope,
336
+ type: e.type,
337
+ sig: sketchOf(e.content).join("."),
338
+ num: values.num.join("."),
339
+ pol: values.pol.join("."),
340
+ rejected_at: at,
341
+ }),
342
+ );
343
+ }
344
+ if (fresh.length === 0) return { recorded: 0, chs };
345
+ const file = rejectedFile();
346
+ // formatLine returns a line WITHOUT its terminator (appendLog adds one), so a
347
+ // batch must be joined with newlines. Joining on "" silently published every
348
+ // record in the batch as one line, of which only the first parsed — and a
349
+ // caller forgetting one row at a time could not see it.
350
+ await withStoreLock(file, () => appendLog(file, fresh.join("\n")), LOCK_WRITE);
351
+ resetTombstoneCache();
352
+ return { recorded: fresh.length, chs };
353
+ }
354
+
355
+ /**
356
+ * Record that a human rejected one value. Delegates to {@link tombstoneMany};
357
+ * the batch form is the one a caller deleting many rows should use.
358
+ */
359
+ export async function tombstone(
360
+ content: string,
361
+ opts: { reason: string; source: string; scope?: string; type?: string },
362
+ ): Promise<{ ch: string; recorded: boolean }> {
363
+ const { recorded, chs } = await tombstoneMany([{ content, scope: opts.scope, type: opts.type }], opts);
364
+ return { ch: chs[0], recorded: recorded > 0 };
365
+ }
366
+
367
+ /**
368
+ * Is this content refused because a human already rejected it?
369
+ *
370
+ * Exact hash first: it is cheap, unambiguous, and the answer a rejection owes.
371
+ * Near-match second, over the whole tombstone set, returning the STRONGEST
372
+ * match rather than the first — the hint names a specific prior rejection, so
373
+ * pointing at a weak one while a better one exists would misreport why the
374
+ * write was refused.
375
+ *
376
+ * A match that {@link differsIn} calls a changed value is skipped, not scored:
377
+ * the guard runs per candidate, so the strongest NON-vetoed match still wins
378
+ * even when a vetoed one scores higher. That case is real — "the service must not
379
+ * enable anonymous access…" scores 0.79 against a rejection of the ENABLE
380
+ * statement (a polarity flip, so correctly not the rejected fact) and 0.70
381
+ * against the rejection of DISABLE, which is what it actually restates.
382
+ */
383
+ export async function probeRejection(content: string): Promise<RejectionProbe> {
384
+ const all = await tombstones();
385
+ if (all.length === 0) return {};
386
+ const ch = contentHash(content);
387
+ const exact = all.find((t) => t.ch === ch);
388
+ if (exact) return { rejection: { kind: "exact", tombstone: exact } };
389
+
390
+ const sig = sketchOf(content);
391
+ // Below the shared-token floor a near-match cannot fire at all, so short
392
+ // content is refused only ever on an exact match.
393
+ if (sig.length < NEAR_MIN_SHARED) return {};
394
+ const values = valueSigOf(content);
395
+ let best: Extract<Rejection, { kind: "near" }> | undefined;
396
+ let vetoed: VetoedMatch | undefined;
397
+ for (const t of all) {
398
+ if (t.sig.length < NEAR_MIN_SHARED) continue;
399
+ const { score, shared } = jaccardShared(sig, t.sig);
400
+ if (shared < NEAR_MIN_SHARED || score < NEAR_FLOOR) continue;
401
+ const differs = differsIn(values, { num: t.num ?? [], pol: t.pol ?? [] });
402
+ if (differs) {
403
+ if (!vetoed || score > vetoed.score) vetoed = { tombstone: t, score, shared, differs };
404
+ continue;
405
+ }
406
+ if (!best || score > best.score) best = { kind: "near", tombstone: t, score, shared };
407
+ }
408
+ if (best) return { rejection: best };
409
+ return vetoed ? { vetoed } : {};
410
+ }
411
+
412
+ /** The verdict without the veto telemetry — see {@link probeRejection}. */
413
+ export async function findRejection(content: string): Promise<Rejection | undefined> {
414
+ return (await probeRejection(content)).rejection;
415
+ }
416
+
417
+ function jaccardShared(a: string[], b: string[]): { score: number; shared: number } {
418
+ const setB = new Set(b);
419
+ let shared = 0;
420
+ for (const h of a) if (setB.has(h)) shared++;
421
+ const union = a.length + b.length - shared;
422
+ return { score: union === 0 ? 0 : shared / union, shared };
423
+ }
424
+
425
+ /**
426
+ * Lift a tombstone. Human-only by construction: this is exported to the
427
+ * viewer's mutation layer and NEVER wired to a plugin tool. A blocked model
428
+ * that could lift its own rejection could re-write the rejected value in the
429
+ * same turn, which would make the whole mechanism advisory. (Same shape as the
430
+ * blocklist, which likewise has no unblock tool.)
431
+ */
432
+ export async function removeTombstone(ch: string): Promise<boolean> {
433
+ const file = rejectedFile();
434
+ return withStoreLock(
435
+ file,
436
+ async () => {
437
+ const since = await fileIdentity(file);
438
+ let text: string;
439
+ try {
440
+ text = await readFile(file, "utf8");
441
+ } catch (err) {
442
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
443
+ throw err;
444
+ }
445
+ const kept = text.split("\n").filter((l) => {
446
+ const row = parseLine(l);
447
+ return !(row && row.ch === ch);
448
+ });
449
+ await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
450
+ resetTombstoneCache();
451
+ return true;
452
+ },
453
+ LOCK_WRITE,
454
+ );
455
+ }
@@ -8,7 +8,8 @@
8
8
  // All mutations require a reason and write audit + evidence lines.
9
9
  import { deletionsFile } from "../config.ts";
10
10
  import { addBlock, removeBlock } from "../blocklist.ts";
11
- import { record, chainId } from "../evidence.ts";
11
+ import { record, chainId, contentHash } from "../evidence.ts";
12
+ import { removeTombstone, tombstone } from "../tombstones.ts";
12
13
  import { redactSecrets } from "../secrets.ts";
13
14
  import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
14
15
  import { withStoreLock, LOCK_WRITE } from "../lock.ts";
@@ -188,4 +189,43 @@ async function audit(
188
189
  );
189
190
  }
190
191
 
192
+ // Blocking is a human rejection, so it tombstones the VALUE as well as hiding
193
+ // the row (#35): without that, re-ingesting the source stores the same content
194
+ // again under a fresh `ts` and the block silently stops protecting anything.
195
+ // Order matters — the block is what the operator asked for and lands first; a
196
+ // failure to tombstone leaves the row hidden (no data loss) rather than the
197
+ // reverse (row visible, rejection half-applied).
198
+ export async function blockMemory(input: { ts: string; reason: string }): Promise<string> {
199
+ requireReason(input.reason);
200
+ const mem = await findMemory(input.ts);
201
+ await addBlock(input.ts, input.reason);
202
+ await tombstone(mem.content, {
203
+ reason: redactSecrets(input.reason),
204
+ source: "block",
205
+ scope: mem.scope,
206
+ type: mem.type,
207
+ });
208
+ return input.ts;
209
+ }
210
+
211
+ // Un-blocking withdraws the rejection, so it lifts the tombstone too — leaving
212
+ // it would mean the value stays refused while the row it was refused on is
213
+ // back in view. The tombstone is keyed on the value, so this withdraws the
214
+ // rejection of that content wherever else a copy of it was blocked; that is the
215
+ // same decision the tombstone made when it was written.
216
+ export async function unblockMemory(ts: string): Promise<boolean> {
217
+ const removed = await removeBlock(ts);
218
+ const mem = (await loadAll()).find((x) => x.ts === ts);
219
+ if (mem) await removeTombstone(contentHash(mem.content));
220
+ return removed;
221
+ }
222
+
223
+ // The explicit un-tombstone escape hatch (#35): lifts a rejection recorded by
224
+ // `forget`, which has no row left to un-block. Human-only — this is reachable
225
+ // from the viewer and deliberately from NO plugin tool, so a session whose
226
+ // write was refused cannot clear its own refusal and retry in the same turn.
227
+ export async function unrejectMemory(ch: string): Promise<boolean> {
228
+ return removeTombstone(ch);
229
+ }
230
+
191
231
  export { addBlock, removeBlock };
@@ -85,6 +85,7 @@
85
85
  <span>superseded <b id="cSuper">0</b></span>
86
86
  <span>blocked <b id="cBlocked">0</b></span>
87
87
  <span>deleted <b id="cDeleted">0</b></span>
88
+ <span>rejected <b id="cRejected">0</b></span>
88
89
  </div>
89
90
  <span class="spacer"></span>
90
91
  <code id="rootLabel" style="color:var(--muted);font-size:12px"></code>
@@ -102,6 +103,7 @@
102
103
  <option value="superseded">superseded</option>
103
104
  <option value="blocked">blocked</option>
104
105
  <option value="deleted">deleted</option>
106
+ <option value="rejected">rejected values</option>
105
107
  </select>
106
108
  </div>
107
109
 
@@ -185,6 +187,7 @@ function currentList() {
185
187
  const fus = $("fStatus").value;
186
188
  if (fus === "blocked") return { list: DATA.blocked, kind: "blocked" };
187
189
  if (fus === "deleted") return { list: DATA.deleted, kind: "deleted" };
190
+ if (fus === "rejected") return { list: DATA.rejections, kind: "rejected" };
188
191
  if (fus === "superseded") return { list: DATA.memories.filter((m) => m.superseded_by), kind: "superseded" };
189
192
  if (fus === "all") return { list: DATA.memories, kind: "all" };
190
193
  return { list: DATA.memories.filter((m) => !m.superseded_by), kind: "active" };
@@ -199,7 +202,24 @@ function render() {
199
202
  let rows = list.slice();
200
203
  if (fs) rows = rows.filter((m) => m.scope === fs);
201
204
  if (ft) rows = rows.filter((m) => m.type === ft);
202
- if (q) rows = rows.filter((m) => `${m.type} ${m.scope} ${m.content}`.toLowerCase().includes(q));
205
+ if (q) rows = rows.filter((m) => `${m.type} ${m.scope} ${m.content ?? m.ch ?? ""}`.toLowerCase().includes(q));
206
+
207
+ // Rejected VALUES (#35) have no row and no prose — the tombstone stores a
208
+ // hash by design, so they get their own row shape rather than pretending to
209
+ // be memories with an empty content cell.
210
+ if (kind === "rejected") {
211
+ $("rows").innerHTML = rows.map((t) => `<tr>
212
+ <td class="ts">${esc(t.rejected_at)}</td>
213
+ <td>${badge("type", t.type || "-")}</td>
214
+ <td>${badge("scope", t.scope || "-")}</td>
215
+ <td class="content"><code>${esc(t.ch)}</code> ${esc(t.reason || "(no reason recorded)")} <span style="color:var(--muted)">· rejected via ${esc(t.source)}</span></td>
216
+ <td>${badge("status-blocked", "rejected")}</td>
217
+ <td class="actions"><button class="btn warn" data-action="un-reject" data-ch="${esc(t.ch)}" title="Lift this rejection so the value can be stored again">un-reject</button></td>
218
+ </tr>`).join("");
219
+ $("empty").style.display = rows.length ? "none" : "block";
220
+ $("cRejected").textContent = DATA.rejections.length;
221
+ return;
222
+ }
203
223
 
204
224
  $("rows").innerHTML = rows.map((m) => {
205
225
  const status = kind === "blocked" ? "blocked" : kind === "deleted" ? "deleted"
@@ -228,6 +248,7 @@ function render() {
228
248
  $("cSuper").textContent = DATA.memories.filter((m) => m.superseded_by).length;
229
249
  $("cBlocked").textContent = DATA.blocked.length;
230
250
  $("cDeleted").textContent = DATA.deleted.length;
251
+ $("cRejected").textContent = DATA.rejections.length;
231
252
  }
232
253
 
233
254
  async function refresh() {
@@ -306,6 +327,17 @@ async function unblock(ts) {
306
327
  } catch (e) { toast(String(e.message), true); }
307
328
  }
308
329
 
330
+ // The human-only escape hatch for #35. No confirmation prompt asking "why": the
331
+ // operator already owns the store, and a rejection they are lifting is by
332
+ // definition one they no longer agree with.
333
+ async function unreject(ch) {
334
+ try {
335
+ await api("/api/unreject", { ch });
336
+ toast(`rejection lifted for ${ch} — the value can be stored again`);
337
+ await refresh();
338
+ } catch (e) { toast(String(e.message), true); }
339
+ }
340
+
309
341
  function restoreEntry(type, scope, content, repo, repoPath) {
310
342
  askModal(
311
343
  "Restore deleted memory?",
@@ -337,6 +369,7 @@ $("rows").addEventListener("click", (e) => {
337
369
  else if (action === "delete") del(ts);
338
370
  else if (action === "block") block(ts);
339
371
  else if (action === "unblock") unblock(ts);
372
+ else if (action === "un-reject") unreject(btn.dataset.ch);
340
373
  else if (action === "restore-deleted") {
341
374
  const { type, scope, content, repo, repoPath } = btn.dataset;
342
375
  restoreEntry(type, scope, content, repo, repoPath);
@@ -7,13 +7,14 @@
7
7
  import { basename, join } from "node:path";
8
8
  import { serve, type Server } from "bun";
9
9
  import { z, type ZodTypeAny } from "zod";
10
- import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody } from "../schema.ts";
10
+ import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody } from "../schema.ts";
11
11
  import { deletionsFile, memoryRoot, snapshotDir } from "../config.ts";
12
12
  import { blockedEntries } from "../blocklist.ts";
13
13
  import { listSnapshots, restoreSnapshot } from "../undo.ts";
14
14
  import { appendMemory, loadAll, memoryFiles } from "../memory.ts";
15
15
  import { parseLine, readLines } from "../logfmt.ts";
16
- import { deleteMemory, editMemory, addBlock, removeBlock, type MutationResult } from "./mutate.ts";
16
+ import { deleteMemory, editMemory, blockMemory, unblockMemory, unrejectMemory, type MutationResult } from "./mutate.ts";
17
+ import { tombstones } from "../tombstones.ts";
17
18
 
18
19
  const PAGE = join(import.meta.dir, "page.html");
19
20
  const HOST = process.env.OPENCODE_VIEWER_HOST || "127.0.0.1";
@@ -174,11 +175,12 @@ export async function startViewer(port: number = PORT): Promise<ViewerServer> {
174
175
  }
175
176
 
176
177
  async function loaded(): Promise<Record<string, unknown>> {
177
- const [memories, blocked, deleted, snaps] = await Promise.all([
178
+ const [memories, blocked, deleted, snaps, rejections] = await Promise.all([
178
179
  loadAll(),
179
180
  blockedRows(),
180
181
  deletedRows(),
181
182
  listSnapshots(),
183
+ tombstones(),
182
184
  ]);
183
185
  const blockedByTs = new Set(blocked.map((b) => b.ts));
184
186
  return {
@@ -200,6 +202,18 @@ async function loaded(): Promise<Record<string, unknown>> {
200
202
  })),
201
203
  blocked,
202
204
  deleted,
205
+ // #35: the value-keyed rejections. Hashes and metadata only — the store
206
+ // never held the prose, so there is nothing to reveal here either. The
207
+ // sketch is omitted: it is matching machinery, not something a reader can
208
+ // act on.
209
+ rejections: rejections.map((t) => ({
210
+ ch: t.ch,
211
+ reason: t.reason,
212
+ source: t.source,
213
+ scope: t.scope ?? "",
214
+ type: t.type ?? "",
215
+ rejected_at: t.rejected_at,
216
+ })),
203
217
  snapshots: snaps.map((s) => ({ name: s.name, bytes: s.bytes })),
204
218
  };
205
219
  }
@@ -211,6 +225,7 @@ async function route(req: Request, url: URL): Promise<Response> {
211
225
  if (url.pathname === "/api/delete") return parseWith(DeleteBody, body, deleteRoute);
212
226
  if (url.pathname === "/api/block") return parseWith(BlockBody, body, blockRoute);
213
227
  if (url.pathname === "/api/unblock") return parseWith(UnblockBody, body, unblockRoute);
228
+ if (url.pathname === "/api/unreject") return parseWith(UnrejectBody, body, unrejectRoute);
214
229
  if (url.pathname === "/api/restore-entry") return parseWith(RestoreEntryBody, body, restoreEntryRoute);
215
230
  // /api/restore is deliberately NOT schema-parsed here: its name check is
216
231
  // basename + pinned-grammar CONTAINMENT, not a shape gate,
@@ -258,11 +273,18 @@ async function deleteRoute(body: z.infer<typeof DeleteBody>): Promise<Response>
258
273
  }
259
274
 
260
275
  async function blockRoute(body: z.infer<typeof BlockBody>): Promise<Response> {
261
- return json({ ts: await addBlock(body.ts, body.reason) });
276
+ return json({ ts: await blockMemory(body) });
262
277
  }
263
278
 
264
279
  async function unblockRoute(body: z.infer<typeof UnblockBody>): Promise<Response> {
265
- return json({ unblocked: await removeBlock(body.ts) });
280
+ return json({ unblocked: await unblockMemory(body.ts) });
281
+ }
282
+
283
+ // The only way a rejection is ever lifted (#35). Human-only: the plugin exposes
284
+ // no tool for this, so a session whose write was refused cannot clear the
285
+ // refusal and re-submit the rejected value.
286
+ async function unrejectRoute(body: z.infer<typeof UnrejectBody>): Promise<Response> {
287
+ return json({ unrejected: await unrejectMemory(body.ch) });
266
288
  }
267
289
 
268
290
  async function restoreEntryRoute(body: z.infer<typeof RestoreEntryBody>): Promise<Response> {