opencode-self-improvement 0.15.3 → 0.15.5

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.
Files changed (99) hide show
  1. package/package.json +2 -2
  2. package/src/capture/candidates.ts +110 -0
  3. package/src/capture/lag.ts +18 -0
  4. package/src/capture/prompt.ts +50 -0
  5. package/src/capture/transcript.ts +59 -0
  6. package/src/{triggers.ts → capture/triggers.ts} +6 -5
  7. package/src/{command.ts → command/ensure.ts} +2 -2
  8. package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
  9. package/src/consolidate/render.ts +30 -0
  10. package/src/core/cmp-ts.ts +16 -0
  11. package/src/core/config/budgets.ts +28 -0
  12. package/src/{config.ts → core/config/paths.ts} +1 -30
  13. package/src/core/logfmt/format.ts +82 -0
  14. package/src/{logfmt.ts → core/logfmt/publish.ts} +3 -92
  15. package/src/core/logfmt/read.ts +15 -0
  16. package/src/{state.ts → core/state.ts} +1 -1
  17. package/src/core/time.ts +6 -0
  18. package/src/{evidence.ts → evidence/record.ts} +7 -5
  19. package/src/{gates.ts → gate/gate.ts} +19 -21
  20. package/src/{resolver.ts → gate/resolver.ts} +1 -1
  21. package/src/{hits.ts → hits/ledger.ts} +8 -6
  22. package/src/index.ts +64 -943
  23. package/src/init/detect.ts +144 -0
  24. package/src/init/format.ts +25 -0
  25. package/src/init/run.ts +188 -0
  26. package/src/inject/anchor.ts +43 -0
  27. package/src/{attribution.ts → inject/attribution.ts} +2 -2
  28. package/src/inject/budget.ts +78 -0
  29. package/src/inject/digest.ts +89 -0
  30. package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
  31. package/src/inject/format.ts +32 -0
  32. package/src/inject/pull.ts +52 -0
  33. package/src/inject/version.ts +31 -0
  34. package/src/portable/decay.ts +20 -0
  35. package/src/portable/export.ts +194 -0
  36. package/src/portable/import.ts +173 -0
  37. package/src/recall/relevant.ts +72 -0
  38. package/src/recall/score.ts +106 -0
  39. package/src/recall/shared-terms.ts +15 -0
  40. package/src/status/format.ts +58 -0
  41. package/src/status/metrics.ts +65 -0
  42. package/src/status/payload.ts +143 -0
  43. package/src/status/report.ts +202 -0
  44. package/src/status/write.ts +102 -0
  45. package/src/{blocklist.ts → store/blocklist.ts} +4 -2
  46. package/src/store/files/append.ts +176 -0
  47. package/src/store/files/deletions.ts +31 -0
  48. package/src/store/files/load.ts +106 -0
  49. package/src/store/files/prune.ts +81 -0
  50. package/src/store/files/snapshots.ts +88 -0
  51. package/src/store/files/supersede.ts +123 -0
  52. package/src/store/files/target.ts +36 -0
  53. package/src/{lock.ts → store/lock.ts} +1 -1
  54. package/src/store/model/memory.ts +91 -0
  55. package/src/store/model/predicates.ts +12 -0
  56. package/src/store/model/visibility.ts +140 -0
  57. package/src/{prune.ts → store/prune.ts} +4 -3
  58. package/src/store/quarantine/release.ts +24 -0
  59. package/src/store/tombstones/rejection.ts +93 -0
  60. package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
  61. package/src/{undo.ts → store/undo.ts} +6 -3
  62. package/src/tools/consolidate.ts +42 -0
  63. package/src/tools/decay.ts +83 -0
  64. package/src/tools/deps.ts +27 -0
  65. package/src/tools/evidence.ts +48 -0
  66. package/src/tools/export.ts +27 -0
  67. package/src/tools/forget.ts +23 -0
  68. package/src/tools/import.ts +57 -0
  69. package/src/tools/init.ts +30 -0
  70. package/src/tools/list.ts +36 -0
  71. package/src/tools/merge-review.ts +138 -0
  72. package/src/tools/recall.ts +72 -0
  73. package/src/tools/registry.ts +40 -0
  74. package/src/tools/remember.ts +49 -0
  75. package/src/{schema.ts → tools/schema.ts} +3 -3
  76. package/src/tools/status-tool.ts +59 -0
  77. package/src/tools/undo.ts +57 -0
  78. package/src/tools/update.ts +342 -0
  79. package/src/{tui.tsx → tui/panel.tsx} +7 -17
  80. package/src/viewer/mutate.ts +15 -15
  81. package/src/viewer/server.ts +10 -8
  82. package/tsconfig.json +2 -2
  83. package/tui.ts +1 -1
  84. package/src/capture.ts +0 -222
  85. package/src/init.ts +0 -333
  86. package/src/inject.ts +0 -471
  87. package/src/memory.ts +0 -851
  88. package/src/portable.ts +0 -379
  89. package/src/status.ts +0 -536
  90. /package/src/{sessions.ts → core/lru.ts} +0 -0
  91. /package/src/{runtime.ts → core/runtime.ts} +0 -0
  92. /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
  93. /package/src/{types.ts → core/types.ts} +0 -0
  94. /package/src/{host.ts → identity/host-events.ts} +0 -0
  95. /package/src/{repokey.ts → identity/repokey.ts} +0 -0
  96. /package/src/{containment.ts → store/containment.ts} +0 -0
  97. /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
  98. /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
  99. /package/src/{secrets.ts → store/secrets.ts} +0 -0
