opencode-self-improvement 0.14.17 → 0.14.19

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
@@ -82,6 +82,8 @@ Zero configuration is the default. To tune, use the object form of the plugin en
82
82
 
83
83
  ## How memory is written
84
84
 
85
+ Promotion evidence keeps a bounded sample of call IDs: the ten most recent code-engagement calls, plus the latest gate check, the latest recorded gate FAIL/fix/PASS recovery, and the latest recorded tool FAIL/PASS retry (at most 16 distinct IDs). `evidence_refs_count` is the total number of recorded session calls before sampling, including non-code tools; the sampled IDs are audit pointers, not a complete history. Grounding and memory attribution still use the full in-memory ledger. Existing evidence day-files are left unchanged: this upgrade does not backfill, compact, or delete historical audit records.
86
+
85
87
  Four gates run before anything is stored, and each emits an ordered evidence line:
86
88
 
87
89
  1. **GATE-1 — code references resolve.** Call signatures and paths embedded in the memory are checked against your live source tree.
@@ -89,7 +91,7 @@ Four gates run before anything is stored, and each emits an ordered evidence lin
89
91
  3. **GATE-3 — no duplicates.** Near-duplicates collapse into the existing row; a contradiction with a superseded memory is rejected.
90
92
  4. **GATE-4 — promotion or block.** The row lands, or the call returns the reason.
91
93
 
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.
94
+ 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
95
 
94
96
  ## Repo scoping
95
97
 
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.19",
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/capture.ts CHANGED
@@ -1,26 +1,13 @@
1
- // Opt-in auto-capture core. Pure and dependency-free: no opencode
2
- // imports, no filesystem, no ambient clock — the transcript, the model call
3
- // and time are all injected by the caller (src/index.ts), so everything here
4
- // is unit-testable. Every candidate that leaves this module still flows
1
+ // Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
2
+ // calls live in src/index.ts. Every candidate that leaves this module flows
5
3
  // through runWriteGate in index.ts: capture NEVER writes memories directly,
6
4
  // so dupes/stale/canonical rules keep the moat (same as model-authored writes).
7
5
  // All parsing functions are TOTAL: any malformed input yields [] / "" / null,
8
6
  // never a throw.
9
- import { STATUSES, TYPES } from "./types.ts";
7
+ import { TYPES } from "./types.ts";
10
8
  import { flattenMemoryText } from "./sanitize.ts";
11
9
  import { redactSecrets } from "./secrets.ts";
12
10
 
