opencode-self-improvement 0.13.0 → 0.13.2

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.13.0",
3
+ "version": "0.13.2",
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
@@ -8,10 +8,11 @@ import {
8
8
  appendMemory,
9
9
  loadAll,
10
10
  loadScope,
11
- markSuperseded,
11
+ markManySuperseded,
12
12
  snapshotFiles,
13
13
  MAX_CONTENT_CHARS,
14
14
  type Memory,
15
+ type SupersedeFields,
15
16
  } from "./memory.ts";
16
17
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
17
18
  import { flattenMemoryText } from "./sanitize.ts";
@@ -357,6 +358,7 @@ export async function runWriteGate(
357
358
  });
358
359
 
359
360
  let supersededTs: string | undefined;
361
+ const driftPlan: { s: StaleRef; target: string; fields: SupersedeFields }[] = [];
360
362
  for (const s of stale) {
361
363
  await record("ref_stale", {
362
364
  gate: 2,
@@ -368,27 +370,33 @@ export async function runWriteGate(
368
370
  chain,
369
371
  });
370
372
  // Drift-fed supersession is AUTO (provable) and target depends on whether a
371
- // valid write will land; stale data is neutralized either way.
373
+ // valid write will land; stale data is neutralized either way. One batch
374
+ // publish for the whole set (#61): a row marked out-of-band between the scan
375
+ // and the pass is skipped by the batch (it re-reads under the lock).
372
376
  const target = g1.candidateStale ? "<-" : chain;
373
- const marked = await markSuperseded(s.memory.ts, {
374
- superseded_by: target,
375
- reason: "drift",
376
- symbol: s.symbol,
377
- from: s.from,
378
- to: s.to,
377
+ if (typeof s.memory.superseded_by === "string") continue;
378
+ driftPlan.push({
379
+ s,
380
+ target,
381
+ fields: { superseded_by: target, reason: "drift", symbol: s.symbol, from: s.from, to: s.to },
379
382
  });
380
- if (marked) {
381
- supersededTs = s.memory.ts;
382
- await record("superseded_by", {
383
- gate: 2,
384
- mem: s.memory.ts,
385
- target,
386
- reason: "drift",
387
- symbol: s.symbol,
388
- from: s.from,
389
- to: s.to,
390
- chain,
391
- });
383
+ }
384
+ if (driftPlan.length > 0) {
385
+ const markedCount = await markManySuperseded(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
386
+ if (markedCount > 0) {
387
+ for (const p of driftPlan) {
388
+ supersededTs = p.s.memory.ts;
389
+ await record("superseded_by", {
390
+ gate: 2,
391
+ mem: p.s.memory.ts,
392
+ target: p.target,
393
+ reason: "drift",
394
+ symbol: p.s.symbol,
395
+ from: p.s.from,
396
+ to: p.s.to,
397
+ chain,
398
+ });
399
+ }
392
400
  }
393
401
  }
394
402
 
@@ -404,29 +412,31 @@ export async function runWriteGate(
404
412
  // Any in-scope entry that contradicts the canonical value is neutralized.
405
413
  const entitySet = new Set(tokens(canon.entry.entity));
406
414
  const valueSet = new Set(tokens(canon.entry.value));
415
+ const target = canon.aligns ? chain : "<-";
416
+ const canonPlan: { ts: string; from: string | undefined }[] = [];
407
417
  for (const m of scopeMems) {
408
418
  if (m.superseded_by) continue;
409
419
  if (tokens(m.content).some((t) => valueSet.has(t))) continue;
410
420
  const from = rawTokens(m.content).find(
411
421
  (t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()) && !valueSet.has(t.toLowerCase()),
412
422
  );
413
- const target = canon.aligns ? chain : "<-";
414
- const marked = await markSuperseded(m.ts, {
415
- superseded_by: target,
416
- reason: "canonical",
417
- entity: canon.entry.entity,
418
- from: from ?? undefined,
419
- to: canon.entry.value,
420
- });
421
- if (marked) {
422
- if (!supersededTs) supersededTs = m.ts;
423
+ canonPlan.push({ ts: m.ts, from });
424
+ }
425
+ // One batch publish for the whole neutralization set (#61); rows marked
426
+ // out-of-band since the scan are skipped by the batch (re-read under lock).
427
+ if ((await markManySuperseded(canonPlan.map((p) => ({
428
+ ts: p.ts,
429
+ fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
430
+ })))) > 0) {
431
+ for (const p of canonPlan) {
432
+ if (!supersededTs) supersededTs = p.ts;
423
433
  await record("superseded_by", {
424
434
  gate: 2,
425
- mem: m.ts,
435
+ mem: p.ts,
426
436
  target,
427
437
  reason: "canonical",
428
438
  entity: canon.entry.entity,
429
- from: from ?? undefined,
439
+ from: p.from,
430
440
  to: canon.entry.value,
431
441
  chain,
432
442
  });
package/src/index.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  isVisibleHere,
21
21
  loadAll,
22
22
  malformedCount,
23
+ markManySuperseded,
23
24
  markSuperseded,
24
25
  resolveMemoryTarget,
25
26
  snapshotFiles,
@@ -644,29 +645,28 @@ const impl = {
644
645
  }
645
646
  // Snapshot-before-mutate: the SAME helper prune() uses in memory.ts,
646
647
  // one whole-file copy per affected file, taken before the first
647
- // mutation. markSuperseded also snapshots internally per row; this
648
- // pass guarantees a pre-decay copy exists even if a later row fails.
648
+ // mutation. The batch pass snapshots again per file it touches; this
649
+ // pass guarantees a pre-decay copy exists even if a later file fails.
649
650
  const snapshot = await snapshotFiles([...new Set(stale.map((m) => m.file))]);
650
- const retiredTs: string[] = [];
651
- for (const m of stale) {
652
- // Idempotent (a no-op on already-superseded rows), so a re-run
653
- // cannot double-mark. No successor row exists — decay retires.
654
- const ok = await markSuperseded(m.ts, { superseded_by: "decay", reason: "decay" });
655
- if (ok) retiredTs.push(m.ts);
656
- }
651
+ // One lock/read/snapshot/publish per file for the whole decay run (#61):
652
+ // N retired rows are one undo point, not N. Idempotent (a no-op on rows
653
+ // already superseded, out-of-band ones skipped under the lock).
654
+ const retired = await markManySuperseded(
655
+ stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })),
656
+ );
657
657
  await record(
658
658
  "decay_applied",
659
659
  {
660
660
  days,
661
- retired: retiredTs.length,
662
- mem: retiredTs.join(",") || "-",
661
+ retired,
662
+ mem: stale.map((m) => m.ts).join(",") || "-",
663
663
  snapshot: snapshot.join(",") || "-",
664
664
  },
665
665
  false,
666
666
  );
667
667
  return {
668
668
  content:
669
- `Decayed ${retiredTs.length} open thread(s) older than ${days} days ` +
669
+ `Decayed ${retired} open thread(s) older than ${days} days ` +
670
670
  `(superseded, not deleted; snapshot: ${snapshot[0] ?? "-"}). ` +
671
671
  "Recover with memory_undo.",
672
672
  };
package/src/memory.ts CHANGED
@@ -341,15 +341,53 @@ async function stampRow(
341
341
  // Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
342
342
  // Idempotent: a second call is a no-op, so no double `superseded_by`.
343
343
  export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
344
+ return (await markManySuperseded([{ ts, fields }])) > 0;
345
+ }
346
+
347
+ // Batch supersession (#61): one lock acquisition, one read, one snapshot and
348
+ // one publish PER FILE touched - N rows retire as one undo point instead of
349
+ // N. decay and the gate's drift/canonical loops used to call markSuperseded
350
+ // per row, which meant N full read-modify-write cycles, N undo points, and
351
+ // N windows where two runs interleave and each re-pays the other's work.
352
+ // Idempotence is unchanged: a row already carrying superseded_by is skipped,
353
+ // so a repeat run marks nothing and writes nothing. Duplicate ts entries in
354
+ // one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
355
+ // Returns the number of rows actually marked.
356
+ export async function markManySuperseded(
357
+ entries: { ts: string; fields: SupersedeFields }[],
358
+ ): Promise<number> {
359
+ if (entries.length === 0) return 0;
360
+ const wanted = new Map<string, SupersedeFields>();
361
+ for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
362
+ let marked = 0;
344
363
  for (const file of await memoryFiles()) {
345
- // The whole line is rewritten rather than extended, so an old-format line
346
- // comes out in the current format with its values unchanged.
347
- const outcome = await stampRow(file, ts, (parsed) =>
348
- typeof parsed.superseded_by === "string" ? null : formatLine({ ...parsed, ...fields }),
364
+ marked += await withStoreLock(
365
+ file,
366
+ async () => {
367
+ const lines = await readLines(file);
368
+ let touched = 0;
369
+ for (let i = 0; i < lines.length; i++) {
370
+ const parsed = parseLine(lines[i]);
371
+ if (!parsed || typeof parsed.superseded_by === "string") continue;
372
+ const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
373
+ if (!fields) continue;
374
+ // Whole line rewritten, not extended: an old-format line comes out in
375
+ // the current format with its values unchanged (as markSuperseded did).
376
+ lines[i] = formatLine({ ...parsed, ...fields });
377
+ touched++;
378
+ }
379
+ if (touched === 0) return 0;
380
+ await snapshotBefore(file);
381
+ await writeAtomic(file, lines.join("\n") + "\n");
382
+ return touched;
383
+ },
384
+ LOCK_WRITE,
349
385
  );
350
- if (outcome !== null) return outcome;
351
386
  }
352
- return false;
387
+ // A ts that appears in several files (should not exist - append mints unique
388
+ // ts) retires in EVERY file here, where the row-by-row loop retired only the
389
+ // first; both are conservation-safe, this one is the more honest tombstone.
390
+ return marked;
353
391
  }
354
392
 
355
393
  // Drop a row's supersession markers IN PLACE (snapshot-first), making it active
package/src/repokey.ts CHANGED
@@ -7,13 +7,16 @@
7
7
  // Two keys, both cheap, with opposite failure modes:
8
8
  // key — sha1 of the normalized origin URL: survives re-clone, moves, and
9
9
  // export/import to another machine. Absent when the repo has no
10
- // origin (fresh or remote-less), where the path is used as the key.
11
- // path — resolved git toplevel: the secondary match, so rows stamped
12
- // before an origin was added keep recognizing their repo.
10
+ // origin (fresh or remote-less): sha1 of the NORMALIZED resolved
11
+ // path instead, so repo= is always a bare token — a raw path with
12
+ // a space gets logfmt-quoted, which breaks naive field extraction
13
+ // and can't be hash-compared (#92). path stays the human-readable
14
+ // secondary, so rows stamped before the hash keep matching.
13
15
  // Rows carry no stamp when their writer had no scope (viewer process,
14
16
  // tests) and legacy rows predate the field: both read as GLOBAL — visible
15
17
  // everywhere — which keeps every upgrade non-breaking.
16
18
  import { createHash } from "node:crypto";
19
+ import { realpathSync } from "node:fs";
17
20
 
18
21
  export interface RepoScope {
19
22
  key: string;
@@ -56,14 +59,31 @@ function git(args: string[], cwd: string): string | null {
56
59
  }
57
60
  }
58
61
 
62
+ // Normalize a directory for hashing: symlinks, junctions, and Windows 8.3
63
+ // 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.
67
+ export function normalizeDirPath(p: string): string {
68
+ let r = p;
69
+ try {
70
+ r = realpathSync(r);
71
+ } catch {
72
+ // deleted/unreadable mid-resolve: hash the given spelling rather than throw
73
+ }
74
+ r = r.replace(/\\/g, "/").replace(/\/+$/, "");
75
+ if (process.platform === "win32" || process.platform === "darwin") r = r.toLowerCase();
76
+ return r || "/";
77
+ }
78
+
59
79
  // Resolve the current repo from any start dir (never throws; a non-git dir
60
- // simply scopes by its own path).
80
+ // simply scopes by the hash of its own normalized path).
61
81
  export function resolveRepo(startDir: string): RepoScope {
62
82
  const path = git(["git", "rev-parse", "--show-toplevel"], startDir) ?? startDir;
63
83
  const remote = git(["git", "remote", "get-url", "origin"], path);
64
84
  const key = remote
65
85
  ? createHash("sha1").update(normalizeRemote(remote)).digest("hex").slice(0, 12)
66
- : path;
86
+ : createHash("sha1").update(normalizeDirPath(path)).digest("hex").slice(0, 12);
67
87
  return { key, path };
68
88
  }
69
89