opencode-self-improvement 0.14.17 → 0.14.18

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
@@ -89,7 +89,7 @@ Four gates run before anything is stored, and each emits an ordered evidence lin
89
89
  3. **GATE-3 — no duplicates.** Near-duplicates collapse into the existing row; a contradiction with a superseded memory is rejected.
90
90
  4. **GATE-4 — promotion or block.** The row lands, or the call returns the reason.
91
91
 
92
- Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget` records a retirement, and `memory_undo` restores a snapshot. `memory_update` takes a `query` that picks the row — its id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it to update the newest entry of that scope and type. A `query` that matches nothing, or several rows, writes nothing and says so.
92
+ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget` records a retirement, and `memory_undo` restores a snapshot. `memory_update` takes a `query` that picks the row — its id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it to update the newest entry of that scope and type. A `query` that matches nothing, or several rows, writes nothing and says so. A prose edit changes only the prose: the row's tags, issue link, retrieval keywords, open/settled standing, and repository all carry over to the new row — updating a `global` row from one machine keeps it global for every other. Naming a row an earlier update already superseded reports the duplicate when the live successor already holds that exact content; when only the metadata you name differs, the update runs against the successor instead of dead-ending. And a failure after the new row is durable is reported as `PARTIAL` — the message names what failed, the replacement stands on disk, and `memory_undo` (merge or force) brings the old row back.
93
93
 
94
94
  ## Repo scoping
