opencode-self-improvement 0.15.4 → 0.15.6

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 (100) hide show
  1. package/README.md +2 -0
  2. package/package.json +2 -2
  3. package/src/capture/candidates.ts +110 -0
  4. package/src/capture/lag.ts +18 -0
  5. package/src/capture/prompt.ts +50 -0
  6. package/src/capture/transcript.ts +59 -0
  7. package/src/{triggers.ts → capture/triggers.ts} +6 -5
  8. package/src/{command.ts → command/ensure.ts} +2 -2
  9. package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
  10. package/src/consolidate/render.ts +30 -0
  11. package/src/core/cmp-ts.ts +16 -0
  12. package/src/core/config/budgets.ts +28 -0
  13. package/src/{config.ts → core/config/paths.ts} +6 -31
  14. package/src/core/logfmt/format.ts +82 -0
  15. package/src/{logfmt.ts → core/logfmt/publish.ts} +20 -96
  16. package/src/core/logfmt/read.ts +15 -0
  17. package/src/core/permissions.ts +47 -0
  18. package/src/{state.ts → core/state.ts} +1 -1
  19. package/src/core/time.ts +6 -0
  20. package/src/{evidence.ts → evidence/record.ts} +7 -5
  21. package/src/{gates.ts → gate/gate.ts} +19 -21
  22. package/src/{resolver.ts → gate/resolver.ts} +1 -1
  23. package/src/{hits.ts → hits/ledger.ts} +8 -6
  24. package/src/index.ts +64 -943
  25. package/src/init/detect.ts +144 -0
  26. package/src/init/format.ts +25 -0
  27. package/src/init/run.ts +188 -0
  28. package/src/inject/anchor.ts +43 -0
  29. package/src/{attribution.ts → inject/attribution.ts} +2 -2
  30. package/src/inject/budget.ts +78 -0
  31. package/src/inject/digest.ts +89 -0
  32. package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
  33. package/src/inject/format.ts +32 -0
  34. package/src/inject/pull.ts +52 -0
  35. package/src/inject/version.ts +31 -0
  36. package/src/portable/decay.ts +20 -0
  37. package/src/portable/export.ts +194 -0
  38. package/src/portable/import.ts +173 -0
  39. package/src/recall/relevant.ts +72 -0
  40. package/src/recall/score.ts +106 -0
  41. package/src/recall/shared-terms.ts +15 -0
  42. package/src/status/format.ts +58 -0
  43. package/src/status/metrics.ts +65 -0
  44. package/src/status/payload.ts +145 -0
  45. package/src/status/report.ts +202 -0
  46. package/src/status/write.ts +114 -0
  47. package/src/{blocklist.ts → store/blocklist.ts} +4 -2
  48. package/src/store/files/append.ts +176 -0
  49. package/src/store/files/deletions.ts +31 -0
  50. package/src/store/files/load.ts +106 -0
  51. package/src/store/files/prune.ts +81 -0
  52. package/src/store/files/snapshots.ts +88 -0
  53. package/src/store/files/supersede.ts +123 -0
  54. package/src/store/files/target.ts +36 -0
  55. package/src/{lock.ts → store/lock.ts} +5 -4
  56. package/src/store/model/memory.ts +91 -0
  57. package/src/store/model/predicates.ts +12 -0
  58. package/src/store/model/visibility.ts +140 -0
  59. package/src/{prune.ts → store/prune.ts} +4 -3
  60. package/src/store/quarantine/release.ts +24 -0
  61. package/src/store/tombstones/rejection.ts +93 -0
  62. package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
  63. package/src/{undo.ts → store/undo.ts} +6 -3
  64. package/src/tools/consolidate.ts +42 -0
  65. package/src/tools/decay.ts +83 -0
  66. package/src/tools/deps.ts +27 -0
  67. package/src/tools/evidence.ts +48 -0
  68. package/src/tools/export.ts +27 -0
  69. package/src/tools/forget.ts +23 -0
  70. package/src/tools/import.ts +57 -0
  71. package/src/tools/init.ts +30 -0
  72. package/src/tools/list.ts +36 -0
  73. package/src/tools/merge-review.ts +138 -0
  74. package/src/tools/recall.ts +72 -0
  75. package/src/tools/registry.ts +40 -0
  76. package/src/tools/remember.ts +49 -0
  77. package/src/{schema.ts → tools/schema.ts} +3 -3
  78. package/src/tools/status-tool.ts +59 -0
  79. package/src/tools/undo.ts +57 -0
  80. package/src/tools/update.ts +342 -0
  81. package/src/{tui.tsx → tui/panel.tsx} +7 -17
  82. package/src/viewer/mutate.ts +15 -15
  83. package/src/viewer/server.ts +10 -8
  84. package/tui.ts +1 -1
  85. package/src/capture.ts +0 -222
  86. package/src/init.ts +0 -333
  87. package/src/inject.ts +0 -471
  88. package/src/memory.ts +0 -851
  89. package/src/portable.ts +0 -379
  90. package/src/status.ts +0 -536
  91. /package/src/{sessions.ts → core/lru.ts} +0 -0
  92. /package/src/{runtime.ts → core/runtime.ts} +0 -0
  93. /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
  94. /package/src/{types.ts → core/types.ts} +0 -0
  95. /package/src/{host.ts → identity/host-events.ts} +0 -0
  96. /package/src/{repokey.ts → identity/repokey.ts} +0 -0
  97. /package/src/{containment.ts → store/containment.ts} +0 -0
  98. /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
  99. /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
  100. /package/src/{secrets.ts → store/secrets.ts} +0 -0
