opencode-self-improvement 0.14.7 → 0.14.9

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.7",
3
+ "version": "0.14.9",
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
@@ -13,8 +13,18 @@ export async function record(
13
13
  ev: EvidenceEvent,
14
14
  fields: Record<string, unknown> = {},
15
15
  includeContext = true,
16
+ sessionID?: string,
16
17
  ): Promise<void> {
17
- const { sid, call } = getCurrent();
18
+ const cur = getCurrent();
19
+ // An explicitly threaded session outranks the ambient one: gate-authored
20
+ // lines must name the session the gate runs FOR, not whichever setCurrent
21
+ // fired last during the gate's own awaits (#118 review note 1 — the rows
22
+ // were fixed in #118, these lines were the residue). When the two disagree,
23
+ // the ambient call belongs to the OTHER session's flow, so it is dropped
24
+ // rather than borrowed. With sessionID undefined (tool paths — issue #121)
25
+ // this is exactly the old ambient read.
26
+ const sid = sessionID ?? cur.sid;
27
+ const call = sessionID !== undefined && sessionID !== cur.sid ? undefined : cur.call;
18
28
  const line = formatLine({
19
29
  ev,
20
30
  ts: new Date().toISOString(),
@@ -63,11 +73,17 @@ export async function recordWriteBlocked(
63
73
  reason: string,
64
74
  flags: string[],
65
75
  chain?: string,
76
+ sessionID?: string,
66
77
  ): Promise<void> {
67
- await record("write_blocked", {
68
- gate,
69
- reason,
70
- flags: `[${flags.join(",")}]`,
71
- ...(chain ? { chain } : {}),
72
- });
78
+ await record(
79
+ "write_blocked",
80
+ {
81
+ gate,
82
+ reason,
83
+ flags: `[${flags.join(",")}]`,
84
+ ...(chain ? { chain } : {}),
85
+ },
86
+ true,
87
+ sessionID,
88
+ );
73
89
  }
package/src/gates.ts CHANGED
@@ -63,6 +63,10 @@ export interface GateContext {
63
63
  // the GATE-4 ambiguity rule: it embeds no refs and has no completion-gate
64
64
  // evidence by construction, but is still evaluated by GATE-1/2/3.
65
65
  trusted?: boolean;
66
+ // ts of the row this write replaces, when the caller is an update. GATE-3
67
+ // excludes it from rivalry: the update IS the sanctioned supersession, so it
68
+ // must never be blocked as a conflict with the row it is about to supersede.
69
+ supersedesTs?: string;
66
70
  }
67
71
 
68
72
  export interface GateOutcome {
@@ -112,6 +116,14 @@ function jaccard(a: string[], b: string[]): number {
112
116
  return union === 0 ? 0 : inter / union;
113
117
  }
114
118
 
119
+ // GATE-3 similarity floors. OVERLAP_FLOOR: reworded near-duplicates of any
120
+ // type are merge-review candidates. CONFLICT_OVERLAP_FLOOR: decisions and
121
+ // preferences compete sooner — a value swap on the same subject is a rivalry
122
+ // at moderate overlap, while distinct statements in a shared scope sit well
123
+ // below this band and must store clean.
124
+ const OVERLAP_FLOOR = 0.9;
125
+ const CONFLICT_OVERLAP_FLOOR = 0.3;
126
+
115
127
  // Planning-flavored content (frontier/thread/proposal language). Used only to
116
128
  // turn GATE-4's ambiguous block into a hint pointing at the open-thread home.
117
129
  const PLANNING_WORDS = new Set([
@@ -215,16 +227,26 @@ export async function runWriteGate(
215
227
  ctx: GateContext,
216
228
  ): Promise<GateOutcome> {
217
229
  const chain = chainId();
230
+ // Gate audit lines thread the session: runWriteGate awaits (analysis, the
231
+ // locked append), and another session's dispatch can move the ambient
232
+ // current mid-gate — ambient-read lines would then name the wrong session
233
+ // (#118 review note 1; the rows were fixed in #118, these were the
234
+ // residue). Where ctx.sessionID is unset (tool paths — issue #121) record()
235
+ // keeps the ambient read, exactly as before.
236
+ const rec = (ev: string, fields: Record<string, unknown> = {}, includeContext = true) =>
237
+ record(ev, fields, includeContext, ctx.sessionID);
238
+ const recBlocked = (gate: number, reason: string, flags: string[], chain?: string) =>
239
+ recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID);
218
240
 
219
241
  // Size/type floor BEFORE any scanning: gate analysis regexes
220
242
  // over megabyte content backtrack super-linearly and freeze the service
221
243
  // event loop (100KB write = 6s, 2MB = never returned).
222
244
  if (typeof candidate.content !== "string") {
223
- await recordWriteBlocked(4, "invalid_content", [`content_type=${typeof candidate.content}`], chain);
245
+ await recBlocked(4, "invalid_content", [`content_type=${typeof candidate.content}`], chain);
224
246
  return { action: "blocked", reason: "invalid_content", chain, hint: "content must be a string." };
225
247
  }
226
248
  if (candidate.content.length > MAX_CONTENT_CHARS) {
227
- await recordWriteBlocked(4, "content_too_long", [`len=${candidate.content.length}`, `max=${MAX_CONTENT_CHARS}`], chain);
249
+ await recBlocked(4, "content_too_long", [`len=${candidate.content.length}`, `max=${MAX_CONTENT_CHARS}`], chain);
228
250
  return {
229
251
  action: "blocked",
230
252
  reason: "content_too_long",
@@ -259,7 +281,7 @@ export async function runWriteGate(
259
281
  badMetadata.push("kw");
260
282
  }
261
283
  if (badMetadata.length) {
262
- await recordWriteBlocked(4, "invalid_metadata", [`fields=${badMetadata.join(",")}`], chain);
284
+ await recBlocked(4, "invalid_metadata", [`fields=${badMetadata.join(",")}`], chain);
263
285
  return {
264
286
  action: "blocked",
265
287
  reason: "invalid_metadata",
@@ -275,7 +297,7 @@ export async function runWriteGate(
275
297
  containsSecret(candidate.issue) ? "issue" : undefined,
276
298
  ].filter((field): field is string => field !== undefined);
277
299
  if (credentialMetadata.length) {
278
- await recordWriteBlocked(
300
+ await recBlocked(
279
301
  4,
280
302
  "credential_in_metadata",
281
303
  credentialMetadata.map((field) => `field=${field}`),
@@ -298,7 +320,7 @@ export async function runWriteGate(
298
320
  };
299
321
 
300
322
  const ch = contentHash(candidate.content);
301
- await record("gate_start", {
323
+ await rec("gate_start", {
302
324
  chain,
303
325
  op: "write",
304
326
  scope: candidate.scope,
@@ -319,7 +341,7 @@ export async function runWriteGate(
319
341
  tree,
320
342
  });
321
343
  if (g1.drift) {
322
- await record("graph_drift", {
344
+ await rec("graph_drift", {
323
345
  gate: 1,
324
346
  symbol: g1.drift.symbol,
325
347
  from: g1.drift.from,
@@ -329,7 +351,7 @@ export async function runWriteGate(
329
351
  chain,
330
352
  });
331
353
  } else {
332
- await record("graph_current", {
354
+ await rec("graph_current", {
333
355
  gate: 1,
334
356
  refs: g1.refs,
335
357
  resolved: g1.resolved.length ? g1.resolved.join(",") : undefined,
@@ -351,7 +373,7 @@ export async function runWriteGate(
351
373
  if (s) stale.push(s);
352
374
  }
353
375
  const bailed = scopeMems.length === 0;
354
- await record("ref_stale_scan", {
376
+ await rec("ref_stale_scan", {
355
377
  gate: 2,
356
378
  scope: candidate.scope,
357
379
  delta: bracketList(delta),
@@ -364,7 +386,7 @@ export async function runWriteGate(
364
386
  let supersededTs: string | undefined;
365
387
  const driftPlan: { s: StaleRef; target: string; fields: SupersedeFields }[] = [];
366
388
  for (const s of stale) {
367
- await record("ref_stale", {
389
+ await rec("ref_stale", {
368
390
  gate: 2,
369
391
  mem: s.memory.ts,
370
392
  scope: candidate.scope,
@@ -390,7 +412,7 @@ export async function runWriteGate(
390
412
  if (markedCount > 0) {
391
413
  for (const p of driftPlan) {
392
414
  supersededTs = p.s.memory.ts;
393
- await record("superseded_by", {
415
+ await rec("superseded_by", {
394
416
  gate: 2,
395
417
  mem: p.s.memory.ts,
396
418
  target: p.target,
@@ -405,7 +427,7 @@ export async function runWriteGate(
405
427
  }
406
428
 
407
429
  if (canon) {
408
- await record("canonical_hit", {
430
+ await rec("canonical_hit", {
409
431
  gate: 2,
410
432
  entity: canon.entry.entity,
411
433
  value: canon.entry.value,
@@ -434,7 +456,7 @@ export async function runWriteGate(
434
456
  })))) > 0) {
435
457
  for (const p of canonPlan) {
436
458
  if (!supersededTs) supersededTs = p.ts;
437
- await record("superseded_by", {
459
+ await rec("superseded_by", {
438
460
  gate: 2,
439
461
  mem: p.ts,
440
462
  target,
@@ -459,49 +481,54 @@ export async function runWriteGate(
459
481
  const exact = exactPoll.find(
460
482
  (m) => m.type === candidate.type && m.content === candidate.content,
461
483
  );
462
- const divergent = active.filter(
463
- (m) => m.type === candidate.type && m.content !== candidate.content,
464
- );
484
+ // Same-type live rows that could compete with the incoming statement; the
485
+ // row an update replaces is never a contender.
486
+ const live = active.filter((m) => m.type === candidate.type && m.ts !== ctx.supersedesTs);
487
+ const divergent = live.filter((m) => m.content !== candidate.content);
465
488
 
466
489
  let collapseMatch: Memory | undefined;
467
490
  let overlapMatch: Memory | undefined;
468
491
  let overlapScore = 0;
469
492
 
493
+ // A rival is a live same-type row stating the same thing differently enough:
494
+ // it must clear a similarity floor, not merely exist. conflictProne types
495
+ // compete at a lower floor than plain rewordings because a value swap
496
+ // ("use Express" vs "use Fastify") is a genuine rivalry far below the
497
+ // rephrase band, while topically distinct decisions/preferences in one
498
+ // scope are normal coexisting statements, not conflicts. A canonical that
499
+ // covers the statement already settles rivalry, so conflictProne types skip
500
+ // the scan; the row an update replaces is never a contender.
501
+ const floor = conflictProne ? CONFLICT_OVERLAP_FLOOR : OVERLAP_FLOOR;
502
+ const contenders = !conflictProne ? live : canon ? [] : divergent;
503
+ let rival: { m: Memory; score: number } | undefined;
504
+ for (const m of contenders) {
505
+ const score = jaccard(tokens(candidate.content), tokens(m.content));
506
+ if (score >= floor && (!rival || score > rival.score)) rival = { m, score };
507
+ }
508
+
470
509
  if (
471
510
  exact &&
472
511
  !exact.superseded_by &&
473
- (canon?.aligns || !(conflictProne && divergent.length))
512
+ (canon?.aligns || !(conflictProne && rival))
474
513
  ) {
475
514
  // Byte-identical duplicate collapses (Principle 2) — exactness is
476
515
  // independent of the canonical registry, so a decided/preferred fact
477
516
  // restated verbatim is never "conflicting" content on its own. Two
478
517
  // exceptions keep the S4/S4b semantics: a canonical that aligns resolves
479
- // the rivalry (echo collapses), but a scope already holding RIVAL
480
- // decision/preference entries with no resolving canon keeps the exact
481
- // restatement review-gated — dedup must not silently bury a conflict.
518
+ // the rivalry (echo collapses), but a scope already holding a RIVAL
519
+ // decision/preference entry (over the conflict floor) with no resolving
520
+ // canon keeps the exact restatement review-gated — dedup must not silently
521
+ // bury a conflict.
482
522
  collapseMatch = exact;
483
- } else if (conflictProne) {
484
- if (!canon && divergent.length) {
485
- // Conflicting decisions without a registry entry -> review-gated merge.
486
- overlapMatch = divergent[0];
487
- overlapScore =
488
- Math.round(jaccard(tokens(candidate.content), tokens(divergent[0].content)) * 100) / 100;
489
- }
490
- } else {
491
- let best: { m: Memory; score: number } | undefined;
492
- for (const m of active) {
493
- if (m.type !== candidate.type) continue;
494
- const score = jaccard(tokens(candidate.content), tokens(m.content));
495
- if (score >= 0.9 && (!best || score > best.score)) best = { m, score };
496
- }
497
- if (best) {
498
- overlapMatch = best.m;
499
- overlapScore = Math.round(best.score * 100) / 100;
500
- }
523
+ } else if (rival) {
524
+ // Review-gated merge: a competing decision/preference, or a reworded
525
+ // near-duplicate of a live row.
526
+ overlapMatch = rival.m;
527
+ overlapScore = Math.round(rival.score * 100) / 100;
501
528
  }
502
529
 
503
530
  if (collapseMatch) {
504
- await record("dedup_collapse", {
531
+ await rec("dedup_collapse", {
505
532
  gate: 3,
506
533
  survivors: scopeMems.length,
507
534
  match: collapseMatch.ts,
@@ -511,7 +538,7 @@ export async function runWriteGate(
511
538
  chain,
512
539
  });
513
540
  } else if (overlapMatch) {
514
- await record("dedup_overlap", {
541
+ await rec("dedup_overlap", {
515
542
  gate: 3,
516
543
  survivors: scopeMems.length,
517
544
  candidate: overlapMatch.ts,
@@ -520,7 +547,7 @@ export async function runWriteGate(
520
547
  chain,
521
548
  });
522
549
  } else {
523
- await record("dedup_clean", {
550
+ await rec("dedup_clean", {
524
551
  gate: 3,
525
552
  survivors: scopeMems.length,
526
553
  candidate: 0,
@@ -568,8 +595,14 @@ export async function runWriteGate(
568
595
  ];
569
596
  } else if (overlapMatch) {
570
597
  blockReason = "superseded_overlap";
571
- const newest = scopeMems[scopeMems.length - 1];
572
- blockFlags = [`supersedes_check_${newest ? newest.ts : "-"}`, "review_gated"];
598
+ blockFlags = [`supersedes_check_${overlapMatch.ts}`, `score=${overlapScore}`, "review_gated"];
599
+ hint =
600
+ `A live ${candidate.type} row ${overlapMatch.ts} in ${candidate.scope || "(no scope)"} competes ` +
601
+ `with this write (overlap ${overlapScore}). Nothing was stored. To replace that row, use ` +
602
+ `memory_update with query="${overlapMatch.ts}" — an update supersedes its target instead of ` +
603
+ `conflicting with it. If both statements should stand, store this one under a distinct ` +
604
+ `scope. memory_merge_review resolves proposals between stored rows only; this candidate was ` +
605
+ `never stored, so it cannot be resolved from here.`;
573
606
  } else if (ambiguous && !collapseMatch) {
574
607
  blockReason = "ambiguous_memory";
575
608
  blockFlags = flags;
@@ -580,15 +613,19 @@ export async function runWriteGate(
580
613
  }
581
614
 
582
615
  if (blockReason) {
583
- await recordWriteBlocked(4, blockReason, blockFlags, chain);
616
+ await recBlocked(4, blockReason, blockFlags, chain);
584
617
  if (blockReason === "superseded_overlap" && overlapMatch) {
585
618
  const newest = scopeMems[scopeMems.length - 1] ?? overlapMatch;
586
- await record("merge_proposal", {
619
+ // Advisory, not actionable: the incoming candidate was never persisted,
620
+ // so no memory_merge_review loser exists for it. The line is rivalry
621
+ // telemetry and a pointer to the stored rival.
622
+ await rec("merge_proposal", {
587
623
  candidate: overlapMatch.ts,
588
624
  incoming: chain,
589
625
  canonical: newest.ts,
590
626
  source: `durable_${candidate.type}`,
591
- review: "required",
627
+ review: "advisory",
628
+ incoming_stored: false,
592
629
  chain,
593
630
  });
594
631
  }
@@ -606,14 +643,14 @@ export async function runWriteGate(
606
643
  g1.refs === 0 && !ctx.hasGateCheck &&
607
644
  ctx.hasEngagement === true && candidate.scope !== "";
608
645
  if (groundedByEngagement) {
609
- await record("gate_injected", { gate: 4, chain });
646
+ await rec("gate_injected", { gate: 4, chain });
610
647
  }
611
648
 
612
649
  const snapshot = await snapshotFiles([join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`)]);
613
650
  // The write carries the CALLER's session, not whatever current says after
614
651
  // the gate's own awaits - capture's stamp must follow the captured session.
615
652
  const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
616
- await record("write_promoted", {
653
+ await rec("write_promoted", {
617
654
  gate: 4,
618
655
  op: "write",
619
656
  mem: ts,
package/src/index.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  type Memory,
28
28
  } from "./memory.ts";
29
29
  import { runWriteGate, type GateContext, type WriteCandidate } from "./gates.ts";
30
+ import { withStoreLock } from "./lock.ts";
30
31
  import { pruneMemory } from "./prune.ts";
31
32
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
32
33
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
@@ -459,45 +460,77 @@ const impl = {
459
460
  options: direct,
460
461
  async execute(args): Promise<{ content: string }> {
461
462
  await bindSessionIdentity(getCurrent().sid);
462
- const prior = (await loadAll()).filter(
463
- (m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleHere(m),
464
- );
465
- // Resolve the row BEFORE the gate: an update that cannot identify its
466
- // target must write nothing, rather than silently superseding whichever
467
- // row happened to be newest in this scope+type.
468
- const resolved = resolveMemoryTarget(prior, args.query);
469
- if (resolved.status === "not_found") {
470
- const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
471
- return {
472
- content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
473
- };
474
- }
475
- if (resolved.status === "ambiguous") {
463
+ // The whole update — resolve, gate, supersede — runs under one
464
+ // UPDATE-ORDER lock. Without it, two concurrent updates that both
465
+ // resolved the same still-active target both promoted and both
466
+ // claimed success: markSuperseded is first-call-wins, so one
467
+ // replacement row silently survived un-superseded (measured 5/5).
468
+ // This outer lock is a DISTINCT file from anything runWriteGate or
469
+ // markSuperseded take (sections run flat — never re-enter a file
470
+ // you hold), and the acquisition order is always update-order
471
+ // then store, never the reverse, so it cannot deadlock against a
472
+ // plain writer. On timeout it FAILS closed: proceeding unlocked
473
+ // is exactly the race this lock exists to close. The loser then
474
+ // re-resolves under the lock, finds its target already retired,
475
+ // and writes nothing — the documented fail-closed contract.
476
+ try {
477
+ return await withStoreLock(
478
+ join(memoryRoot(), "update-order"),
479
+ async () => {
480
+ const prior = (await loadAll()).filter(
481
+ (m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleHere(m),
482
+ );
483
+ // Resolve the row BEFORE the gate: an update that cannot identify its
484
+ // target must write nothing, rather than silently superseding whichever
485
+ // row happened to be newest in this scope+type.
486
+ const resolved = resolveMemoryTarget(prior, args.query);
487
+ if (resolved.status === "not_found") {
488
+ const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
489
+ return {
490
+ content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
491
+ };
492
+ }
493
+ if (resolved.status === "ambiguous") {
494
+ return {
495
+ content:
496
+ `memory_update blocked: ${JSON.stringify(args.query)} matches ${resolved.candidates.length} active ` +
497
+ `${args.type} rows in ${args.scope} (${resolved.candidates.map((m) => m.ts).join(", ")}). ` +
498
+ "Pass a row id or a unique content substring. Nothing was written.",
499
+ };
500
+ }
501
+ const target = resolved.target;
502
+ const outcome = await runWriteGate(
503
+ { type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
504
+ { ...gateContext(), supersedesTs: target.ts },
505
+ );
506
+ if (outcome.action === "promoted" && outcome.ts && target) {
507
+ await markSuperseded(target.ts, {
508
+ superseded_by: outcome.ts,
509
+ reason: "update",
510
+ symbol: target.ts,
511
+ from: target.ts,
512
+ to: outcome.ts,
513
+ });
514
+ return { content: `Updated ${args.type} in ${args.scope} (superseded ${target.ts})` };
515
+ }
516
+ if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
517
+ if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
518
+ return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
519
+ },
520
+ {
521
+ onTimeout: "fail",
522
+ onEvent: (event, waitedMs) => {
523
+ void record("store_lock", { event, waited_ms: waitedMs, op: "update" });
524
+ },
525
+ },
526
+ );
527
+ } catch (err) {
528
+ // Only the fail-closed lock timeout throws here; the write path
529
+ // has its own outcomes. Nothing was written either way.
476
530
  return {
477
- content:
478
- `memory_update blocked: ${JSON.stringify(args.query)} matches ${resolved.candidates.length} active ` +
479
- `${args.type} rows in ${args.scope} (${resolved.candidates.map((m) => m.ts).join(", ")}). ` +
480
- "Pass a row id or a unique content substring. Nothing was written.",
531
+ content: `memory_update blocked: ${(err as Error).message} Nothing was written.`,
481
532
  };
482
533
  }
483
- const target = resolved.target;
484
- const outcome = await runWriteGate(
485
- { type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
486
- gateContext(),
487
- );
488
- if (outcome.action === "promoted" && outcome.ts && target) {
489
- await markSuperseded(target.ts, {
490
- superseded_by: outcome.ts,
491
- reason: "update",
492
- symbol: target.ts,
493
- from: target.ts,
494
- to: outcome.ts,
495
- });
496
- return { content: `Updated ${args.type} in ${args.scope} (superseded ${target.ts})` };
497
- }
498
- if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
499
- if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
500
- return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
501
534
  },
502
535
  }));
503
536
 
@@ -587,12 +620,24 @@ const impl = {
587
620
  editor.add(validated(MergeReviewArgs, {
588
621
  name: "memory_merge_review",
589
622
  description:
590
- "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. Fails closed (no partial apply) when the reason or the survivor id is missing, or the loser is already superseded.",
623
+ "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. Fails closed (no partial apply) when the reason or the survivor id is missing, the survivor id names no row in the store, or the loser is already superseded or is the survivor itself.",
591
624
  options: direct,
592
625
  async execute(args): Promise<{ content: string }> {
593
626
  if (!args.loser || !args.survivor || !args.reason) {
594
627
  return { content: "merge_review blocked: loser, survivor, and reason are all required (fail-closed)." };
595
628
  }
629
+ // Probed: marking with a survivor id that names no row retired the
630
+ // loser toward a pointer to nothing (the scope ended with zero
631
+ // active rows) while the response declared it canonical. Validate
632
+ // BEFORE touching the loser — a resolution must never retire real
633
+ // data for a phantom. (Same-row input would mark and then revive
634
+ // the same row: a silent no-op that reports full success.)
635
+ if (args.loser === args.survivor) {
636
+ return { content: "merge_review blocked: loser and survivor are the same row — nothing to resolve. No evidence written." };
637
+ }
638
+ if (!(await loadAll()).some((m) => m.ts === args.survivor)) {
639
+ return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
640
+ }
596
641
  const ok = await markSuperseded(args.loser, {
597
642
  superseded_by: args.survivor,
598
643
  reason: args.reason,
@@ -607,6 +652,16 @@ const impl = {
607
652
  // this very call just made the loser). Declaring it canonical has to
608
653
  // make it recallable, so clear its own marker too.
609
654
  const revived = await clearSuperseded(args.survivor);
655
+ // The response has always claimed "Evidence recorded" — now it is
656
+ // true. The host tool_result hook covers grep/read/edit/shell only,
657
+ // so a merge used to leave zero trace: which reviewer decision, on
658
+ // which reason, reviving what — unauditable.
659
+ await record("merge_resolved", {
660
+ loser: args.loser,
661
+ survivor: args.survivor,
662
+ revived,
663
+ reason: args.reason,
664
+ });
610
665
  return {
611
666
  content:
612
667
  `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
package/src/schema.ts CHANGED
@@ -127,8 +127,10 @@ export const EvidenceArgs = z.object({
127
127
  });
128
128
 
129
129
  export const MergeReviewArgs = z.object({
130
- loser: z.string().describe("Evidence id of the rival/overlap write to supersede"),
131
- survivor: z.string().describe("Evidence id of the canonical winning write"),
130
+ loser: z
131
+ .string()
132
+ .describe("Ts id of the stored losing row to supersede (a blocked write was never stored and has no id)"),
133
+ survivor: z.string().describe("Ts id of the stored canonical winning row"),
132
134
  reason: z.string().describe("Why the survivor is canonical over the loser (written to evidence)"),
133
135
  });
134
136