opencode-self-improvement 0.34.0 → 0.34.1

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.
@@ -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.1",
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": {
@@ -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
  }
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()