@@ -15,9 +15,9 @@
15
15
  // * Store reads deliberately do NOT use zod: they get a plain ISO-instant
16
16
  // check in memory.ts (row identity), where the row schema lives.
17
17
  import { z, type ZodTypeAny } from "zod";
18
- import { STATUSES, TYPES } from "./types.ts";
19
- import { flattenMemoryText } from "./sanitize.ts";
20
- import { MAX_KEYWORDS } from "./memory.ts";
18
+ import { STATUSES, TYPES } from "../core/types.ts";
19
+ import { flattenMemoryText } from "../store/sanitize.ts";
20
+ import { MAX_KEYWORDS } from "../store/model/memory.ts";
21
21
 
22
22
  type JSONSchema = Record<string, unknown>;
23
23
 
@@ -0,0 +1,59 @@
1
+ // The memory_status tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { neverRetrieved, readLedger } from "../hits/ledger.ts";
6
+ import { formatMemory } from "../inject/format.ts";
7
+ import { loadAll, malformedCount } from "../store/files/load.ts"
8
+ import { isActive } from "../store/model/predicates.ts"
9
+ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
10
+ import { isQuarantined, quarantineReasons } from "../store/quarantine/quarantine.ts";
11
+ import { EmptyArgs, validated } from "./schema.ts";
12
+ import { captureLag, captureLagLines, rowsPerDay } from "../status/metrics.ts"
13
+ import { renderMemoryReport } from "../status/report.ts"
14
+ import { blockedRecent } from "../status/write.ts";
15
+ import type { StoreCounts } from "../status/payload.ts";
16
+
17
+ export const register: ToolRegister = (editor, deps) => {
18
+ const { toolIds, sessions, direct } = deps;
19
+ editor.add(validated(EmptyArgs, {
20
+ name: "memory_status",
21
+ description:
22
+ "Plain-text memory report for chat clients (desktop/web/IDE), same sections as the terminal /memory panel: CONTEXT (this session's injected block, budget use, cumulative ride and abstentions), CACHE (plain-language cache receipts: bust count, and the provider-reported share of prompt tokens served from cache — the proof that memory never mutates your prefix), the block verbatim, recent blocked writes with gate reasons, and store stats. Reads only — no model call.",
23
+ options: direct,
24
+ async execute(_args, context): Promise<{ content: string }> {
25
+ // In-process truth: the live epoch + ledger, fresher than any file.
26
+ const sid = toolIds(context).sid;
27
+ const reportReader = readerFromSid(sid);
28
+ if (sid !== "?") await sessions.refresh(sid);
29
+ const status = sid === "?" ? null : await sessions.buildPayload(sid);
30
+ const all = await loadAll();
31
+ const act = all.filter(isActive);
32
+ const store: StoreCounts = {
33
+ active: act.length,
34
+ superseded: all.length - act.length,
35
+ open: act.filter((m) => m.status === "open").length,
36
+ scopes: new Set(act.map((m) => m.scope)).size,
37
+ malformed: malformedCount(),
38
+ };
39
+ // Use ledger (#42): how much of the store has never been surfaced.
40
+ // Reported, never acted on — retirement is a decision, not a metric.
41
+ const ledger = await readLedger();
42
+ store.neverRetrieved = neverRetrieved(act, ledger).length;
43
+ store.ledgerSince = ledger.since;
44
+ // Self-metrics (#44): what the store costs, how fast it grows, and how
45
+ // stale a capture is when it fires. Same rule as above — the numbers
46
+ // are the point, not a verdict on them.
47
+ store.bytes = act.reduce((n, m) => n + new TextEncoder().encode(formatMemory(m)).length, 0);
48
+ store.bytesPerRow = act.length ? Math.round(store.bytes / act.length) : 0;
49
+ store.rowsPerDay = rowsPerDay(act) ?? undefined;
50
+ store.captureLag = captureLag(await captureLagLines());
51
+ return {
52
+ content: renderMemoryReport({ status, store, blocked: await blockedRecent(6),
53
+ quarantined: act.filter((m) => isVisibleTo(m, reportReader) && isQuarantined(m))
54
+ .map((m) => ({ ts: m.ts, patterns: quarantineReasons(m) })),
55
+ }),
56
+ };
57
+ },
58
+ }));
59
+ };
@@ -0,0 +1,57 @@
1
+ // The memory_undo tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { memoryRoot } from "../core/config/paths.ts";
6
+ import { readerFromSid } from "../store/model/visibility.ts";
7
+ import { UndoArgs, validated } from "./schema.ts";
8
+ import { listSnapshots, restoreSnapshot } from "../store/undo.ts";
9
+ import { basename } from "node:path";
10
+
11
+ export const register: ToolRegister = (editor, deps) => {
12
+ const { toolIds, direct } = deps;
13
+ editor.add(validated(UndoArgs, {
14
+ name: "memory_undo",
15
+ description:
16
+ "List memory snapshots, or restore one (rollback). Only snapshots inside this store's snapshots directory are accepted: pass a bare name from the list or its full path. Non-standard files in snapshots/ are not listed or restorable. SAFE BY DEFAULT: restore refuses if the current file has rows added or edited since the snapshot, and audited human/tool deletions stay deleted. Re-run with merge=true to restore AND keep divergent rows, or force=true for an explicit exact rollback. Blocklisted rows remain inactive in every mode. Rows belonging to other repositories are never restored, rewound, or dropped in any mode — their lines survive verbatim, though a restore may place them later in the shared file. Global rows are visible to every repository, so they are in every repository's rollback scope.",
17
+ options: direct,
18
+ async execute(args, context): Promise<{ content: string }> {
19
+ if (args.snapshot) {
20
+ const mode = args.force ? "force" : args.merge ? "merge" : "check";
21
+ // Day files are shared across repositories (#153): the rollback
22
+ // carries the CALLER's reader, so rows another repo owns survive
23
+ // untouched in every mode instead of riding the snapshot wholesale.
24
+ const { sid } = toolIds(context);
25
+ const res = await restoreSnapshot(args.snapshot, memoryRoot(), mode, readerFromSid(sid));
26
+ if (!res.restored) {
27
+ const parts = [...res.concurrentAdded, ...res.concurrentChanged];
28
+ return {
29
+ content:
30
+ `Undo refused: ${res.concurrentAdded.length} row(s) added and ` +
31
+ `${res.concurrentChanged.length} changed since this snapshot — the shared file ` +
32
+ `moved after it. Divergent rows (ts): ${parts.join(", ")}. ` +
33
+ `If those belong to another session, re-run with merge=true (restore the file ` +
34
+ `AND keep them); if they are the writes you are undoing, use force=true. ` +
35
+ (res.foreignPreserved
36
+ ? `${res.foreignPreserved} row(s) in this file belong to other repositories; they survive in every mode.`
37
+ : "Rows belonging to other repositories survive in every mode."),
38
+ };
39
+ }
40
+ const kept = res.mode === "merge" && (res.concurrentAdded.length || res.concurrentChanged.length)
41
+ ? ` Kept ${res.concurrentAdded.length} added / ${res.concurrentChanged.length} changed row(s) written after the snapshot.`
42
+ : "";
43
+ const safety = res.safety ? ` Pre-restore file snapshotted -> ${res.safety}.` : "";
44
+ const omitted = res.deletedOmitted.length
45
+ ? ` Omitted ${res.deletedOmitted.length} deliberately deleted row(s); use force=true to recover them.`
46
+ : "";
47
+ const foreign = res.foreignPreserved
48
+ ? ` Left ${res.foreignPreserved} row(s) belonging to other repositories untouched.`
49
+ : "";
50
+ return { content: `Restored ${basename(res.target)} from ${res.mode} snapshot -> ${res.target}.${kept}${safety}${omitted}${foreign}` };
51
+ }
52
+ const snaps = await listSnapshots();
53
+ if (!snaps.length) return { content: "No snapshots" };
54
+ return { content: snaps.map((s) => `${s.name} (${s.bytes} bytes)`).join("\n") };
55
+ },
56
+ }));
57
+ };
@@ -0,0 +1,342 @@
1
+ // The memory_update tool, extracted from index.ts (#168). Schema, description
2
+ // and handler are byte-identical to the pre-split source; closure access arrives
3
+ // through ToolDeps.
4
+ import type { ToolRegister } from "./deps.ts";
5
+ import { memoryRoot } from "../core/config/paths.ts";
6
+ import { record } from "../evidence/record.ts";
7
+ import { auditCaveat, runWriteGate, sameStrList } from "../gate/gate.ts";
8
+ import { withStoreLock } from "../store/lock.ts";
9
+ import { loadAll } from "../store/files/load.ts"
10
+ import { markSuperseded } from "../store/files/supersede.ts"
11
+ import { resolveMemoryTarget } from "../store/files/target.ts"
12
+ import { isActive } from "../store/model/predicates.ts"
13
+ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
14
+ import type { Memory } from "../store/model/memory.ts";
15
+ import { UpdateArgs, validated } from "./schema.ts";
16
+ import { redactSecrets } from "../store/secrets.ts";
17
+ import { join } from "node:path";
18
+
19
+ export const register: ToolRegister = (editor, deps) => {
20
+ const { toolIds, bindSessionIdentity, ownerlessWriter, refuseOwnerlessWrite, gateContext, direct } = deps;
21
+ editor.add(validated(UpdateArgs, {
22
+ name: "memory_update",
23
+ description:
24
+ "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.",
25
+ options: direct,
26
+ async execute(args, context): Promise<{ content: string }> {
27
+ const { sid } = toolIds(context);
28
+ await bindSessionIdentity(sid);
29
+ const ownerless = ownerlessWriter(sid);
30
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
31
+ const reader = readerFromSid(sid);
32
+ const updateGate = gateContext(sid);
33
+ // The whole update — resolve, gate, supersede — runs under one
34
+ // UPDATE-ORDER lock. Without it, two concurrent updates that both
35
+ // resolved the same still-active target both promoted and both
36
+ // claimed success: markSuperseded is first-call-wins, so one
37
+ // replacement row silently survived un-superseded (measured 5/5).
38
+ // This outer lock is a DISTINCT file from anything runWriteGate or
39
+ // markSuperseded take (sections run flat — never re-enter a file
40
+ // you hold), and the acquisition order is always update-order
41
+ // then store, never the reverse, so it cannot deadlock against a
42
+ // plain writer. On timeout it FAILS closed: proceeding unlocked
43
+ // is exactly the race this lock exists to close. The loser then
44
+ // re-resolves under the lock, finds its target already retired,
45
+ // and writes nothing — the documented fail-closed contract.
46
+ // Flips once a replacement row is durable, so the catch below can
47
+ // never claim "Nothing was written" about a write that happened
48
+ // (#155's lie).
49
+ let mutated = false;
50
+ // The gate's durable steps: rows GATE-2 retired before a later
51
+ // failure (round-3 probe 3). Non-empty means "Nothing was written"
52
+ // is no longer writable.
53
+ const gateDurable: string[] = [];
54
+ try {
55
+ return await withStoreLock(
56
+ join(memoryRoot(), "update-order"),
57
+ async () => {
58
+ const prior = (await loadAll()).filter(
59
+ (m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleTo(m, reader),
60
+ );
61
+ // Resolve the row BEFORE the gate: an update that cannot identify its
62
+ // target must write nothing, rather than silently superseding whichever
63
+ // row happened to be newest in this scope+type.
64
+ let resolved = resolveMemoryTarget(prior, args.query);
65
+ if (resolved.status === "not_found") {
66
+ // Naming a SUPERSEDED row is not a miss (#155): the retry
67
+ // after a partial update lands here, and when that row's
68
+ // active successor already carries exactly this content the
69
+ // honest verdict is the duplicate one, not a dead end. Two
70
+ // subtleties the first cut missed: the successor's prose was
71
+ // stored REDACTED while a retry re-carries the raw input
72
+ // (the comparison must scrub), and "exactly this content"
73
+ // must mean the metadata too — a retry that also names new
74
+ // keywords still has work to do, and that work belongs on
75
+ // the chain head, so the update CONTINUES against the
76
+ // successor instead of collapsing here.
77
+ let chainHead: Memory | undefined;
78
+ if (args.query) {
79
+ const rows = (await loadAll()).filter(
80
+ (m) => m.scope === args.scope && m.type === args.type && isVisibleTo(m, reader),
81
+ );
82
+ const stale = resolveMemoryTarget(rows, args.query);
83
+ if (stale.status === "ok" && stale.target && !isActive(stale.target)) {
84
+ let latest = stale.target;
85
+ const walked = new Set<string>([latest.ts]);
86
+ while (latest.superseded_by) {
87
+ const next = rows.find((m) => m.ts === latest.superseded_by);
88
+ if (!next || walked.has(next.ts)) break;
89
+ walked.add(next.ts);
90
+ latest = next;
91
+ }
92
+ if (isActive(latest) && latest.content.trim() === redactSecrets(args.content).trim()) {
93
+ const restated =
94
+ (args.kw === undefined || sameStrList(args.kw, latest.kw)) &&
95
+ (args.status === undefined || args.status === (latest.status ?? "settled"));
96
+ if (restated) {
97
+ // Every other verdict is auditable; this one must
98
+ // be too — the message tells the model to consult
99
+ // memory_evidence.
100
+ await record(
101
+ "dedup_collapse",
102
+ { op: "update", named: stale.target.ts, match: latest.ts, action: "exact_successor", incoming_ignored: true },
103
+ true,
104
+ sid,
105
+ );
106
+ return {
107
+ content:
108
+ `Duplicate ignored: ${args.type}/${args.scope} — ${JSON.stringify(args.query)} was already ` +
109
+ `updated to exactly this content (${latest.ts}). Nothing was written.`,
110
+ };
111
+ }
112
+ chainHead = latest;
113
+ }
114
+ }
115
+ }
116
+ if (!chainHead) {
117
+ const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
118
+ return {
119
+ content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
120
+ };
121
+ }
122
+ resolved = { status: "ok", target: chainHead };
123
+ }
124
+ if (resolved.status === "ambiguous") {
125
+ return {
126
+ content:
127
+ `memory_update blocked: ${JSON.stringify(args.query)} matches ${resolved.candidates.length} active ` +
128
+ `${args.type} rows in ${args.scope} (${resolved.candidates.map((m) => m.ts).join(", ")}). ` +
129
+ "Pass a row id or a unique content substring. Nothing was written.",
130
+ };
131
+ }
132
+ const target = resolved.target;
133
+ // A prose edit is not a metadata reset (#154): fields the
134
+ // call does not name carry over from the row being
135
+ // replaced, so updating an imported row can no longer
136
+ // launder away its provenance or issue link. kw follows
137
+ // the same rule with an override: omitted keeps the
138
+ // target's, provided replaces. The carry completes to the
139
+ // five fields of the #129 viewer precedent: STATUS (an
140
+ // open frontier row stays open) and REPO (updating a
141
+ // global row from one repository must not re-house it out
142
+ // of every other repository's view — "an edit must never
143
+ // widen visibility", and it must never narrow it either).
144
+ // These are also the fields the collapse-completion judges
145
+ // (review round 3): the fold asks whether the survivor
146
+ // already carries the REQUESTED state — not the pre-edit
147
+ // target's. An update naming kw:["new-alias"] is not
148
+ // "already standing" on a row holding ["old-alias"].
149
+ const requested = {
150
+ kw: args.kw ?? target.kw,
151
+ tags: target.tags,
152
+ issue: target.issue,
153
+ status: (args.status ?? target.status) ?? "settled",
154
+ repo: target.repo ?? "global",
155
+ };
156
+ const outcome = await runWriteGate(
157
+ {
158
+ type: args.type,
159
+ scope: args.scope,
160
+ content: args.content,
161
+ kw: requested.kw,
162
+ tags: requested.tags,
163
+ issue: requested.issue,
164
+ status: requested.status,
165
+ repo: requested.repo,
166
+ repoPath: target.repo ? target.repoPath : undefined,
167
+ },
168
+ { ...updateGate, reader, supersedesTs: target.ts, durable: gateDurable },
169
+ );
170
+ if (outcome.action === "promoted" && outcome.ts && target) {
171
+ mutated = true;
172
+ const replacement = outcome.ts;
173
+ const retired = target.ts;
174
+ // The merge_review PARTIAL shape (156e887) applied to
175
+ // update: the replacement IS durable, so the message says
176
+ // exactly which follow-up step failed and what a retry does
177
+ // (#155 — never claim "Nothing was written" from here).
178
+ const partial = (why: string) => ({
179
+ content:
180
+ `memory_update PARTIAL: replacement ${replacement} IS on disk (memory_undo merge or force ` +
181
+ `restores ${retired}), but ${why}. Re-running this update reports the duplicate.`,
182
+ });
183
+ let retiredNow = false;
184
+ try {
185
+ retiredNow = await markSuperseded(retired, {
186
+ superseded_by: replacement,
187
+ reason: "update",
188
+ symbol: retired,
189
+ from: retired,
190
+ to: replacement,
191
+ });
192
+ } catch (err) {
193
+ return partial(
194
+ `retiring ${retired} failed: ${err instanceof Error && err.message ? err.message : String(err)}`,
195
+ );
196
+ }
197
+ if (!retiredNow) {
198
+ // merge_review checks exactly this boolean (156e887);
199
+ // "Updated (superseded X)" cannot be printed over a
200
+ // retirement a parallel supersession performed — that
201
+ // pointer names a DIFFERENT successor, and the confident
202
+ // line would hide a second active row.
203
+ return partial(
204
+ `${retired} had ALREADY been retired by another supersession while this call ran — ` +
205
+ `it points at that successor, not at ${replacement}; check memory_evidence`,
206
+ );
207
+ }
208
+ if (outcome.evidenceError !== undefined) {
209
+ return partial(`its write_promoted audit line was not recorded (${outcome.evidenceError})`);
210
+ }
211
+ return { content: `Updated ${args.type} in ${args.scope} (superseded ${retired})` };
212
+ }
213
+ if (outcome.action === "promoted")
214
+ return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
215
+ if (outcome.action === "collapsed") {
216
+ // Completion (#155 convergence): when a retry collapses
217
+ // because an ACTIVE row already holds exactly this content
218
+ // while the row it NAMES is still active (the supersede
219
+ // step of an earlier PARTIAL attempt never landed), the
220
+ // idempotent close is to retire the named row in the
221
+ // survivor's favor — a bare "Duplicate ignored" would leave
222
+ // two active rows forever and a retry that never converges.
223
+ // first-call-wins makes this safe to attempt on any path.
224
+ // But the fold must not INVERT #154 (review): retiring the
225
+ // named row is loss-free only when the survivor already
226
+ // carries what the named row carries — the SAME predicate
227
+ // GATE-3 uses to call same-prose-different-metadata an
228
+ // edit rather than a duplicate. Otherwise the survivor
229
+ // would stand stripped of the named row's issue link,
230
+ // keywords, tags or OPEN frontier standing, and a "clean
231
+ // no-op" message would paper over a metadata destruction.
232
+ // On disagreement nothing retires: both ids are named and
233
+ // a human (or an update on the survivor) decides.
234
+ const survivorTs = outcome.collapsedWith;
235
+ if (target && survivorTs && survivorTs !== target.ts) {
236
+ // #175: the gate can observe a session move after this call captured
237
+ // its reader. Recheck before trusting or describing the survivor.
238
+ const survivor = (await loadAll()).find(
239
+ (m) => m.ts === survivorTs && !m.superseded_by && isVisibleTo(m, reader),
240
+ );
241
+ if (survivor) {
242
+ // #175: private rows are visible by key OR path. Equal keys alone
243
+ // can drop another checkout's access after an origin change.
244
+ // For global rows, isVisibleTo ignores paths.
245
+ // Match raw paths like isVisibleTo; filesystem aliases need not
246
+ // grant the same readers access. This restricts automatic folds;
247
+ // explicit merge_review authorizes both seats under #131 instead.
248
+ const samePathVisibility = requested.repo === "global" ||
249
+ (target.repoPath ?? "") === (survivor.repoPath ?? "");
250
+ // The predicate is the REQUESTED state vs the survivor
251
+ // (round 3): content equality is already proven by the
252
+ // collapse, so the fold is loss-free only when the
253
+ // survivor also carries the metadata THIS call asked
254
+ // for — and stands where the target stands for readers
255
+ // of other repositories (repo visibility: folding a
256
+ // global row into a repo-private survivor would
257
+ // narrow a visibility the promotion path exists to
258
+ // preserve, and the reverse would leak).
259
+ if (
260
+ sameStrList(requested.kw, survivor.kw) &&
261
+ sameStrList(requested.tags, survivor.tags) &&
262
+ requested.issue === survivor.issue &&
263
+ requested.status === (survivor.status ?? "settled") &&
264
+ requested.repo === (survivor.repo ?? "global") &&
265
+ samePathVisibility
266
+ ) {
267
+ const done = await markSuperseded(target.ts, {
268
+ superseded_by: survivorTs,
269
+ reason: "update",
270
+ symbol: target.ts,
271
+ from: target.ts,
272
+ to: survivorTs,
273
+ }, gateDurable);
274
+ if (done) {
275
+ return {
276
+ content:
277
+ `Duplicate: ${args.type}/${args.scope} already stands active as ${survivorTs}; ` +
278
+ `${target.ts} was retired in its favor. Nothing new was written.`,
279
+ };
280
+ }
281
+ } else {
282
+ const differs: string[] = [];
283
+ if (requested.status !== (survivor.status ?? "settled"))
284
+ differs.push(`status ${requested.status} vs ${survivor.status ?? "settled"}`);
285
+ if (requested.issue !== survivor.issue)
286
+ differs.push(`issue ${requested.issue ?? "-"} vs ${survivor.issue ?? "-"}`);
287
+ if (!sameStrList(requested.kw, survivor.kw))
288
+ differs.push(`kw [${(requested.kw ?? []).join(", ") || "-"}] vs [${(survivor.kw ?? []).join(", ") || "-"}]`);
289
+ if (!sameStrList(requested.tags, survivor.tags))
290
+ differs.push(`tags [${(requested.tags ?? []).join(", ") || "-"}] vs [${(survivor.tags ?? []).join(", ") || "-"}]`);
291
+ if (requested.repo !== (survivor.repo ?? "global"))
292
+ differs.push(`visibility ${requested.repo} vs ${survivor.repo ?? "global"}`);
293
+ if (!samePathVisibility) differs.push("repository path visibility differs");
294
+ return {
295
+ content:
296
+ `Duplicate: ${args.type}/${args.scope} stands active as ${survivorTs}, but ${target.ts} ` +
297
+ `was NOT retired — the survivor does not carry what this update asked for ` +
298
+ `(${differs.join("; ")}), and the fold would drop it. Both stay active. To deliberately ` +
299
+ `keep only the survivor, use memory_merge_review with loser="${target.ts}", ` +
300
+ `survivor="${survivorTs}", and an explicit reason. This keeps the survivor's metadata and visibility.`,
301
+ };
302
+ }
303
+ }
304
+ }
305
+ return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
306
+ }
307
+ return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
308
+ },
309
+ {
310
+ onTimeout: "fail",
311
+ onEvent: (event, waitedMs) => {
312
+ void record("store_lock", { event, waited_ms: waitedMs, op: "update" });
313
+ },
314
+ },
315
+ );
316
+ } catch (err) {
317
+ // Everything that still throws here was PRE-WRITE for THIS call's
318
+ // replacement: the fail-closed lock timeout, the #152 choke-point
319
+ // refusal, an evidence fault BEFORE the append. Post-append audit
320
+ // failures no longer reach this catch — the gate reports them on
321
+ // the promoted outcome (#155). mutated is the belt-and-braces
322
+ // truth check: a future post-write throw must report a partial,
323
+ // never a clean nothing. And gateDurable closes the last gap
324
+ // (round 3): the gate may have RETIRED OTHER rows at GATE-2
325
+ // before the fault that got here — those tombstones are on disk,
326
+ // and naming them beats the "Nothing was written" premise.
327
+ const msg = err instanceof Error && err.message ? err.message : String(err);
328
+ return {
329
+ content: mutated
330
+ ? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
331
+ "Re-running this update reports the duplicate; inspect with memory_evidence."
332
+ : gateDurable.length > 0
333
+ ? `memory_update PARTIAL: ${msg} No replacement was written, but this call had ALREADY retired ` +
334
+ `${gateDurable.length} row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
335
+ "disk and their audit lines may not all have landed. Re-running this update will not undo " +
336
+ "them — reconcile with memory_evidence / memory_undo before retrying."
337
+ : `memory_update blocked: ${msg} Nothing was written.`,
338
+ };
339
+ }
340
+ },
341
+ }));
342
+ };
@@ -12,23 +12,13 @@ import { watch, type FSWatcher } from "node:fs";
12
12
  import { For, Show, createSignal } from "solid-js";
13
13
  import { Plugin, usePlugin } from "@opencode/plugin/tui";
14
14
  import type { PanelInput } from "@opencode/plugin/tui/context";
15
- import { memoryRoot, evidenceDir } from "./config.ts";
16
- import { fmtBytes, fmtMs } from "./status.ts";
17
- import {
18
- attributionLines,
19
- blockedRecent,
20
- cacheHealth,
21
- cacheRate,
22
- cacheLines,
23
- contextLines,
24
- ledgerIsYoung,
25
- readStatus,
26
- statusDir,
27
- windowLines,
28
- type BlockedRow,
29
- type CacheHealth,
30
- type StatusPayload,
31
- } from "./status.ts";
15
+ import { evidenceDir, memoryRoot } from "../core/config/paths.ts";
16
+ import { fmtBytes, fmtMs } from "../status/format.ts";
17
+ import { cacheHealth, cacheRate, type CacheHealth } from "../status/format.ts"
18
+ import { ledgerIsYoung } from "../status/metrics.ts"
19
+ import { type BlockedRow, type StatusPayload } from "../status/payload.ts"
20
+ import { attributionLines, cacheLines, contextLines, windowLines } from "../status/report.ts"
21
+ import { blockedRecent, readStatus, statusDir } from "../status/write.ts";
32
22
 
33
23
  const PANEL = "self-improvement.memory";
34
24
  const POLL_MS = 5000;
@@ -6,21 +6,21 @@
6
6
  // and the old entry stays visible as superseded. Block is the poison
7
7
  // intervention: keep the entry on disk but hide it from every read path.
8
8
  // All mutations require a reason and write audit + evidence lines.
9
- import { deletionsFile } from "../config.ts";
10
- import { addBlock, removeBlock } from "../blocklist.ts";
11
- import { record, chainId, contentHash } from "../evidence.ts";
12
- import { removeTombstone, tombstone } from "../tombstones.ts";
13
- import { redactSecrets } from "../secrets.ts";
14
- import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
15
- import { withStoreLock, LOCK_WRITE } from "../lock.ts";
16
- import {
17
- appendMemory,
18
- loadAll,
19
- markSuperseded,
20
- snapshotFiles,
21
- releaseQuarantine,
22
- type Memory,
23
- } from "../memory.ts";
9
+ import { deletionsFile } from "../core/config/paths.ts";
10
+ import { addBlock, removeBlock } from "../store/blocklist.ts";
11
+ import { record, chainId, contentHash } from "../evidence/record.ts";
12
+ import { removeTombstone, tombstone } from "../store/tombstones/tombstone.ts";
13
+ import { redactSecrets } from "../store/secrets.ts";
14
+ import { formatLine, parseLine } from "../core/logfmt/format.ts"
15
+ import { appendLog, fileIdentity, writeAtomic } from "../core/logfmt/publish.ts"
16
+ import { readLines } from "../core/logfmt/read.ts";
17
+ import { withStoreLock, LOCK_WRITE } from "../store/lock.ts";
18
+ import { appendMemory } from "../store/files/append.ts"
19
+ import { loadAll } from "../store/files/load.ts"
20
+ import { snapshotFiles } from "../store/files/snapshots.ts"
21
+ import { markSuperseded } from "../store/files/supersede.ts"
22
+ import { type Memory } from "../store/model/memory.ts"
23
+ import { releaseQuarantine } from "../store/quarantine/release.ts";
24
24
 
25
25
  export interface EditInput {
26
26
  ts: string;
@@ -8,16 +8,18 @@ import { basename, join } from "node:path";
8
8
  import { isIP } from "node:net";
9
9
  import { serve, type Server } from "bun";
10
10
  import { z, type ZodTypeAny } from "zod";
11
- import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody, ReleaseQuarantineBody } from "../schema.ts";
12
- import { deletionsFile, memoryRoot, snapshotDir } from "../config.ts";
13
- import { blockedEntries } from "../blocklist.ts";
14
- import { listSnapshots, restoreSnapshot } from "../undo.ts";
15
- import { appendMemory, loadAll, memoryFiles } from "../memory.ts";
16
- import { parseLine, readLines } from "../logfmt.ts";
11
+ import { BlockBody, DeleteBody, EditBody, RestoreEntryBody, UnblockBody, UnrejectBody, ReleaseQuarantineBody } from "../tools/schema.ts";
12
+ import { deletionsFile, memoryRoot, snapshotDir } from "../core/config/paths.ts";
13
+ import { blockedEntries } from "../store/blocklist.ts";
14
+ import { listSnapshots, restoreSnapshot } from "../store/undo.ts";
15
+ import { appendMemory } from "../store/files/append.ts"
16
+ import { loadAll, memoryFiles } from "../store/files/load.ts";
17
+ import { parseLine } from "../core/logfmt/format.ts"
18
+ import { readLines } from "../core/logfmt/read.ts";
17
19
  import { releaseQuarantinedMemory } from "./mutate.ts";
18
- import { isQuarantined, quarantineReasons } from "../quarantine.ts";
20
+ import { isQuarantined, quarantineReasons } from "../store/quarantine/quarantine.ts";
19
21
  import { deleteMemory, editMemory, blockMemory, unblockMemory, unrejectMemory, type MutationResult } from "./mutate.ts";
20
- import { tombstones } from "../tombstones.ts";
22
+ import { tombstones } from "../store/tombstones/tombstone.ts";
21
23
 
22
24
  const PAGE = join(import.meta.dir, "page.html");
23
25
  const HOST = process.env.OPENCODE_VIEWER_HOST || "127.0.0.1";
package/tsconfig.json CHANGED
@@ -13,5 +13,5 @@
13
13
  "jsx": "preserve",
14
14
  "jsxImportSource": "@opentui/solid"
15
15
  },
16
- "include": ["index.ts", "src", "test", "bench", "e2e"]
17
- }
16
+ "include": ["index.ts", "src", "test", "bench", "e2e", "scripts"]
17
+ }
package/tui.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  // Convenience re-export for the loose plugin-discovery layout
2
2
  // (<config>/plugins/<name>/index.ts + tui.ts). Package installs resolve
3
3
  // "./tui" through package.json exports to src/tui.tsx directly.
4
- export { default } from "./src/tui.tsx";
4
+ export { default } from "./src/tui/panel.tsx";