opencode-self-improvement 0.15.34 → 0.15.36

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.15.34",
3
+ "version": "0.15.36",
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": {
@@ -115,13 +115,37 @@ export async function markManySupersededReport(
115
115
  return { marked };
116
116
  }
117
117
 
118
+ // The #126 provenance guard: which supersession a merge_review may clear.
119
+ export interface ClearProvenance {
120
+ // The review's loser: a survivor the loser itself superseded first is the
121
+ // legitimate revival the merge exists for.
122
+ supersededBy: string;
123
+ // The review's reason: a marker this very review wrote (a retried apply)
124
+ // is its own provenance.
125
+ reason: string;
126
+ }
127
+
118
128
  // Drop a row's supersession markers IN PLACE (snapshot-first), making it active
119
129
  // again. Used by memory_merge_review: a declared survivor must be recallable
120
130
  // even when an earlier row — now the loser — had superseded it first.
121
- export async function clearSuperseded(ts: string): Promise<boolean> {
131
+ // #126: with a provenance guard the marker is cleared ONLY when it points at
132
+ // this review's loser or carries the review's reason. A survivor superseded by
133
+ // anything else (e.g. a memory_update that retired it after the review was
134
+ // filed) keeps its marker and the clear reports false — erasing that later
135
+ // supersession would revive the retired row next to its live replacement.
136
+ export async function clearSuperseded(
137
+ ts: string,
138
+ provenance?: ClearProvenance,
139
+ ): Promise<boolean> {
122
140
  for (const file of await memoryFiles()) {
123
141
  const outcome = await stampRow(file, ts, (parsed) => {
124
142
  if (typeof parsed.superseded_by !== "string") return null;
143
+ if (
144
+ provenance &&
145
+ parsed.superseded_by !== provenance.supersededBy &&
146
+ parsed.reason !== provenance.reason
147
+ )
148
+ return null;
125
149
  // These six keys are written only by markSuperseded (drift, canonical,
126
150
  // update and merge_review), never by appendMemory, so they are all part of
127
151
  // the marker and go with it. Field order round-trips because parseLine
package/src/store/undo.ts CHANGED
@@ -9,7 +9,9 @@
9
9
  // the caller. The default mode CHECK refuses and lists the divergent rows;
10
10
  // MERGE replays them on top of the snapshot; FORCE is the old exact rollback,
11
11
  // and additionally snapshots the file it replaces, so the state it drops stays
12
- // undoable (result.safety).
12
+ // undoable (result.safety). Every mode consults the rejection tombstones: a
13
+ // row whose content was rejected by a human is omitted from what it publishes,
14
+ // never revived (#35, decision #214 A).
13
15
  //
14
16
  // A day file is shared across REPOSITORIES too, and foreign rows are outside
15
17
  // a caller's reach in every sense (#153): no mode revives them from the
@@ -27,6 +29,7 @@
27
29
  import { lstat, readFile, realpath, stat } from "node:fs/promises";
28
30
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
29
31
  import { deletionsFile, snapshotDir } from "../core/config/paths.ts";
32
+ import { contentHash } from "../evidence/record.ts";
30
33
  import { isWithin } from "./containment.ts";
31
34
  import { parseLine } from "../core/logfmt/format.ts";
32
35
  import {
@@ -37,6 +40,7 @@ import {
37
40
  import { readLines } from "../core/logfmt/read.ts";
38
41
  import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
39
42
  import { snapshotFiles } from "./files/snapshots.ts";
43
+ import { tombstones } from "./tombstones/tombstone.ts";
40
44
  import {
41
45
  ADMIN_READER,
42
46
  lineVisibleTo,
@@ -103,8 +107,18 @@ export interface RestoreResult {
103
107
  concurrentAdded: string[];
104
108
  concurrentChanged: string[];
105
109
  // ts of rows intentionally deleted after this snapshot. CHECK and MERGE
106
- // leave them deleted; FORCE is the explicit recovery path.
110
+ // leave them deleted; FORCE is the explicit recovery path — except for rows
111
+ // whose content carries a rejection tombstone, which no mode recovers
112
+ // (rejectedOmitted): a rejection is absolute (#35, decision #214 A).
107
113
  deletedOmitted: string[];
114
+ // ts of caller-owned rows the restore omitted because their content carries a
115
+ // rejection tombstone. Reporting them separately from deletedOmitted is the
116
+ // contract: a deliberately-deleted row is force-recoverable, a rejected one
117
+ // is not — recovery is human (lift the tombstone in the viewer, then
118
+ // restore). The floor applies to every mode's published rows, not just FORCE:
119
+ // an older snapshot identity can carry a value a human rejected through a
120
+ // different row, which the identity-keyed deletion audit cannot catch.
121
+ rejectedOmitted: string[];
108
122
  // Live rows owned by other repositories, whose lines are carried over
109
123
  // verbatim (appended at the end) in every mode (#153). Admin restores
110
124
  // report 0 — there is no foreign reader.
@@ -259,6 +273,15 @@ export async function restoreSnapshot(
259
273
  // finished just before this restore is honoured.
260
274
  const audited =
261
275
  mode !== "force" ? await auditedDeletions() : new Set<string>();
276
+ // Rejection tombstones are keyed on the VALUE (#35), and a rejection is
277
+ // absolute (decision #214 A): no tool lifts one, so EVERY mode reads them
278
+ // and applies the content-hash floor to the caller-owned rows it publishes
279
+ // (see the floor below), not just FORCE. The identity-keyed deletion audit
280
+ // above cannot catch a rejected value carried by an older snapshot
281
+ // identity, so the value floor is what closes that route. Read inside the
282
+ // lock, like the deletion audit, so a forget that finished just before
283
+ // this restore is honoured.
284
+ const rejected = new Set((await tombstones()).map((t) => t.ch));
262
285
  // Ownership before anything else (#153): rows a foreign repo owns are
263
286
  // excluded from the snapshot side in EVERY mode (never revived, never
264
287
  // rewound), excluded from the deletion audit and the divergence
@@ -318,10 +341,46 @@ export async function restoreSnapshot(
318
341
  concurrentAdded,
319
342
  concurrentChanged,
320
343
  deletedOmitted,
344
+ rejectedOmitted: [],
321
345
  foreignPreserved: curForeign.length,
322
346
  };
323
347
  }
324
348
 
349
+ // The caller-owned rows this restore will publish, before the rejection
350
+ // floor. FORCE and CHECK publish the snapshot's own rows; MERGE is a
351
+ // deliberate superset — it keeps the CURRENT version of rows the snapshot
352
+ // also has (in-place edits, e.g. a supersede stamp, win), then appends the
353
+ // rows the snapshot never saw. Rows the snapshotter wrote after the
354
+ // snapshot are NOT dropped by MERGE; choose FORCE for that.
355
+ let pubOwn = snapLines;
356
+ if (mode === "merge") {
357
+ pubOwn = snapLines
358
+ .map((l) => curByKey.get(rowKey(l)) ?? l)
359
+ .concat(curOwn.filter((l) => !snapByKey.has(rowKey(l))));
360
+ }
361
+
362
+ // Rejection is absolute (#35, decision #214 A): the content-hash floor is
363
+ // the last gate before publishing, applied to the caller-owned rows of
364
+ // EVERY mode. A row whose content carries a tombstone is omitted here and
365
+ // reported in rejectedOmitted, so the store never ends up holding an
366
+ // active row it also records as rejected. This closes the route the
367
+ // identity-keyed deletion audit above cannot: an older snapshot identity
368
+ // carrying a value a human later rejected through a DIFFERENT row (a force
369
+ // rollback drops the original with no audit, then a later copy is
370
+ // forgotten). The tombstone file itself is read-only to a restore —
371
+ // mis-forget recovery stays human. Foreign rows are carried verbatim and
372
+ // never filtered: they are outside this caller's reach (#153).
373
+ const rejectedOmitted: string[] = [];
374
+ if (rejected.size > 0) {
375
+ pubOwn = pubOwn.filter((line) => {
376
+ const content = parseLine(line)?.content;
377
+ if (typeof content !== "string") return true;
378
+ if (!rejected.has(contentHash(content))) return true;
379
+ rejectedOmitted.push(rowKey(line));
380
+ return false;
381
+ });
382
+ }
383
+
325
384
  // FORCE is the mode that drops rows, so the file it replaces is
326
385
  // snapshotted HERE — inside the lock, which is what makes rows a
327
386
  // concurrent session appended moments earlier part of the copy. A caller
@@ -329,23 +388,13 @@ export async function restoreSnapshot(
329
388
  const safety =
330
389
  mode === "force" ? (await snapshotFiles([target]))[0] : undefined;
331
390
 
332
- let out = snapLines;
333
- if (mode === "merge") {
334
- // Keep the CURRENT version of rows the snapshot also has (in-place edits —
335
- // e.g. a supersede stamp — made after the snapshot win), then append the
336
- // rows the snapshot never saw. Merge is a deliberate superset: rows the
337
- // snapshotter wrote after the snapshot are NOT dropped here; choose FORCE
338
- // for that.
339
- out = snapLines
340
- .map((l) => curByKey.get(rowKey(l)) ?? l)
341
- .concat(curOwn.filter((l) => !snapByKey.has(rowKey(l))));
342
- }
343
- // FORCE's "exact rollback" is exact FOR THE CALLER'S REPOSITORY, not
344
- // beyond it: foreign live lines rejoin the file verbatim in every mode,
345
- // appended at the end — line content preserved, position not (#153).
346
- // Under the admin reader curForeign is empty and the write is the
347
- // historical whole-file restore, byte for byte.
348
- out = out.concat(curForeign);
391
+ // Foreign live lines are re-admitted verbatim in every mode, appended at
392
+ // the end — line content preserved, position not (#153). Under the admin
393
+ // reader curForeign is empty and the write is the historical whole-file
394
+ // restore, byte for byte — modulo the rejected-row omission above, which
395
+ // applies to every reader and every mode: a rejection is absolute, not
396
+ // per-repository.
397
+ const out = pubOwn.concat(curForeign);
349
398
  await ensureDir(memoryRootDir);
350
399
  await writeAtomic(target, out.length ? out.join("\n") + "\n" : "", since);
351
400
  return {
@@ -356,6 +405,7 @@ export async function restoreSnapshot(
356
405
  concurrentAdded,
357
406
  concurrentChanged,
358
407
  deletedOmitted,
408
+ rejectedOmitted,
359
409
  foreignPreserved: curForeign.length,
360
410
  };
361
411
  },
@@ -7,6 +7,7 @@ import { withStoreLock } from "../store/lock.ts";
7
7
  import { loadAll } from "../store/files/load.ts";
8
8
  import { clearSuperseded, markSuperseded } from "../store/files/supersede.ts";
9
9
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
10
+ import { isActive } from "../store/model/predicates.ts";
10
11
  import { MergeReviewArgs, validated } from "./schema.ts";
11
12
  import { join } from "node:path";
12
13
 
@@ -16,7 +17,7 @@ export const register: ToolRegister = (editor, deps) => {
16
17
  validated(MergeReviewArgs, {
17
18
  name: "memory_merge_review",
18
19
  description:
19
- "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, either id names a missing or blocklisted row, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row. Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
20
+ "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, either id names a missing or blocklisted row, the loser is already superseded or is the survivor itself, either seat names a foreign repository's row, or the survivor's supersession was written by a row other than this review's loser (a later update's marker is never erased). Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
20
21
  options: direct,
21
22
  async execute(args, context): Promise<{ content: string }> {
22
23
  const { sid } = toolIds(context);
@@ -99,6 +100,31 @@ export const register: ToolRegister = (editor, deps) => {
99
100
  "merge_review blocked: the survivor belongs to another repository — this session may not promote or revive it. Nothing was done. No evidence written.",
100
101
  };
101
102
  }
103
+ // Provenance guard (#126): a survivor carrying a supersession
104
+ // written by anything OTHER than this review — its marker points
105
+ // at a later row (a memory_update that retired the survivor
106
+ // after the review was filed), and the marker's reason is not
107
+ // this review's reason — must not be revived. Clearing that
108
+ // marker would erase the later supersession and leave the
109
+ // retired survivor active next to its live replacement. Refuse
110
+ // BEFORE touching the loser: a half-applied merge is exactly the
111
+ // state this guard exists to prevent.
112
+ const later = survivorRow.superseded_by;
113
+ if (
114
+ later &&
115
+ later !== args.loser &&
116
+ survivorRow.reason !== args.reason
117
+ ) {
118
+ const laterRow = all.find((m) => m.ts === later);
119
+ return {
120
+ content:
121
+ `merge_review blocked: survivor ${args.survivor} was superseded by ${later}` +
122
+ (laterRow && isActive(laterRow)
123
+ ? ` — ${later} is the current live row`
124
+ : "") +
125
+ ` after this review was written; reviving the survivor would erase that supersession. Nothing was done. No evidence written.`,
126
+ };
127
+ }
102
128
  const ok = await markSuperseded(
103
129
  args.loser,
104
130
  {
@@ -118,8 +144,14 @@ export const register: ToolRegister = (editor, deps) => {
118
144
  }
119
145
  // The survivor may itself have been superseded earlier (e.g. by
120
146
  // a row this very call just made the loser). Declaring it
121
- // canonical has to make it recallable, so clear its own marker.
122
- const revived = await clearSuperseded(args.survivor);
147
+ // canonical has to make it recallable, so clear its own marker —
148
+ // but only the marker this review owns (#126): the guard above
149
+ // already refused anything else, and this re-check runs under the
150
+ // file lock against the line as it is at mutation time.
151
+ const revived = await clearSuperseded(args.survivor, {
152
+ supersededBy: args.loser,
153
+ reason: args.reason,
154
+ });
123
155
  // The response has always claimed "Evidence recorded" — now it
124
156
  // is true, and it names the session the merge ran FOR (#121's
125
157
  // residue on this line). The host tool_result hook covers
package/src/tools/undo.ts CHANGED
@@ -14,7 +14,7 @@ export const register: ToolRegister = (editor, deps) => {
14
14
  validated(UndoArgs, {
15
15
  name: "memory_undo",
16
16
  description:
17
- "List memory snapshots, or restore one (rollback). Only snapshots inside this store's snapshots directory are accepted: pass a bare name from the list or its full path. Non-standard files in snapshots/ are not listed or restorable. SAFE BY DEFAULT: restore refuses if the current file has rows added or edited since the snapshot, and audited human/tool deletions stay deleted. Re-run with merge=true to restore AND keep divergent rows, or force=true for an explicit exact rollback. Blocklisted rows remain inactive in every mode. Rows belonging to other repositories are never restored, rewound, or dropped in any mode — their lines survive verbatim, though a restore may place them later in the shared file. Global rows are visible to every repository, so they are in every repository's rollback scope.",
17
+ "List memory snapshots, or restore one (rollback). Only snapshots inside this store's snapshots directory are accepted: pass a bare name from the list or its full path. Non-standard files in snapshots/ are not listed or restorable. SAFE BY DEFAULT: restore refuses if the current file has rows added or edited since the snapshot, and audited human/tool deletions stay deleted. Re-run with merge=true to restore AND keep divergent rows, or force=true for an explicit exact rollback. Blocklisted rows remain inactive in every mode. Rejection is absolute: no mode resurrects a row whose content a human rejected — every mode omits such rows and reports them; recovery is human-only (lift the tombstone, then restore). Rows belonging to other repositories are never restored, rewound, or dropped in any mode — their lines survive verbatim, though a restore may place them later in the shared file. Global rows are visible to every repository, so they are in every repository's rollback scope.",
18
18
  options: direct,
19
19
  async execute(args, context): Promise<{ content: string }> {
20
20
  if (args.snapshot) {
@@ -44,6 +44,7 @@ export const register: ToolRegister = (editor, deps) => {
44
44
  `moved after it. Divergent rows (ts): ${parts.join(", ")}. ` +
45
45
  `If those belong to another session, re-run with merge=true (restore the file ` +
46
46
  `AND keep them); if they are the writes you are undoing, use force=true. ` +
47
+ `Rows whose content a human rejected stay omitted in every mode. ` +
47
48
  (res.foreignPreserved
48
49
  ? `${res.foreignPreserved} row(s) in this file belong to other repositories; they survive in every mode.`
49
50
  : "Rows belonging to other repositories survive in every mode."),
@@ -60,11 +61,14 @@ export const register: ToolRegister = (editor, deps) => {
60
61
  const omitted = res.deletedOmitted.length
61
62
  ? ` Omitted ${res.deletedOmitted.length} deliberately deleted row(s); use force=true to recover them.`
62
63
  : "";
64
+ const rejected = res.rejectedOmitted.length
65
+ ? ` Omitted ${res.rejectedOmitted.length} row(s) whose content a human rejected (ts: ${res.rejectedOmitted.join(", ")}); rejections are absolute — a human must lift the tombstone before any restore can bring them back.`
66
+ : "";
63
67
  const foreign = res.foreignPreserved
64
68
  ? ` Left ${res.foreignPreserved} row(s) belonging to other repositories untouched.`
65
69
  : "";
66
70
  return {
67
- content: `Restored ${basename(res.target)} from ${res.mode} snapshot -> ${res.target}.${kept}${safety}${omitted}${foreign}`,
71
+ content: `Restored ${basename(res.target)} from ${res.mode} snapshot -> ${res.target}.${kept}${safety}${omitted}${rejected}${foreign}`,
68
72
  };
69
73
  }
70
74
  const snaps = await listSnapshots();