opencode-self-improvement 0.14.25 → 0.14.27

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
@@ -117,6 +117,8 @@ Rows are stamped with your git origin (an id that survives re-clones and moves b
117
117
 
118
118
  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.
119
119
 
120
+ Gate-authored evidence captures attribution at operation entry: if a session moves repositories while the gate runs, its audit lines remain in the starting repository's partition and can be read with `memory_evidence` from a session bound there. Caller-level init/capture lifecycle events still resolve attribution per event and can land in a different partition; [#199](https://github.com/abogartz/opencode-self-improvement/issues/199) tracks that boundary.
121
+
120
122
  ## Token cost and caching
121
123
 
122
124
  - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
@@ -319,7 +321,7 @@ Use Bun **1.4.4** for development checks, matching CI. `bun run test` and `bun r
319
321
  | `memory_remember` says blocked | A gate rejected the write: a stale code reference, a cited path that doesn't exist in the repo, overlap with a superseded memory, or an ambiguous claim. The reason is in `memory_evidence`; rephrase against current code and retry. |
320
322
  | `invalid arguments to memory_*` | The call didn't match the tool's input schema; nothing was done and the message names the offending fields. Gate blocks look different (`blocked at GATE (…)`). |
321
323
  | STORE shows `N malformed` | A daily file has a `ts=` that is not a valid ISO instant (typically a hand-edit). Every reader skips those rows; fix the `ts=` or restore the file with `memory_undo`. |
322
- | `memory store is busy` | Another session or the viewer held that store file for over 5s. Ordinary writes proceed anyway; only `memory_undo` and the viewer's restore refuse, because a forced rollback under a live writer would drop rows. Retry. A lock left by a killed process is taken over after 10s. |
324
+ | `memory store is busy` | A store write exhausted its 5s lock-wait budget. Appends, rewrites, and restores refuse that mutation rather than proceed unlocked and risk losing another writer's rows. Retry after contention clears. An operation spanning several files or steps may have completed earlier steps; refusal is not a rollback of those steps. If the reply reports `PARTIAL`, inspect the named rows and `memory_evidence` / `memory_undo` before retrying. A lock left by a killed process is taken over after 10s. |
323
325
  | Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping; safe to delete while nothing is writing. |
324
326
  | `/repo-init` missing from the command list | The self-install couldn't write to `~/.config/opencode/commands/`. Create it and restart, or ask the model to "init memory for this repo" — the same tool. |
325
327
  | Init says `Graph: unavailable` | `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.25",
3
+ "version": "0.14.27",
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/evidence.ts CHANGED
@@ -6,7 +6,7 @@ import { dirname, join, resolve } from "node:path";
6
6
  import { createHash } from "node:crypto";
7
7
  import { dateStr, evidenceDir } from "./config.ts";
8
8
  import { appendLog, formatLine } from "./logfmt.ts";
9
- import { repoScope, sessionScope } from "./repokey.ts";
9
+ import { repoScope, sessionScope, type RepoScope } from "./repokey.ts";
10
10
  import { getCurrent } from "./state.ts";
11
11
  import { redactSecrets } from "./secrets.ts";
12
12
 
@@ -55,20 +55,27 @@ function scrubFields(fields: Record<string, unknown>): Record<string, unknown> {
55
55
  return out;
56
56
  }
57
57
 
58
- export async function record(
59
- ev: EvidenceEvent,
60
- fields: Record<string, unknown> = {},
61
- includeContext = true,
62
- sessionID?: string,
63
- ): Promise<void> {
58
+ // Immutable operation attribution, captured before the caller's first await.
59
+ // Null scope is significant: a named-unresolved session must stay private.
60
+ export interface EvidenceContext {
61
+ readonly sid: string;
62
+ readonly call: string | undefined;
63
+ readonly scope: Readonly<RepoScope> | null;
64
+ }
65
+
66
+ export function captureEvidenceContext(sessionID?: string): EvidenceContext {
64
67
  const cur = getCurrent();
65
68
  // An explicitly threaded session outranks the ambient one: gate-authored
66
69
  // lines must name the session the gate runs FOR, not whichever setCurrent
67
70
  // fired last during the gate's own awaits (#118 review note 1 — the rows
68
71
  // were fixed in #118, these lines were the residue). When the two disagree,
69
72
  // the ambient call belongs to the OTHER session's flow, so it is dropped
70
- // rather than borrowed. With sessionID undefined (tool paths — issue #121)
71
- // this is exactly the old ambient read.
73
+ // rather than borrowed. With sessionID undefined this captures the ambient
74
+ // session and call at entry by design (maintenance/direct callers). An
75
+ // explicit "?" keeps the ambient call only when cur.sid is also "?";
76
+ // otherwise it stays absent, even if a later setCurrent supplies a call.
77
+ // Normal tool hooks setCurrent before execute; this snapshot never guesses
78
+ // a missing operation call from a later hook. See #121 for identity context.
72
79
  const sid = sessionID ?? cur.sid;
73
80
  const call = sessionID !== undefined && sessionID !== cur.sid ? undefined : cur.call;
74
81
  // Read-side partitioning of the shared log (#131's rule, applied to
@@ -85,6 +92,17 @@ export async function record(
85
92
  // scope-less process) keep their historical global reading.
86
93
  const named = typeof sid === "string" && sid !== "" && sid !== "?";
87
94
  const scope = named ? sessionScope(sid) : repoScope();
95
+ return Object.freeze({ sid, call, scope: scope ? Object.freeze({ ...scope }) : null });
96
+ }
97
+
98
+ export async function record(
99
+ ev: EvidenceEvent,
100
+ fields: Record<string, unknown> = {},
101
+ includeContext = true,
102
+ sessionID?: string,
103
+ context?: EvidenceContext,
104
+ ): Promise<void> {
105
+ const { sid, call, scope } = context ?? captureEvidenceContext(sessionID);
88
106
  const line = formatLine({
89
107
  ev,
90
108
  ts: new Date().toISOString(),
@@ -135,6 +153,7 @@ export async function recordWriteBlocked(
135
153
  flags: string[],
136
154
  chain?: string,
137
155
  sessionID?: string,
156
+ context?: EvidenceContext,
138
157
  ): Promise<void> {
139
158
  await record(
140
159
  "write_blocked",
@@ -146,5 +165,6 @@ export async function recordWriteBlocked(
146
165
  },
147
166
  true,
148
167
  sessionID,
168
+ context,
149
169
  );
150
170
  }
package/src/gates.ts CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  type Memory,
14
14
  type SupersedeFields,
15
15
  } from "./memory.ts";
16
- import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
16
+ import { captureEvidenceContext, type EvidenceContext, chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
17
17
  import { getCurrent, noteAuthored } from "./state.ts";
18
18
  import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
19
19
  import { flattenMemoryText } from "./sanitize.ts";
@@ -77,6 +77,7 @@ export interface GateContext {
77
77
  // absent/"?" callers capture ambient authority at entry (not after awaits).
78
78
  reader?: Reader;
79
79
  writeAt?: WriteTarget;
80
+ evidenceContext?: EvidenceContext;
80
81
  evidenceCalls: string[];
81
82
  // Total before the telemetry window was selected. Legacy/direct callers
82
83
  // may still supply their complete list; the writer bounds that too.
@@ -249,17 +250,13 @@ export async function runWriteGate(
249
250
  ): Promise<GateOutcome> {
250
251
  const reader = ctx.reader ?? readerFromSid(ctx.sessionID);
251
252
  const writeAt = ctx.writeAt ?? writeTarget(ctx.sessionID ?? getCurrent().sid);
253
+ const evidenceContext = ctx.evidenceContext ?? captureEvidenceContext(ctx.sessionID);
252
254
  const chain = chainId();
253
- // Gate audit lines thread the session: runWriteGate awaits (analysis, the
254
- // locked append), and another session's dispatch can move the ambient
255
- // current mid-gate — ambient-read lines would then name the wrong session
256
- // (#118 review note 1; the rows were fixed in #118, these were the
257
- // residue). Where ctx.sessionID is unset (tool paths — issue #121) record()
258
- // keeps the ambient read, exactly as before.
255
+ // Keep all gate audit lines with entry-time attribution, including refusals.
259
256
  const rec = (ev: string, fields: Record<string, unknown> = {}, includeContext = true) =>
260
- record(ev, fields, includeContext, ctx.sessionID);
257
+ record(ev, fields, includeContext, ctx.sessionID, evidenceContext);
261
258
  const recBlocked = (gate: number, reason: string, flags: string[], chain?: string) =>
262
- recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID);
259
+ recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID, evidenceContext);
263
260
 
264
261
  // Size/type floor BEFORE any scanning: gate analysis regexes
265
262
  // over megabyte content backtrack super-linearly and freeze the service
@@ -444,11 +441,10 @@ export async function runWriteGate(
444
441
  });
445
442
  }
446
443
  if (driftPlan.length > 0) {
447
- const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
444
+ const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })), ctx.durable);
448
445
  if (marked.length > 0) {
449
446
  // Ledger BEFORE the audit lines: what is on disk now stays on disk no
450
447
  // matter what the record loop below does (round-3 probe 3).
451
- ctx.durable?.push(...marked);
452
448
  for (const p of driftPlan) {
453
449
  supersededTs = p.s.memory.ts;
454
450
  await rec("superseded_by", {
@@ -497,10 +493,10 @@ export async function runWriteGate(
497
493
  ts: p.ts,
498
494
  fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
499
495
  })),
496
+ ctx.durable,
500
497
  );
501
498
  if (canonMarked.length > 0) {
502
499
  // Same ledger discipline as the drift batch above.
503
- ctx.durable?.push(...canonMarked);
504
500
  for (const p of canonPlan) {
505
501
  if (!supersededTs) supersededTs = p.ts;
506
502
  await rec("superseded_by", {
package/src/hits.ts CHANGED
@@ -127,6 +127,9 @@ export async function recordHits(
127
127
  );
128
128
  return true;
129
129
  } catch {
130
+ // Fail-closed lock contention can drop this use observation. Decay and
131
+ // consolidation therefore see a best-effort ledger, not proof of non-use;
132
+ // retrieval remains available even when its telemetry cannot be persisted.
130
133
  return false; // telemetry never breaks retrieval
131
134
  }
132
135
  }
package/src/index.ts CHANGED
@@ -31,7 +31,7 @@ import { pruneMemory } from "./prune.ts";
31
31
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
32
32
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
33
33
  import { SESSION_CAP, SessionLru } from "./sessions.ts";
34
- import { evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
34
+ import { captureEvidenceContext, evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
35
35
  import { proposeConsolidations, renderProposals } from "./consolidate.ts";
36
36
  import { readReads } from "./hits.ts";
37
37
  import {
@@ -298,6 +298,7 @@ const impl = {
298
298
  sessionID: sid,
299
299
  reader: readerFromSid(sid),
300
300
  writeAt: writeTarget(bound),
301
+ evidenceContext: captureEvidenceContext(sid),
301
302
  // NOTE (re-review): this one lookup is intentionally NON-firm — a
302
303
  // provisional binding may supply the gate's verification TREE. The
303
304
  // tree is where a referenced file is checked to exist, not who the
@@ -554,6 +555,7 @@ const impl = {
554
555
  const ownerless = ownerlessWriter(sid);
555
556
  if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
556
557
  const reader = readerFromSid(sid);
558
+ const updateGate = gateContext(sid);
557
559
  // The whole update — resolve, gate, supersede — runs under one
558
560
  // UPDATE-ORDER lock. Without it, two concurrent updates that both
559
561
  // resolved the same still-active target both promoted and both
@@ -689,7 +691,7 @@ const impl = {
689
691
  repo: requested.repo,
690
692
  repoPath: target.repo ? target.repoPath : undefined,
691
693
  },
692
- { ...gateContext(sid), reader, supersedesTs: target.ts, durable: gateDurable },
694
+ { ...updateGate, reader, supersedesTs: target.ts, durable: gateDurable },
693
695
  );
694
696
  if (outcome.action === "promoted" && outcome.ts && target) {
695
697
  mutated = true;
@@ -794,7 +796,7 @@ const impl = {
794
796
  symbol: target.ts,
795
797
  from: target.ts,
796
798
  to: survivorTs,
797
- });
799
+ }, gateDurable);
798
800
  if (done) {
799
801
  return {
800
802
  content:
@@ -854,8 +856,8 @@ const impl = {
854
856
  ? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
855
857
  "Re-running this update reports the duplicate; inspect with memory_evidence."
856
858
  : gateDurable.length > 0
857
- ? `memory_update blocked: ${msg} No replacement was written, but the gate had ALREADY retired ` +
858
- `${gateDurable.length} other row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
859
+ ? `memory_update PARTIAL: ${msg} No replacement was written, but this call had ALREADY retired ` +
860
+ `${gateDurable.length} row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
859
861
  "disk and their audit lines may not all have landed. Re-running this update will not undo " +
860
862
  "them — reconcile with memory_evidence / memory_undo before retrying."
861
863
  : `memory_update blocked: ${msg} Nothing was written.`,
@@ -872,6 +874,7 @@ const impl = {
872
874
  async execute(args, context): Promise<{ content: string }> {
873
875
  const { sid } = toolIds(context);
874
876
  const res = await pruneMemory(args.scope, args.type, args.reason, sid);
877
+ if (res.error) return { content: `memory_forget PARTIAL: deleted row(s) ${res.deleted.map((d) => d.memory.ts).join(", ")}; stopped: ${res.error}. Rejection tombstones or audit lines may be incomplete. Inspect memory_evidence / memory_undo before retrying.` };
875
878
  if (!res.deleted.length) return { content: `No memories found for ${args.type} in ${args.scope}` };
876
879
  return { content: `Deleted ${res.deleted.length} ${args.type} memory(s) from ${args.scope}. Audit: ${res.audit}` };
877
880
  },
@@ -985,7 +988,7 @@ const impl = {
985
988
  editor.add(validated(MergeReviewArgs, {
986
989
  name: "memory_merge_review",
987
990
  description:
988
- "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Fails closed (no partial apply) when the reason or the survivor id is missing, the survivor id names no row in the store, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row.",
991
+ "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, the survivor id names no row in the store, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row. Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
989
992
  options: direct,
990
993
  async execute(args, context): Promise<{ content: string }> {
991
994
  const { sid } = toolIds(context);
@@ -1008,11 +1011,9 @@ const impl = {
1008
1011
  // this cannot deadlock against a plain writer; on timeout it fails
1009
1012
  // closed with nothing written.
1010
1013
  const reader = readerFromSid(sid);
1011
- // Where a throw lands decides what is true to say: before the
1012
- // mutation nothing was written (the documented fail-closed
1013
- // contract); AFTER markSuperseded the loser IS retired on disk and
1014
- // claiming "nothing was done" is a lie (review probe 5).
1015
- let mutated = false;
1014
+ // A batch may publish the loser then refuse a later file. The sink
1015
+ // records that publish before the overall promise settles (#197).
1016
+ const mergeDurable: string[] = [];
1016
1017
  try {
1017
1018
  return await withStoreLock(
1018
1019
  join(memoryRoot(), "update-order"),
@@ -1047,11 +1048,10 @@ const impl = {
1047
1048
  symbol: args.loser,
1048
1049
  from: args.loser,
1049
1050
  to: args.survivor,
1050
- });
1051
+ }, mergeDurable);
1051
1052
  if (!ok) {
1052
1053
  return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
1053
1054
  }
1054
- mutated = true;
1055
1055
  // The survivor may itself have been superseded earlier (e.g. by
1056
1056
  // a row this very call just made the loser). Declaring it
1057
1057
  // canonical has to make it recallable, so clear its own marker.
@@ -1089,19 +1089,19 @@ const impl = {
1089
1089
  );
1090
1090
  } catch (err) {
1091
1091
  // Before mutation this is the fail-closed lock contract: nothing
1092
- // written. After markSuperseded succeeded the loser IS retired —
1092
+ // written. Once a file published, the loser IS retired —
1093
1093
  // the honest report names the completed mutation and the failed
1094
1094
  // follow-up (evidence/revive), not a blanket "nothing was done".
1095
- if (!mutated) {
1095
+ const why = err instanceof Error ? err.message : String(err);
1096
+ if (mergeDurable.length === 0) {
1096
1097
  return {
1097
- content: "merge_review blocked: the store was busy past the lock budget — nothing was done. Retry.",
1098
+ content: `merge_review blocked: ${why} — nothing was done. Retry.`,
1098
1099
  };
1099
1100
  }
1100
- const why = err instanceof Error ? err.message : String(err);
1101
1101
  return {
1102
1102
  content:
1103
1103
  `merge_review PARTIAL: ${args.loser} IS retired on disk (superseded_by ${args.survivor}; ` +
1104
- `recoverable via memory_undo) but a post-mutation step failed: ${why}. ` +
1104
+ `recoverable via memory_undo) but the remaining operation failed: ${why}. ` +
1105
1105
  `The evidence line may be missing; re-running reports the loser already superseded.`,
1106
1106
  };
1107
1107
  }
@@ -1211,15 +1211,24 @@ const impl = {
1211
1211
  // One lock/read/snapshot/publish per file for the whole decay run (#61):
1212
1212
  // N retired rows are one undo point, not N. Idempotent (a no-op on rows
1213
1213
  // already superseded, out-of-band ones skipped under the lock).
1214
- const retired = await markManySuperseded(
1215
- stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })),
1216
- );
1214
+ const durable: string[] = [];
1215
+ let retired: number;
1216
+ try {
1217
+ retired = await markManySuperseded(
1218
+ stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })), durable,
1219
+ );
1220
+ } catch (err) {
1221
+ if (durable.length === 0) throw err;
1222
+ let why = err instanceof Error ? err.message : String(err);
1223
+ await record("decay_applied", { days, retired: durable.length, mem: durable.join(","), snapshot: snapshot.join(","), partial: true, error: why }, false).catch((audit) => { why += `; audit failed: ${String(audit)}`; });
1224
+ return { content: `memory_decay PARTIAL: retired row(s) ${durable.join(", ")}; stopped: ${why}. Recover with memory_undo; inspect memory_evidence before retrying.` };
1225
+ }
1217
1226
  await record(
1218
1227
  "decay_applied",
1219
1228
  {
1220
1229
  days,
1221
1230
  retired,
1222
- mem: stale.map((m) => m.ts).join(",") || "-",
1231
+ mem: durable.join(",") || "-",
1223
1232
  snapshot: snapshot.join(",") || "-",
1224
1233
  },
1225
1234
  false,
@@ -1557,16 +1566,28 @@ const impl = {
1557
1566
  const text = typeof out === "string" ? out : out?.text ?? "";
1558
1567
  const candidates = parseCandidates(text, captureMax);
1559
1568
  for (const c of candidates) {
1560
- const outcome = await runWriteGate(
1561
- {
1562
- ...c,
1563
- tags:
1564
- trigger === "compaction"
1565
- ? ["auto-capture", CAPTURE_COMPACT_TAG]
1566
- : ["auto-capture"],
1567
- },
1568
- captureGate,
1569
- );
1569
+ const durable: string[] = [];
1570
+ let outcome: Awaited<ReturnType<typeof runWriteGate>>;
1571
+ try {
1572
+ outcome = await runWriteGate(
1573
+ {
1574
+ ...c,
1575
+ tags:
1576
+ trigger === "compaction"
1577
+ ? ["auto-capture", CAPTURE_COMPACT_TAG]
1578
+ : ["auto-capture"],
1579
+ },
1580
+ { ...captureGate, durable },
1581
+ );
1582
+ } catch (err) {
1583
+ // A refused write must not disappear into the hook's fail-soft
1584
+ // wrapper. Preserve any earlier gate retirements in the receipt.
1585
+ await record(durable.length ? "auto_capture_partial" : "auto_capture_refused", {
1586
+ session: sid, trigger, type: c.type, scope: redactSecrets(c.scope),
1587
+ reason: String(err), retired: durable.join(",") || undefined,
1588
+ }, false, sid);
1589
+ continue;
1590
+ }
1570
1591
  await record(
1571
1592
  trigger === "compaction"
1572
1593
  ? `auto_capture_compaction_${outcome.action}`
package/src/init.ts CHANGED
@@ -10,7 +10,7 @@ import { existsSync } from "node:fs";
10
10
  import { cbmBin } from "./config.ts";
11
11
  import { isVisibleTo, loadAll, markSuperseded, readerFromSid, type Reader } from "./memory.ts";
12
12
  import { runWriteGate, type GateContext } from "./gates.ts";
13
- import { record } from "./evidence.ts";
13
+ import { captureEvidenceContext, record } from "./evidence.ts";
14
14
  import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
15
  import { writeTarget } from "./repokey.ts";
16
16
  import { getCurrent } from "./state.ts";
@@ -210,6 +210,7 @@ export async function initStamp(scope: string, sid?: string, reader: Reader = re
210
210
  export async function runInit(args: InitArgs): Promise<InitSummary> {
211
211
  const reader = readerFromSid(args.sessionID);
212
212
  const writeAt = writeTarget(args.sessionID ?? getCurrent().sid);
213
+ const evidenceContext = captureEvidenceContext(args.sessionID);
213
214
  const root = await gitRootOf(args.liveRoot);
214
215
  const scope = basename(root) || basename(args.liveRoot);
215
216
  const head = await gitHead(root);
@@ -220,6 +221,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
220
221
  liveRoot: root,
221
222
  reader,
222
223
  writeAt,
224
+ evidenceContext,
223
225
  ...writeEvidence(args.sessionID ?? getCurrent().sid),
224
226
  hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
225
227
  // Stamps land on the caller's session even though runInit awaits git
package/src/lock.ts CHANGED
@@ -48,18 +48,20 @@ export interface LockOptions {
48
48
  /**
49
49
  * What waiting past `timeoutMs` means. "fail" refuses the mutation (for
50
50
  * callers where proceeding unlocked could destroy more than it saves, e.g.
51
- * snapshot restore). "proceed" runs it anyway: strictly no worse than the
52
- * pre-lock behaviour, and it never costs a user their write.
51
+ * snapshot restore). The legacy default, "proceed", runs it unlocked and
52
+ * can lose acknowledged writes when another caller rewrites the same file.
53
+ * Store writers must use LOCK_WRITE (or an explicit fail-closed policy).
53
54
  */
54
55
  onTimeout?: "proceed" | "fail";
55
56
  onEvent?: (event: LockEvent, waitedMs: number) => void;
56
57
  }
57
58
 
58
- // How each store caller treats contention. An ordinary write PROCEEDS past the
59
- // timeout rather than lose the user's memory, and the wait is audited; restore
60
- // fails closed, because "force" drops rows and must not guess under a racing
61
- // writer.
59
+ // Every writer of a shared store file must respect exclusion, INCLUDING
60
+ // appenders: an unlocked append inside a holder's read-modify-write window is
61
+ // overwritten by its publish. Refuse at the deadline so the caller can retry;
62
+ // never acknowledge a mutation performed outside the holder's lock (#196).
62
63
  export const LOCK_WRITE: LockOptions = {
64
+ onTimeout: "fail",
63
65
  onEvent: (event, waitedMs) => {
64
66
  void record("store_lock", { event, waited_ms: waitedMs, op: "write" });
65
67
  },
package/src/logfmt.ts CHANGED
@@ -124,13 +124,10 @@ let tmpSeq = 0;
124
124
 
125
125
  export async function writeAtomic(file: string, content: string, since?: string): Promise<void> {
126
126
  await ensureDir(dirname(file));
127
- // Unique PER CALL, not per process: the store lock guarantees one writer
128
- // only until a starved waiter's budget expires and lock.ts lets it proceed
129
- // anyway. That degraded writer can be inside writeAtomic for the same file
130
- // at the same instant - with a pid-stable name its bytes would sit in the
131
- // very temp the anchored publish's ≤2s retry keeps renaming, and the retry
132
- // would publish THOSE bytes under our success report. One extra leftover
133
- // per failed attempt is the (unlinkable) price of that safety.
127
+ // Unique PER CALL, not per process: shared store writers now fail closed on
128
+ // lock timeout, but direct/legacy callers can still overlap. A pid-stable
129
+ // name would let one call replace the bytes another call's anchored publish
130
+ // is retrying. Keep separate temps even when the caller holds a lock.
134
131
  const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
135
132
  try {
136
133
  await Bun.write(tmp, content);
@@ -147,8 +144,8 @@ export async function writeAtomic(file: string, content: string, since?: string)
147
144
  // while that handle lives. Readers of a small store file cycle their handle on
148
145
  // a microsecond scale, so that failure is usually transient and worth a retry
149
146
  // window (~2s, well inside the 5s lock budget) — but a retry alone is not safe
150
- // here. If an unlocked writer (a starved lock waiter runs its write anyway;
151
- // see lock.ts onTimeout) appends into the destination DURING the window, the
147
+ // here. If an out-of-band or legacy unlocked writer appends into the
148
+ // destination DURING the window, the
152
149
  // retried rename publishes our now-stale copy over that row — a slower way to
153
150
  // lose exactly what the immediate failure preserved. So the retry runs only
154
151
  // while the destination still matches `since`, the identity from before the
package/src/memory.ts CHANGED
@@ -399,8 +399,8 @@ async function stampRow(
399
399
 
400
400
  // Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
401
401
  // Idempotent: a second call is a no-op, so no double `superseded_by`.
402
- export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
403
- return (await markManySupersededReport([{ ts, fields }])).marked.length > 0;
402
+ export async function markSuperseded(ts: string, fields: SupersedeFields, durable?: string[]): Promise<boolean> {
403
+ return (await markManySupersededReport([{ ts, fields }], durable)).marked.length > 0;
404
404
  }
405
405
 
406
406
  // Batch supersession (#61): one lock acquisition, one read, one snapshot and
@@ -412,8 +412,8 @@ export async function markSuperseded(ts: string, fields: SupersedeFields): Promi
412
412
  // so a repeat run marks nothing and writes nothing. Duplicate ts entries in
413
413
  // one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
414
414
  // Returns the number of rows actually marked.
415
- export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[]): Promise<number> {
416
- return (await markManySupersededReport(entries)).marked.length;
415
+ export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[], durable?: string[]): Promise<number> {
416
+ return (await markManySupersededReport(entries, durable)).marked.length;
417
417
  }
418
418
 
419
419
  // Same operation, reporting WHICH rows retired rather than how many (#158
@@ -424,6 +424,9 @@ export async function markManySuperseded(entries: { ts: string; fields: Supersed
424
424
  // this call did not perform.
425
425
  export async function markManySupersededReport(
426
426
  entries: { ts: string; fields: SupersedeFields }[],
427
+ // Updated immediately after EACH publish, even if a later file refuses its
428
+ // lock or lock cleanup throws. A rejected promise is not a rollback.
429
+ durable?: string[],
427
430
  ): Promise<{ marked: string[] }> {
428
431
  if (entries.length === 0) return { marked: [] };
429
432
  const wanted = new Map<string, SupersedeFields>();
@@ -464,6 +467,7 @@ export async function markManySupersededReport(
464
467
  if (ids.length === 0) return [];
465
468
  await snapshotBefore(file);
466
469
  await writeAtomic(file, lines.join("\n") + "\n", since);
470
+ durable?.push(...ids);
467
471
  return ids;
468
472
  },
469
473
  LOCK_WRITE,
@@ -623,9 +627,9 @@ export async function prune(
623
627
  type: string,
624
628
  reason: string,
625
629
  reader: Reader = readerForAmbient(),
630
+ durable: PruneResult = { deleted: [], snapshot: [] },
626
631
  ): Promise<PruneResult> {
627
- const deleted: DeletedMemory[] = [];
628
- const snapshot: string[] = [];
632
+ const { deleted, snapshot } = durable;
629
633
  for (const file of await memoryFiles()) {
630
634
  await withStoreLock(
631
635
  file,
@@ -633,6 +637,7 @@ export async function prune(
633
637
  const since = await fileIdentity(file);
634
638
  const lines = await readLines(file);
635
639
  const kept: string[] = [];
640
+ const fileDeleted: DeletedMemory[] = [];
636
641
  let changed = false;
637
642
  for (const line of lines) {
638
643
  const parsed = parseLine(line);
@@ -641,7 +646,7 @@ export async function prune(
641
646
  // another repo's row for scope X — same basename collisions are real
642
647
  // (a fork next to its upstream).
643
648
  if (m && m.scope === scope && m.type === type && isVisibleTo(m, reader)) {
644
- deleted.push({ memory: m, reason });
649
+ fileDeleted.push({ memory: m, reason });
645
650
  await logDeletion(m, reason);
646
651
  changed = true;
647
652
  continue;
@@ -651,6 +656,7 @@ export async function prune(
651
656
  if (!changed) return;
652
657
  snapshot.push(...(await snapshotFiles([file])));
653
658
  await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
659
+ deleted.push(...fileDeleted);
654
660
  },
655
661
  LOCK_WRITE,
656
662
  );
package/src/prune.ts CHANGED
@@ -13,8 +13,15 @@ export async function pruneMemory(
13
13
  // CALLER's identity, captured at tool entry, not the ambient current the
14
14
  // locked file walk may outlive. "?" / undefined keep ambient semantics.
15
15
  sid?: string,
16
- ): Promise<PruneResult & { audit: string }> {
17
- const res = await prune(scope, type, reason, readerFromSid(sid));
16
+ ): Promise<PruneResult & { audit: string; error?: string }> {
17
+ const res: PruneResult = { deleted: [], snapshot: [] };
18
+ let error: string | undefined;
19
+ try {
20
+ await prune(scope, type, reason, readerFromSid(sid), res);
21
+ } catch (err) {
22
+ if (res.deleted.length === 0) throw err;
23
+ error = err instanceof Error ? err.message : String(err);
24
+ }
18
25
  const memTs = res.deleted.map((d) => d.memory.ts).join(",") || "-";
19
26
  await record(
20
27
  "prune",
@@ -24,9 +31,14 @@ export async function pruneMemory(
24
31
  snapshot: res.snapshot[0] ?? "-",
25
32
  audit: deletionsFile(),
26
33
  tool: "memory_forget",
34
+ partial: error ? true : undefined,
35
+ error,
27
36
  },
28
37
  true,
29
38
  sid,
30
- );
31
- return { ...res, audit: deletionsFile() };
39
+ ).catch((audit) => {
40
+ if (!error) throw audit;
41
+ error += `; audit failed: ${String(audit)}`;
42
+ });
43
+ return { ...res, audit: deletionsFile(), ...(error ? { error } : {}) };
32
44
  }
package/src/tombstones.ts CHANGED
@@ -295,10 +295,9 @@ export async function tombstones(): Promise<Tombstone[]> {
295
295
  * pair plus a full read per row, and `memory_forget` deletes by scope+type, so a
296
296
  * bulk forget issued hundreds of lock cycles while other sessions were writing.
297
297
  * The heavy concurrent scenario on the Windows runner failed 2/2 with that shape
298
- * (run 41112466339) and never on main; src/lock.ts gives up waiting after 5s and
299
- * proceeds UNLOCKED, which is precisely how a row gets lost behind a long
300
- * read-modify-write. Whether the batch is sufficient there is the open question
301
- * this commit's CI run answers; the cost it removes is real either way.
298
+ * (run 41112466339). At that time, lock-budget expiry let a writer proceed
299
+ * unlocked, losing rows behind a long read-modify-write. LOCK_WRITE now refuses
300
+ * on timeout (#196); batching still reduces lock contention and its I/O cost.
302
301
  *
303
302
  * Still idempotent by `ch`, and de-duplicated WITHIN the batch too, so a forget
304
303
  * that removes fifty rows carrying the same content records one tombstone.
@@ -90,10 +90,15 @@ export async function editMemory(input: EditInput): Promise<MutationResult> {
90
90
  repo: target.repo ?? "global",
91
91
  repoPath: target.repo ? target.repoPath : undefined,
92
92
  });
93
- await markSuperseded(input.ts, {
94
- superseded_by: newTs,
95
- reason: "human_edit",
96
- });
93
+ const retired: string[] = [];
94
+ try {
95
+ await markSuperseded(input.ts, {
96
+ superseded_by: newTs,
97
+ reason: "human_edit",
98
+ }, retired);
99
+ } catch (err) {
100
+ throw new Error(`viewer edit PARTIAL: replacement ${newTs} IS on disk; original ${input.ts} ${retired.includes(input.ts) ? "IS retired" : "was NOT retired by this edit"}. Stopped: ${String(err)}. Inspect the rows or use memory_undo before retrying.`);
101
+ }
97
102
  await audit("edited", target, input.ts, newTs, input.reason);
98
103
  await record("viewer_edit", {
99
104
  chain,
@@ -228,4 +233,4 @@ export async function unrejectMemory(ch: string): Promise<boolean> {
228
233
  return removeTombstone(ch);
229
234
  }
230
235
 
231
- export { addBlock, removeBlock };
236
+ export { addBlock, removeBlock };