opencode-self-improvement 0.14.13 → 0.14.14

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
@@ -95,7 +95,7 @@ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget`
95
95
 
96
96
  Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
97
97
 
98
- Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
98
+ Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Writes follow that rule in the stricter direction: a named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing — the alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row. A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
99
99
 
100
100
  ## Token cost and caching
101
101
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.13",
3
+ "version": "0.14.14",
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/index.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  readerFromSid,
28
28
  resolveMemoryTarget,
29
29
  snapshotFiles,
30
+ unresolvedWriteMessage,
30
31
  visibleTo,
31
32
  type Memory,
32
33
  } from "./memory.ts";
@@ -81,7 +82,7 @@ import {
81
82
  onCompacting,
82
83
  } from "./triggers.ts";
83
84
  import { getCurrent, setCurrent } from "./state.ts";
84
- import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional } from "./repokey.ts";
85
+ import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
85
86
  import { parseLine, readLines } from "./logfmt.ts";
86
87
  import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
87
88
  import { redactSecrets } from "./secrets.ts";
@@ -343,6 +344,24 @@ const impl = {
343
344
  };
344
345
  };
345
346
 
347
+ // A durable write needs an OWNER (#152). Reads already fail closed for a
348
+ // session whose repository never resolved — it sees global rows and nothing
349
+ // else — so such a session may not write either: the alternatives were the
350
+ // last setup's repository or an unstamped (hence global) row. This answers
351
+ // at the entry, where the model can be told what to do, and records the
352
+ // refusal so "why is nothing stored" is answerable from memory_evidence.
353
+ // appendMemory throws the same rule at the choke point; the two share one
354
+ // message so they cannot drift.
355
+ const ownerlessWriter = (sid: string | undefined): string | null => {
356
+ const target = writeTarget(sid);
357
+ return target.ok ? null : target.sid;
358
+ };
359
+
360
+ const refuseOwnerlessWrite = async (sid: string, op: string): Promise<{ content: string }> => {
361
+ await record("write_refused", { op }, true, sid);
362
+ return { content: unresolvedWriteMessage(sid) };
363
+ };
364
+
346
365
  // Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
347
366
  // the first await of the call comes after this. The V2 host hands every
348
367
  // execute a per-call ToolContext carrying sessionID; the harness and any
@@ -457,6 +476,12 @@ const impl = {
457
476
  repo: args.global ? "global" : undefined,
458
477
  };
459
478
  await bindSessionIdentity(sid);
479
+ // An explicit global write needs no repository owner; anything else
480
+ // does (#152).
481
+ if (!args.global) {
482
+ const ownerless = ownerlessWriter(sid);
483
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
484
+ }
460
485
  const outcome = await runWriteGate(candidate, gateContext(sid));
461
486
  if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
462
487
  if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
@@ -503,6 +528,8 @@ const impl = {
503
528
  async execute(args, context): Promise<{ content: string }> {
504
529
  const { sid } = toolIds(context);
505
530
  await bindSessionIdentity(sid);
531
+ const ownerless = ownerlessWriter(sid);
532
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "init");
506
533
  const summary = await runInit({
507
534
  liveRoot: gateContext(sid).liveRoot,
508
535
  force: args.force,
@@ -563,6 +590,8 @@ const impl = {
563
590
  async execute(args, context): Promise<{ content: string }> {
564
591
  const { sid } = toolIds(context);
565
592
  await bindSessionIdentity(sid);
593
+ const ownerless = ownerlessWriter(sid);
594
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
566
595
  const reader = readerFromSid(sid);
567
596
  // The whole update — resolve, gate, supersede — runs under one
568
597
  // UPDATE-ORDER lock. Without it, two concurrent updates that both
@@ -896,6 +925,12 @@ const impl = {
896
925
  options: direct,
897
926
  async execute(args, context): Promise<{ content: string }> {
898
927
  const { sid } = toolIds(context);
928
+ // Resolve before touching the file: every imported row is re-stamped
929
+ // with the IMPORTING session's repository, so an unresolved caller
930
+ // would move a whole export into whoever set up last (#152).
931
+ await bindSessionIdentity(sid);
932
+ const ownerless = ownerlessWriter(sid);
933
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
899
934
  try {
900
935
  const t = await importMemories(
901
936
  args.file,
@@ -1440,6 +1475,14 @@ const impl = {
1440
1475
  // no-op there). SYNC only: a lookup call here would break the
1441
1476
  // zero-token promise of the capture tests.
1442
1477
  bindSessionProvisional(sid, instanceDir);
1478
+ // #152: an instance with no workspace cannot say which repository the
1479
+ // mined rows belong to, and rows with no owner are exactly what the
1480
+ // store refuses. Skip BEFORE the model call — no tokens spent on a
1481
+ // capture that cannot be stored — and leave the reason in evidence.
1482
+ if (!writeTarget(sid).ok) {
1483
+ await record("auto_capture_refused", { session: sid, trigger }, true, sid);
1484
+ return;
1485
+ }
1443
1486
  let transcript = seeded;
1444
1487
  let msgs = seededMsgs;
1445
1488
  if (transcript.length < 200) {
package/src/memory.ts CHANGED
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
6
6
  import { open } 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
- import { repoScopeFor, sessionScope, type RepoScope } from "./repokey.ts";
9
+ import { repoScopeFor, sessionScope, writeTarget, type RepoScope } from "./repokey.ts";
10
10
  import { getCurrent } from "./state.ts";
11
11
  import {
12
12
  appendLog,
@@ -219,6 +219,30 @@ async function existingTs(file: string): Promise<Set<string>> {
219
219
  return set;
220
220
  }
221
221
 
222
+ // #152: the store's answer to a write whose owner it cannot determine. Thrown
223
+ // from the one place that knows what an owner is (the stamp resolution below),
224
+ // so no caller — gate, import, capture, or a future one — can quietly persist
225
+ // an ownerless row. `unresolvedWriteMessage` is the same text the model-facing
226
+ // tools return, kept here so the two can never drift.
227
+ export function unresolvedWriteMessage(sid: string): string {
228
+ return (
229
+ `Write refused: session ${sid} has no resolvable repository, so nothing was stored. ` +
230
+ `A memory with no owner must not be stamped into another repository or published as a ` +
231
+ `global row. Retry from a session in the project you mean, or pass global:true for a ` +
232
+ `deliberate cross-project memory.`
233
+ );
234
+ }
235
+
236
+ export class UnresolvedWriterError extends Error {
237
+ /** The named-but-unresolved session whose write was refused. */
238
+ sid: string;
239
+ constructor(sid: string) {
240
+ super(unresolvedWriteMessage(sid));
241
+ this.name = "UnresolvedWriterError";
242
+ this.sid = sid;
243
+ }
244
+ }
245
+
222
246
  // Append a durable memory. GATE-4 promotions and the viewer's edit/restore-entry
223
247
  // paths all call this single write choke point.
224
248
  export async function appendMemory(input: AppendMemoryInput): Promise<string> {
@@ -270,10 +294,20 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
270
294
  // the last setCurrent before persistence may belong to another session
271
295
  // entirely (#116). Unnamed writers (tools, viewer, restore) keep the
272
296
  // ambient binding.
273
- const cur = repoScopeFor(input.sessionID ?? getCurrent().sid);
274
- if (cur) {
275
- repo = cur.key;
276
- repoPath = cur.path;
297
+ //
298
+ // A NAMED session that never resolved a repository is not an unnamed one
299
+ // (#152): falling back to the module scope stamped its rows into whatever
300
+ // workspace set up last, and with no module scope at all it stamped nothing
301
+ // — which every reader calls global. Both outcomes publish private content
302
+ // somewhere its owner can no longer see it, so the store refuses the write
303
+ // instead of guessing an owner. Tools answer with this message before the
304
+ // gate runs; throwing here is what covers every caller, including ones that
305
+ // reach the store without a tool.
306
+ const target = writeTarget(input.sessionID ?? getCurrent().sid);
307
+ if (!target.ok) throw new UnresolvedWriterError(target.sid);
308
+ if (target.scope) {
309
+ repo = target.scope.key;
310
+ repoPath = target.scope.path;
277
311
  }
278
312
  }
279
313
  // Day file chosen before the lock (it IS the lock key). A ts bumped across
package/src/portable.ts CHANGED
@@ -8,8 +8,15 @@ import { mkdir, open } from "node:fs/promises";
8
8
  import { dirname, join } from "node:path";
9
9
  import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
10
10
  import { resolveContained } from "./containment.ts";
11
- import { isActive, isVisibleTo, loadAll, readerFromSid, type Memory } from "./memory.ts";
12
- import { repoScopeFor } from "./repokey.ts";
11
+ import {
12
+ isActive,
13
+ isVisibleTo,
14
+ loadAll,
15
+ readerFromSid,
16
+ UnresolvedWriterError,
17
+ type Memory,
18
+ } from "./memory.ts";
19
+ import { writeTarget } from "./repokey.ts";
13
20
  import { getCurrent } from "./state.ts";
14
21
  import { TYPES } from "./types.ts";
15
22
  import type { WriteCandidate } from "./gates.ts";
@@ -262,7 +269,14 @@ export async function importMemories(
262
269
  const file = Bun.file(target);
263
270
  if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
264
271
  const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
265
- const currentScope = repoScopeFor(sessionID ?? getCurrent().sid);
272
+ // #152: the importing session's repository is resolved BEFORE the first row,
273
+ // through the writer rule rather than the ambient one. An unresolved named
274
+ // session has no write target, and half a file re-stamped into whatever
275
+ // workspace happened to set up last is worse than none — so this throws
276
+ // before a single row is gated, not partway through the tally.
277
+ const writeAt = writeTarget(sessionID ?? getCurrent().sid);
278
+ if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
279
+ const currentScope = writeAt.scope;
266
280
  let allowFrontier = false;
267
281
  let first = true;
268
282
  for (const line of (await file.text()).split("\n")) {
package/src/repokey.ts CHANGED
@@ -154,10 +154,37 @@ export function repoScopeFor(sid?: string): RepoScope | null {
154
154
  // (#127), never inherit a module scope that belongs to another workspace (or
155
155
  // is null, which the ambient reader has always read as "everything").
156
156
  export function sessionScope(sid?: unknown): RepoScope | undefined {
157
- if (typeof sid !== "string" || sid === "" || sid === "?") return undefined;
157
+ if (!isNamedSid(sid)) return undefined;
158
158
  return bySession.get(sid)?.scope;
159
159
  }
160
160
 
161
+ /** Did the host actually name a session? ("?" and absent mean nobody.) */
162
+ export function isNamedSid(sid: unknown): sid is string {
163
+ return typeof sid === "string" && sid !== "" && sid !== "?";
164
+ }
165
+
166
+ // The repository a DURABLE WRITE belongs to (#152) — the write-side twin of
167
+ // sessionScope, and deliberately not `repoScopeFor`: that helper's last resort
168
+ // is the module scope, which is the identity of whoever called setup() LAST.
169
+ // Reading with the wrong owner can only ever show too little (an unbound
170
+ // session reads global rows and nothing else), but writing with the wrong owner
171
+ // MOVES private content into a repository that cannot recall where it came
172
+ // from — and a null module scope turns the same write into an unstamped, hence
173
+ // global, row that every other project then reads. So an identity the host
174
+ // named but never resolved has NO write target: `ok:false`, which callers must
175
+ // refuse rather than downgrade. A caller that names nobody (viewer process,
176
+ // restore, scripts, unit tests) keeps the historical module-scope answer,
177
+ // including "no scope at all" — that is the deliberate admin path.
178
+ export type WriteTarget =
179
+ | { ok: true; scope: RepoScope | null }
180
+ | { ok: false; sid: string };
181
+
182
+ export function writeTarget(sid?: unknown): WriteTarget {
183
+ if (!isNamedSid(sid)) return { ok: true, scope: current };
184
+ const scope = sessionScope(sid);
185
+ return scope ? { ok: true, scope } : { ok: false, sid };
186
+ }
187
+
161
188
  export function resetSessionScopes(): void {
162
189
  bySession.clear();
163
190
  byDir.clear();