opencode-self-improvement 0.14.0 → 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 +1 -1
- package/src/blocklist.ts +3 -2
- package/src/lock.ts +46 -3
- package/src/logfmt.ts +74 -6
- package/src/memory.ts +17 -3
- package/src/resolver.ts +9 -1
- package/src/undo.ts +5 -2
- package/src/viewer/mutate.ts +3 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
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/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
|
-
|
|
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
|
-
|
|
126
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
105
|
-
//
|
|
106
|
-
|
|
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
|
|
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 {
|
|
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
|
-
|
|
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,
|
package/src/viewer/mutate.ts
CHANGED
|
@@ -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
|
);
|