opencode-self-improvement 0.34.0 → 0.34.2

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.
@@ -10,8 +10,10 @@ modulo case, wrapping and markup — or whose only content is a command the
10
10
  project's own gates declare, is REFUSED at capture time and logged on the
11
11
  `auto_capture_restatable` evidence line, which names the file or the gate.
12
12
  The figure-subset invariant bounds both paths: a refusal claims the passage it
13
- cites states EVERY figure the candidate states, as whole tokens (`1.5`,
14
- `1.4.3`, `10.20.30.40` are single figures) — on the text path that passage is
13
+ cites states EVERY figure the candidate states, as whole tokens compared by
14
+ canonical value (`1.5`, `1.4.3`, `10.20.30.40` and `1,024` are single figures,
15
+ and `1,024` and `1024` are the same figure once the grouping comma is
16
+ dropped) — on the text path that passage is
15
17
  the region the match covered, not the tree at large, since a figure in another
16
18
  sentence is another sentence's business — and on the gate path the figures are
17
19
  compared against the declared command, never against the candidate's own
@@ -29,11 +31,13 @@ is not enough: `--target staging --fallback canary` declared against
29
31
  `--target canary --fallback staging` has every word present and the pairing
30
32
  wrong. One relation, both paths.
31
33
 
32
- Atomicity is the spine, not another guard. A figure is one token wherever the
33
- matcher reads it — `tokens()` treats `.` as a word character, so `1.5`, `1.4.3`
34
- and the `11.` of a sentence ending on one are single figures — therefore the
35
- claim splitter never cuts inside a figure and a match is admitted only when no
36
- figure run crosses either edge of it. Half-figures are what every earlier round
34
+ Atomicity is the spine, not another guard. A figure is one definition wherever
35
+ the matcher reads it: the figure grammar exported from `core/tokenize.ts` makes
36
+ a digit-bearing word run, where `.` and `,` belong to it only between digits —
37
+ `1.5`, `1.4.3` and `1,024` are single figures, and the `.` that ends a sentence
38
+ on one is prose, so `1.5.` states the figure `1.5` — therefore the claim
39
+ splitter never cuts inside a figure and a match is admitted only when no figure
40
+ run crosses either edge of it. Half-figures are what every earlier round
37
41
  kept meeting from a different angle: a claim ending at the `3` of `3.12` is cut,
38
42
  then re-tokenized by the region slice as a figure the tree never states. Judging
39
43
  the boundary makes that shape unrepresentable rather than merely unvouched. The
@@ -11,7 +11,7 @@ rules and links here.
11
11
 