package/src/portable.ts DELETED
@@ -1,379 +0,0 @@
1
- // Portability: JSONL export/import of the durable store, plus the
2
- // stale-open-thread query that backs memory_decay. Import NEVER writes: every
3
- // row flows through the caller-provided gate callback (index.ts wires it to
4
- // runWriteGate), so moving memories between machines cannot bypass the 4-gate
5
- // moat. Decay is supersede-not-delete and snapshot-first, mirroring prune.
6
- import { constants } from "node:fs";
7
- import { randomUUID } from "node:crypto";
8
- import { mkdir, open, readFile } from "node:fs/promises";
9
- import { dirname, join } from "node:path";
10
- import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
11
- import { resolveContained } from "./containment.ts";
12
- import { isQuarantined, quarantineCandidate } from "./quarantine.ts";
13
- import {
14
- isActive,
15
- isInjectable,
16
- isVisibleTo,
17
- loadAll,
18
- readerFromSid,
19
- UnresolvedWriterError,
20
- type Memory,
21
- } from "./memory.ts";
22
- import { writeTarget } from "./repokey.ts";
23
- import { getCurrent } from "./state.ts";
24
- import { TYPES } from "./types.ts";
25
- import type { WriteCandidate } from "./gates.ts";
26
- import { flattenMemoryText } from "./sanitize.ts";
27
-
28
- // --- export -------------------------------------------------------------------
29
-
30
- // Export header line: the first line of a v1 export identifies the file as
31
- // machine-made by memory_export. It is what vouches for status="open" frontier
32
- // rows on import — the open status exempts a row from ref grounding at the
33
- // gate, so it must not be granted by an attacker-chosen field in a
34
- // hand-written JSONL. The header is friction, not a boundary (anyone can
35
- // paste one); the real defense against planted content is the injection
36
- // framing + provenance in inject.ts and the write gates.
37
- export const EXPORT_HEADER = "opencode-self-improvement";
38
- export const EXPORT_VERSION = 1;
39
-
40
- export interface ExportOptions {
41
- /** Only export rows from this exact scope. */
42
- scope?: string;
43
- /**
44
- * Destination, confined to <memory-root>/exports/ (see containment.ts).
45
- * Defaults to <memory-root>/exports/<stamp>-<unique>.jsonl: a UNIQUE name,
46
- * created exclusively, so two exports in the same second can never replace
47
- * each other's artifact (#143's review). An explicit `file` keeps the
48
- * historical replace semantics backups rely on.
49
- */
50
- file?: string;
51
- /**
52
- * The calling session's identity (#143): an export carries exactly the rows
53
- * its reader can read — own repo plus global. "?" or absent resolves the
54
- * AMBIENT reader: out-of-plugin callers (viewer, CLI maintenance) keep the
55
- * full-store breadth; breadth stays a property of the entry point.
56
- */
57
- sessionID?: string;
58
- }
59
-
60
- export interface ExportResult {
61
- path: string;
62
- count: number;
63
- }
64
-
65
- // Filesystem-safe YYYY-MM-DDTHHMMSS (no colons) plus a unique suffix for each
66
- // default export. The timestamp alone was second-granular: two sessions
67
- // exporting in the same second got the SAME path, and O_TRUNC let the later
68
- // one destroy the earlier one's artifact AND its returned path (#143 review).
69
- // Milliseconds would still collide; uniqueness comes from the name, not the
70
- // clock.
71
- function stamp(d: Date = new Date()): string {
72
- return `${d.toISOString().slice(0, 19).replace(/:/g, "")}-${randomUUID()}`;
73
- }
74
-
75
- // An export is a full copy of the live store, so it may only be written inside
76
- // the store's own exports/ directory: ~/.gitconfig, a relative path landing in
77
- // the host process's cwd, ../.., and links out of the root are all rejected.
78
- // Only an absent `file` means the default — an empty or whitespace-only one is
79
- // a caller bug and fails rather than silently redirecting.
80
- async function resolveExportTarget(file: string | undefined): Promise<string> {
81
- const allowOutside = allowOutsideStorePaths();
82
- const opts = {
83
- label: "memory_export file",
84
- hint: `omit file for the default, or name a path under ${exportsDir()}`,
85
- // An exports/ that is itself a symlink must not move the write out of the
86
- // store either — same two-level check undo.ts's restore makes.
87
- outerRoot: memoryRoot(),
88
- allowOutside,
89
- };
90
- // A default destination is still a destination. Routing it through the same
91
- // check is what stops an exports/ that is a link from writing the whole store
92
- // copy outside the store on the argument-free call — the one a model reaches
93
- // without knowing anything about the layout. Under the operator escape hatch
94
- // there is nothing to check, so the plain join is what remains.
95
- if (file === undefined && allowOutside) return join(exportsDir(), `${stamp()}.jsonl`);
96
- return resolveContained(file ?? `${stamp()}.jsonl`, exportsDir(), opts);
97
- }
98
-
99
- // An export is a plaintext copy of the whole store, so it is written 0600 and
100
- // opened O_NOFOLLOW. The flag matters: the containment check and this open are
101
- // separate syscalls, and the gap is the entire store read — single-digit to tens
102
- // of milliseconds on a 5 000-row store depending on the machine, which is long
103
- // enough for anything that can create a link inside exports/.
104
- //
105
- // Both are POSIX guarantees. libuv does not implement O_NOFOLLOW on Windows
106
- // (verified on the CI windows leg: the open follows the link) and Windows
107
- // reports every writable file as 0666, so there the containment check that ran
108
- // before this call is the only protection.
109
- //
110
- // Exported so the flag itself can be pinned: the containment layer refuses an
111
- // existing link long before this runs, so the only way to test O_NOFOLLOW
112
- // without racing is to call the writer directly.
113
- export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
114
- await mkdir(dirname(path), { recursive: true });
115
- // exclusive = a default destination WE chose: create it or fail, never
116
- // silently replace another export's file. An explicit caller-supplied
117
- // `file` keeps the historical O_TRUNC replace (backup workflows rewrite
118
- // the same path on purpose).
119
- const flags =
120
- constants.O_WRONLY |
121
- constants.O_CREAT |
122
- (exclusive ? constants.O_EXCL : constants.O_TRUNC) |
123
- (constants.O_NOFOLLOW ?? 0);
124
- const handle = await open(path, flags, 0o600);
125
- try {
126
- await handle.writeFile(text, "utf8");
127
- // open()'s mode applies only when the file is created, so re-exporting over
128
- // a file that already existed (a 0644 one, say) would otherwise leave it
129
- // world-readable and make the 0600 above a claim rather than a guarantee.
130
- await handle.chmod(0o600);
131
- } finally {
132
- await handle.close();
133
- }
134
- }
135
-
136
- // Write the ACTIVE store as JSONL — a header line followed by one JSON object
137
- // per line carrying {ts,type,scope,content,status,tags,issue}. Superseded rows
138
- // are not exported: the export is the live store, and history stays auditable
139
- // where it lives (the original logfmt files + snapshots). The header is always
140
- // written, even for an empty store, so "has header" is a format invariant.
141
- //
142
- // "the live store" means the store AS THE CALLER CAN READ IT (#143): rows are
143
- // filtered through the caller's Reader, exactly as recall and injection do.
144
- // Full breadth remains the ambient/admin entry point's, never a missing
145
- // session's.
146
- //
147
- // The destination is model-supplied, so it is resolved and confined BEFORE the
148
- // store is read: a rejected export must not leave a file behind, and must not
149
- // be a way to learn how many rows matched either.
150
- export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
151
- const path = await resolveExportTarget(opts.file);
152
- const reader = readerFromSid(opts.sessionID);
153
- let mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
154
- if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
155
- const header = JSON.stringify({
156
- _export: EXPORT_HEADER,
157
- version: EXPORT_VERSION,
158
- exportedAt: new Date().toISOString(),
159
- count: mems.length,
160
- });
161
- const lines = mems.map((m) =>
162
- JSON.stringify({
163
- ts: m.ts,
164
- type: m.type,
165
- scope: m.scope,
166
- content: m.content,
167
- status: m.status,
168
- tags: m.tags,
169
- kw: m.kw,
170
- issue: m.issue,
171
- // Origin stamps ride along so a same-repo machine hop can retain them.
172
- // Import validates them against its current repo before promotion.
173
- repo: m.repo,
174
- repoPath: m.repoPath,
175
- }),
176
- );
177
- try {
178
- await writeExport(path, `${[header, ...lines].join("\n")}\n`, opts.file === undefined);
179
- } catch (err) {
180
- // Past containment, so this is not an existence oracle: `path` is one the
181
- // plugin chose or already validated. The errno stays, because it is the
182
- // operator's only diagnostic — but in our sentence rather than the runtime's,
183
- // so a model-facing tool result never carries a raw stack-adjacent string.
184
- const code = err instanceof Error && "code" in err ? String(err.code) : "unknown error";
185
- throw new Error(`memory_export could not write ${path} (${code})`);
186
- }
187
- return { path, count: mems.length };
188
- }
189
-
190
- // --- import -------------------------------------------------------------------
191
-
192
- export interface ImportTally {
193
- promoted: number;
194
- quarantined?: number;
195
- collapsed: number;
196
- blocked: number;
197
- skipped: number;
198
- /** Open rows downgraded because the file cannot grant that frontier scope. */
199
- downgraded: number;
200
- /** Promoted rows whose write_promoted audit line failed to land (#155 review). */
201
- unaudited: number;
202
- /** First audit-fault message, so the reply can name what went wrong. */
203
- auditError?: string;
204
- }
205
-
206
- // Recognize the export header line (see EXPORT_HEADER). A version NEWER than
207
- // we understand does NOT grant the frontier exemption — we cannot know what
208
- // its writer meant (fail closed).
209
- function exportHeader(line: string): { version: number } | null {
210
- let row: unknown;
211
- try {
212
- row = JSON.parse(line);
213
- } catch {
214
- return null;
215
- }
216
- if (!row || typeof row !== "object" || Array.isArray(row)) return null;
217
- const r = row as Record<string, unknown>;
218
- if (r._export !== EXPORT_HEADER) return null;
219
- return { version: typeof r.version === "number" ? r.version : 1 };
220
- }
221
-
222
- // A line is malformed (skipped, never gated) unless it is a JSON object with a
223
- // known type, a non-empty scope, and non-empty content. Optional fields are
224
- // sanitized rather than fatal where noted. Control characters in structured
225
- // metadata make the row malformed; content alone may remain multiline.
226
- function parseRow(line: string): WriteCandidate | null {
227
- let row: unknown;
228
- try {
229
- row = JSON.parse(line);
230
- } catch {
231
- return null;
232
- }
233
- if (!row || typeof row !== "object" || Array.isArray(row)) return null;
234
- const r = row as Record<string, unknown>;
235
- if (typeof r.type !== "string" || !(TYPES as readonly string[]).includes(r.type)) return null;
236
- if (typeof r.scope !== "string" || !r.scope.trim()) return null;
237
- if (flattenMemoryText(r.scope) !== r.scope) return null;
238
- if (typeof r.content !== "string" || !r.content.trim()) return null;
239
- if (
240
- Array.isArray(r.tags) &&
241
- r.tags.some((t) => typeof t === "string" && flattenMemoryText(t) !== t)
242
- ) return null;
243
- if (typeof r.issue === "string" && flattenMemoryText(r.issue) !== r.issue) return null;
244
- // Keywords widen recall only, so a malformed entry costs them, never the row
245
- // (contrast scope/content, where a bad value makes the line malformed).
246
- const kw = Array.isArray(r.kw)
247
- ? r.kw.filter(
248
- (k): k is string =>
249
- typeof k === "string" && !!k.trim() && flattenMemoryText(k.trim()) === k.trim(),
250
- )
251
- : undefined;
252
- const c: WriteCandidate = { type: r.type, scope: r.scope, content: r.content };
253
- if (r.status === "open" || r.status === "settled") c.status = r.status;
254
- if (Array.isArray(r.tags) && r.tags.every((t) => typeof t === "string")) c.tags = r.tags;
255
- if (kw?.length) c.kw = kw;
256
- if (typeof r.issue === "string" && r.issue) c.issue = r.issue;
257
- // Origin stamps survive an export/import hop (repokey.ts): a row written
258
- // for repo X stays visible only where repo X is opened, even on a new
259
- // machine. Unstamped rows stay global.
260
- if (typeof r.repo === "string" && r.repo) c.repo = r.repo;
261
- if (typeof r.repoPath === "string" && r.repoPath) c.repoPath = r.repoPath;
262
- return quarantineCandidate(c);
263
- }
264
-
265
- // Read a JSONL export and run every valid row through `gate`. The CALLER owns
266
- // promotion (index.ts passes runWriteGate with the "import" tag), so imported
267
- // rows face the same canonical/stale/dedup/ambiguity gates as any other write.
268
- // Blocked and collapsed rows are normal outcomes, tallied rather than raised.
269
- // Frontier policy: status="open" exempts a row from ref grounding
270
- // at the gate, so it is honored ONLY when the file opens with our export
271
- // header (version <= ours); otherwise every open row is downgraded to settled
272
- // and tallied. Imported origin stamps are honored only when they match the
273
- // importing session's current repo (or are an explicit "global"); foreign
274
- // stamps are removed so the write choke point stamps the importing repo
275
- // instead. With no current scope, stamps are kept (removing them would widen
276
- // the row to global) and a stamped open row is downgraded, since its stamp
277
- // cannot be verified. Only a missing file throws.
278
- //
279
- // The path is a model-supplied READ primitive, so it is confined to the memory
280
- // root BEFORE the filesystem is touched, and containment's error never says
281
- // whether the path exists — otherwise a rejection is an existence oracle for
282
- // files outside the store. The .jsonl requirement closes the rest of that door:
283
- // without it, the tally ("N malformed lines skipped") would leak line counts of
284
- // day files, snapshots and the blocklist, none of which are import formats.
285
- export async function importMemories(
286
- path: string,
287
- gate: (c: WriteCandidate) => Promise<{ action: string; evidenceError?: string }>,
288
- // The importing session, captured at tool entry (#127): "the importing
289
- // session's current repo" must be the CALLER's repo even though this loop
290
- // awaits the gate on every row, during which a concurrent session can move
291
- // the ambient current.
292
- sessionID?: string,
293
- ): Promise<ImportTally> {
294
- // Capture the importing owner before file I/O: later session moves must not
295
- // re-home rows partway through the import (#183). Resolve with the writer
296
- // rule so an unresolved named session never borrows the ambient repo (#152).
297
- const writeAt = writeTarget(sessionID ?? getCurrent().sid);
298
- const target = await resolveContained(path, memoryRoot(), {
299
- label: "memory_import file",
300
- // Deliberately no mention of the operator escape hatch: this string goes
301
- // back to the model, and naming the variable there is an instruction it can
302
- // relay. The hatch lives in the README.
303
- hint: `copy the export under ${memoryRoot()} first`,
304
- allowOutside: allowOutsideStorePaths(),
305
- });
306
- if (!target.toLowerCase().endsWith(".jsonl")) {
307
- throw new Error(`memory_import file must be a .jsonl export (got "${path}")`);
308
- }
309
- let text: string;
310
- try {
311
- text = await readFile(target, "utf8");
312
- } catch (err) {
313
- if ((err as NodeJS.ErrnoException).code === "ENOENT") throw new Error(`import file not found: ${target}`);
314
- throw err;
315
- }
316
- const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
317
- // Preserve file-validation error precedence, but reject an unresolved owner
318
- // before gating any row. Resolution happened at entry, not at this await.
319
- if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
320
- const currentScope = writeAt.scope;
321
- let allowFrontier = false;
322
- let first = true;
323
- for (const line of text.replace(/^\uFEFF/, "").split("\n")) {
324
- if (!line.trim()) continue;
325
- if (first) {
326
- first = false;
327
- const hdr = exportHeader(line);
328
- if (hdr) {
329
- allowFrontier = hdr.version <= EXPORT_VERSION;
330
- continue; // metadata line: never a memory row, never a skipped one
331
- }
332
- }
333
- const c = parseRow(line);
334
- if (!c) {
335
- tally.skipped++;
336
- continue;
337
- }
338
- const claimedGlobal = c.repo === "global";
339
- const hadStamp = c.repo !== undefined || c.repoPath !== undefined;
340
- // A foreign stamp is treated like no stamp, so appendMemory stamps the
341
- // importing repo. Explicit "global" is not a foreign repo and is kept (open
342
- // global rows are downgraded below). With no current scope there is nothing
343
- // to re-stamp with: dropping the stamp would widen the row to global, so it
344
- // is kept and only the open-row exemption is withdrawn.
345
- if (currentScope && !claimedGlobal) {
346
- if (c.repo !== currentScope.key) delete c.repo;
347
- if (c.repoPath !== currentScope.path) delete c.repoPath;
348
- }
349
- if (c.status === "open" && (!allowFrontier || claimedGlobal || (hadStamp && !currentScope))) {
350
- c.status = "settled";
351
- tally.downgraded++;
352
- }
353
- const outcome = await gate(c);
354
- if (outcome.action === "promoted") {
355
- tally.promoted++;
356
- if (isQuarantined(c)) tally.quarantined = (tally.quarantined ?? 0) + 1;
357
- if (outcome.evidenceError !== undefined) {
358
- tally.unaudited++;
359
- tally.auditError ??= outcome.evidenceError;
360
- }
361
- } else if (outcome.action === "collapsed") tally.collapsed++;
362
- else tally.blocked++;
363
- }
364
- return tally;
365
- }
366
-
367
- // --- decay support --------------------------------------------------------------
368
-
369
- // Active open threads with ts older than `days` days, oldest first (both sides
370
- // are UTC-Z ISO strings, so plain lexicographic compare is correct).
371
- export async function findStaleOpen(days: number, sid?: string): Promise<Memory[]> {
372
- const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
373
- const reader = readerFromSid(sid);
374
- return (await loadAll())
375
- // Decay is repo-scoped: running it here must not retire
376
- // another repo's open threads.
377
- .filter((m) => isInjectable(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
378
- .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
379
- }