95
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.17",
3
+ "version": "0.14.18",
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,7 +8,7 @@ import {
8
8
  appendMemory,
9
9
  loadAll,
10
10
  loadScope,
11
- markManySuperseded,
11
+ markManySupersededReport,
12
12
  snapshotFiles,
13
13
  MAX_CONTENT_CHARS,
14
14
  type Memory,
@@ -48,6 +48,25 @@ export interface WriteCandidate {
48
48
  repoPath?: string;
49
49
  }
50
50
 
51
+ // Metadata-list equality (retrieval keywords, tags): pairwise, undefined and
52
+ // empty counting as the same content. Shared by GATE-3's update carve-out and
53
+ // memory_update's successor verdict so both sides ask the same question.
54
+ // ORDER-SENSITIVE on purpose: ["a","b"] vs ["b","a"] counts as a metadata
55
+ // edit (a new row, the old one intact) — a set comparison would silently
56
+ // collapse an edit whose ordering the caller changed deliberately, and the
57
+ // conservative direction for a truth-claim is the one that writes more.
58
+ export const sameStrList = (a?: string[], c?: string[]) =>
59
+ (a?.length ?? 0) === (c?.length ?? 0) && (a ?? []).every((x, i) => (c ?? [])[i] === x);
60
+
61
+ // The sentence every success reply owes the reader when the gate promoted a
62
+ // row but its write_promoted audit line failed to land (#155 review): the
63
+ // row IS durable — and memory_evidence, where every other verdict points
64
+ // the curious reader, will show NOTHING for it. Only silence was optional.
65
+ export const auditCaveat = (outcome: GateOutcome): string =>
66
+ outcome.evidenceError !== undefined
67
+ ? ` (its audit line was not recorded: ${outcome.evidenceError})`
68
+ : "";
69
+
51
70
  export interface GateContext {
52
71
  liveRoot: string;
53
72
  evidenceCalls: string[];
@@ -69,6 +88,12 @@ export interface GateContext {
69
88
  // excludes it from rivalry: the update IS the sanctioned supersession, so it
70
89
  // must never be blocked as a conflict with the row it is about to supersede.
71
90
  supersedesTs?: string;
91
+ // Optional caller-owned ledger (#158 round 3): GATE-2's drift/canonical
92
+ // supersessions append the ts values they made durable HERE, immediately
93
+ // after the batch publish and BEFORE their audit lines — so a failed audit
94
+ // line can no longer hide a persisted retirement from the caller's catch.
95
+ // "Nothing was written" is only writable when this stays empty.
96
+ durable?: string[];
72
97
  }
73
98
 
74
99
  export interface GateOutcome {
@@ -77,6 +102,18 @@ export interface GateOutcome {
77
102
  ts?: string;
78
103
  chain: string;
79
104
  hint?: string;
105
+ // Promoted with the row DURABLE but its post-append write_promoted audit
106
+ // line failed (#155). Entry points with a further post-mutation step
107
+ // (memory_update's supersede) must still run it and report a partial
108
+ // result. Throwing was the old shape of this signal and it lied: callers
109
+ // read it as "nothing happened" while the row sat on disk. Pre-append
110
+ // faults keep throwing — there, nothing was in fact written.
111
+ evidenceError?: string;
112
+ // On a collapsed (un-stored) write: the ts of the ACTIVE row whose content
113
+ // already IS the candidate. An update completing its supersession needs the
114
+ // survivor's id to retire its own target in the survivor's favor (#155
115
+ // convergence: a retry must be able to end with one active row).
116
+ collapsedWith?: string;
80
117
  }
81
118
 
82
119
  const STOPWORDS = new Set([
@@ -414,6 +451,14 @@ export async function runWriteGate(
414
451
  // and the pass is skipped by the batch (it re-reads under the lock).
415
452
  const target = g1.candidateStale ? "<-" : chain;
416
453
  if (typeof s.memory.superseded_by === "string") continue;
454
+ // The row an UPDATE replaces is retired by the update itself, with its
455
+ // own pointer. A drift stamp here wins first-call-wins against the
456
+ // caller's markSuperseded and leaves a chain id the caller's retry can
457
+ // never walk — so the tool would print "(superseded X)" naming a
458
+ // retirement it did not perform. Same principle GATE-3 applies to
459
+ // rivalry (the target is never a contender): the update IS the sanctioned
460
+ // supersession for that row.
461
+ if (s.memory.ts === ctx.supersedesTs) continue;
417
462
  driftPlan.push({
418
463
  s,
419
464
  target,
@@ -421,8 +466,11 @@ export async function runWriteGate(
421
466
  });
422
467
  }
423
468
  if (driftPlan.length > 0) {
424
- const markedCount = await markManySuperseded(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
425
- if (markedCount > 0) {
469
+ const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
470
+ if (marked.length > 0) {
471
+ // Ledger BEFORE the audit lines: what is on disk now stays on disk no
472
+ // matter what the record loop below does (round-3 probe 3).
473
+ ctx.durable?.push(...marked);
426
474
  for (const p of driftPlan) {
427
475
  supersededTs = p.s.memory.ts;
428
476
  await rec("superseded_by", {
@@ -455,6 +503,9 @@ export async function runWriteGate(
455
503
  const canonPlan: { ts: string; from: string | undefined }[] = [];
456
504
  for (const m of scopeMems) {
457
505
  if (m.superseded_by) continue;
506
+ // The update's own target retires in the update's hand, not the
507
+ // canonical registry's (see the GATE-2 drift skip above).
508
+ if (m.ts === ctx.supersedesTs) continue;
458
509
  if (tokens(m.content).some((t) => valueSet.has(t))) continue;
459
510
  const from = rawTokens(m.content).find(
460
511
  (t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()) && !valueSet.has(t.toLowerCase()),
@@ -463,10 +514,15 @@ export async function runWriteGate(
463
514
  }
464
515
  // One batch publish for the whole neutralization set (#61); rows marked
465
516
  // out-of-band since the scan are skipped by the batch (re-read under lock).
466
- if ((await markManySuperseded(canonPlan.map((p) => ({
467
- ts: p.ts,
468
- fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
469
- })))) > 0) {
517
+ const { marked: canonMarked } = await markManySupersededReport(
518
+ canonPlan.map((p) => ({
519
+ ts: p.ts,
520
+ fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
521
+ })),
522
+ );
523
+ if (canonMarked.length > 0) {
524
+ // Same ledger discipline as the drift batch above.
525
+ ctx.durable?.push(...canonMarked);
470
526
  for (const p of canonPlan) {
471
527
  if (!supersededTs) supersededTs = p.ts;
472
528
  await rec("superseded_by", {
@@ -491,8 +547,21 @@ export async function runWriteGate(
491
547
  const exactPoll = scopeMems.filter(
492
548
  (m) => m.superseded_by === undefined || m.reason === "drift",
493
549
  );
550
+ // Byte-exact duplicate prose collapses (Principle 2) — with one UPDATE-only
551
+ // carve-out: the row being replaced counts as a duplicate of the candidate
552
+ // only if the update also restates its metadata. Same prose plus different
553
+ // retrieval keywords or status is a metadata EDIT on that row (GATE-3
554
+ // already refuses to see it as a rival), and collapsing it would silently
555
+ // drop the edit — the tool could then never edit kw or status at all.
494
556
  const exact = exactPoll.find(
495
- (m) => m.type === candidate.type && m.content === candidate.content,
557
+ (m) =>
558
+ m.type === candidate.type &&
559
+ m.content === candidate.content &&
560
+ (m.ts !== ctx.supersedesTs ||
561
+ (sameStrList(m.kw, candidate.kw) &&
562
+ sameStrList(m.tags, candidate.tags) &&
563
+ m.issue === candidate.issue &&
564
+ (m.status ?? "settled") === (candidate.status ?? "settled"))),
496
565
  );
497
566
  // Same-type live rows that could compete with the incoming statement; the
498
567
  // row an update replaces is never a contender.
@@ -646,7 +715,7 @@ export async function runWriteGate(
646
715
  }
647
716
 
648
717
  if (collapseMatch) {
649
- return { action: "collapsed", chain };
718
+ return { action: "collapsed", chain, collapsedWith: collapseMatch.ts };
650
719
  }
651
720
 
652
721
  // The write is specifically promoted on engagement (no refs, no gate check,
@@ -667,21 +736,34 @@ export async function runWriteGate(
667
736
  // prompt-cache bust to be shown its own thought. Only promoted writes are
668
737
  // attributed — a blocked candidate created nothing.
669
738
  noteAuthored(ctx.sessionID, ts);
670
- await rec("write_promoted", {
671
- gate: 4,
672
- op: "write",
673
- mem: ts,
674
- scope: candidate.scope,
675
- type: candidate.type,
676
- status: candidate.status ?? "settled",
677
- ch,
678
- supersedes: supersededTs ?? "-",
679
- canonical: canon ? `canonical.logfmt:${canon.entry.ts}` : "-",
680
- evidence_refs: bracketList(ctx.evidenceCalls),
681
- snapshot: snapshot[0] ?? "-",
682
- trusted: ctx.trusted ? true : undefined,
683
- grounded_by: groundedByEngagement ? "engagement" : undefined,
684
- chain,
685
- });
686
- return { action: "promoted", ts, chain };
739
+ // Everything past the append is durable state: an audit failure from here
740
+ // must not escape as a throw, or the caller reports a write that happened
741
+ // as if it had not (#155 — memory_update told the model "Nothing was
742
+ // written" while the replacement row sat un-superseded on disk). The
743
+ // outcome carries the error instead.
744
+ let evidenceError: string | undefined;
745
+ try {
746
+ await rec("write_promoted", {
747
+ gate: 4,
748
+ op: "write",
749
+ mem: ts,
750
+ scope: candidate.scope,
751
+ type: candidate.type,
752
+ status: candidate.status ?? "settled",
753
+ ch,
754
+ supersedes: supersededTs ?? "-",
755
+ canonical: canon ? `canonical.logfmt:${canon.entry.ts}` : "-",
756
+ evidence_refs: bracketList(ctx.evidenceCalls),
757
+ snapshot: snapshot[0] ?? "-",
758
+ trusted: ctx.trusted ? true : undefined,
759
+ grounded_by: groundedByEngagement ? "engagement" : undefined,
760
+ chain,
761
+ });
762
+ } catch (err) {
763
+ // NOT `(err as Error).message`: a messageless Error (or a non-Error
764
+ // rejection) would make the field FALSY, and callers test it for truth —
765
+ // the lie this field exists to kill would return as a clean success.
766
+ evidenceError = err instanceof Error && err.message ? err.message : String(err);
767
+ }
768
+ return { action: "promoted", ts, chain, evidenceError };
687
769
  }
package/src/index.ts CHANGED
@@ -31,7 +31,7 @@ import {
31
31
  visibleTo,
32
32
  type Memory,
33
33
  } from "./memory.ts";
34
- import { runWriteGate, type GateContext, type WriteCandidate } from "./gates.ts";
34
+ import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gates.ts";
35
35
  import { withStoreLock } from "./lock.ts";
36
36
  import { pruneMemory } from "./prune.ts";
37
37
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
@@ -483,7 +483,11 @@ const impl = {
483
483
  if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
484
484
  }
485
485
  const outcome = await runWriteGate(candidate, gateContext(sid));
486
- if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
486
+ // A durable row whose audit line fell is NOT a clean success
487
+ // (#155 review): the reply says what is missing where it is
488
+ // missing, and the row itself stands.
489
+ if (outcome.action === "promoted")
490
+ return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
487
491
  if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
488
492
  return {
489
493
  content: `Write blocked at GATE (${outcome.reason}). ${
@@ -585,7 +589,7 @@ const impl = {
585
589
  editor.add(validated(UpdateArgs, {
586
590
  name: "memory_update",
587
591
  description:
588
- "Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing.",
592
+ "Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing. A prose edit carries over everything the call does not name — tags, issue, keywords, status, and the row's repository. Naming a row that was already updated to exactly this content (metadata included) reports the duplicate; if its live successor holds the prose and only the metadata you name differs, the successor is updated. A failure after the write is reported as PARTIAL: the replacement is durable and memory_undo merge/force restores the old row.",
589
593
  options: direct,
590
594
  async execute(args, context): Promise<{ content: string }> {
591
595
  const { sid } = toolIds(context);
@@ -606,6 +610,14 @@ const impl = {
606
610
  // is exactly the race this lock exists to close. The loser then
607
611
  // re-resolves under the lock, finds its target already retired,
608
612
  // and writes nothing — the documented fail-closed contract.
613
+ // Flips once a replacement row is durable, so the catch below can
614
+ // never claim "Nothing was written" about a write that happened
615
+ // (#155's lie).
616
+ let mutated = false;
617
+ // The gate's durable steps: rows GATE-2 retired before a later
618
+ // failure (round-3 probe 3). Non-empty means "Nothing was written"
619
+ // is no longer writable.
620
+ const gateDurable: string[] = [];
609
621
  try {
610
622
  return await withStoreLock(
611
623
  join(memoryRoot(), "update-order"),
@@ -616,12 +628,65 @@ const impl = {
616
628
  // Resolve the row BEFORE the gate: an update that cannot identify its
617
629
  // target must write nothing, rather than silently superseding whichever
618
630
  // row happened to be newest in this scope+type.
619
- const resolved = resolveMemoryTarget(prior, args.query);
631
+ let resolved = resolveMemoryTarget(prior, args.query);
620
632
  if (resolved.status === "not_found") {
621
- const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
622
- return {
623
- content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
624
- };
633
+ // Naming a SUPERSEDED row is not a miss (#155): the retry
634
+ // after a partial update lands here, and when that row's
635
+ // active successor already carries exactly this content the
636
+ // honest verdict is the duplicate one, not a dead end. Two
637
+ // subtleties the first cut missed: the successor's prose was
638
+ // stored REDACTED while a retry re-carries the raw input
639
+ // (the comparison must scrub), and "exactly this content"
640
+ // must mean the metadata too — a retry that also names new
641
+ // keywords still has work to do, and that work belongs on
642
+ // the chain head, so the update CONTINUES against the
643
+ // successor instead of collapsing here.
644
+ let chainHead: Memory | undefined;
645
+ if (args.query) {
646
+ const rows = (await loadAll()).filter(
647
+ (m) => m.scope === args.scope && m.type === args.type && isVisibleTo(m, reader),
648
+ );
649
+ const stale = resolveMemoryTarget(rows, args.query);
650
+ if (stale.status === "ok" && stale.target && !isActive(stale.target)) {
651
+ let latest = stale.target;
652
+ const walked = new Set<string>([latest.ts]);
653
+ while (latest.superseded_by) {
654
+ const next = rows.find((m) => m.ts === latest.superseded_by);
655
+ if (!next || walked.has(next.ts)) break;
656
+ walked.add(next.ts);
657
+ latest = next;
658
+ }
659
+ if (isActive(latest) && latest.content.trim() === redactSecrets(args.content).trim()) {
660
+ const restated =
661
+ (args.kw === undefined || sameStrList(args.kw, latest.kw)) &&
662
+ (args.status === undefined || args.status === (latest.status ?? "settled"));
663
+ if (restated) {
664
+ // Every other verdict is auditable; this one must
665
+ // be too — the message tells the model to consult
666
+ // memory_evidence.
667
+ await record(
668
+ "dedup_collapse",
669
+ { op: "update", named: stale.target.ts, match: latest.ts, action: "exact_successor", incoming_ignored: true },
670
+ true,
671
+ sid,
672
+ );
673
+ return {
674
+ content:
675
+ `Duplicate ignored: ${args.type}/${args.scope} — ${JSON.stringify(args.query)} was already ` +
676
+ `updated to exactly this content (${latest.ts}). Nothing was written.`,
677
+ };
678
+ }
679
+ chainHead = latest;
680
+ }
681
+ }
682
+ }
683
+ if (!chainHead) {
684
+ const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
685
+ return {
686
+ content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
687
+ };
688
+ }
689
+ resolved = { status: "ok", target: chainHead };
625
690
  }
626
691
  if (resolved.status === "ambiguous") {
627
692
  return {
@@ -632,22 +697,165 @@ const impl = {
632
697
  };
633
698
  }
634
699
  const target = resolved.target;
700
+ // A prose edit is not a metadata reset (#154): fields the
701
+ // call does not name carry over from the row being
702
+ // replaced, so updating an imported row can no longer
703
+ // launder away its provenance or issue link. kw follows
704
+ // the same rule with an override: omitted keeps the
705
+ // target's, provided replaces. The carry completes to the
706
+ // five fields of the #129 viewer precedent: STATUS (an
707
+ // open frontier row stays open) and REPO (updating a
708
+ // global row from one repository must not re-house it out
709
+ // of every other repository's view — "an edit must never
710
+ // widen visibility", and it must never narrow it either).
711
+ // These are also the fields the collapse-completion judges
712
+ // (review round 3): the fold asks whether the survivor
713
+ // already carries the REQUESTED state — not the pre-edit
714
+ // target's. An update naming kw:["new-alias"] is not
715
+ // "already standing" on a row holding ["old-alias"].
716
+ const requested = {
717
+ kw: args.kw ?? target.kw,
718
+ tags: target.tags,
719
+ issue: target.issue,
720
+ status: (args.status ?? target.status) ?? "settled",
721
+ repo: target.repo ?? "global",
722
+ };
635
723
  const outcome = await runWriteGate(
636
- { type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
637
- { ...gateContext(sid), supersedesTs: target.ts },
724
+ {
725
+ type: args.type,
726
+ scope: args.scope,
727
+ content: args.content,
728
+ kw: requested.kw,
729
+ tags: requested.tags,
730
+ issue: requested.issue,
731
+ status: requested.status,
732
+ repo: requested.repo,
733
+ repoPath: target.repo ? target.repoPath : undefined,
734
+ },
735
+ { ...gateContext(sid), supersedesTs: target.ts, durable: gateDurable },
638
736
  );
639
737
  if (outcome.action === "promoted" && outcome.ts && target) {
640
- await markSuperseded(target.ts, {
641
- superseded_by: outcome.ts,
642
- reason: "update",
643
- symbol: target.ts,
644
- from: target.ts,
645
- to: outcome.ts,
738
+ mutated = true;
739
+ const replacement = outcome.ts;
740
+ const retired = target.ts;
741
+ // The merge_review PARTIAL shape (156e887) applied to
742
+ // update: the replacement IS durable, so the message says
743
+ // exactly which follow-up step failed and what a retry does
744
+ // (#155 — never claim "Nothing was written" from here).
745
+ const partial = (why: string) => ({
746
+ content:
747
+ `memory_update PARTIAL: replacement ${replacement} IS on disk (memory_undo merge or force ` +
748
+ `restores ${retired}), but ${why}. Re-running this update reports the duplicate.`,
646
749
  });
647
- return { content: `Updated ${args.type} in ${args.scope} (superseded ${target.ts})` };
750
+ let retiredNow = false;
751
+ try {
752
+ retiredNow = await markSuperseded(retired, {
753
+ superseded_by: replacement,
754
+ reason: "update",
755
+ symbol: retired,
756
+ from: retired,
757
+ to: replacement,
758
+ });
759
+ } catch (err) {
760
+ return partial(
761
+ `retiring ${retired} failed: ${err instanceof Error && err.message ? err.message : String(err)}`,
762
+ );
763
+ }
764
+ if (!retiredNow) {
765
+ // merge_review checks exactly this boolean (156e887);
766
+ // "Updated (superseded X)" cannot be printed over a
767
+ // retirement a parallel supersession performed — that
768
+ // pointer names a DIFFERENT successor, and the confident
769
+ // line would hide a second active row.
770
+ return partial(
771
+ `${retired} had ALREADY been retired by another supersession while this call ran — ` +
772
+ `it points at that successor, not at ${replacement}; check memory_evidence`,
773
+ );
774
+ }
775
+ if (outcome.evidenceError !== undefined) {
776
+ return partial(`its write_promoted audit line was not recorded (${outcome.evidenceError})`);
777
+ }
778
+ return { content: `Updated ${args.type} in ${args.scope} (superseded ${retired})` };
779
+ }
780
+ if (outcome.action === "promoted")
781
+ return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
782
+ if (outcome.action === "collapsed") {
783
+ // Completion (#155 convergence): when a retry collapses
784
+ // because an ACTIVE row already holds exactly this content
785
+ // while the row it NAMES is still active (the supersede
786
+ // step of an earlier PARTIAL attempt never landed), the
787
+ // idempotent close is to retire the named row in the
788
+ // survivor's favor — a bare "Duplicate ignored" would leave
789
+ // two active rows forever and a retry that never converges.
790
+ // first-call-wins makes this safe to attempt on any path.
791
+ // But the fold must not INVERT #154 (review): retiring the
792
+ // named row is loss-free only when the survivor already
793
+ // carries what the named row carries — the SAME predicate
794
+ // GATE-3 uses to call same-prose-different-metadata an
795
+ // edit rather than a duplicate. Otherwise the survivor
796
+ // would stand stripped of the named row's issue link,
797
+ // keywords, tags or OPEN frontier standing, and a "clean
798
+ // no-op" message would paper over a metadata destruction.
799
+ // On disagreement nothing retires: both ids are named and
800
+ // a human (or an update on the survivor) decides.
801
+ const survivorTs = outcome.collapsedWith;
802
+ if (target && survivorTs && survivorTs !== target.ts) {
803
+ const survivor = (await loadAll()).find((m) => m.ts === survivorTs && !m.superseded_by);
804
+ if (survivor) {
805
+ // The predicate is the REQUESTED state vs the survivor
806
+ // (round 3): content equality is already proven by the
807
+ // collapse, so the fold is loss-free only when the
808
+ // survivor also carries the metadata THIS call asked
809
+ // for — and stands where the target stands for readers
810
+ // of other repositories (repo visibility: folding a
811
+ // global row into a repo-private survivor would
812
+ // narrow a visibility the promotion path exists to
813
+ // preserve, and the reverse would leak).
814
+ if (
815
+ sameStrList(requested.kw, survivor.kw) &&
816
+ sameStrList(requested.tags, survivor.tags) &&
817
+ requested.issue === survivor.issue &&
818
+ requested.status === (survivor.status ?? "settled") &&
819
+ requested.repo === (survivor.repo ?? "global")
820
+ ) {
821
+ const done = await markSuperseded(target.ts, {
822
+ superseded_by: survivorTs,
823
+ reason: "update",
824
+ symbol: target.ts,
825
+ from: target.ts,
826
+ to: survivorTs,
827
+ });
828
+ if (done) {
829
+ return {
830
+ content:
831
+ `Duplicate: ${args.type}/${args.scope} already stands active as ${survivorTs}; ` +
832
+ `${target.ts} was retired in its favor. Nothing new was written.`,
833
+ };
834
+ }
835
+ } else {
836
+ const differs: string[] = [];
837
+ if (requested.status !== (survivor.status ?? "settled"))
838
+ differs.push(`status ${requested.status} vs ${survivor.status ?? "settled"}`);
839
+ if (requested.issue !== survivor.issue)
840
+ differs.push(`issue ${requested.issue ?? "-"} vs ${survivor.issue ?? "-"}`);
841
+ if (!sameStrList(requested.kw, survivor.kw))
842
+ differs.push(`kw [${(requested.kw ?? []).join(", ") || "-"}] vs [${(survivor.kw ?? []).join(", ") || "-"}]`);
843
+ if (!sameStrList(requested.tags, survivor.tags))
844
+ differs.push(`tags [${(requested.tags ?? []).join(", ") || "-"}] vs [${(survivor.tags ?? []).join(", ") || "-"}]`);
845
+ if (requested.repo !== (survivor.repo ?? "global"))
846
+ differs.push(`visibility ${requested.repo} vs ${survivor.repo ?? "global"}`);
847
+ return {
848
+ content:
849
+ `Duplicate: ${args.type}/${args.scope} stands active as ${survivorTs}, but ${target.ts} ` +
850
+ `was NOT retired — the survivor does not carry what this update asked for ` +
851
+ `(${differs.join("; ")}), and the fold would drop it. Both stay active: restate them ` +
852
+ `onto ${survivorTs} with a memory_update, or memory_forget the row that should lose.`,
853
+ };
854
+ }
855
+ }
856
+ }
857
+ return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
648
858
  }
649
- if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
650
- if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
651
859
  return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
652
860
  },
653
861
  {
@@ -658,10 +866,27 @@ const impl = {
658
866
  },
659
867
  );
660
868
  } catch (err) {
661
- // Only the fail-closed lock timeout throws here; the write path
662
- // has its own outcomes. Nothing was written either way.
869
+ // Everything that still throws here was PRE-WRITE for THIS call's
870
+ // replacement: the fail-closed lock timeout, the #152 choke-point
871
+ // refusal, an evidence fault BEFORE the append. Post-append audit
872
+ // failures no longer reach this catch — the gate reports them on
873
+ // the promoted outcome (#155). mutated is the belt-and-braces
874
+ // truth check: a future post-write throw must report a partial,
875
+ // never a clean nothing. And gateDurable closes the last gap
876
+ // (round 3): the gate may have RETIRED OTHER rows at GATE-2
877
+ // before the fault that got here — those tombstones are on disk,
878
+ // and naming them beats the "Nothing was written" premise.
879
+ const msg = err instanceof Error && err.message ? err.message : String(err);
663
880
  return {
664
- content: `memory_update blocked: ${(err as Error).message} Nothing was written.`,
881
+ content: mutated
882
+ ? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
883
+ "Re-running this update reports the duplicate; inspect with memory_evidence."
884
+ : gateDurable.length > 0
885
+ ? `memory_update blocked: ${msg} No replacement was written, but the gate had ALREADY retired ` +
886
+ `${gateDurable.length} other row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
887
+ "disk and their audit lines may not all have landed. Re-running this update will not undo " +
888
+ "them — reconcile with memory_evidence / memory_undo before retrying."
889
+ : `memory_update blocked: ${msg} Nothing was written.`,
665
890
  };
666
891
  }
667
892
  },
@@ -958,6 +1183,12 @@ const impl = {
958
1183
  `${t.blocked} blocked by the gate, ${t.skipped} malformed lines skipped.` +
959
1184
  (t.downgraded
960
1185
  ? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
1186
+ : "") +
1187
+ // Rows that landed without their write_promoted line are
1188
+ // durable but invisible to memory_evidence (#155 review) —
1189
+ // the tally owes the reader the count, not silence.
1190
+ (t.unaudited
1191
+ ? ` ${t.unaudited} promoted rows landed without their write_promoted audit line (${t.auditError}); memory_evidence will miss them.`
961
1192
  : ""),
962
1193
  };
963
1194
  } catch (err) {
@@ -1642,7 +1873,17 @@ const impl = {
1642
1873
  ? `auto_capture_compaction_${outcome.action}`
1643
1874
  : `auto_capture_${outcome.action}`,
1644
1875
  // A blocked credential-shaped scope must not reach the evidence log either.
1645
- { session: sid, trigger, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
1876
+ // The promoted line also carries the audit fault when the
1877
+ // write_promoted line fell (#155 review — capture has no
1878
+ // reply to caveat, so this line is the trail's only note).
1879
+ {
1880
+ session: sid,
1881
+ trigger,
1882
+ type: c.type,
1883
+ scope: redactSecrets(c.scope),
1884
+ reason: outcome.reason ?? "",
1885
+ audit_error: outcome.evidenceError,
1886
+ },
1646
1887
  false,
1647
1888
  );
1648
1889
  }
package/src/init.ts CHANGED
@@ -47,6 +47,8 @@ export interface InitSummary {
47
47
  written: number;
48
48
  collapsed: number;
49
49
  blocked: number;
50
+ /** Written rows whose write_promoted audit line fell (#155 review). */
51
+ unaudited?: number;
50
52
  }
51
53
 
52
54
  const NOTABLE_KEYS = ["test", "e2e", "lint", "typecheck", "check", "build", "format"];
@@ -247,14 +249,19 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
247
249
  let written = 0;
248
250
  let collapsed = 0;
249
251
  let blocked = 0;
252
+ // Promoted rows whose write_promoted audit line fell (#155 review: the
253
+ // fault must be visible to every writer, bookkeeping included).
254
+ let unaudited = 0;
250
255
  for (const s of scripts) {
251
256
  const content = `${scope} ${s.key} command: run "${s.cmd}" from the repo root (${s.source}).`;
252
257
  const outcome = await runWriteGate(
253
258
  { type: "pattern", scope, content, tags: ["init", s.source] },
254
259
  gateCtx,
255
260
  );
256
- if (outcome.action === "promoted") written++;
257
- else if (outcome.action === "collapsed") collapsed++;
261
+ if (outcome.action === "promoted") {
262
+ written++;
263
+ if (outcome.evidenceError !== undefined) unaudited++;
264
+ } else if (outcome.action === "collapsed") collapsed++;
258
265
  else blocked++;
259
266
  }
260
267
 
@@ -267,6 +274,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
267
274
  if (stampOutcome.action === "promoted" && prior && stampOutcome.ts) {
268
275
  await markSuperseded(prior.ts, { superseded_by: stampOutcome.ts, reason: "init" });
269
276
  }
277
+ if (stampOutcome.action === "promoted" && stampOutcome.evidenceError !== undefined) unaudited++;
270
278
 
271
279
  await record(
272
280
  "init_complete",
@@ -280,6 +288,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
280
288
  written,
281
289
  collapsed,
282
290
  blocked,
291
+ unaudited,
283
292
  stamp: stampTs ?? "-",
284
293
  },
285
294
  false,
@@ -296,6 +305,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
296
305
  written,
297
306
  collapsed,
298
307
  blocked,
308
+ unaudited,
299
309
  };
300
310
  }
301
311
 
@@ -308,6 +318,8 @@ export function formatInit(s: InitSummary): string {
308
318
  `Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
309
319
  `Graph: ${s.graph.action}${s.graph.name ? ` (${s.graph.name})` : ""} [mode=${s.graph.mode}]`,
310
320
  scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
311
- `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}; stamp=${s.stampTs ?? "-"}`,
321
+ `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
322
+ (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
323
+ `; stamp=${s.stampTs ?? "-"}`,
312
324
  ].join("\n");
313
325
  }
package/src/memory.ts CHANGED
@@ -396,7 +396,7 @@ async function stampRow(
396
396
  // Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
397
397
  // Idempotent: a second call is a no-op, so no double `superseded_by`.
398
398
  export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
399
- return (await markManySuperseded([{ ts, fields }])) > 0;
399
+ return (await markManySupersededReport([{ ts, fields }])).marked.length > 0;
400
400
  }
401
401
 
402
402
  // Batch supersession (#61): one lock acquisition, one read, one snapshot and
@@ -408,56 +408,68 @@ export async function markSuperseded(ts: string, fields: SupersedeFields): Promi
408
408
  // so a repeat run marks nothing and writes nothing. Duplicate ts entries in
409
409
  // one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
410
410
  // Returns the number of rows actually marked.
411
- export async function markManySuperseded(
411
+ export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[]): Promise<number> {
412
+ return (await markManySupersededReport(entries)).marked.length;
413
+ }
414
+
415
+ // Same operation, reporting WHICH rows retired rather than how many (#158
416
+ // round 3): the write gate needs the ids to keep a durable-mutation ledger,
417
+ // because a failed audit line after a persisted retirement must still be able
418
+ // to name what actually landed. Skipped-by-the-batch rows (already retired
419
+ // out of band) are absent from `marked` — the ledger never claims a retirement
420
+ // this call did not perform.
421
+ export async function markManySupersededReport(
412
422
  entries: { ts: string; fields: SupersedeFields }[],
413
- ): Promise<number> {
414
- if (entries.length === 0) return 0;
423
+ ): Promise<{ marked: string[] }> {
424
+ if (entries.length === 0) return { marked: [] };
415
425
  const wanted = new Map<string, SupersedeFields>();
416
426
  for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
417
- let marked = 0;
427
+ const marked: string[] = [];
418
428
  for (const file of await memoryFiles()) {
419
- marked += await withStoreLock(
420
- file,
421
- async () => {
429
+ marked.push(
430
+ ...(await withStoreLock(
431
+ file,
432
+ async () => {
422
433
  // #106: identity BEFORE the read, like every other whole-file
423
434
  // read-modify-write (#89's contract) - the publish below may retry a
424
435
  // Windows handover only while the destination still matches this.
425
- const since = await fileIdentity(file);
426
- const lines = await readLines(file);
427
- let touched = 0;
428
- for (let i = 0; i < lines.length; i++) {
429
- const parsed = parseLine(lines[i]);
430
- if (!parsed || typeof parsed.superseded_by === "string") continue;
431
- const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
432
- if (!fields) continue;
433
- // Whole line rewritten, not extended: an old-format line comes out in
434
- // the current format with its values unchanged (as markSuperseded did).
435
- // The one exception is SECRET SCRUB (#128, review probe 4): the
436
- // fields a merge/decay/update copies into the loser's row carry
437
- // caller-authored prose (the rotation note "key ghp_... rotated"),
438
- // and content already scrubs at this same boundary (line 260). The
439
- // durable row must not be the one place a credential survives when
440
- // the evidence line beside it was cleaned.
441
- const clean: SupersedeFields = { ...fields };
442
- for (const k of Object.keys(clean)) {
443
- const v = (clean as unknown as Record<string, unknown>)[k];
444
- if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
436
+ const since = await fileIdentity(file);
437
+ const lines = await readLines(file);
438
+ const ids: string[] = [];
439
+ for (let i = 0; i < lines.length; i++) {
440
+ const parsed = parseLine(lines[i]);
441
+ if (!parsed || typeof parsed.superseded_by === "string") continue;
442
+ const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
443
+ if (!fields) continue;
444
+ // Whole line rewritten, not extended: an old-format line comes out in
445
+ // the current format with its values unchanged (as markSuperseded did).
446
+ // The one exception is SECRET SCRUB (#128, review probe 4): the
447
+ // fields a merge/decay/update copies into the loser's row carry
448
+ // caller-authored prose (the rotation note "key ghp_... rotated"),
449
+ // and content already scrubs at this same boundary (line 260). The
450
+ // durable row must not be the one place a credential survives when
451
+ // the evidence line beside it was cleaned.
452
+ const clean: SupersedeFields = { ...fields };
453
+ for (const k of Object.keys(clean)) {
454
+ const v = (clean as unknown as Record<string, unknown>)[k];
455
+ if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
456
+ }
457
+ lines[i] = formatLine({ ...parsed, ...clean });
458
+ ids.push(parsed.ts as string);
445
459
  }
446
- lines[i] = formatLine({ ...parsed, ...clean });
447
- touched++;
448
- }
449
- if (touched === 0) return 0;
450
- await snapshotBefore(file);
451
- await writeAtomic(file, lines.join("\n") + "\n", since);
452
- return touched;
453
- },
454
- LOCK_WRITE,
460
+ if (ids.length === 0) return [];
461
+ await snapshotBefore(file);
462
+ await writeAtomic(file, lines.join("\n") + "\n", since);
463
+ return ids;
464
+ },
465
+ LOCK_WRITE,
466
+ ))
455
467
  );
456
468
  }
457
469
  // A ts that appears in several files (should not exist - append mints unique
458
470
  // ts) retires in EVERY file here, where the row-by-row loop retired only the
459
471
  // first; both are conservation-safe, this one is the more honest tombstone.
460
- return marked;
472
+ return { marked };
461
473
  }
462
474
 
463
475
  // Drop a row's supersession markers IN PLACE (snapshot-first), making it active
package/src/portable.ts CHANGED
@@ -194,6 +194,10 @@ export interface ImportTally {
194
194
  skipped: number;
195
195
  /** Open rows downgraded because the file cannot grant that frontier scope. */
196
196
  downgraded: number;
197
+ /** Promoted rows whose write_promoted audit line failed to land (#155 review). */
198
+ unaudited: number;
199
+ /** First audit-fault message, so the reply can name what went wrong. */
200
+ auditError?: string;
197
201
  }
198
202
 
199
203
  // Recognize the export header line (see EXPORT_HEADER). A version NEWER than
@@ -277,7 +281,7 @@ function parseRow(line: string): WriteCandidate | null {
277
281
  // day files, snapshots and the blocklist, none of which are import formats.
278
282
  export async function importMemories(
279
283
  path: string,
280
- gate: (c: WriteCandidate) => Promise<{ action: string }>,
284
+ gate: (c: WriteCandidate) => Promise<{ action: string; evidenceError?: string }>,
281
285
  // The importing session, captured at tool entry (#127): "the importing
282
286
  // session's current repo" must be the CALLER's repo even though this loop
283
287
  // awaits the gate on every row, during which a concurrent session can move
@@ -297,7 +301,7 @@ export async function importMemories(
297
301
  }
298
302
  const file = Bun.file(target);
299
303
  if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
300
- const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
304
+ const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
301
305
  // #152: the importing session's repository is resolved BEFORE the first row,
302
306
  // through the writer rule rather than the ambient one. An unresolved named
303
307
  // session has no write target, and half a file re-stamped into whatever
@@ -339,8 +343,13 @@ export async function importMemories(
339
343
  tally.downgraded++;
340
344
  }
341
345
  const outcome = await gate(c);
342
- if (outcome.action === "promoted") tally.promoted++;
343
- else if (outcome.action === "collapsed") tally.collapsed++;
346
+ if (outcome.action === "promoted") {
347
+ tally.promoted++;
348
+ if (outcome.evidenceError !== undefined) {
349
+ tally.unaudited++;
350
+ tally.auditError ??= outcome.evidenceError;
351
+ }
352
+ } else if (outcome.action === "collapsed") tally.collapsed++;
344
353
  else tally.blocked++;
345
354
  }
346
355
  return tally;
package/src/schema.ts CHANGED
@@ -93,7 +93,10 @@ export const UpdateArgs = z.object({
93
93
  "Row selector: id (ts), clock fragment, or unique content substring. Omit to target the newest active row of scope+type.",
94
94
  )
95
95
  .optional(),
96
- status: z.enum(STATUSES).optional(),
96
+ status: z
97
+ .enum(STATUSES)
98
+ .describe("Settled or open; omitted keeps the target row's standing (an open frontier row stays open)")
99
+ .optional(),
97
100
  });
98
101
 
99
102
  export const ForgetArgs = z.object({