opencode-self-improvement 0.14.7 → 0.14.8

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.8",
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
@@ -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([
@@ -459,45 +471,50 @@ export async function runWriteGate(
459
471
  const exact = exactPoll.find(
460
472
  (m) => m.type === candidate.type && m.content === candidate.content,
461
473
  );
462
- const divergent = active.filter(
463
- (m) => m.type === candidate.type && m.content !== candidate.content,
464
- );
474
+ // Same-type live rows that could compete with the incoming statement; the
475
+ // row an update replaces is never a contender.
476
+ const live = active.filter((m) => m.type === candidate.type && m.ts !== ctx.supersedesTs);
477
+ const divergent = live.filter((m) => m.content !== candidate.content);
465
478
 
466
479
  let collapseMatch: Memory | undefined;
467
480
  let overlapMatch: Memory | undefined;
468
481
  let overlapScore = 0;
469
482
 
483
+ // A rival is a live same-type row stating the same thing differently enough:
484
+ // it must clear a similarity floor, not merely exist. conflictProne types
485
+ // compete at a lower floor than plain rewordings because a value swap
486
+ // ("use Express" vs "use Fastify") is a genuine rivalry far below the
487
+ // rephrase band, while topically distinct decisions/preferences in one
488
+ // scope are normal coexisting statements, not conflicts. A canonical that
489
+ // covers the statement already settles rivalry, so conflictProne types skip
490
+ // the scan; the row an update replaces is never a contender.
491
+ const floor = conflictProne ? CONFLICT_OVERLAP_FLOOR : OVERLAP_FLOOR;
492
+ const contenders = !conflictProne ? live : canon ? [] : divergent;
493
+ let rival: { m: Memory; score: number } | undefined;
494
+ for (const m of contenders) {
495
+ const score = jaccard(tokens(candidate.content), tokens(m.content));
496
+ if (score >= floor && (!rival || score > rival.score)) rival = { m, score };
497
+ }
498
+
470
499
  if (
471
500
  exact &&
472
501
  !exact.superseded_by &&
473
- (canon?.aligns || !(conflictProne && divergent.length))
502
+ (canon?.aligns || !(conflictProne && rival))
474
503
  ) {
475
504
  // Byte-identical duplicate collapses (Principle 2) — exactness is
476
505
  // independent of the canonical registry, so a decided/preferred fact
477
506
  // restated verbatim is never "conflicting" content on its own. Two
478
507
  // 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.
508
+ // the rivalry (echo collapses), but a scope already holding a RIVAL
509
+ // decision/preference entry (over the conflict floor) with no resolving
510
+ // canon keeps the exact restatement review-gated — dedup must not silently
511
+ // bury a conflict.
482
512
  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
- }
513
+ } else if (rival) {
514
+ // Review-gated merge: a competing decision/preference, or a reworded
515
+ // near-duplicate of a live row.
516
+ overlapMatch = rival.m;
517
+ overlapScore = Math.round(rival.score * 100) / 100;
501
518
  }
502
519
 
503
520
  if (collapseMatch) {
@@ -568,8 +585,14 @@ export async function runWriteGate(
568
585
  ];
569
586
  } else if (overlapMatch) {
570
587
  blockReason = "superseded_overlap";
571
- const newest = scopeMems[scopeMems.length - 1];
572
- blockFlags = [`supersedes_check_${newest ? newest.ts : "-"}`, "review_gated"];
588
+ blockFlags = [`supersedes_check_${overlapMatch.ts}`, `score=${overlapScore}`, "review_gated"];
589
+ hint =
590
+ `A live ${candidate.type} row ${overlapMatch.ts} in ${candidate.scope || "(no scope)"} competes ` +
591
+ `with this write (overlap ${overlapScore}). Nothing was stored. To replace that row, use ` +
592
+ `memory_update with query="${overlapMatch.ts}" — an update supersedes its target instead of ` +
593
+ `conflicting with it. If both statements should stand, store this one under a distinct ` +
594
+ `scope. memory_merge_review resolves proposals between stored rows only; this candidate was ` +
595
+ `never stored, so it cannot be resolved from here.`;
573
596
  } else if (ambiguous && !collapseMatch) {
574
597
  blockReason = "ambiguous_memory";
575
598
  blockFlags = flags;
@@ -583,12 +606,16 @@ export async function runWriteGate(
583
606
  await recordWriteBlocked(4, blockReason, blockFlags, chain);
584
607
  if (blockReason === "superseded_overlap" && overlapMatch) {
585
608
  const newest = scopeMems[scopeMems.length - 1] ?? overlapMatch;
609
+ // Advisory, not actionable: the incoming candidate was never persisted,
610
+ // so no memory_merge_review loser exists for it. The line is rivalry
611
+ // telemetry and a pointer to the stored rival.
586
612
  await record("merge_proposal", {
587
613
  candidate: overlapMatch.ts,
588
614
  incoming: chain,
589
615
  canonical: newest.ts,
590
616
  source: `durable_${candidate.type}`,
591
- review: "required",
617
+ review: "advisory",
618
+ incoming_stored: false,
592
619
  chain,
593
620
  });
594
621
  }
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