opencode-self-improvement 0.13.2 → 0.14.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.13.2",
3
+ "version": "0.14.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": {
package/src/blocklist.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // memory scan must never pick it up.
6
6
  import { join } from "node:path";
7
7
  import { memoryRoot } from "./config.ts";
8
- import { appendLog, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
8
+ import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
9
9
  import { withStoreLock, LOCK_WRITE } from "./lock.ts";
10
10
 
11
11
  const BLOCKLIST_FILENAME = "blocklist.logfmt";
@@ -59,11 +59,12 @@ export async function removeBlock(ts: string): Promise<boolean> {
59
59
  async () => {
60
60
  const store = Bun.file(file);
61
61
  if (!(await store.exists())) return false;
62
+ const since = await fileIdentity(file);
62
63
  const kept = (await store.text()).split("\n").filter((l) => {
63
64
  const row = parseLine(l);
64
65
  return !(row && row.ts === ts);
65
66
  });
66
- await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""));
67
+ await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
67
68
  return true;
68
69
  },
69
70
  LOCK_WRITE,
package/src/index.ts CHANGED
@@ -186,6 +186,12 @@ function resultMeta(result: unknown): Record<string, unknown> {
186
186
 
187
187
  const PLUGIN_ID = "opencode-self-improvement";
188
188
 
189
+ // Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
190
+ // the shared "auto-capture" provenance tag (src/inject.ts renders it) and add
191
+ // this one so decay/status can tell which trigger wrote them — the same
192
+ // distinction the auto_capture_compaction_* evidence lines carry.
193
+ const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
194
+
189
195
  // The setup-time Bun-floor warning fires once per process (setup can run for
190
196
  // more than one location).
191
197
  let bunFloorChecked = false;
@@ -844,6 +850,12 @@ const impl = {
844
850
  };
845
851
 
846
852
  // ---- hooks (all fail-closed) -------------------------------------------
853
+ // Seam set by the auto-capture wiring below ONLY when the compaction
854
+ // trigger is live (autoCapture on, captureOnCompact not false, valid
855
+ // captureModel). The compaction hook calls it fire-and-forget; undefined
856
+ // means "off". Declared here because the hook registers before capture.
857
+ let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
858
+
847
859
  // Bookkeeping: track the active session/tool/call before a tool runs.
848
860
  await ctx.tool?.hook("execute.before", (event: any) =>
849
861
  guarded("tool.execute.before", async () => {
@@ -936,7 +948,9 @@ const impl = {
936
948
  // compaction: the durable-memory anchor is pushed onto the hook's system
937
949
  // parts (visible to the summarizer model, which runs AFTER hooks) so the
938
950
  // summary preserves the facts. Never sets event.result — that would skip
939
- // the summarizer call entirely.
951
+ // the summarizer call entirely. Also fires the context-death auto-capture
952
+ // (issue #41, opt-in; see the capture section): the transcript is mined
953
+ // while it still exists, BEFORE the summarizer replaces it.
940
954
  await ctx.session?.hook("compaction", (event: any) =>
941
955
  guarded("session.compaction (onCompacting)", async () => {
942
956
  setCurrent({ sessionID: event?.sessionID });
@@ -947,6 +961,13 @@ const impl = {
947
961
  }
948
962
  const anchor = await compactionAnchor();
949
963
  if (anchor) event?.system?.push?.({ type: "text", text: anchor });
964
+ // Fire-and-forget: a capture model call must never delay the compaction
965
+ // the user is waiting for, and failures stay inside the guarded path.
966
+ // The payload's own messages ride along so the mining sees the
967
+ // pre-compaction transcript even if the store moves under it.
968
+ if (onCompactCapture && typeof event?.sessionID === "string") {
969
+ onCompactCapture(event.sessionID, event.messages);
970
+ }
950
971
  }),
951
972
  );
952
973
 
@@ -1020,22 +1041,27 @@ const impl = {
1020
1041
  })();
1021
1042
  }
1022
1043
 
1023
- // ---- opt-in auto-capture on session idle --------------------------------
1044
+ // ---- opt-in auto-capture (idle + compaction triggers) ------------------
1024
1045
  // Default OFF: capture never reads sessions and never calls a model. (The
1025
1046
  // measured-cache listener above does subscribe to the event stream by
1026
1047
  // default, but it is zero-model: pure bookkeeping of message usage.) When
1027
1048
  // enabled (options.autoCapture === true AND a valid captureModel), each
1028
- // session.idle event runs ONE cheap ctx.generate.text call whose reply is
1029
- // parsed into candidates that go through the SAME runWriteGate as
1049
+ // session.idle event — and, unless captureOnCompact === false, each
1050
+ // compaction hook call too — runs ONE cheap ctx.generate.text call whose
1051
+ // reply is parsed into candidates that go through the SAME runWriteGate as
1030
1052
  // model-authored writes — capture can never bypass the moat, and it only
1031
- // ever writes through the gate. A per-session cooldown bounds the cost.
1032
- // Every failure inside the loop is swallowed: capture must never be able
1033
- // to break a session.
1053
+ // ever writes through the gate. A per-session, per-trigger cooldown bounds
1054
+ // the cost. Compaction-triggered rows carry the CAPTURE_COMPACT_TAG tag and
1055
+ // auto_capture_compaction_* evidence lines, idle rows keep auto_capture_*,
1056
+ // so decay/status — and bench/capture-trigger-compare.ts — can measure
1057
+ // which trigger earns its tokens. Every failure is swallowed: capture must
1058
+ // never be able to break a session.
1034
1059
  let captureCleanup: Cleanup | undefined;
1035
1060
  if (ctx.options?.autoCapture === true) {
1036
1061
  const captureModel =
1037
1062
  typeof ctx.options.captureModel === "string" ? ctx.options.captureModel : "";
1038
1063
  const captureMax = Number(ctx.options.captureMax) || 3;
1064
+ const captureOnCompact = ctx.options?.captureOnCompact !== false;
1039
1065
  const modelRef = parseModelRef(captureModel);
1040
1066
  if (!modelRef) {
1041
1067
  // Invalid/missing model: skip registering the whole subscription
@@ -1058,6 +1084,63 @@ const impl = {
1058
1084
  // setup guard proves it exists, but property narrowing does not survive
1059
1085
  // into the closure, and undefined degrades safely (empty transcript).
1060
1086
  const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
1087
+
1088
+ // ONE capture pass, shared by both triggers. `seeded` is a transcript
1089
+ // already in hand — the compaction hook carries the PRE-compaction
1090
+ // messages, which is the whole point (Compaction Cliff: one round
1091
+ // retains 53% of exact-wording rules); when it is absent (older host
1092
+ // shapes) or too thin, the session context is read instead, the same
1093
+ // source the idle trigger mines.
1094
+ async function captureSession(
1095
+ sid: string,
1096
+ seeded: string,
1097
+ trigger: "idle" | "compaction",
1098
+ seededMsgs?: unknown,
1099
+ ): Promise<void> {
1100
+ // Bind the capturing session so captures stamp (and gate against)
1101
+ // that session's repo, not whatever tool call ran last.
1102
+ setCurrent({ sessionID: sid });
1103
+ let transcript = seeded;
1104
+ let msgs = seededMsgs;
1105
+ if (transcript.length < 200) {
1106
+ msgs = await contextFn({ sessionID: sid });
1107
+ transcript = flattenTranscript(msgs);
1108
+ }
1109
+ if (transcript.length < 200) return; // too thin to mine reliably
1110
+ // #44: how stale is a capture? Distance from the newest message of
1111
+ // the mined transcript to this instant - measured on whatever the
1112
+ // trigger actually mined (the hook payload for compaction, the
1113
+ // session context for idle), so both triggers' lag is comparable.
1114
+ const lagMs = lagSince(msgs);
1115
+ const out = await generateApi.text({
1116
+ model: modelRef,
1117
+ prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1118
+ });
1119
+ const text = typeof out === "string" ? out : out?.text ?? "";
1120
+ const candidates = parseCandidates(text, captureMax);
1121
+ for (const c of candidates) {
1122
+ const outcome = await runWriteGate(
1123
+ {
1124
+ ...c,
1125
+ tags:
1126
+ trigger === "compaction"
1127
+ ? ["auto-capture", CAPTURE_COMPACT_TAG]
1128
+ : ["auto-capture"],
1129
+ },
1130
+ gateContext(),
1131
+ );
1132
+ await record(
1133
+ trigger === "compaction"
1134
+ ? `auto_capture_compaction_${outcome.action}`
1135
+ : `auto_capture_${outcome.action}`,
1136
+ // A blocked credential-shaped scope must not reach the evidence log either.
1137
+ { session: sid, trigger, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
1138
+ false,
1139
+ );
1140
+ }
1141
+ await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
1142
+ }
1143
+
1061
1144
  void (async () => {
1062
1145
  try {
1063
1146
  for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
@@ -1065,39 +1148,12 @@ const impl = {
1065
1148
  if (event?.type !== "session.idle") continue;
1066
1149
  const sid = event.sessionID ?? event.properties?.sessionID ?? event.data?.sessionID;
1067
1150
  if (typeof sid !== "string") continue;
1068
- // Bind the idle session so captures stamp (and gate against)
1069
- // that session's repo, not whatever tool call ran last.
1070
1151
  setCurrent({ sessionID: sid });
1071
1152
  const now = Date.now();
1072
1153
  if (now - (lastRun.get(sid) ?? 0) < 5 * 60_000) continue; // 5-min cooldown
1073
1154
  lastRun.set(sid, now);
1074
1155
  try {
1075
- const msgs = await contextFn({ sessionID: sid });
1076
- const transcript = flattenTranscript(msgs);
1077
- if (transcript.length < 200) continue; // too thin to mine reliably
1078
- // #44: how stale is a capture? Distance from the last message of
1079
- // the transcript to this instant. Sessions idle for an hour
1080
- // produce an hour-old capture, and the surfaces now say so.
1081
- const lagMs = lagSince(msgs);
1082
- const out = await generateApi.text({
1083
- model: modelRef,
1084
- prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1085
- });
1086
- const text = typeof out === "string" ? out : out?.text ?? "";
1087
- const candidates = parseCandidates(text, captureMax);
1088
- for (const c of candidates) {
1089
- const outcome = await runWriteGate(
1090
- { ...c, tags: ["auto-capture"] },
1091
- gateContext(),
1092
- );
1093
- await record(
1094
- `auto_capture_${outcome.action}`,
1095
- // A blocked credential-shaped scope must not reach the evidence log either.
1096
- { session: sid, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
1097
- false,
1098
- );
1099
- }
1100
- await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
1156
+ await captureSession(sid, "", "idle");
1101
1157
  } catch {
1102
1158
  // fail-closed: a broken capture attempt is invisible to the session
1103
1159
  }
@@ -1107,7 +1163,29 @@ const impl = {
1107
1163
  }
1108
1164
  })();
1109
1165
  captureCleanup = () => controller.abort();
1166
+
1167
+ // The compaction trigger needs no extra subscription: the session
1168
+ // compaction hook (registered above) calls through this seam. Separate
1169
+ // cooldown map from idle, so measuring a trigger is not confounded by
1170
+ // the other trigger having fired moments ago.
1171
+ if (captureOnCompact) {
1172
+ const lastCompactRun = new Map<string, number>();
1173
+ onCompactCapture = (sid, messages) => {
1174
+ if (controller.signal.aborted) return;
1175
+ const now = Date.now();
1176
+ if (now - (lastCompactRun.get(sid) ?? 0) < 5 * 60_000) return; // 5-min cooldown
1177
+ lastCompactRun.set(sid, now);
1178
+ void guarded("session.compaction (auto-capture)", () =>
1179
+ captureSession(sid, flattenTranscript(messages), "compaction", messages),
1180
+ );
1181
+ };
1182
+ }
1110
1183
  }
1184
+ } else if (ctx.options?.captureOnCompact === true) {
1185
+ // autoCapture is the master switch (zero-token default preserved).
1186
+ console.warn(
1187
+ "[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
1188
+ );
1111
1189
  }
1112
1190
  // Single cleanup returned by setup: tears down the measured listener and,
1113
1191
  // when enabled, the capture subscription. Future teardowns merge in here.
package/src/lock.ts CHANGED
@@ -31,6 +31,10 @@ const STALE_MS = 10_000;
31
31
  const DEFAULT_TIMEOUT_MS = 5_000;
32
32
  const MIN_BACKOFF_MS = 1;
33
33
  const MAX_BACKOFF_MS = 25;
34
+ // How many consecutive create-failures with a proven-absent lock file mean
35
+ // "this filesystem is not letting us create it" rather than "we are losing a
36
+ // race with a live holder". The wait is a fast, bounded spin, not a budget.
37
+ const ABSENT_THROW_STRIKES = 8;
34
38
 
35
39
  export function lockFileFor(file: string): string {
36
40
  return file + LOCK_SUFFIX;
@@ -84,12 +88,29 @@ async function timed(prev: Promise<void>, ms: number): Promise<boolean> {
84
88
  return gained;
85
89
  }
86
90
 
91
+ // The one probe that can answer "there is no holder" without itself being a
92
+ // creation attempt: stat reports a held file happily (Windows shares metadata
93
+ // reads with the handle owner), and ENOENT — uniquely — proves absence.
94
+ async function lockFileAbsent(lockPath: string): Promise<boolean> {
95
+ try {
96
+ await stat(lockPath);
97
+ return false;
98
+ } catch (probe) {
99
+ return (probe as NodeJS.ErrnoException).code === "ENOENT";
100
+ }
101
+ }
102
+
87
103
  async function stealIfStale(lockPath: string, now: number): Promise<boolean> {
88
104
  let age = -1;
89
105
  try {
90
106
  age = now - (await stat(lockPath)).mtimeMs;
91
107
  } catch {
92
- return true; // vanished between EEXIST and stat: retry the create
108
+ // Age undeterminable — typically the holder finished and removed the
109
+ // file a moment before this stat. "Not stealable" is the safe answer:
110
+ // the caller backs off within the budget and the next create wins.
111
+ // The old "retry the create immediately" here turned a stat that keeps
112
+ // failing into a hot spin that never consulted the budget at all.
113
+ return false;
93
114
  }
94
115
  if (age < STALE_MS) return false;
95
116
  try {
@@ -112,6 +133,8 @@ async function holdFileLock<T>(
112
133
  const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
113
134
  const started = Date.now();
114
135
  let backoff = MIN_BACKOFF_MS;
136
+ let firstErr: unknown;
137
+ let absentStrikes = 0;
115
138
  for (;;) {
116
139
  try {
117
140
  const handle = await open(lockPath, "wx");
@@ -122,8 +145,23 @@ async function holdFileLock<T>(
122
145
  }
123
146
  break;
124
147
  } catch (err) {
125
- const code = (err as NodeJS.ErrnoException).code;
126
- if (code !== "EEXIST") throw err;
148
+ // Any creation failure means: wait for the current holder, whatever
149
+ // label it carries (POSIX EEXIST; Windows sharing violations EPERM/
150
+ // EACCES; or the file vanishing between this open and any later probe
151
+ // — the holder simply finished). Policies that trusted a label or a
152
+ // one-shot probe were tried and lost rows: throwing on non-EEXIST
153
+ // aborted writers on mislabelled contention, and throwing on a
154
+ // stat-probe ENOENT aborted them in the vanish race.
155
+ // The filesystem still gets the last word: if creation keeps failing
156
+ // while stat keeps proving NO lock file exists, there is no holder to
157
+ // wait for — our own ability to create files is what is broken, and
158
+ // the original error must surface instead of rotting into a timeout.
159
+ firstErr ??= err;
160
+ if (await lockFileAbsent(lockPath)) {
161
+ if (++absentStrikes >= ABSENT_THROW_STRIKES) throw firstErr;
162
+ } else {
163
+ absentStrikes = 0;
164
+ }
127
165
  if (await stealIfStale(lockPath, Date.now())) {
128
166
  opts.onEvent?.("steal", Date.now() - started);
129
167
  continue;
@@ -135,6 +173,11 @@ async function holdFileLock<T>(
135
173
  `memory store is busy: ${basename(file)} has been locked for ${Date.now() - started}ms — retry`,
136
174
  );
137
175
  }
176
+ // Proceeding without the lock is the designed concession to
177
+ // contention — but never while the lock file has been absent this
178
+ // whole time: on a filesystem where we cannot create it, writing
179
+ // "unlocked" would just mean writing unguarded.
180
+ if (absentStrikes > 0) throw firstErr;
138
181
  return fn();
139
182
  }
140
183
  await sleep(backoff);
package/src/logfmt.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  // Minimal logfmt reader/writer shared by the durable store and the evidence
2
2
  // log. Field order is preserved on write so chains are diffable.
3
3
  import { dirname } from "node:path";
4
- import { appendFile, mkdir, rename, unlink } from "node:fs/promises";
4
+ import { appendFile, mkdir, rename, stat, unlink } from "node:fs/promises";
5
+
6
+ const IS_WINDOWS = process.platform === "win32";
5
7
 
6
8
  export type Fields = Record<string, unknown>;
7
9
 
@@ -94,25 +96,91 @@ export async function appendLog(file: string, line: string): Promise<void> {
94
96
  await appendFile(file, next);
95
97
  }
96
98
 
99
+ // A change-detection token for one file: any append, rewrite or replacement
100
+ // changes it. "absent" marks a file that does not exist yet. Readers of the
101
+ // freshness contract below take it BEFORE reading, so it pins the state the
102
+ // published content was derived from.
103
+ export async function fileIdentity(file: string): Promise<string> {
104
+ try {
105
+ const s = await stat(file, { bigint: true });
106
+ return `${s.ino}|${s.size}|${s.mtimeNs}`;
107
+ } catch (err) {
108
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
109
+ return "absent";
110
+ }
111
+ }
112
+
97
113
  // Publish whole-file content so no reader can observe a partial store. Recall,
98
114
  // injection and the viewer read these files without taking the lock, so the
99
115
  // handover is a same-directory rename (atomic on POSIX): a reader sees either
100
116
  // the previous file or the new one, never a truncated middle. Callers hold the
101
117
  // store lock for the whole read-modify-write.
102
- export async function writeAtomic(file: string, content: string): Promise<void> {
118
+ //
119
+ // `since` is the fileIdentity() taken before the caller read the file it is
120
+ // deriving `content` from. With it, a Windows handover that fails on reader
121
+ // contention can retry without risking a stale publish (see handoverRename).
122
+ // Without it, publishing behaves exactly as it always has: one rename.
123
+ let tmpSeq = 0;
124
+
125
+ export async function writeAtomic(file: string, content: string, since?: string): Promise<void> {
103
126
  await ensureDir(dirname(file));
104
- // One writer per file (the store lock), so the temp name is stable per
105
- // process and a crash leaves one leftover instead of one per attempt.
106
- const tmp = `${file}.${process.pid}.tmp`;
127
+ // Unique PER CALL, not per process: the store lock guarantees one writer
128
+ // only until a starved waiter's budget expires and lock.ts lets it proceed
129
+ // anyway. That degraded writer can be inside writeAtomic for the same file
130
+ // at the same instant - with a pid-stable name its bytes would sit in the
131
+ // very temp the anchored publish's ≤2s retry keeps renaming, and the retry
132
+ // would publish THOSE bytes under our success report. One extra leftover
133
+ // per failed attempt is the (unlinkable) price of that safety.
134
+ const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
107
135
  try {
108
136
  await Bun.write(tmp, content);
109
- await rename(tmp, file);
137
+ await handoverRename(tmp, file, since);
110
138
  } catch (err) {
111
139
  await unlink(tmp).catch(() => undefined);
112
140
  throw err;
113
141
  }
114
142
  }
115
143
 
144
+ // POSIX renames swap a file out from under an open reader; the handover needs
145
+ // one call, and a failure there is fatal, never contention. Windows mandatory
146
+ // locking instead REFUSES to replace a destination any reader still holds,
147
+ // while that handle lives. Readers of a small store file cycle their handle on
148
+ // a microsecond scale, so that failure is usually transient and worth a retry
149
+ // window (~2s, well inside the 5s lock budget) — but a retry alone is not safe
150
+ // here. If an unlocked writer (a starved lock waiter runs its write anyway;
151
+ // see lock.ts onTimeout) appends into the destination DURING the window, the
152
+ // retried rename publishes our now-stale copy over that row — a slower way to
153
+ // lose exactly what the immediate failure preserved. So the retry runs only
154
+ // while the destination still matches `since`, the identity from before the
155
+ // caller's read: match means no one moved the file and the blocker is a bare
156
+ // reader handle, a mismatch means the write's premise is gone and it fails
157
+ // with the original error, as the no-retry path always did. Hence also: no
158
+ // `since`, no retry.
159
+ async function handoverRename(tmp: string, file: string, since?: string): Promise<void> {
160
+ try {
161
+ await rename(tmp, file);
162
+ return;
163
+ } catch (err) {
164
+ if (!IS_WINDOWS || since === undefined) throw err;
165
+ const deadline = Date.now() + 2000;
166
+ let backoff = 1;
167
+ for (;;) {
168
+ const now = Date.now();
169
+ if (now >= deadline) throw err;
170
+ await new Promise((r) => setTimeout(r, Math.min(backoff, deadline - now)));
171
+ backoff = Math.min(backoff * 2, 50);
172
+ if ((await fileIdentity(file)) !== since) throw err; // destination moved; our copy is stale
173
+ try {
174
+ await rename(tmp, file);
175
+ return;
176
+ } catch {
177
+ // Still the reader's turn to block us (or a fresh one); the identity
178
+ // check at the top of the next pass is what distinguishes the two.
179
+ }
180
+ }
181
+ }
182
+ }
183
+
116
184
  export async function readLines(file: string): Promise<string[]> {
117
185
  const f = Bun.file(file);
118
186
  if (!(await f.exists())) return [];
package/src/memory.ts CHANGED
@@ -8,7 +8,16 @@ import { join, basename } from "node:path";
8
8
  import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
9
9
  import { repoScopeFor } from "./repokey.ts";
10
10
  import { getCurrent } from "./state.ts";
11
- import { appendLog, ensureDir, formatLine, parseLine, readLines, writeAtomic, type Fields } from "./logfmt.ts";
11
+ import {
12
+ appendLog,
13
+ ensureDir,
14
+ fileIdentity,
15
+ formatLine,
16
+ parseLine,
17
+ readLines,
18
+ writeAtomic,
19
+ type Fields,
20
+ } from "./logfmt.ts";
12
21
  import { withStoreLock, LOCK_WRITE } from "./lock.ts";
13
22
  import { blockedTs } from "./blocklist.ts";
14
23
  import { containsSecret, redactSecrets } from "./secrets.ts";
@@ -319,6 +328,10 @@ async function stampRow(
319
328
  return withStoreLock(
320
329
  file,
321
330
  async () => {
331
+ // Identity BEFORE the read: it pins the state `lines` was derived from,
332
+ // so writeAtomic can refuse to publish if anything moved the file
333
+ // meanwhile (Windows retry path — see logfmt.ts handoverRename).
334
+ const since = await fileIdentity(file);
322
335
  const lines = await readLines(file);
323
336
  const idx = lines.findIndex((l) => {
324
337
  const f = parseLine(l);
@@ -331,7 +344,7 @@ async function stampRow(
331
344
  if (next === null) return false;
332
345
  lines[idx] = next;
333
346
  await snapshotBefore(file);
334
- await writeAtomic(file, lines.join("\n") + "\n");
347
+ await writeAtomic(file, lines.join("\n") + "\n", since);
335
348
  return true;
336
349
  },
337
350
  LOCK_WRITE,
@@ -528,6 +541,7 @@ export async function prune(scope: string, type: string, reason: string): Promis
528
541
  await withStoreLock(
529
542
  file,
530
543
  async () => {
544
+ const since = await fileIdentity(file);
531
545
  const lines = await readLines(file);
532
546
  const kept: string[] = [];
533
547
  let changed = false;
@@ -547,7 +561,7 @@ export async function prune(scope: string, type: string, reason: string): Promis
547
561
  }
548
562
  if (!changed) return;
549
563
  snapshot.push(...(await snapshotFiles([file])));
550
- await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""));
564
+ await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
551
565
  },
552
566
  LOCK_WRITE,
553
567
  );
package/src/resolver.ts CHANGED
@@ -277,7 +277,15 @@ async function walkSources(absDir: string, relDir: string, out: string[]): Promi
277
277
  } catch {
278
278
  // Directory vanished mid-walk: keep what was collected.
279
279
  } finally {
280
- dh.close().catch(() => {});
280
+ // Close by awaiting, never by chaining off the return value: Bun 1.3.10
281
+ // returns undefined from DirHandle.close() (there the old `.catch()` chain
282
+ // threw a TypeError that killed the walk), 1.4.4 returns a Promise, and
283
+ // awaiting serves both — the optional call covers runtimes without it.
284
+ try {
285
+ await dh.close?.();
286
+ } catch {
287
+ // The walk is done: a handle that refuses to close is GC's problem.
288
+ }
281
289
  }
282
290
  }
283
291
 
package/src/undo.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  import { lstat, realpath, stat } from "node:fs/promises";
14
14
  import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
15
15
  import { deletionsFile, snapshotDir } from "./config.ts";
16
- import { ensureDir, parseLine, readLines, writeAtomic } from "./logfmt.ts";
16
+ import { ensureDir, fileIdentity, parseLine, readLines, writeAtomic } from "./logfmt.ts";
17
17
  import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
18
18
  import { snapshotFiles } from "./memory.ts";
19
19
 
@@ -206,6 +206,9 @@ export async function restoreSnapshot(
206
206
  return withStoreLock(
207
207
  target,
208
208
  async () => {
209
+ // Identity before the first read of `target` here: everything published
210
+ // below derives from what this read sees (logfmt.ts handoverRename).
211
+ const since = await fileIdentity(target);
209
212
  const cur = Bun.file(target);
210
213
  const curLines = (await cur.exists()) ? rows(await cur.text()) : [];
211
214
  // Deliberate deletions are read inside the lock too, so a forget that
@@ -254,7 +257,7 @@ export async function restoreSnapshot(
254
257
  );
255
258
  }
256
259
  await ensureDir(memoryRootDir);
257
- await writeAtomic(target, out.length ? out.join("\n") + "\n" : "");
260
+ await writeAtomic(target, out.length ? out.join("\n") + "\n" : "", since);
258
261
  return { target, restored: true, mode, safety, concurrentAdded, concurrentChanged, deletedOmitted };
259
262
  },
260
263
  LOCK_RESTORE,
@@ -9,7 +9,7 @@
9
9
  import { deletionsFile } from "../config.ts";
10
10
  import { addBlock, removeBlock } from "../blocklist.ts";
11
11
  import { record, chainId } from "../evidence.ts";
12
- import { appendLog, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
12
+ import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
13
13
  import { withStoreLock, LOCK_WRITE } from "../lock.ts";
14
14
  import {
15
15
  appendMemory,
@@ -106,6 +106,7 @@ export async function deleteMemory(input: DeleteInput): Promise<MutationResult>
106
106
  await withStoreLock(
107
107
  target.file,
108
108
  async () => {
109
+ const since = await fileIdentity(target.file);
109
110
  const lines = await readLines(target.file);
110
111
  const kept = lines.filter((l) => {
111
112
  const f = parseLine(l);
@@ -113,7 +114,7 @@ export async function deleteMemory(input: DeleteInput): Promise<MutationResult>
113
114
  });
114
115
  if (kept.length === lines.length) throw new Error(`memory line not found: ${input.ts}`);
115
116
  snapshot = await snapshotFiles([target.file]);
116
- await writeAtomic(target.file, kept.join("\n") + (kept.length ? "\n" : ""));
117
+ await writeAtomic(target.file, kept.join("\n") + (kept.length ? "\n" : ""), since);
117
118
  },
118
119
  LOCK_WRITE,
119
120
  );