opencode-self-improvement 0.14.4 → 0.14.6

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.4",
3
+ "version": "0.14.6",
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/gates.ts CHANGED
@@ -50,6 +50,10 @@ export interface GateContext {
50
50
  liveRoot: string;
51
51
  evidenceCalls: string[];
52
52
  hasGateCheck: boolean;
53
+ // The session this write belongs to, when the caller knows it by name.
54
+ // Repo-stamp resolution prefers it over the mutable global current, which
55
+ // a capture's model-call await can outlive into another session (#116).
56
+ sessionID?: string;
53
57
  // True when the session exercised the code (read/grep/edit/bash results
54
58
  // recorded). Empirical engagement substitutes for hand-copied refs (gate
55
59
  // injection): the write encodes behavior that actually happened here, so the
@@ -606,7 +610,9 @@ export async function runWriteGate(
606
610
  }
607
611
 
608
612
  const snapshot = await snapshotFiles([join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`)]);
609
- const ts = await appendMemory(candidate);
613
+ // The write carries the CALLER's session, not whatever current says after
614
+ // the gate's own awaits - capture's stamp must follow the captured session.
615
+ const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
610
616
  await record("write_promoted", {
611
617
  gate: 4,
612
618
  op: "write",
package/src/index.ts CHANGED
@@ -268,12 +268,21 @@ const impl = {
268
268
  }
269
269
  }
270
270
 
271
- const gateContext = (): GateContext => ({
272
- liveRoot: sessionDir(getCurrent().sid) ?? liveRoot,
273
- evidenceCalls: evidenceCalls(getCurrent().sid),
274
- hasGateCheck: hasGateCheck(getCurrent().sid),
275
- hasEngagement: hasEngagement(getCurrent().sid),
276
- });
271
+ const gateContext = (sid?: string): GateContext => {
272
+ // Every session-scoped member resolves for the CALLER's session when it
273
+ // knows one (#116): capture awaits a model call between setCurrent and
274
+ // persistence, and on a multi-session server the global current moves
275
+ // during that await. Falling back to getCurrent() is exactly today's
276
+ // behavior for callers whose current IS their session (tool hooks).
277
+ const bound = sid ?? getCurrent().sid;
278
+ return {
279
+ sessionID: sid,
280
+ liveRoot: sessionDir(bound) ?? liveRoot,
281
+ evidenceCalls: evidenceCalls(bound),
282
+ hasGateCheck: hasGateCheck(bound),
283
+ hasEngagement: hasEngagement(bound),
284
+ };
285
+ };
277
286
 
278
287
  // Identity-event race backstop: a resumed session's FIRST turn can write
279
288
  // before the subscription has delivered its execution.started, and the
@@ -1124,8 +1133,10 @@ const impl = {
1124
1133
  trigger: "idle" | "compaction",
1125
1134
  seededMsgs?: unknown,
1126
1135
  ): Promise<void> {
1127
- // Bind the capturing session so captures stamp (and gate against)
1128
- // that session's repo, not whatever tool call ran last.
1136
+ // Bind the capturing session for the synchronous stretches of this
1137
+ // path - but NOT as a promise: the awaits below let another session
1138
+ // move current, so the gate context and the persisted rows thread
1139
+ // `sid` explicitly instead of reading it back from the global (#116).
1129
1140
  setCurrent({ sessionID: sid });
1130
1141
  let transcript = seeded;
1131
1142
  let msgs = seededMsgs;
@@ -1154,7 +1165,7 @@ const impl = {
1154
1165
  ? ["auto-capture", CAPTURE_COMPACT_TAG]
1155
1166
  : ["auto-capture"],
1156
1167
  },
1157
- gateContext(),
1168
+ gateContext(sid),
1158
1169
  );
1159
1170
  await record(
1160
1171
  trigger === "compaction"
package/src/lock.ts CHANGED
@@ -90,13 +90,17 @@ async function timed(prev: Promise<void>, ms: number): Promise<boolean> {
90
90
 
91
91
  // The one probe that can answer "there is no holder" without itself being a
92
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> {
93
+ // reads with the handle owner), ENOENT — uniquely — proves absence, and any
94
+ // other answer (an ACL that lets us neither create nor see, say) is no answer
95
+ // at all: it must count as neither.
96
+ type LockProbe = "present" | "absent" | "unknown";
97
+
98
+ async function probeLock(lockPath: string): Promise<LockProbe> {
95
99
  try {
96
100
  await stat(lockPath);
97
- return false;
101
+ return "present";
98
102
  } catch (probe) {
99
- return (probe as NodeJS.ErrnoException).code === "ENOENT";
103
+ return (probe as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unknown";
100
104
  }
101
105
  }
102
106
 
@@ -121,20 +125,32 @@ async function stealIfStale(lockPath: string, now: number): Promise<boolean> {
121
125
  return true;
122
126
  }
123
127
 
124
- /** Cross-process half: hold the lock file while `fn` runs. */
125
- async function holdFileLock<T>(
128
+ /**
129
+ * Cross-process half: hold the lock file while `fn` runs. `now` is a seam for
130
+ * tests that must land the budget deadline inside a specific probe iteration;
131
+ * production callers never pass it and the real clock is used.
132
+ */
133
+ export async function holdFileLock<T>(
126
134
  lockPath: string,
127
135
  file: string,
128
136
  fn: () => Promise<T>,
129
137
  opts: LockOptions,
130
138
  budgetMs: number,
139
+ now: () => number = Date.now,
131
140
  ): Promise<T> {
132
141
  await mkdir(dirname(lockPath), { recursive: true });
133
142
  const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
134
- const started = Date.now();
143
+ const started = now();
135
144
  let backoff = MIN_BACKOFF_MS;
136
145
  let firstErr: unknown;
137
146
  let absentStrikes = 0;
147
+ // #107: did ANY probe see a lock file during this wait? The rethrow at the
148
+ // deadline promises we never proceed as a stranger to the lock file — but
149
+ // `absentStrikes > 0` only remembers the LAST probe, so a holder that
150
+ // legitimately finished and unlinked just as the budget expired was
151
+ // throwing away ordinary writes instead of taking the contention
152
+ // concession it describes.
153
+ let everSawHolder = false;
138
154
  for (;;) {
139
155
  try {
140
156
  const handle = await open(lockPath, "wx");
@@ -157,27 +173,31 @@ async function holdFileLock<T>(
157
173
  // wait for — our own ability to create files is what is broken, and
158
174
  // the original error must surface instead of rotting into a timeout.
159
175
  firstErr ??= err;
160
- if (await lockFileAbsent(lockPath)) {
176
+ const seen = await probeLock(lockPath);
177
+ if (seen === "absent") {
161
178
  if (++absentStrikes >= ABSENT_THROW_STRIKES) throw firstErr;
162
179
  } else {
163
180
  absentStrikes = 0;
181
+ if (seen === "present") everSawHolder = true;
164
182
  }
165
- if (await stealIfStale(lockPath, Date.now())) {
166
- opts.onEvent?.("steal", Date.now() - started);
183
+ if (await stealIfStale(lockPath, now())) {
184
+ opts.onEvent?.("steal", now() - started);
167
185
  continue;
168
186
  }
169
- if (Date.now() - started >= budgetMs) {
170
- opts.onEvent?.("timeout", Date.now() - started);
187
+ if (now() - started >= budgetMs) {
188
+ opts.onEvent?.("timeout", now() - started);
171
189
  if (opts.onTimeout === "fail") {
172
190
  throw new Error(
173
- `memory store is busy: ${basename(file)} has been locked for ${Date.now() - started}ms — retry`,
191
+ `memory store is busy: ${basename(file)} has been locked for ${now() - started}ms — retry`,
174
192
  );
175
193
  }
176
194
  // 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;
195
+ // contention — but never while we have seen the lock file not even
196
+ // once: on a filesystem where we cannot create it, writing "unlocked"
197
+ // would just mean writing unguarded. A holder we DID see and then lost
198
+ // is ordinary contention, and belongs to the concession (#107 —
199
+ // `absentStrikes > 0` remembered only the last probe, not the wait).
200
+ if (!everSawHolder) throw firstErr;
181
201
  return fn();
182
202
  }
183
203
  await sleep(backoff);
package/src/memory.ts CHANGED
@@ -200,6 +200,9 @@ export interface AppendMemoryInput {
200
200
  // appendMemory against the live repo scope.
201
201
  repo?: string;
202
202
  repoPath?: string;
203
+ // Which session the write belongs to, when the caller knows it (the gate
204
+ // threads it from GateContext, #116). Preferred over the ambient current.
205
+ sessionID?: string;
203
206
  }
204
207
 
205
208
  // ts values already in `file`. An appended row's ts is "now", so the only rows
@@ -262,7 +265,11 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
262
265
  let repo = input.repo;
263
266
  let repoPath = input.repoPath;
264
267
  if (repo === undefined) {
265
- const cur = repoScopeFor(getCurrent().sid);
268
+ // The caller's session when it named one: capture awaits a model call, and
269
+ // the last setCurrent before persistence may belong to another session
270
+ // entirely (#116). Unnamed writers (tools, viewer, restore) keep the
271
+ // ambient binding.
272
+ const cur = repoScopeFor(input.sessionID ?? getCurrent().sid);
266
273
  if (cur) {
267
274
  repo = cur.key;
268
275
  repoPath = cur.path;