12
12
  Daily memory writes publish a complete replacement file under that lock, so concurrent readers see the previous or new complete file rather than a partially appended record. Appending a row therefore rewrites the day file (in addition to the existing timestamp-uniqueness read). On Windows, a reader handle that prevents replacement can make the write refuse after the replacement retry window; the previous bytes remain intact and the caller can retry once the handle closes. This publication rule applies to daily memory files, not append-only evidence, use, rejection, or audit logs; [#198](https://github.com/abogartz/opencode-self-improvement/issues/198) tracks the broader read boundary.
13
13
 
14
- The lock covers one **file**, not the store directory. Two sessions writing different days of the same store therefore do not wait on each other. A directory-wide lock was tried first and lost writes: a whole-file publish waits up to two seconds on Windows for a reader to let go of the destination, and with one lock for the directory that wait stops every other writer in the store. Per file it stops only the writers of that file, which is what the publish's safety check needs. The cost is a database plus its write-ahead log per locked file; they exist only while a connection is open, and the number of open connections is bounded. A writer never holds two file locks at once, and batches that must serialize a whole read-then-supersede sequence (`memory_update`, `memory_merge_review`) take a separate named lock (`.store-batch.update-order.sqlite`), always before the file locks their steps take — so a batch never holds a file lock across its whole run.
14
+ The lock covers one **file**, not the store directory. Two sessions writing different days of the same store therefore do not wait on each other. A directory-wide lock was tried first and lost writes: a whole-file publish waits up to two seconds on Windows for a reader to let go of the destination, and with one lock for the directory that wait stops every other writer in the store. Per file it stops only the writers of that file, which is what the publish's safety check needs. The cost is a database plus its write-ahead log per locked file; they exist only while a connection is open, and the number of open connections is bounded. Updates, merge reviews, and snapshot restores share a named lock (`.store-batch.update-order.sqlite`) within a store. Each takes that lock before its day-file locks, so a restore cannot replace either row between consolidation validation and retirement. A writer holds at most one day-file lock at a time. Even a restore for another day can wait behind an update or merge. If the lock times out, the restore returns a busy error and can be retried.
15
15
 
16
16
  Two unsupported placements. The write-ahead log needs mmap'd shared memory, which SQLite does not provide on network filesystems, so a memory root on SMB, NFS or a OneDrive-mounted folder is **not supported**: writes there can report a disk I/O error rather than serialise. Configure `OPENCODE_MEMORY_DIR` on local disk. And during the update that introduced this lock, a session still running the previous release honours `<date>.logfmt.lock` while an updated session honours the SQLite lock, so those two do not exclude each other until every running session has restarted.
17
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.34.0",
3
+ "version": "0.34.2",
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": {
@@ -55,6 +55,7 @@ import { lstatSync, readFileSync } from "node:fs";
55
55
  import { join, relative } from "node:path";
56
56
  import {
57
57
  POL_NEG,
58
+ figureExtent,
58
59
  numericTokens,
59
60
  polaritySigns,
60
61
  tokens,
@@ -244,8 +245,10 @@ function cueNegated(text: string): boolean {
244
245
  * candidate's own spans: a row whose command span carries a flag value
245
246
  * (`--timeout 5000`) would supply the figure that clears its own veto, and the
246
247
  * declaration, not the row, is what must vouch for the number.
247
- * `numericTokens` keeps dotted numbers whole, so versions and addresses are
248
- * single figures and cannot be assembled out of separate integers.
248
+ * `numericTokens` reads the figure grammar exported from `core/tokenize.ts`:
249
+ * a grouped figure is one figure (`1,024` reads as `1024`), a sentence dot is
250
+ * not part of one, and dotted versions and addresses stay whole, so no figure
251
+ * can be assembled out of separate integers.
249
252
  */
250
253
  function introducesNewNumber(text: string, matched: string): boolean {
251
254
  const known = new Set(numericTokens(matched));
@@ -573,9 +576,10 @@ function gateHit(spans: string[], gates: Gate[]): Gate | null {
573
576
  * A split never falls inside a figure. Splitting `1.5` at its dot produced two
574
577
  * claims that each matched their own sentence and reassembled into a figure the
575
578
  * tree never states, and the same fragments let a claim end mid-number in the
576
- * tree. `tokens()` reads `.` as a word character, so the boundary waits for the
577
- * figure run to end — including the sentence dot a figure ends on, which belongs
578
- * to that token (`numericTokens("The cost is 11.")` is `["11."]`). A claim that
579
+ * tree. The boundary waits for `figureExtent`'s figure run to end — including
580
+ * the sentence dot a figure ends on, which the splitter treats as run territory
581
+ * even though the figure's canonical value excludes it
582
+ * (`numericTokens("The cost is 11.")` is `["11"]`). A claim that
579
583
  * therefore spans a sentence boundary is fail-open: a longer claim is harder to
580
584
  * match, so the rule can only remove refusals.
581
585
  */
@@ -592,14 +596,14 @@ function claims(text: string): string[] {
592
596
  return out;
593
597
  }
594
598
 
595
- /** The assertion boundaries, minus a `.` that sits inside a figure. */
599
+ /** The assertion boundaries, minus a `.` that sits inside a figure run. */
596
600
  function splitClaims(text: string): string[] {
597
601
  const parts: string[] = [];
598
602
  let from = 0;
599
603
  for (let i = 0; i < text.length; i++) {
600
604
  const c = text.charCodeAt(i);
601
605
  if (c !== 46 && c !== 59 && c !== 58 && c !== 10) continue;
602
- if (c === 46 && figureRun(text, i)) continue;
606
+ if (c === 46 && figureExtent(text, i)) continue;
603
607
  parts.push(text.slice(from, i));
604
608
  from = i + 1;
605
609
  }
@@ -683,6 +687,27 @@ function warnsAgainst(prefix: string): boolean {
683
687
  return WARNS_AGAINST.test(prefix);
684
688
  }
685
689
 
690
+ /**
691
+ * Does a hit cover every figure it touches, whole? A clause ending at the `3`
692
+ * of `3.12`, or starting at the `5` of `30.5`, cuts a figure in half, and the
693
+ * half re-tokenizes as a whole figure the tree never states: `3` is not in a
694
+ * README that says `Requires Python 3.12`, it is what slicing leaves behind.
695
+ * Word boundaries do not settle this — `.` is a word character to the tokenizer
696
+ * and a sentence boundary to the claim splitter, and the two disagree exactly
697
+ * inside a number. So a hit is admitted only when no figure run crosses either
698
+ * edge, which makes a half-figure unrepresentable rather than merely unvouched.
699
+ * The edges are `figureExtent`'s, from `core/tokenize.ts` — the same definition
700
+ * `numericTokens` compares with, so the boundary this veto admits and the set
701
+ * the refusal vouches cannot disagree.
702
+ */
703
+ function hitCoversFigures(hay: string, start: number, end: number): boolean {
704
+ for (const pos of [start - 1, end]) {
705
+ const run = figureExtent(hay, pos);
706
+ if (run && (run.start < start || run.end > end)) return false;
707
+ }
708
+ return true;
709
+ }
710
+
686
711
  /**
687
712
  * Where the tree states `clause` as its own words, in a sentence of the same
688
713
  * polarity. -1 means "not available".
@@ -701,55 +726,6 @@ function warnsAgainst(prefix: string): boolean {
701
726
  * A reversed clause is not evidence of availability, and every uncertainty in
702
727
  * this file keeps the candidate.
703
728
  */
704
- function isTokenChar(code: number): boolean {
705
- return (
706
- (code >= 48 && code <= 57) || // 0-9
707
- (code >= 97 && code <= 122) || // a-z, after norm()
708
- code === 95 || // _
709
- code === 46 // .
710
- );
711
- }
712
-
713
- /**
714
- * The extent of the token `tokens()` would read at `pos`, when that token
715
- * states a digit. `tokens()` splits on `[^a-z0-9_.]+`, so a dot is a word
716
- * character: `1.5`, `1.4.3` and `10.20.30.40` are single tokens, and so is the
717
- * `11.` of a sentence that ends on one. Nothing else in this file may decide
718
- * where a figure begins or ends, because the same definition is what the figure
719
- * subset check compares with.
720
- */
721
- function figureRun(
722
- text: string,
723
- pos: number,
724
- ): { start: number; end: number } | null {
725
- if (pos < 0 || pos >= text.length || !isTokenChar(text.charCodeAt(pos)))
726
- return null;
727
- let start = pos;
728
- while (start > 0 && isTokenChar(text.charCodeAt(start - 1))) start--;
729
- let end = pos;
730
- while (end + 1 < text.length && isTokenChar(text.charCodeAt(end + 1))) end++;
731
- if (!/[0-9]/.test(text.slice(start, end + 1))) return null;
732
- return { start, end: end + 1 };
733
- }
734
-
735
- /**
736
- * Does a hit cover every figure it touches, whole? A clause ending at the `3`
737
- * of `3.12`, or starting at the `5` of `30.5`, cuts a figure in half, and the
738
- * half re-tokenizes as a whole figure the tree never states: `3` is not in a
739
- * README that says `Requires Python 3.12`, it is what slicing leaves behind.
740
- * Word boundaries do not settle this — `.` is a word character to the tokenizer
741
- * and a sentence boundary to the claim splitter, and the two disagree exactly
742
- * inside a number. So a hit is admitted only when no figure run crosses either
743
- * edge, which makes a half-figure unrepresentable rather than merely unvouched.
744
- */
745
- function hitCoversFigures(hay: string, start: number, end: number): boolean {
746
- for (const pos of [start - 1, end]) {
747
- const run = figureRun(hay, pos);
748
- if (run && (run.start < start || run.end > end)) return false;
749
- }
750
- return true;
751
- }
752
-
753
729
  function findClause(hay: string, clause: string, start = 0): number {
754
730
  const reversed = cueNegated(clause);
755
731
  for (let from = start; ; ) {
@@ -26,6 +26,7 @@
26
26
  // 3. PROPOSALS, not writes. Nothing here mutates the store. A human resolves a
27
27
  // proposal through memory_merge_review (supersede-not-delete, recoverable).
28
28
  // 4. The most recently used member is never a loser (the rule, inherited).
29
+ import { createHash } from "node:crypto";
29
30
  import {
30
31
  MAX_KEYWORDS,
31
32
  type Memory,
@@ -191,6 +192,20 @@ export function absorbAliases(survivor: Memory, loser: Memory): Memory {
191
192
  };
192
193
  }
193
194
 
195
+ /** Bind one resolve command to the retrieval state that its step would publish. */
196
+ export function consolidationStepKey(merged: Memory, loser: Memory): string {
197
+ const seats = [merged, loser].map((m) => [
198
+ m.ts,
199
+ m.repo ?? "global",
200
+ m.repoPath,
201
+ m.type,
202
+ m.scope,
203
+ m.content,
204
+ m.kw ?? [],
205
+ ]);
206
+ return createHash("sha256").update(JSON.stringify(seats)).digest("hex");
207
+ }
208
+
194
209
  /**
195
210
  * Replay the cluster's real reads against a store where the cluster has been
196
211
  * replaced by the merged row. `rows` is the whole active store; the function
@@ -1,6 +1,10 @@
1
1
  // render — split from src/consolidate.ts. Declaration bodies are unchanged.
2
2
 
3
- import { type ProposalReport } from "./propose.ts";
3
+ import {
4
+ absorbAliases,
5
+ consolidationStepKey,
6
+ type ProposalReport,
7
+ } from "./propose.ts";
4
8
  import { flattenMemoryText } from "../store/sanitize.ts";
5
9
 
6
10
  /** Human-readable proposal list. Ends with the exact command to resolve one. */
@@ -11,6 +15,12 @@ export function renderProposals(report: ProposalReport): string {
11
15
  return out.join("\n");
12
16
  }
13
17
  for (const p of report.plans) {
18
+ let projected = p.survivor;
19
+ const commands = p.losers.map((loser) => {
20
+ projected = absorbAliases(projected, loser);
21
+ const expected = consolidationStepKey(projected, loser);
22
+ return ` resolve: memory_merge_review(loser="${loser.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}", consolidate=true, expected="${expected}")`;
23
+ });
14
24
  out.push(
15
25
  `${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
16
26
  ` keep ${p.survivor.ts}`,
@@ -23,10 +33,7 @@ export function renderProposals(report: ProposalReport): string {
23
33
  ),
24
34
  ` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
25
35
  ` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
26
- ...p.losers.map(
27
- (loser) =>
28
- ` resolve: memory_merge_review(loser="${loser.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}", consolidate=true)`,
29
- ),
36
+ ...commands,
30
37
  "",
31
38
  );
32
39
  }
@@ -31,10 +31,100 @@ export const STOPWORDS: ReadonlySet<string> = new Set([
31
31
  ]);
32
32
 
33
33
  export function tokens(text: string): string[] {
34
- return text
35
- .toLowerCase()
36
- .split(/[^a-z0-9_.]+/)
37
- .filter((t) => t.length > 0);
34
+ const lower = text.toLowerCase();
35
+ const out: string[] = [];
36
+ let start = -1;
37
+ for (let i = 0; i <= lower.length; i++) {
38
+ const word = i < lower.length && isWordChar(lower.charCodeAt(i));
39
+ if (word && start < 0) start = i;
40
+ else if (!word && start >= 0) {
41
+ out.push(lower.slice(start, i));
42
+ start = -1;
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // One figure grammar, stated once.
50
+ //
51
+ // A figure is a word run that carries a digit — `30`, `3.12`, `9ae0998`,
52
+ // `1,024` — where `.` and `,` belong to the run only while the run keeps
53
+ // reading as a number: a separator joins when a digit sits on each side
54
+ // (`1,024`, `1.4.3`), and a `.` that merely ends a sentence is prose, not the
55
+ // tail of the figure (`1.5.` states `1.5`). `tokens()` alone is not this: it
56
+ // splits `1,024` at the comma and glues the sentence dot of `1.5.` onto the
57
+ // figure, and a matcher that reads those two edges differently in two places
58
+ // will refuse a truncation of `1` as a restatement of `1,024` while keeping a
59
+ // verbatim restatement of `1.5`. Every decision about where a figure begins or
60
+ // ends — the availability matcher's claim splitter, its hit-coverage veto and
61
+ // the figure-subset check below — reads `figureExtent`, so the edges cannot
62
+ // drift apart.
63
+ // ---------------------------------------------------------------------------
64
+
65
+ const CODE_COMMA = 44;
66
+ const CODE_DOT = 46;
67
+ const CODE_ZERO = 48;
68
+ const CODE_NINE = 57;
69
+ const CODE_UPPER_A = 65;
70
+ const CODE_UPPER_Z = 90;
71
+ const CODE_LOWER_A = 97;
72
+ const CODE_LOWER_Z = 122;
73
+ const CODE_UNDERSCORE = 95;
74
+
75
+ function isDigit(code: number): boolean {
76
+ return code >= CODE_ZERO && code <= CODE_NINE;
77
+ }
78
+
79
+ /** A character `tokens()` keeps inside a token: a digit, a letter, `_` or `.`.
80
+ * This char class IS the split rule — `tokens()` splits wherever it is false. */
81
+ export function isWordChar(code: number): boolean {
82
+ return (
83
+ isDigit(code) ||
84
+ (code >= CODE_LOWER_A && code <= CODE_LOWER_Z) ||
85
+ (code >= CODE_UPPER_A && code <= CODE_UPPER_Z) ||
86
+ code === CODE_UNDERSCORE ||
87
+ code === CODE_DOT
88
+ );
89
+ }
90
+
91
+ /** Does the `,` at `i` join two digits, making `1,024` one figure? */
92
+ function joinsDigits(text: string, i: number): boolean {
93
+ return (
94
+ text.charCodeAt(i) === CODE_COMMA &&
95
+ i > 0 &&
96
+ i + 1 < text.length &&
97
+ isDigit(text.charCodeAt(i - 1)) &&
98
+ isDigit(text.charCodeAt(i + 1))
99
+ );
100
+ }
101
+
102
+ function isRunChar(text: string, i: number): boolean {
103
+ return isWordChar(text.charCodeAt(i)) || joinsDigits(text, i);
104
+ }
105
+
106
+ /**
107
+ * The extent of the figure at `pos`, or null when `pos` is not part of one.
108
+ * A figure is the maximal run of word characters around `pos` — joined across
109
+ * a `,` between digits — that carries a digit, with the dots of a sentence
110
+ * ending trimmed: `1,024`, `1.4.3` and `9ae0998` are figures; the `.` that
111
+ * closes `The ratio is 1.5.` is not part of one, so the extent of the run at
112
+ * that dot is `1.5`, not `1.5.`.
113
+ */
114
+ export function figureExtent(
115
+ text: string,
116
+ pos: number,
117
+ ): { start: number; end: number } | null {
118
+ if (pos < 0 || pos >= text.length || !isRunChar(text, pos)) return null;
119
+ let start = pos;
120
+ while (start > 0 && isRunChar(text, start - 1)) start--;
121
+ let end = pos + 1;
122
+ while (end < text.length && isRunChar(text, end)) end++;
123
+ while (end > start && text.charCodeAt(end - 1) === CODE_DOT) end--;
124
+ if (end === start) return null;
125
+ for (let i = start; i < end; i++)
126
+ if (isDigit(text.charCodeAt(i))) return { start, end };
127
+ return null;
38
128
  }
39
129
 
40
130
  // Case-preserving tokens, for reporting asserted values back to the user.
@@ -70,11 +160,26 @@ export function jaccard(a: string[], b: string[]): number {
70
160
  // number or its sign are not the same words.
71
161
  // ---------------------------------------------------------------------------
72
162
 
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. */
163
+ /** Every figure a statement asserts, deduped, sorted and canonical: the
164
+ * quantities, versions, ids and durations carried by `figureExtent` runs,
165
+ * with grouping commas removed so `1,024` reads as `1024` and a sentence dot
166
+ * excluded so `1.5.` reads as `1.5`. Two texts state the same figure exactly
167
+ * when their canonical values match; a figure cannot be assembled out of
168
+ * separate integers because only a run the text itself states is read. A
169
+ * change here is a different fact, not a rephrasing. */
76
170
  export function numericTokens(text: string): string[] {
77
- return [...new Set(tokens(text).filter((t) => /\d/.test(t)))].sort();
171
+ const lower = text.toLowerCase();
172
+ const out = new Set<string>();
173
+ for (let i = 0; i < lower.length; ) {
174
+ const ext = figureExtent(lower, i);
175
+ if (ext === null) {
176
+ i++;
177
+ continue;
178
+ }
179
+ out.add(lower.slice(ext.start, ext.end).replace(/,/g, ""));
180
+ i = Math.max(ext.end, i + 1);
181
+ }
182
+ return [...out].sort();
78
183
  }
79
184
 
80
185
  export const POL_POS = "pos";
package/src/store/undo.ts CHANGED
@@ -39,7 +39,7 @@ import { readLines } from "../core/logfmt/read.ts";
39
39
  import { contentHash } from "../telemetry/record.ts";
40
40
  import { isWithin } from "./containment.ts";
41
41
  import { snapshotFiles } from "./files/snapshots.ts";
42
- import { LOCK_RESTORE, withStoreLock } from "./lock.ts";
42
+ import { LOCK_RESTORE, withStoreBatch, withStoreLock } from "./lock.ts";
43
43
  import {
44
44
  ADMIN_READER,
45
45
  lineVisibleTo,
@@ -217,6 +217,22 @@ export async function restoreSnapshot(
217
217
  reader: Reader = ADMIN_READER,
218
218
  ): Promise<RestoreResult> {
219
219
  const snap = await resolveSnapshot(snapshot, memoryRootDir);
220
+ // A restore can replace either seat of a merge. Join its outer lock before
221
+ // taking a day-file lock so both seats stay stable through retirement.
222
+ return withStoreBatch(
223
+ memoryRootDir,
224
+ "update-order",
225
+ () => restoreResolvedSnapshot(snap, memoryRootDir, mode, reader),
226
+ LOCK_RESTORE,
227
+ );
228
+ }
229
+
230
+ async function restoreResolvedSnapshot(
231
+ snap: Awaited<ReturnType<typeof resolveSnapshot>>,
232
+ memoryRootDir: string,
233
+ mode: RestoreMode,
234
+ reader: Reader,
235
+ ): Promise<RestoreResult> {
220
236
  const rootReal = await realpath(resolve(memoryRootDir));
221
237
  const realTarget = resolve(rootReal, snap.original);
222
238
  if (!isWithin(rootReal, realTarget)) {
@@ -9,6 +9,7 @@ import { stampRow } from "../store/files/snapshots.ts";
9
9
  import { formatLine } from "../core/logfmt/format.ts";
10
10
  import {
11
11
  absorbAliases,
12
+ consolidationStepKey,
12
13
  sameConsolidationScope,
13
14
  } from "../consolidate/propose.ts";
14
15
  import { clearSuperseded, markSuperseded } from "../store/files/supersede.ts";
@@ -22,7 +23,7 @@ export const register: ToolRegister = (editor, deps) => {
22
23
  validated(MergeReviewArgs, {
23
24
  name: "memory_merge_review",
24
25
  description:
25
- "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.",
26
+ "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). A consolidation command also refuses before writing if its expected digest is missing or no longer matches the store. Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
26
27
  options: direct,
27
28
  async execute(args, context): Promise<{ content: string }> {
28
29
  const { sid } = toolIds(context);
@@ -38,6 +39,12 @@ export const register: ToolRegister = (editor, deps) => {
38
39
  "merge_review blocked: loser, survivor, and reason are all required (fail-closed).",
39
40
  };
40
41
  }
42
+ if (args.expected !== undefined && !args.consolidate) {
43
+ return {
44
+ content:
45
+ "Consolidation blocked: use the full command printed by memory_consolidate.",
46
+ };
47
+ }
41
48
  if (args.loser === args.survivor) {
42
49
  // (Same-row input would mark and then revive the same row: a
43
50
  // silent no-op that reports full success.)
@@ -150,7 +157,7 @@ export const register: ToolRegister = (editor, deps) => {
150
157
  }
151
158
  // Publish the aliases first. If retirement fails, the loser
152
159
  // remains searchable and reapplying the union is idempotent.
153
- consolidationStarted = true;
160
+ let stale = false;
154
161
  const present = await stampRow(
155
162
  survivorRow.file,
156
163
  survivorRow.ts,
@@ -169,12 +176,25 @@ export const register: ToolRegister = (editor, deps) => {
169
176
  throw new Error("survivor changed since the proposal");
170
177
  }
171
178
  const merged = absorbAliases(current, loserRow);
179
+ if (
180
+ consolidationStepKey(merged, loserRow) !== args.expected
181
+ ) {
182
+ stale = true;
183
+ return null;
184
+ }
185
+ consolidationStarted = true;
172
186
  const kw = merged.kw?.join(",");
173
187
  const tags = merged.tags!.join(",");
174
188
  if (fields.kw === kw && fields.tags === tags) return null;
175
189
  return formatLine({ ...fields, kw, tags });
176
190
  },
177
191
  );
192
+ if (stale) {
193
+ return {
194
+ content:
195
+ "Consolidation blocked: this command no longer matches the preview or is missing its expected value. Run memory_consolidate again and review the new read estimate before applying it.",
196
+ };
197
+ }
178
198
  if (present === null)
179
199
  throw new Error("survivor no longer exists");
180
200
  }
@@ -147,6 +147,12 @@ export const EvidenceArgs = z.object({
147
147
  });
148
148
 
149
149
  export const MergeReviewArgs = z.object({
150
+ expected: z
151
+ .string()
152
+ .optional()
153
+ .describe(
154
+ "Required with consolidate=true. Copy this step's expected value from the printed consolidation command.",
155
+ ),
150
156
  consolidate: z
151
157
  .boolean()
152
158
  .optional()