opencode-self-improvement 0.14.22 → 0.14.24

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.14.22",
3
+ "version": "0.14.24",
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
@@ -3,6 +3,7 @@
3
3
  // path: recall, the injected digest and contextual pull, and the viewer's
4
4
  // active list. Blocklist lives at <memoryRoot>/blocklist.logfmt so a recursive
5
5
  // memory scan must never pick it up.
6
+ import { readFile } from "node:fs/promises";
6
7
  import { join } from "node:path";
7
8
  import { memoryRoot } from "./config.ts";
8
9
  import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
@@ -57,10 +58,15 @@ export async function removeBlock(ts: string): Promise<boolean> {
57
58
  return withStoreLock(
58
59
  file,
59
60
  async () => {
60
- const store = Bun.file(file);
61
- if (!(await store.exists())) return false;
62
61
  const since = await fileIdentity(file);
63
- const kept = (await store.text()).split("\n").filter((l) => {
62
+ let text: string;
63
+ try {
64
+ text = await readFile(file, "utf8");
65
+ } catch (err) {
66
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
67
+ throw err;
68
+ }
69
+ const kept = text.split("\n").filter((l) => {
64
70
  const row = parseLine(l);
65
71
  return !(row && row.ts === ts);
66
72
  });
package/src/gates.ts CHANGED
@@ -14,11 +14,12 @@ import {
14
14
  type SupersedeFields,
15
15
  } from "./memory.ts";
16
16
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
17
- import { noteAuthored } from "./state.ts";
17
+ import { getCurrent, noteAuthored } from "./state.ts";
18
18
  import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
19
19
  import { flattenMemoryText } from "./sanitize.ts";
20
20
  import { containsSecret, redactSecrets } from "./secrets.ts";
21
- import { readerForSession } from "./memory.ts";
21
+ import { readerFromSid, UnresolvedWriterError, type Reader } from "./memory.ts";
22
+ import { writeTarget, type WriteTarget } from "./repokey.ts";
22
23
  import {
23
24
  displayCall,
24
25
  extractCallForms,
@@ -69,6 +70,11 @@ export const auditCaveat = (outcome: GateOutcome): string =>
69
70
 
70
71
  export interface GateContext {
71
72
  liveRoot: string;
73
+ // Capture authority before awaiting locks, model calls, or gate evidence.
74
+ // Named callers read their repo; named-unbound callers read global-only;
75
+ // absent/"?" callers capture ambient authority at entry (not after awaits).
76
+ reader?: Reader;
77
+ writeAt?: WriteTarget;
72
78
  evidenceCalls: string[];
73
79
  // Total before the telemetry window was selected. Legacy/direct callers
74
80
  // may still supply their complete list; the writer bounds that too.
@@ -274,6 +280,8 @@ export async function runWriteGate(
274
280
  candidate: WriteCandidate,
275
281
  ctx: GateContext,
276
282
  ): Promise<GateOutcome> {
283
+ const reader = ctx.reader ?? readerFromSid(ctx.sessionID);
284
+ const writeAt = ctx.writeAt ?? writeTarget(ctx.sessionID ?? getCurrent().sid);
277
285
  const chain = chainId();
278
286
  // Gate audit lines thread the session: runWriteGate awaits (analysis, the
279
287
  // locked append), and another session's dispatch can move the ambient
@@ -379,13 +387,7 @@ export async function runWriteGate(
379
387
  const scopeMems = candidate.scope
380
388
  ? await loadScope(
381
389
  candidate.scope,
382
- // Dedup/stale reads partition on the WRITE's session, captured at
383
- // flow entry — not the ambient current after this await (#127). An
384
- // unknown "?" (or absent) caller is the readerFromSid AMBIENT case,
385
- // exactly as before: readerForSession is for named sessions only.
386
- ctx.sessionID !== undefined && ctx.sessionID !== "?"
387
- ? readerForSession(ctx.sessionID)
388
- : undefined,
390
+ reader,
389
391
  )
390
392
  : [];
391
393
  // One tree index per write, shared by gate1 and every gate2 stale scan.
@@ -740,7 +742,15 @@ export async function runWriteGate(
740
742
  const snapshot = await snapshotFiles([join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`)]);
741
743
  // The write carries the CALLER's session, not whatever current says after
742
744
  // the gate's own awaits - capture's stamp must follow the captured session.
743
- const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
745
+ if (candidate.repo === undefined && !writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
746
+ // A captured unscoped ambient writer deliberately publishes repo=global.
747
+ // Leaving repo undefined would make appendMemory resolve ambient ownership
748
+ // again after awaits. This changes the old unstamped shape: exports now keep
749
+ // this row global on import instead of adopting the importing repository.
750
+ const owner = candidate.repo === undefined && writeAt.ok
751
+ ? { repo: writeAt.scope?.key ?? "global", repoPath: writeAt.scope?.path }
752
+ : {};
753
+ const ts = await appendMemory({ ...candidate, ...owner, sessionID: ctx.sessionID });
744
754
  // #165: remember who made this row, so the writing session is not billed a
745
755
  // prompt-cache bust to be shown its own thought. Only promoted writes are
746
756
  // attributed — a blocked candidate created nothing.
package/src/hits.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  // is in memory.ts's RESERVED set so loadAll() cannot ingest it), and it logs no
15
15
  // prompt text — only the tokens a row and the query shared, each of which
16
16
  // already exists inside that row.
17
+ import { readFile, stat } from "node:fs/promises";
17
18
  import { join } from "node:path";
18
19
  import { memoryRoot, HITS_FILENAME } from "./config.ts";
19
20
  import { appendLog, bracketList, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
@@ -63,14 +64,19 @@ export function resetHitThrottle(): void {
63
64
  }
64
65
 
65
66
  async function rotateIfNeeded(): Promise<void> {
66
- const file = Bun.file(hitsFile());
67
- const size = await file.size;
67
+ let size: number;
68
+ try {
69
+ size = (await stat(hitsFile())).size;
70
+ } catch (err) {
71
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
72
+ throw err;
73
+ }
68
74
  if (size <= MAX_HITS_BYTES) return;
69
75
  // #106: anchor the halving like every other whole-file publish (#89) - on
70
76
  // Windows the rename can be refused by a reader's handle, and the retry is
71
77
  // only safe while nothing else moved this file.
72
78
  const since = await fileIdentity(hitsFile());
73
- const lines = (await file.text()).split("\n").filter((l) => l.trim());
79
+ const lines = (await readFile(hitsFile(), "utf8")).split("\n").filter((l) => l.trim());
74
80
  await writeAtomic(hitsFile(), lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n", since);
75
81
  }
76
82
 
package/src/index.ts CHANGED
@@ -296,6 +296,8 @@ const impl = {
296
296
  const bound = sid ?? getCurrent().sid;
297
297
  return {
298
298
  sessionID: sid,
299
+ reader: readerFromSid(sid),
300
+ writeAt: writeTarget(bound),
299
301
  // NOTE (re-review): this one lookup is intentionally NON-firm — a
300
302
  // provisional binding may supply the gate's verification TREE. The
301
303
  // tree is where a referenced file is checked to exist, not who the
@@ -687,7 +689,7 @@ const impl = {
687
689
  repo: requested.repo,
688
690
  repoPath: target.repo ? target.repoPath : undefined,
689
691
  },
690
- { ...gateContext(sid), supersedesTs: target.ts, durable: gateDurable },
692
+ { ...gateContext(sid), reader, supersedesTs: target.ts, durable: gateDurable },
691
693
  );
692
694
  if (outcome.action === "promoted" && outcome.ts && target) {
693
695
  mutated = true;
@@ -1137,13 +1139,14 @@ const impl = {
1137
1139
  await bindSessionIdentity(sid);
1138
1140
  const ownerless = ownerlessWriter(sid);
1139
1141
  if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
1142
+ const importGate = gateContext(sid);
1140
1143
  try {
1141
1144
  const t = await importMemories(
1142
1145
  args.file,
1143
1146
  (c) =>
1144
1147
  runWriteGate(
1145
1148
  { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
1146
- gateContext(sid),
1149
+ importGate,
1147
1150
  ),
1148
1151
  sid,
1149
1152
  );
@@ -1529,6 +1532,7 @@ const impl = {
1529
1532
  await record("auto_capture_refused", { session: sid, trigger }, true, sid);
1530
1533
  return;
1531
1534
  }
1535
+ const captureGate = gateContext(sid);
1532
1536
  let transcript = seeded;
1533
1537
  let msgs = seededMsgs;
1534
1538
  if (transcript.length < 200) {
@@ -1561,7 +1565,7 @@ const impl = {
1561
1565
  ? ["auto-capture", CAPTURE_COMPACT_TAG]
1562
1566
  : ["auto-capture"],
1563
1567
  },
1564
- gateContext(sid),
1568
+ captureGate,
1565
1569
  );
1566
1570
  await record(
1567
1571
  trigger === "compaction"
package/src/init.ts CHANGED
@@ -8,10 +8,11 @@
8
8
  import { basename, join } from "node:path";
9
9
  import { existsSync } from "node:fs";
10
10
  import { cbmBin } from "./config.ts";
11
- import { isVisibleTo, loadAll, markSuperseded, readerFromSid } from "./memory.ts";
11
+ import { isVisibleTo, loadAll, markSuperseded, readerFromSid, type Reader } from "./memory.ts";
12
12
  import { runWriteGate, type GateContext } from "./gates.ts";
13
13
  import { record } from "./evidence.ts";
14
14
  import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
+ import { writeTarget } from "./repokey.ts";
15
16
  import { getCurrent } from "./state.ts";
16
17
 
17
18
  export interface ScriptRecord {
@@ -190,13 +191,12 @@ export interface InitStamp {
190
191
  head: string;
191
192
  }
192
193
 
193
- export async function initStamp(scope: string, sid?: string): Promise<InitStamp | null> {
194
+ export async function initStamp(scope: string, sid?: string, reader: Reader = readerFromSid(sid)): Promise<InitStamp | null> {
194
195
  // Scope is a basename, so two different repos can share one
195
196
  // ("api" next to "api", a fork beside its upstream). Visibility filtering
196
197
  // makes each repo see only its own stamp — basename collisions no longer
197
198
  // alias init state between repos. The reader comes from the CALLER's
198
199
  // session, not from the global current after this await (#127).
199
- const reader = readerFromSid(sid);
200
200
  const mems = (await loadAll()).filter((m) => !m.superseded_by && isVisibleTo(m, reader));
201
201
  for (const m of mems) {
202
202
  if (m.type !== "context" || m.scope !== scope) continue;
@@ -208,6 +208,8 @@ export async function initStamp(scope: string, sid?: string): Promise<InitStamp
208
208
  }
209
209
 
210
210
  export async function runInit(args: InitArgs): Promise<InitSummary> {
211
+ const reader = readerFromSid(args.sessionID);
212
+ const writeAt = writeTarget(args.sessionID ?? getCurrent().sid);
211
213
  const root = await gitRootOf(args.liveRoot);
212
214
  const scope = basename(root) || basename(args.liveRoot);
213
215
  const head = await gitHead(root);
@@ -216,6 +218,8 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
216
218
 
217
219
  const gateCtx: GateContext = {
218
220
  liveRoot: root,
221
+ reader,
222
+ writeAt,
219
223
  ...writeEvidence(args.sessionID ?? getCurrent().sid),
220
224
  hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
221
225
  // Stamps land on the caller's session even though runInit awaits git
@@ -224,7 +228,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
224
228
  trusted: true,
225
229
  };
226
230
 
227
- const prior = await initStamp(scope, args.sessionID);
231
+ const prior = await initStamp(scope, args.sessionID, reader);
228
232
  if (prior && !force && prior.head === head) {
229
233
  await record("init_skip", { scope, head, since: prior.ts }, false);
230
234
  return {
package/src/memory.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // vendor/opencode-memory/LICENSE) and extends it with the fields the write-gate
4
4
  // needs: supersession markers, snapshots and audited deletion.
5
5
  import { existsSync } from "node:fs";
6
- import { open } from "node:fs/promises";
6
+ import { open, readFile } from "node:fs/promises";
7
7
  import { join, basename } from "node:path";
8
8
  import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
9
9
  import { repoScopeFor, sessionScope, writeTarget, type RepoScope } from "./repokey.ts";
@@ -570,10 +570,15 @@ async function claimSnapshot(file: string): Promise<string> {
570
570
  export async function snapshotFiles(files: string[]): Promise<string[]> {
571
571
  const snaps: string[] = [];
572
572
  for (const file of files) {
573
- const f = Bun.file(file);
574
- if (!(await f.exists())) continue;
573
+ let contents: Buffer;
574
+ try {
575
+ contents = await readFile(file);
576
+ } catch (err) {
577
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
578
+ throw err;
579
+ }
575
580
  const snap = await claimSnapshot(file);
576
- await Bun.write(snap, await f.text());
581
+ await Bun.write(snap, contents);
577
582
  snaps.push(snap);
578
583
  }
579
584
  return snaps;
package/src/portable.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // moat. Decay is supersede-not-delete and snapshot-first, mirroring prune.
6
6
  import { constants } from "node:fs";
7
7
  import { randomUUID } from "node:crypto";
8
- import { mkdir, open } from "node:fs/promises";
8
+ import { mkdir, open, readFile } from "node:fs/promises";
9
9
  import { dirname, join } from "node:path";
10
10
  import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
11
11
  import { resolveContained } from "./containment.ts";
@@ -288,6 +288,10 @@ export async function importMemories(
288
288
  // the ambient current.
289
289
  sessionID?: string,
290
290
  ): Promise<ImportTally> {
291
+ // Capture the importing owner before file I/O: later session moves must not
292
+ // re-home rows partway through the import (#183). Resolve with the writer
293
+ // rule so an unresolved named session never borrows the ambient repo (#152).
294
+ const writeAt = writeTarget(sessionID ?? getCurrent().sid);
291
295
  const target = await resolveContained(path, memoryRoot(), {
292
296
  label: "memory_import file",
293
297
  // Deliberately no mention of the operator escape hatch: this string goes
@@ -299,20 +303,21 @@ export async function importMemories(
299
303
  if (!target.toLowerCase().endsWith(".jsonl")) {
300
304
  throw new Error(`memory_import file must be a .jsonl export (got "${path}")`);
301
305
  }
302
- const file = Bun.file(target);
303
- if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
306
+ let text: string;
307
+ try {
308
+ text = await readFile(target, "utf8");
309
+ } catch (err) {
310
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") throw new Error(`import file not found: ${target}`);
311
+ throw err;
312
+ }
304
313
  const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
305
- // #152: the importing session's repository is resolved BEFORE the first row,
306
- // through the writer rule rather than the ambient one. An unresolved named
307
- // session has no write target, and half a file re-stamped into whatever
308
- // workspace happened to set up last is worse than none — so this throws
309
- // before a single row is gated, not partway through the tally.
310
- const writeAt = writeTarget(sessionID ?? getCurrent().sid);
314
+ // Preserve file-validation error precedence, but reject an unresolved owner
315
+ // before gating any row. Resolution happened at entry, not at this await.
311
316
  if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
312
317
  const currentScope = writeAt.scope;
313
318
  let allowFrontier = false;
314
319
  let first = true;
315
- for (const line of (await file.text()).split("\n")) {
320
+ for (const line of text.replace(/^\uFEFF/, "").split("\n")) {
316
321
  if (!line.trim()) continue;
317
322
  if (first) {
318
323
  first = false;
package/src/status.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // Scope of v2: same-machine reads. Against a REMOTE server the terminal panel
14
14
  // sees no status files (it says so) — the RPC surface is the planned follow-up.
15
- import { readdir, rm, stat } from "node:fs/promises";
15
+ import { readFile, readdir, rm, stat } from "node:fs/promises";
16
16
  import { join } from "node:path";
17
17
  import { dateStr, evidenceDir, memoryRoot } from "./config.ts";
18
18
  import { parseLine, readLines } from "./logfmt.ts";
@@ -247,9 +247,7 @@ export async function writeStatus(p: StatusPayload): Promise<void> {
247
247
 
248
248
  async function readJson(path: string): Promise<StatusPayload | null> {
249
249
  try {
250
- const f = Bun.file(path);
251
- if (!(await f.exists())) return null;
252
- const v: unknown = await f.json();
250
+ const v: unknown = JSON.parse((await readFile(path, "utf8")).replace(/^\uFEFF/, ""));
253
251
  if (!v || typeof v !== "object") return null;
254
252
  const p = v as Partial<StatusPayload>;
255
253
  if (typeof p.at !== "string" || typeof p.block !== "string") return null;
package/src/undo.ts CHANGED
@@ -24,7 +24,7 @@
24
24
  // what you may read", the same rule memory_forget applies to global scope.
25
25
  // Admin readers (the viewer, out-of-plugin maintenance) keep the whole-file
26
26
  // restore exactly as it was.
27
- import { lstat, realpath, stat } from "node:fs/promises";
27
+ import { lstat, readFile, realpath, stat } from "node:fs/promises";
28
28
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
29
29
  import { deletionsFile, snapshotDir } from "./config.ts";
30
30
  import { isWithin } from "./containment.ts";
@@ -213,7 +213,7 @@ export async function restoreSnapshot(
213
213
  // Checks above ran on real paths; lock and write through the same lexical
214
214
  // path every other writer uses, so the in-process lock queue is shared.
215
215
  const target = resolve(memoryRootDir, snap.original);
216
- const rawSnapLines = rows(await Bun.file(snap.path).text());
216
+ const rawSnapLines = rows(await readFile(snap.path, "utf8"));
217
217
 
218
218
  // Comparing and publishing happen under the same lock: a divergence check on
219
219
  // a stale read would wave through a row that landed after it. A restore waits
@@ -226,8 +226,13 @@ export async function restoreSnapshot(
226
226
  // Identity before the first read of `target` here: everything published
227
227
  // below derives from what this read sees (logfmt.ts handoverRename).
228
228
  const since = await fileIdentity(target);
229
- const cur = Bun.file(target);
230
- const curLines = (await cur.exists()) ? rows(await cur.text()) : [];
229
+ let current = "";
230
+ try {
231
+ current = await readFile(target, "utf8");
232
+ } catch (err) {
233
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
234
+ }
235
+ const curLines = rows(current);
231
236
  // Deliberate deletions are read inside the lock too, so a forget that
232
237
  // finished just before this restore is honoured.
233
238
  const audited = mode !== "force" ? await auditedDeletions() : new Set<string>();