13
- export interface CaptureOptions {
14
- model: string; // "provider/id"
15
- max: number;
16
- }
17
-
18
- export interface CaptureDeps {
19
- generate: (prompt: string) => Promise<string>;
20
- sessionText: string;
21
- now: () => Date;
22
- }
23
-
24
11
  export interface CaptureCandidate {
25
12
  type: string;
26
13
  scope: string;
package/src/gates.ts CHANGED
@@ -6,9 +6,8 @@ import { memoryRoot, canonicalFile } from "./config.ts";
6
6
  import { bracketList, parseLine, readLines } from "./logfmt.ts";
7
7
  import {
8
8
  appendMemory,
9
- loadAll,
10
9
  loadScope,
11
- markManySuperseded,
10
+ markManySupersededReport,
12
11
  snapshotFiles,
13
12
  MAX_CONTENT_CHARS,
14
13
  type Memory,
@@ -16,6 +15,7 @@ import {
16
15
  } from "./memory.ts";
17
16
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
18
17
  import { noteAuthored } from "./state.ts";
18
+ import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
19
19
  import { flattenMemoryText } from "./sanitize.ts";
20
20
  import { containsSecret, redactSecrets } from "./secrets.ts";
21
21
  import { readerForSession } from "./memory.ts";
@@ -48,9 +48,31 @@ 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[];
73
+ // Total before the telemetry window was selected. Legacy/direct callers
74
+ // may still supply their complete list; the writer bounds that too.
75
+ evidenceCallsCount?: number;
54
76
  hasGateCheck: boolean;
55
77
  // The session this write belongs to, when the caller knows it by name.
56
78
  // Repo-stamp resolution prefers it over the mutable global current, which
@@ -69,16 +91,40 @@ export interface GateContext {
69
91
  // excludes it from rivalry: the update IS the sanctioned supersession, so it
70
92
  // must never be blocked as a conflict with the row it is about to supersede.
71
93
  supersedesTs?: string;
94
+ // Optional caller-owned ledger (#158 round 3): GATE-2's drift/canonical
95
+ // supersessions append the ts values they made durable HERE, immediately
96
+ // after the batch publish and BEFORE their audit lines — so a failed audit
97
+ // line can no longer hide a persisted retirement from the caller's catch.
98
+ // "Nothing was written" is only writable when this stays empty.
99
+ durable?: string[];
72
100
  }
73
101
 
74
- export interface GateOutcome {
75
- action: "promoted" | "blocked" | "collapsed";
102
+ // Shared optional fields remain readable by diagnostic callers before they
103
+ // narrow on action. The variants below require the fields each verdict owes.
104
+ interface GateOutcomeFields {
76
105
  reason?: string;
77
106
  ts?: string;
78
107
  chain: string;
79
108
  hint?: string;
109
+ // Promoted with the row DURABLE but its post-append write_promoted audit
110
+ // line failed (#155). Entry points with a further post-mutation step
111
+ // (memory_update's supersede) must still run it and report a partial
112
+ // result. Throwing was the old shape of this signal and it lied: callers
113
+ // read it as "nothing happened" while the row sat on disk. Pre-append
114
+ // faults keep throwing — there, nothing was in fact written.
115
+ evidenceError?: string;
116
+ // On a collapsed (un-stored) write: the ts of the ACTIVE row whose content
117
+ // already IS the candidate. An update completing its supersession needs the
118
+ // survivor's id to retire its own target in the survivor's favor (#155
119
+ // convergence: a retry must be able to end with one active row).
120
+ collapsedWith?: string;
80
121
  }
81
122
 
123
+ export type GateOutcome =
124
+ | (GateOutcomeFields & { action: "promoted"; ts: string })
125
+ | (GateOutcomeFields & { action: "blocked"; reason: string })
126
+ | (GateOutcomeFields & { action: "collapsed" });
127
+
82
128
  const STOPWORDS = new Set([
83
129
  "use",
84
130
  "using",
@@ -414,6 +460,14 @@ export async function runWriteGate(
414
460
  // and the pass is skipped by the batch (it re-reads under the lock).
415
461
  const target = g1.candidateStale ? "<-" : chain;
416
462
  if (typeof s.memory.superseded_by === "string") continue;
463
+ // The row an UPDATE replaces is retired by the update itself, with its
464
+ // own pointer. A drift stamp here wins first-call-wins against the
465
+ // caller's markSuperseded and leaves a chain id the caller's retry can
466
+ // never walk — so the tool would print "(superseded X)" naming a
467
+ // retirement it did not perform. Same principle GATE-3 applies to
468
+ // rivalry (the target is never a contender): the update IS the sanctioned
469
+ // supersession for that row.
470
+ if (s.memory.ts === ctx.supersedesTs) continue;
417
471
  driftPlan.push({
418
472
  s,
419
473
  target,
@@ -421,8 +475,11 @@ export async function runWriteGate(
421
475
  });
422
476
  }
423
477
  if (driftPlan.length > 0) {
424
- const markedCount = await markManySuperseded(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
425
- if (markedCount > 0) {
478
+ const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
479
+ if (marked.length > 0) {
480
+ // Ledger BEFORE the audit lines: what is on disk now stays on disk no
481
+ // matter what the record loop below does (round-3 probe 3).
482
+ ctx.durable?.push(...marked);
426
483
  for (const p of driftPlan) {
427
484
  supersededTs = p.s.memory.ts;
428
485
  await rec("superseded_by", {
@@ -455,6 +512,9 @@ export async function runWriteGate(
455
512
  const canonPlan: { ts: string; from: string | undefined }[] = [];
456
513
  for (const m of scopeMems) {
457
514
  if (m.superseded_by) continue;
515
+ // The update's own target retires in the update's hand, not the
516
+ // canonical registry's (see the GATE-2 drift skip above).
517
+ if (m.ts === ctx.supersedesTs) continue;
458
518
  if (tokens(m.content).some((t) => valueSet.has(t))) continue;
459
519
  const from = rawTokens(m.content).find(
460
520
  (t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()) && !valueSet.has(t.toLowerCase()),
@@ -463,10 +523,15 @@ export async function runWriteGate(
463
523
  }
464
524
  // One batch publish for the whole neutralization set (#61); rows marked
465
525
  // 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) {
526
+ const { marked: canonMarked } = await markManySupersededReport(
527
+ canonPlan.map((p) => ({
528
+ ts: p.ts,
529
+ fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
530
+ })),
531
+ );
532
+ if (canonMarked.length > 0) {
533
+ // Same ledger discipline as the drift batch above.
534
+ ctx.durable?.push(...canonMarked);
470
535
  for (const p of canonPlan) {
471
536
  if (!supersededTs) supersededTs = p.ts;
472
537
  await rec("superseded_by", {
@@ -491,8 +556,21 @@ export async function runWriteGate(
491
556
  const exactPoll = scopeMems.filter(
492
557
  (m) => m.superseded_by === undefined || m.reason === "drift",
493
558
  );
559
+ // Byte-exact duplicate prose collapses (Principle 2) — with one UPDATE-only
560
+ // carve-out: the row being replaced counts as a duplicate of the candidate
561
+ // only if the update also restates its metadata. Same prose plus different
562
+ // retrieval keywords or status is a metadata EDIT on that row (GATE-3
563
+ // already refuses to see it as a rival), and collapsing it would silently
564
+ // drop the edit — the tool could then never edit kw or status at all.
494
565
  const exact = exactPoll.find(
495
- (m) => m.type === candidate.type && m.content === candidate.content,
566
+ (m) =>
567
+ m.type === candidate.type &&
568
+ m.content === candidate.content &&
569
+ (m.ts !== ctx.supersedesTs ||
570
+ (sameStrList(m.kw, candidate.kw) &&
571
+ sameStrList(m.tags, candidate.tags) &&
572
+ m.issue === candidate.issue &&
573
+ (m.status ?? "settled") === (candidate.status ?? "settled"))),
496
574
  );
497
575
  // Same-type live rows that could compete with the incoming statement; the
498
576
  // row an update replaces is never a contender.
@@ -646,7 +724,7 @@ export async function runWriteGate(
646
724
  }
647
725
 
648
726
  if (collapseMatch) {
649
- return { action: "collapsed", chain };
727
+ return { action: "collapsed", chain, collapsedWith: collapseMatch.ts };
650
728
  }
651
729
 
652
730
  // The write is specifically promoted on engagement (no refs, no gate check,
@@ -667,21 +745,35 @@ export async function runWriteGate(
667
745
  // prompt-cache bust to be shown its own thought. Only promoted writes are
668
746
  // attributed — a blocked candidate created nothing.
669
747
  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 };
748
+ // Everything past the append is durable state: an audit failure from here
749
+ // must not escape as a throw, or the caller reports a write that happened
750
+ // as if it had not (#155 — memory_update told the model "Nothing was
751
+ // written" while the replacement row sat un-superseded on disk). The
752
+ // outcome carries the error instead.
753
+ let evidenceError: string | undefined;
754
+ try {
755
+ await rec("write_promoted", {
756
+ gate: 4,
757
+ op: "write",
758
+ mem: ts,
759
+ scope: candidate.scope,
760
+ type: candidate.type,
761
+ status: candidate.status ?? "settled",
762
+ ch,
763
+ supersedes: supersededTs ?? "-",
764
+ canonical: canon ? `canonical.logfmt:${canon.entry.ts}` : "-",
765
+ evidence_refs: bracketList(ctx.evidenceCalls.slice(-MAX_WRITE_EVIDENCE_REFS)),
766
+ evidence_refs_count: ctx.evidenceCallsCount ?? ctx.evidenceCalls.length,
767
+ snapshot: snapshot[0] ?? "-",
768
+ trusted: ctx.trusted ? true : undefined,
769
+ grounded_by: groundedByEngagement ? "engagement" : undefined,
770
+ chain,
771
+ });
772
+ } catch (err) {
773
+ // NOT `(err as Error).message`: a messageless Error (or a non-Error
774
+ // rejection) would make the field FALSY, and callers test it for truth —
775
+ // the lie this field exists to kill would return as a clean success.
776
+ evidenceError = err instanceof Error && err.message ? err.message : String(err);
777
+ }
778
+ return { action: "promoted", ts, chain, evidenceError };
687
779
  }
package/src/host.ts ADDED
@@ -0,0 +1,97 @@
1
+ // Compatibility boundary for host payloads. These adapters only read data;
2
+ // repository binding, ambient fallbacks, clocks, and I/O belong to the caller.
3
+ function fields(value: unknown): Record<string, unknown> {
4
+ return value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
5
+ }
6
+
7
+ export interface ToolIdentity {
8
+ sessionID?: string;
9
+ callID?: string;
10
+ }
11
+
12
+ /** V2 ToolContext uses `id` for the call; absent/empty fields need a fallback. */
13
+ export function toolIdentity(context: unknown): ToolIdentity {
14
+ const { sessionID, id } = fields(context);
15
+ return {
16
+ sessionID: typeof sessionID === "string" && sessionID ? sessionID : undefined,
17
+ callID: typeof id === "string" && id ? id : undefined,
18
+ };
19
+ }
20
+
21
+ export interface SessionIdentity {
22
+ sessionID: string;
23
+ directory?: string;
24
+ }
25
+
26
+ /** A directory-less identity still lets the caller resolve the session row. */
27
+ export function sessionIdentityEvent(raw: unknown): SessionIdentity | undefined {
28
+ const event = fields(raw);
29
+ if (
30
+ event.type !== "session.created" &&
31
+ event.type !== "session.execution.started" &&
32
+ event.type !== "session.moved"
33
+ ) return undefined;
34
+ const data = fields(event.data ?? event.properties);
35
+ const info = fields(data.info ?? data);
36
+ const sessionID = info.sessionID ?? data.sessionID;
37
+ const directory = fields(info.location).directory ?? fields(data.location).directory
38
+ ?? fields(event.location).directory ?? info.directory;
39
+ if (typeof sessionID !== "string") return undefined;
40
+ return { sessionID, directory: typeof directory === "string" ? directory : undefined };
41
+ }
42
+
43
+ /** Legacy context messages sometimes carry location directly or inside info. */
44
+ export function sessionDirectoryFromMessages(messages: unknown): string | undefined {
45
+ if (!Array.isArray(messages)) return undefined;
46
+ for (const message of messages) {
47
+ const row = fields(message);
48
+ const directory = fields(row.location).directory ?? fields(fields(row.info).location).directory;
49
+ if (typeof directory === "string" && directory) return directory;
50
+ }
51
+ return undefined;
52
+ }
53
+
54
+ /** session.get returns either a row or a {data: row} response. */
55
+ export function sessionDirectoryFromRow(result: unknown): string | undefined {
56
+ const response = fields(result);
57
+ const row = fields(response.data ?? response);
58
+ const directory = fields(row.location).directory ?? row.directory;
59
+ return typeof directory === "string" && directory ? directory : undefined;
60
+ }
61
+
62
+ export interface SessionUsage {
63
+ sessionID: string;
64
+ input: number;
65
+ read: number;
66
+ write: number;
67
+ }
68
+
69
+ /** V2 session usage, or the assistant-message usage emitted by older hosts. */
70
+ export function sessionUsageEvent(raw: unknown): SessionUsage | undefined {
71
+ const event = fields(raw);
72
+ let info: Record<string, unknown>;
73
+ if (event.type === "session.usage.updated") {
74
+ info = fields(event.data);
75
+ } else if (event.type === "message.updated") {
76
+ info = fields(fields(event.properties).info ?? event.info ?? fields(event.data).info);
77
+ if (info.role !== "assistant") return undefined;
78
+ } else {
79
+ return undefined;
80
+ }
81
+ if (typeof info.sessionID !== "string" || !info.tokens) return undefined;
82
+ const tokens = fields(info.tokens);
83
+ const cache = fields(tokens.cache);
84
+ return {
85
+ sessionID: info.sessionID,
86
+ input: Number(tokens.input) || 0,
87
+ read: Number(cache.read) || 0,
88
+ write: Number(cache.write) || 0,
89
+ };
90
+ }
91
+
92
+ /** Session ID envelopes accepted by capture; trigger selection stays separate. */
93
+ export function captureSessionID(raw: unknown): string | undefined {
94
+ const event = fields(raw);
95
+ const sessionID = fields(event.data).sessionID ?? event.sessionID ?? fields(event.properties).sessionID;
96
+ return typeof sessionID === "string" ? sessionID : undefined;
97
+ }