opencode-self-improvement 0.15.5 → 0.15.7

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/README.md CHANGED
@@ -51,6 +51,8 @@ Daily memory writes publish a complete replacement file under that lock, so conc
51
51
 
52
52
  Memory is stored outside every repository, under `~/.config/opencode/memory` by default (override with `OPENCODE_MEMORY_DIR`). To start over, delete that directory.
53
53
 
54
+ On POSIX systems, new store directories use owner-only `0700` permissions and new files use `0600` (subject to a more restrictive umask). This includes temporary replacements, snapshots, locks, status files, and append-only logs. Accessing an existing store attempts to remove group/other permissions from its root; existing directories and appended/status files are tightened when written, without adding owner permissions. Old descendants are not recursively migrated: a successfully tightened root prevents other users from traversing to them. If directory chmod reports `EPERM`, `EROFS`, `EOPNOTSUPP`, or `ENOSYS` (for example an immutable or foreign-owned root, or a mount without chmod support), reads remain available with the existing permissions: owner-only traversal is not guaranteed. Correct ownership, mount support, or permissions outside the plugin when that privacy guarantee is required. File permission enforcement on writes remains unchanged. Existing ancestors outside the store are left unchanged. A store root that is itself a symlink is refused; configure its real directory instead. These modes do not revoke already-open handles or protect copies/hard links outside the private root. On Windows, privacy depends on the directory's ACL; the plugin does not change Windows ACLs.
55
+
54
56
  ## Options
55
57
 
56
58
  Zero configuration is the default. To tune, use the object form of the plugin entry in `opencode.json(c)`:
