opencode-self-improvement 0.14.24 → 0.14.26

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.
@@ -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,454 @@
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). At that time, lock-budget expiry let a writer proceed
299
+ * unlocked, losing rows behind a long read-modify-write. LOCK_WRITE now refuses
300
+ * on timeout (#196); batching still reduces lock contention and its I/O cost.
301
+ *
302
+ * Still idempotent by `ch`, and de-duplicated WITHIN the batch too, so a forget
303
+ * that removes fifty rows carrying the same content records one tombstone.
304
+ * The read-then-write is not a compare-and-set: two processes rejecting the same
305
+ * NEW value at the same instant can both append. The value ends up tombstoned
306
+ * either way and no third party's line is lost, because every writer of this
307
+ * file takes the same lock and the append is O_APPEND.
308
+ */
309
+ export async function tombstoneMany(
310
+ entries: Array<{ content: string; scope?: string; type?: string }>,
311
+ opts: { reason: string; source: string },
312
+ ): Promise<{ recorded: number; chs: string[] }> {
313
+ if (entries.length === 0) return { recorded: 0, chs: [] };
314
+ const known = new Set((await tombstones()).map((t) => t.ch));
315
+ const at = new Date().toISOString();
316
+ // An audit reason is human prose (prune passes the caller's straight through),
317
+ // and this is the boundary where it becomes durable — the same rule the
318
+ // deletion audit and the evidence log apply (#128). Scrubbing here rather than
319
+ // at each call site is what keeps a future caller from forgetting to.
320
+ const reason = redactSecrets(opts.reason);
321
+ const fresh: string[] = [];
322
+ const chs: string[] = [];
323
+ for (const e of entries) {
324
+ const ch = contentHash(e.content);
325
+ chs.push(ch);
326
+ if (known.has(ch)) continue;
327
+ known.add(ch);
328
+ const values = valueSigOf(e.content);
329
+ fresh.push(
330
+ formatLine({
331
+ ch,
332
+ reason,
333
+ source: opts.source,
334
+ scope: e.scope,
335
+ type: e.type,
336
+ sig: sketchOf(e.content).join("."),
337
+ num: values.num.join("."),
338
+ pol: values.pol.join("."),
339
+ rejected_at: at,
340
+ }),
341
+ );
342
+ }
343
+ if (fresh.length === 0) return { recorded: 0, chs };
344
+ const file = rejectedFile();
345
+ // formatLine returns a line WITHOUT its terminator (appendLog adds one), so a
346
+ // batch must be joined with newlines. Joining on "" silently published every
347
+ // record in the batch as one line, of which only the first parsed — and a
348
+ // caller forgetting one row at a time could not see it.
349
+ await withStoreLock(file, () => appendLog(file, fresh.join("\n")), LOCK_WRITE);
350
+ resetTombstoneCache();
351
+ return { recorded: fresh.length, chs };
352
+ }
353
+
354
+ /**
355
+ * Record that a human rejected one value. Delegates to {@link tombstoneMany};
356
+ * the batch form is the one a caller deleting many rows should use.
357
+ */
358
+ export async function tombstone(
359
+ content: string,
360
+ opts: { reason: string; source: string; scope?: string; type?: string },
361
+ ): Promise<{ ch: string; recorded: boolean }> {
362
+ const { recorded, chs } = await tombstoneMany([{ content, scope: opts.scope, type: opts.type }], opts);
363
+ return { ch: chs[0], recorded: recorded > 0 };
364
+ }
365
+
366
+ /**
367
+ * Is this content refused because a human already rejected it?
368
+ *
369
+ * Exact hash first: it is cheap, unambiguous, and the answer a rejection owes.
370
+ * Near-match second, over the whole tombstone set, returning the STRONGEST
371
+ * match rather than the first — the hint names a specific prior rejection, so
372
+ * pointing at a weak one while a better one exists would misreport why the
373
+ * write was refused.
374
+ *
375
+ * A match that {@link differsIn} calls a changed value is skipped, not scored:
376
+ * the guard runs per candidate, so the strongest NON-vetoed match still wins
377
+ * even when a vetoed one scores higher. That case is real — "the service must not
378
+ * enable anonymous access…" scores 0.79 against a rejection of the ENABLE
379
+ * statement (a polarity flip, so correctly not the rejected fact) and 0.70
380
+ * against the rejection of DISABLE, which is what it actually restates.
381
+ */
382
+ export async function probeRejection(content: string): Promise<RejectionProbe> {
383
+ const all = await tombstones();
384
+ if (all.length === 0) return {};
385
+ const ch = contentHash(content);
386
+ const exact = all.find((t) => t.ch === ch);
387
+ if (exact) return { rejection: { kind: "exact", tombstone: exact } };
388
+
389
+ const sig = sketchOf(content);
390
+ // Below the shared-token floor a near-match cannot fire at all, so short
391
+ // content is refused only ever on an exact match.
392
+ if (sig.length < NEAR_MIN_SHARED) return {};
393
+ const values = valueSigOf(content);
394
+ let best: Extract<Rejection, { kind: "near" }> | undefined;
395
+ let vetoed: VetoedMatch | undefined;
396
+ for (const t of all) {
397
+ if (t.sig.length < NEAR_MIN_SHARED) continue;
398
+ const { score, shared } = jaccardShared(sig, t.sig);
399
+ if (shared < NEAR_MIN_SHARED || score < NEAR_FLOOR) continue;
400
+ const differs = differsIn(values, { num: t.num ?? [], pol: t.pol ?? [] });
401
+ if (differs) {
402
+ if (!vetoed || score > vetoed.score) vetoed = { tombstone: t, score, shared, differs };
403
+ continue;
404
+ }
405
+ if (!best || score > best.score) best = { kind: "near", tombstone: t, score, shared };
406
+ }
407
+ if (best) return { rejection: best };
408
+ return vetoed ? { vetoed } : {};
409
+ }
410
+
411
+ /** The verdict without the veto telemetry — see {@link probeRejection}. */
412
+ export async function findRejection(content: string): Promise<Rejection | undefined> {
413
+ return (await probeRejection(content)).rejection;
414
+ }
415
+
416
+ function jaccardShared(a: string[], b: string[]): { score: number; shared: number } {
417
+ const setB = new Set(b);
418
+ let shared = 0;
419
+ for (const h of a) if (setB.has(h)) shared++;
420
+ const union = a.length + b.length - shared;
421
+ return { score: union === 0 ? 0 : shared / union, shared };
422
+ }
423
+
424
+ /**
425
+ * Lift a tombstone. Human-only by construction: this is exported to the
426
+ * viewer's mutation layer and NEVER wired to a plugin tool. A blocked model
427
+ * that could lift its own rejection could re-write the rejected value in the
428
+ * same turn, which would make the whole mechanism advisory. (Same shape as the
429
+ * blocklist, which likewise has no unblock tool.)
430
+ */
431
+ export async function removeTombstone(ch: string): Promise<boolean> {
432
+ const file = rejectedFile();
433
+ return withStoreLock(
434
+ file,
435
+ async () => {
436
+ const since = await fileIdentity(file);
437
+ let text: string;
438
+ try {
439
+ text = await readFile(file, "utf8");
440
+ } catch (err) {
441
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
442
+ throw err;
443
+ }
444
+ const kept = text.split("\n").filter((l) => {
445
+ const row = parseLine(l);
446
+ return !(row && row.ch === ch);
447
+ });
448
+ await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
449
+ resetTombstoneCache();
450
+ return true;
451
+ },
452
+ LOCK_WRITE,
453
+ );
454
+ }