@@ -324,6 +326,18 @@ Use Bun **1.4.4** for development checks, matching CI. `bun run test` and `bun r
324
326
 
325
327
  `e2e/` boots the **real opencode CLI** against each candidate in a fully isolated instance (fresh config, fresh db, fresh memory store, empty `HOME`) driven by a scripted OpenAI-compatible fake model — no API keys. It covers loading from the source tree and from the packed npm artifact installed runtime-deps-only, plus BDD flows for remember, recall, exact and near duplicates, ungrounded claims, and forget. Needs `opencode` on `PATH` locally, or set `OPENCODE_BIN`. A `test-windows` leg also runs the suite on Windows; it reports without gating merges.
326
328
 
329
+ ### Mutation sweep
330
+
331
+ ```sh
332
+ bun run sweep:test
333
+ ```
334
+
335
+ `bun run sweep:test` (`scripts/test-sweep.ts`) audits the test suite rather than testing the plugin. Each mutant breaks exactly one claimed invariant in a detached `git worktree` of HEAD, runs the `test/` suite (unit + scenario) against that mutated tree, and reports whether the suite noticed. A mutant no test kills is an unpinned invariant: the test titles may claim coverage, but nothing died with the invariant. The clean tree is measured first and its failing tests are subtracted from every mutant run, so only new failures count as a kill and a flake never masquerades as one. Mutants are applied only to scratch worktrees beside the checkout, never to the working tree under your feet.
336
+
337
+ The output is a canonical mutation score — killed over total, with equivalent mutants and load errors excluded from the denominator — plus the survivors, the unpinned invariants. Survivors are the audit's output, not a scandal: some mutants are expected to survive and become entries on the unpinned list rather than red CI.
338
+
339
+ Run it when you want to know whether the suite still has teeth — after changing tests or coverage, or as a pre-release gate with `bun scripts/test-sweep.ts --fail-on-survivors`, which exits 4 when anything survives. Two cheaper checks come first: `bun scripts/test-sweep.ts --validate` confirms every mutation pattern still lands on exactly one source site without running the suite, and `bun scripts/test-sweep.ts --selftest` plants a mutation in a trivially-tested pure function and fails unless the suite kills it — proof the instrument itself can go red.
340
+
327
341
  ## Troubleshooting
328
342
 
329
343
  | Problem | Fix |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.15.5",
3
+ "version": "0.15.7",
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": {
@@ -5,12 +5,16 @@
5
5
  import { homedir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+ import { tightenDirectory } from "../permissions.ts";
8
9
 
9
10
  export function memoryRoot(): string {
10
- return (
11
+ const root = (
11
12
  process.env.OPENCODE_MEMORY_DIR ||
12
13
  join(homedir(), ".config", "opencode", "memory")
13
14
  );
15
+ // Protect old stores even on read-only use; do not create an absent store.
16
+ tightenDirectory(root);
17
+ return root;
14
18
  }
15
19
 
16
20
  // Where the plugin mirrors its own slash command (/repo-init). Written once at
@@ -2,18 +2,21 @@
2
2
  // Minimal logfmt reader/writer shared by the durable store and the evidence
3
3
  // log. Field order is preserved on write so chains are diffable.
4
4
  import { dirname } from "node:path";
5
- import { appendFile, mkdir, rename, stat, unlink } from "node:fs/promises";
5
+ import { mkdir, open, rename, stat, unlink } from "node:fs/promises";
6
+ import { constants } from "node:fs";
7
+ import { tightenDirectory } from "../permissions.ts";
6
8
  import { IS_WINDOWS } from "./format.ts";
7
9
 
8
10
  export async function ensureDir(path: string): Promise<void> {
9
- await mkdir(path, { recursive: true });
11
+ await mkdir(path, { recursive: true, mode: 0o700 });
12
+ tightenDirectory(path);
10
13
  }
11
14
 
12
15
  export async function appendLog(file: string, line: string): Promise<void> {
13
16
  await ensureDir(dirname(file));
14
17
  const next = line.endsWith("\n") ? line : line + "\n";
15
18
  // One O_APPEND write: read-modify-write loses rows under concurrent
16
- // appenders (20 concurrent appends left 2 on disk). appendFile's "a" flag is
19
+ // appenders (20 concurrent appends left 2 on disk). The handle uses
17
20
  // O_APPEND|O_CREAT — atomic small writes on local POSIX filesystems,
18
21
  // covering interleaved async tasks in the service AND a second process
19
22
  // (the viewer) appending the same day file. Do NOT "simplify" back to
@@ -21,7 +24,13 @@ export async function appendLog(file: string, line: string): Promise<void> {
21
24
  // Appending is safe against other appenders only. Callers writing a file that
22
25
  // is ALSO rewritten whole (a daily memory file, the blocklist) hold the store
23
26
  // lock around this — see lock.ts.
24
- await appendFile(file, next);
27
+ const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
28
+ try {
29
+ if (!IS_WINDOWS) await handle.chmod((await handle.stat()).mode & 0o600);
30
+ await handle.appendFile(next);
31
+ } finally {
32
+ await handle.close();
33
+ }
25
34
  }
26
35
 
27
36
  // A change-detection token for one file: any append, rewrite or replacement
@@ -57,11 +66,15 @@ export async function writeAtomic(file: string, content: string, since?: string)
57
66
  // name would let one call replace the bytes another call's anchored publish
58
67
  // is retrying. Keep separate temps even when the caller holds a lock.
59
68
  const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
69
+ let claimed = false;
60
70
  try {
71
+ const handle = await open(tmp, "wx", 0o600);
72
+ claimed = true;
73
+ await handle.close();
61
74
  await Bun.write(tmp, content);
62
75
  await handoverRename(tmp, file, since);
63
76
  } catch (err) {
64
- await unlink(tmp).catch(() => undefined);
77
+ if (claimed) await unlink(tmp).catch(() => undefined);
65
78
  throw err;
66
79
  }
67
80
  }
@@ -0,0 +1,47 @@
1
+ // POSIX modes protect local store data, not Windows ACLs. Never follow a
2
+ // final-component link while tightening permissions, or add owner access that
3
+ // an operator deliberately removed (e.g. a read-only store).
4
+ import { closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+
7
+ export function tightenDirectory(path: string): void {
8
+ if (process.platform === "win32") return;
9
+ let fd: number;
10
+ try {
11
+ fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
12
+ } catch (err) {
13
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
14
+ throw err;
15
+ }
16
+ try {
17
+ const mode = fstatSync(fd).mode & 0o7777;
18
+ const privateMode = mode & 0o700;
19
+ if (mode !== privateMode) {
20
+ try {
21
+ fchmodSync(fd, privateMode);
22
+ } catch (err) {
23
+ // A readable store may be immutable, foreign-owned, or on a mount
24
+ // without chmod support. Keep reads available without claiming that
25
+ // its existing permissions were tightened. Open-time refusals above
26
+ // remain policy errors; unexpected I/O failures still propagate.
27
+ const code = (err as NodeJS.ErrnoException).code;
28
+ if (!code || !["EPERM", "EROFS", "EOPNOTSUPP", "ENOSYS"].includes(code)) throw err;
29
+ }
30
+ }
31
+ } finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+
36
+ // Status publication keeps its existing Bun.write scheduling. Claim/tighten
37
+ // the file before that write, without first exposing its contents at 0644.
38
+ export function preparePrivateFile(path: string): void {
39
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
40
+ tightenDirectory(dirname(path));
41
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
42
+ try {
43
+ if (process.platform !== "win32") fchmodSync(fd, fstatSync(fd).mode & 0o600);
44
+ } finally {
45
+ closeSync(fd);
46
+ }
47
+ }
@@ -16,7 +16,7 @@
16
16
  // tests) and legacy rows predate the field: both read as GLOBAL — visible
17
17
  // everywhere — which keeps every upgrade non-breaking.
18
18
  import { createHash } from "node:crypto";
19
- import { realpathSync } from "node:fs";
19
+ import { lstatSync, realpathSync, statSync } from "node:fs";
20
20
 
21
21
  export interface RepoScope {
22
22
  key: string;
@@ -59,11 +59,91 @@ function git(args: string[], cwd: string): string | null {
59
59
  }
60
60
  }
61
61
 
62
+ // --- case-sensitivity probe (#109) --------------------------------------------
63
+ // Folding case by PLATFORM leaked rows across directories: a case-SENSITIVE
64
+ // APFS volume is a legitimate macOS choice (and NTFS has per-directory
65
+ // sensitivity), where "Foo" and "foo" really are two dirs that must not share
66
+ // one repo= key. Probe the filesystem instead: flip one cased character of the
67
+ // deepest existing component; if the flipped spelling still names the SAME
68
+ // dev+inode without following a symlink at the changed component, the probe
69
+ // accepts case folding. A case-variant symlink is an alias, not evidence of
70
+ // filesystem case folding. Answers cache per path (volume semantics do not
71
+ // change at runtime). The map is FIFO-capped like the session map.
72
+ // Undecided — nothing of the path exists, or no
73
+ // component carries case — falls back to the old platform rule, which is also
74
+ // a no-op whenever the path has no cased characters to fold.
75
+ const caseFoldCache = new Map<string, boolean>();
76
+
77
+ function statOrNull(p: string) {
78
+ try {
79
+ return statSync(p);
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ // Return the component whose LAST cased character is flipped. Trim any
86
+ // uncased descendants: lstat("Foo/123") would still follow a symlink at Foo,
87
+ // whereas lstat("Foo") lets the caller distinguish that alias from a real
88
+ // case-insensitive lookup. Index 0 stays untouched for Windows drive letters.
89
+ function caseProbePair(p: string): { original: string; flipped: string } | null {
90
+ for (let i = p.length - 1; i > 0; i--) {
91
+ const c = p[i];
92
+ const f = c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase();
93
+ if (f !== c) {
94
+ const suffix = p.slice(i).search(/[\\/]/);
95
+ const end = suffix < 0 ? p.length : i + suffix;
96
+ return {
97
+ original: p.slice(0, end),
98
+ flipped: p.slice(0, i) + f + p.slice(i + 1, end),
99
+ };
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Does the filesystem holding `dir` name-match across case? true = fold is
107
+ * safe; false = "Foo" and "foo" are distinct; null = undecided (fall back to
108
+ * the platform rule). Walks up to the nearest existing component when `dir`
109
+ * itself is gone, and flips an ancestor's name when the deepest name has no
110
+ * case to flip.
111
+ */
112
+ export function isCaseInsensitivePath(dir: string): boolean | null {
113
+ const cached = caseFoldCache.get(dir);
114
+ if (cached !== undefined) return cached;
115
+ let cur = dir;
116
+ for (let up = 0; up < 10; up++) {
117
+ const st = statOrNull(cur);
118
+ if (st) {
119
+ const pair = caseProbePair(cur);
120
+ if (pair) {
121
+ let ans = false;
122
+ try {
123
+ const original = lstatSync(pair.original);
124
+ const flipped = lstatSync(pair.flipped);
125
+ ans = !original.isSymbolicLink() && !flipped.isSymbolicLink()
126
+ && original.dev === flipped.dev && original.ino === flipped.ino;
127
+ } catch {
128
+ // Missing or unreadable alternate spelling cannot justify folding.
129
+ }
130
+ if (caseFoldCache.size >= 64)
131
+ caseFoldCache.delete(caseFoldCache.keys().next().value as string);
132
+ caseFoldCache.set(dir, ans);
133
+ return ans;
134
+ }
135
+ }
136
+ const parent = cur.replace(/[\\/]+$/, "").replace(/[\\/][^\\/]*$/, "");
137
+ if (!parent || parent === cur) break;
138
+ cur = parent;
139
+ }
140
+ return null;
141
+ }
142
+
62
143
  // Normalize a directory for hashing: symlinks, junctions, and Windows 8.3
63
144
  // aliases collapse to the real path (realpath), separators unify to "/",
64
- // a trailing separator disappears, and case folds ONLY on the
65
- // case-insensitive filesystems (win32/darwin) where two spellings are the
66
- // same directory — Linux folds nothing, there "Foo" and "foo" are two dirs.
145
+ // a trailing separator disappears, and case folds ONLY where the probe says
146
+ // the volume folds names itself (#109) — never trusting the platform alone.
67
147
  export function normalizeDirPath(p: string): string {
68
148
  let r = p;
69
149
  try {
@@ -72,7 +152,8 @@ export function normalizeDirPath(p: string): string {
72
152
  // deleted/unreadable mid-resolve: hash the given spelling rather than throw
73
153
  }
74
154
  r = r.replace(/\\/g, "/").replace(/\/+$/, "");
75
- if (process.platform === "win32" || process.platform === "darwin") r = r.toLowerCase();
155
+ const fold = isCaseInsensitivePath(r) ?? (process.platform === "win32" || process.platform === "darwin");
156
+ if (fold) r = r.toLowerCase();
76
157
  return r || "/";
77
158
  }
78
159
 
@@ -101,7 +101,7 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
101
101
  // existing link long before this runs, so the only way to test O_NOFOLLOW
102
102
  // without racing is to call the writer directly.
103
103
  export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
104
- await mkdir(dirname(path), { recursive: true });
104
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
105
105
  // exclusive = a default destination WE chose: create it or fail, never
106
106
  // silently replace another export's file. An explicit caller-supplied
107
107
  // `file` keeps the historical O_TRUNC replace (backup workflows rewrite
@@ -13,6 +13,7 @@
13
13
  //
14
14
  // Scope of v2: same-machine reads. Against a REMOTE server the terminal panel
15
15
  // sees no status files (it says so) — the RPC surface is the planned follow-up.
16
+ import { preparePrivateFile } from "../core/permissions.ts";
16
17
  import { readFile } from "node:fs/promises";
17
18
  import type { Attribution } from "../inject/attribution.ts";
18
19
  import { captureLag, ledgerIsYoung, rowsPerDay } from "./metrics.ts";
@@ -123,6 +124,7 @@ export const SESSION_FILE_CAP = 32;
123
124
 
124
125
  export async function writeJson(path: string, p: StatusPayload): Promise<boolean> {
125
126
  try {
127
+ preparePrivateFile(path);
126
128
  await Bun.write(path, JSON.stringify(p, null, 2) + "\n");
127
129
  return true;
128
130
  } catch {
@@ -64,10 +64,14 @@ async function pruneStatusDir(): Promise<void> {
64
64
  // Best-effort by design: a status write must never break injection. Writes the
65
65
  // per-session file (primary) AND the global latest file (fallback).
66
66
  export async function writeStatus(p: StatusPayload): Promise<void> {
67
- await writeJson(statusFile(), p);
68
- if (typeof p.sessionID === "string" && p.sessionID) {
69
- await writeJson(sessionStatusFile(p.sessionID), p);
70
- await pruneStatusDir();
67
+ try {
68
+ await writeJson(statusFile(), p);
69
+ if (typeof p.sessionID === "string" && p.sessionID) {
70
+ await writeJson(sessionStatusFile(p.sessionID), p);
71
+ await pruneStatusDir();
72
+ }
73
+ } catch {
74
+ // Resolving an existing root can also fail its permission check.
71
75
  }
72
76
  }
73
77
 
@@ -77,26 +81,34 @@ export async function writeStatus(p: StatusPayload): Promise<void> {
77
81
  * Without one: the global latest file.
78
82
  */
79
83
  export async function readStatus(sessionID?: string): Promise<StatusPayload | null> {
80
- if (sessionID) return readJson(sessionStatusFile(sessionID));
81
- return readJson(statusFile());
84
+ try {
85
+ if (sessionID) return await readJson(sessionStatusFile(sessionID));
86
+ return await readJson(statusFile());
87
+ } catch {
88
+ return null; // an inaccessible root is also "no data"
89
+ }
82
90
  }
83
91
 
84
92
  // Newest-first last `limit` write_blocked evidence rows, scanning today and
85
93
  // yesterday so a block just before midnight stays visible.
86
94
  export async function blockedRecent(limit = 6): Promise<BlockedRow[]> {
87
- const today = dateStr();
88
- const yesterday = new Date(Date.now() - 86_400_000).toISOString().split("T")[0]!;
89
- const rows: BlockedRow[] = [];
90
- for (const day of [yesterday, today]) {
91
- for (const line of await readLines(join(evidenceDir(), `${day}.logfmt`))) {
92
- const f = parseLine(line);
93
- if (!f || f.ev !== "write_blocked") continue;
94
- rows.push({
95
- ts: String(f.ts ?? day),
96
- sid: String(f.sid ?? "?"),
97
- reason: String(f.reason ?? "?"),
98
- });
95
+ try {
96
+ const today = dateStr();
97
+ const yesterday = new Date(Date.now() - 86_400_000).toISOString().split("T")[0]!;
98
+ const rows: BlockedRow[] = [];
99
+ for (const day of [yesterday, today]) {
100
+ for (const line of await readLines(join(evidenceDir(), `${day}.logfmt`))) {
101
+ const f = parseLine(line);
102
+ if (!f || f.ev !== "write_blocked") continue;
103
+ rows.push({
104
+ ts: String(f.ts ?? day),
105
+ sid: String(f.sid ?? "?"),
106
+ reason: String(f.reason ?? "?"),
107
+ });
108
+ }
99
109
  }
110
+ return rows.slice(-limit).reverse();
111
+ } catch {
112
+ return []; // A refused root is no status data, not an unhandled panel refresh.
100
113
  }
101
- return rows.slice(-limit).reverse();
102
114
  }
@@ -58,7 +58,7 @@ async function claimSnapshot(file: string): Promise<string> {
58
58
  for (;;) {
59
59
  const snap = join(snapshotDir(), `${stamp}-${basename(file)}`);
60
60
  try {
61
- const handle = await open(snap, "wx");
61
+ const handle = await open(snap, "wx", 0o600);
62
62
  await handle.close();
63
63
  return snap;
64
64
  } catch (err) {
package/src/store/lock.ts CHANGED
@@ -21,7 +21,8 @@
21
21
  // Readers take NO lock: publishers hand over the new file with a rename
22
22
  // (writeAtomic in logfmt.ts), so a reader always sees a complete store, never
23
23
  // the middle of a rewrite.
24
- import { mkdir, open, stat, unlink } from "node:fs/promises";
24
+ import { open, stat, unlink } from "node:fs/promises";
25
+ import { ensureDir } from "../core/logfmt/publish.ts";
25
26
  import { basename, dirname } from "node:path";
26
27
  import { record } from "../evidence/record.ts";
27
28
 
@@ -140,7 +141,7 @@ export async function holdFileLock<T>(
140
141
  budgetMs: number,
141
142
  now: () => number = Date.now,
142
143
  ): Promise<T> {
143
- await mkdir(dirname(lockPath), { recursive: true });
144
+ await ensureDir(dirname(lockPath));
144
145
  const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
145
146
  const started = now();
146
147
  let backoff = MIN_BACKOFF_MS;
@@ -155,7 +156,7 @@ export async function holdFileLock<T>(
155
156
  let everSawHolder = false;
156
157
  for (;;) {
157
158
  try {
158
- const handle = await open(lockPath, "wx");
159
+ const handle = await open(lockPath, "wx", 0o600);
159
160
  try {
160
161
  await handle.write(token);
161
162
  } finally {