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
package/src/memory.ts DELETED
@@ -1,851 +0,0 @@
1
- // Durable memory store engine. Reproduces the opencode-memory logfmt format
2
- // (MIT, github.com/shuans/opencode-memory; license retained under
3
- // vendor/opencode-memory/LICENSE) and extends it with the fields the write-gate
4
- // needs: supersession markers, snapshots and audited deletion.
5
- import { existsSync } from "node:fs";
6
- import { open, readFile } from "node:fs/promises";
7
- import { join, basename } from "node:path";
8
- import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
9
- import { repoScopeFor, sessionScope, writeTarget, type RepoScope } from "./repokey.ts";
10
- import { getCurrent } from "./state.ts";
11
- import {
12
- appendLog,
13
- ensureDir,
14
- fileIdentity,
15
- formatLine,
16
- parseLine,
17
- readLines,
18
- writeAtomic,
19
- type Fields,
20
- } from "./logfmt.ts";
21
- import { withStoreLock, LOCK_WRITE } from "./lock.ts";
22
- import { blockedTs } from "./blocklist.ts";
23
- import { tombstoneMany } from "./tombstones.ts";
24
- import { containsSecret, redactSecrets } from "./secrets.ts";
25
- import { flattenMemoryText } from "./sanitize.ts";
26
- import { isQuarantined, QUARANTINE_TAG, quarantineReasons } from "./quarantine.ts";
27
-
28
- export type MemoryStatus = "open" | "settled";
29
-
30
- // Hard ceiling on stored content. No entry point may persist a line longer
31
- // than this: injection ever shows ~1200 chars, the gate runs on the shared
32
- // service event loop, and regex scanning over megabyte-scale strings froze
33
- // sessions (100KB write = 6s, 2MB = hang).
34
- // Enforced twice — politely in runWriteGate (blocked outcome + evidence),
35
- // absolutely in appendMemory (throws, covering gate-bypassing callers).
36
- export const MAX_CONTENT_CHARS = 4000;
37
-
38
- /** How many retrieval keywords a row may carry, and how long each one may be. */
39
- export const MAX_KEYWORDS = 8;
40
- export const MAX_KEYWORD_CHARS = 48;
41
-
42
- /**
43
- * Normalise author-supplied retrieval keywords: trim, lowercase, split on the
44
- * storage delimiter, de-duplicate, drop empties and over-long entries, cap the
45
- * count. TOTAL on purpose — junk yields a shorter list rather than a throw,
46
- * because keywords only ever widen recall and must never be able to fail a
47
- * write the prose alone deserved.
48
- */
49
- export function normalizeKeywords(kw: unknown): string[] | undefined {
50
- if (!Array.isArray(kw)) return undefined;
51
- const out: string[] = [];
52
- for (const item of kw) {
53
- if (typeof item !== "string") continue;
54
- // Commas are the storage delimiter (kw serialises as one comma-joined
55
- // scalar), so an item carrying one would read back fragmented. Treat them
56
- // as separators: "build, test" becomes two aliases, never a " test".
57
- for (const part of item.split(",")) {
58
- const k = part.trim().toLowerCase();
59
- if (!k || k.length > MAX_KEYWORD_CHARS) continue;
60
- if (!out.includes(k)) out.push(k);
61
- if (out.length === MAX_KEYWORDS) break;
62
- }
63
- if (out.length === MAX_KEYWORDS) break;
64
- }
65
- return out.length ? out : undefined;
66
- }
67
-
68
-
69
- export interface Memory {
70
- ts: string;
71
- type: string;
72
- scope: string;
73
- content: string;
74
- issue?: string;
75
- tags?: string[];
76
- // Retrieval keywords (#40): author-supplied aliases, verb forms and synonyms
77
- // for this row, written at capture time. They widen the scoring haystack
78
- // ONLY — a row is never rendered through them, so injection bytes and the
79
- // content cap stay exactly what the prose says. This is the zero-embedding
80
- // answer to the bench's strict-paraphrase wall (0% R@1: the user's words are
81
- // not the memory's words).
82
- kw?: string[];
83
- superseded_by?: string;
84
- reason?: string;
85
- status?: MemoryStatus;
86
- // Origin repo: sha1 of the normalized origin URL, the toplevel
87
- // path when the repo had no remote, the literal "global" for cross-project
88
- // writes, or absent for legacy/viewer rows — all three read as described
89
- // in isVisibleHere().
90
- repo?: string;
91
- repoPath?: string;
92
- file: string;
93
- index: number;
94
- }
95
-
96
- const RESERVED = new Set([
97
- "deletions.logfmt",
98
- "deleted.logfmt",
99
- "canonical.logfmt",
100
- "blocklist.logfmt",
101
- // Value-keyed rejection tombstones (#35). Hashes only, never prose — and it
102
- // must never be ingested as a row, exported, or restored by undo.
103
- "rejected.logfmt",
104
- // The use ledger (src/hits.ts): telemetry, not memory. A hit line must never
105
- // be able to become a row — or to be superseded, exported, or injected.
106
- HITS_FILENAME,
107
- ]);
108
-
109
- // Row identity is `ts`: supersede chains, the blocklist, undo matching, and
110
- // the viewer's action buttons all key off it. A row whose ts is
111
- // not an ISO instant must never become an addressable live row — readers
112
- // treat it as malformed: skipped, counted, warned once per file. The shape
113
- // check lives here (the store knows its schema); logfmt stays a dumb parser.
114
- const ISO_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
115
- let malformedRows = 0;
116
- const malformedWarnedFiles = new Set<string>();
117
-
118
- /** Rows skipped as malformed by the most recent store read (approximate, in-process). */
119
- export function malformedCount(): number {
120
- return malformedRows;
121
- }
122
-
123
- function toMemory(fields: Record<string, unknown>, file: string, index: number): Memory | null {
124
- const ts = fields.ts;
125
- const type = fields.type;
126
- const scope = fields.scope;
127
- if (typeof ts !== "string" || typeof type !== "string") return null;
128
- if (typeof scope !== "string") return null;
129
- if (!ISO_TS_RE.test(ts) || Number.isNaN(Date.parse(ts))) {
130
- malformedRows++;
131
- if (!malformedWarnedFiles.has(file)) {
132
- malformedWarnedFiles.add(file);
133
- console.warn(
134
- `[memory] malformed row skipped in ${file} (ts is not an ISO instant): ${JSON.stringify(ts.slice(0, 48))}`,
135
- );
136
- }
137
- return null;
138
- }
139
- return {
140
- ts,
141
- type,
142
- scope,
143
- content: typeof fields.content === "string" ? fields.content : "",
144
- issue: typeof fields.issue === "string" ? fields.issue : undefined,
145
- tags: typeof fields.tags === "string" ? fields.tags.split(",") : undefined,
146
- kw: typeof fields.kw === "string" && fields.kw
147
- ? fields.kw.split(",").map((k) => k.trim()).filter((k) => k.length > 0)
148
- : undefined,
149
- superseded_by: typeof fields.superseded_by === "string" ? fields.superseded_by : undefined,
150
- reason: typeof fields.reason === "string" ? fields.reason : undefined,
151
- status:
152
- fields.status === "open" || fields.status === "settled" ? fields.status : undefined,
153
- repo: typeof fields.repo === "string" ? fields.repo : undefined,
154
- repoPath: typeof fields.repoPath === "string" ? fields.repoPath : undefined,
155
- file,
156
- index,
157
- };
158
- }
159
-
160
- export async function memoryFiles(): Promise<string[]> {
161
- const root = memoryRoot();
162
- // Bun.Glob.scan throws ENOENT on a missing root; a fresh store must read as
163
- // empty so the system-digest hook never throws (it runs on every request,
164
- // including the compaction model call).
165
- if (!existsSync(root)) return [];
166
- const glob = new Bun.Glob("*.logfmt");
167
- const files: string[] = [];
168
- for await (const f of glob.scan(root)) {
169
- if (!RESERVED.has(f)) files.push(join(root, f));
170
- }
171
- return files.sort();
172
- }
173
-
174
- export async function loadAll(): Promise<Memory[]> {
175
- malformedRows = 0; // per-load telemetry: the most recent read wins
176
- const blocked = await blockedTs();
177
- const out: Memory[] = [];
178
- for (const file of await memoryFiles()) {
179
- const lines = await readLines(file);
180
- lines.forEach((line, index) => {
181
- const m = toMemory(parseLine(line) ?? {}, file, index);
182
- if (m && !blocked.has(m.ts)) out.push(m);
183
- });
184
- }
185
- return out;
186
- }
187
-
188
- export async function loadScope(scope: string, reader: Reader = readerForAmbient()): Promise<Memory[]> {
189
- // Gate dedup/stale reads are repo-scoped: a row from another repo must not
190
- // collapse or supersede a write here. The reader is the CALLER's identity,
191
- // resolved at flow entry — not whatever current says after this await.
192
- return (await loadAll()).filter((m) => m.scope === scope && isVisibleTo(m, reader));
193
- }
194
-
195
- export interface AppendMemoryInput {
196
- type: string;
197
- scope: string;
198
- content: string;
199
- issue?: string;
200
- tags?: string[];
201
- /** Retrieval keywords (#40); normalised and capped by appendMemory. */
202
- kw?: string[];
203
- status?: MemoryStatus;
204
- // "global" for explicit cross-project writes; imports may carry a validated
205
- // same-repo origin stamp (see portable.ts). Any missing value is resolved by
206
- // appendMemory against the live repo scope.
207
- repo?: string;
208
- repoPath?: string;
209
- // Which session the write belongs to, when the caller knows it (the gate
210
- // threads it from GateContext, #116). Preferred over the ambient current.
211
- sessionID?: string;
212
- }
213
-
214
- // ts values already in `file`. An appended row's ts is "now", so the only rows
215
- // it can collide with are ones this same file received in the same millisecond;
216
- // scanning just it keeps the locked section to one read of one file. (A row
217
- // hand-placed with today's ts in another day's file is outside this promise.)
218
- function existingTs(text: string): Set<string> {
219
- const set = new Set<string>();
220
- for (const line of text.split("\n")) {
221
- const f = parseLine(line);
222
- if (f && typeof f.ts === "string") set.add(f.ts);
223
- }
224
- return set;
225
- }
226
-
227
- // #152: the store's answer to a write whose owner it cannot determine. Thrown
228
- // from the one place that knows what an owner is (the stamp resolution below),
229
- // so no caller — gate, import, capture, or a future one — can quietly persist
230
- // an ownerless row. `unresolvedWriteMessage` is the same text the model-facing
231
- // tools return, kept here so the two can never drift.
232
- export function unresolvedWriteMessage(sid: string): string {
233
- return (
234
- `Write refused: session ${sid} has no resolvable repository, so nothing was stored. ` +
235
- `A memory with no owner must not be stamped into another repository or published as a ` +
236
- `global row. Retry from a session in the project you mean, or pass global:true for a ` +
237
- `deliberate cross-project memory.`
238
- );
239
- }
240
-
241
- export class UnresolvedWriterError extends Error {
242
- /** The named-but-unresolved session whose write was refused. */
243
- sid: string;
244
- constructor(sid: string) {
245
- super(unresolvedWriteMessage(sid));
246
- this.name = "UnresolvedWriterError";
247
- this.sid = sid;
248
- }
249
- }
250
-
251
- // Append a durable memory. GATE-4 promotions and the viewer's edit/restore-entry
252
- // paths all call this single write choke point.
253
- export async function appendMemory(input: AppendMemoryInput): Promise<string> {
254
- // Absolute floor: every write SHOULD arrive through the gate,
255
- // which rejects invalid input politely; viewer writes do not, so enforce the
256
- // same storage rules here before anything reaches disk.
257
- if (typeof input.content !== "string") throw new Error("memory content must be a string");
258
- if (input.content.length > MAX_CONTENT_CHARS) {
259
- throw new Error(`memory content exceeds ${MAX_CONTENT_CHARS} chars (${input.content.length})`);
260
- }
261
- for (const [field, value] of [
262
- ["type", input.type],
263
- ["scope", input.scope],
264
- ["issue", input.issue],
265
- ] as const) {
266
- if (value !== undefined && flattenMemoryText(value) !== value) {
267
- throw new Error(`memory ${field} must not contain control characters`);
268
- }
269
- }
270
- if (input.tags?.some((tag) => flattenMemoryText(tag) !== tag)) {
271
- throw new Error("memory tags must not contain control characters");
272
- }
273
- // Keywords are indexed, never rendered, but they still live on the row's
274
- // single line, so the same control-character floor applies.
275
- if (input.kw?.some((k) => typeof k !== "string" || flattenMemoryText(k) !== k)) {
276
- throw new Error("memory keywords must not contain control characters");
277
- }
278
- const credentialMetadata = [
279
- containsSecret(input.scope) ? "scope" : undefined,
280
- input.tags?.some(containsSecret) ? "tags" : undefined,
281
- input.kw?.some(containsSecret) ? "kw" : undefined,
282
- containsSecret(input.issue) ? "issue" : undefined,
283
- ].filter((field): field is string => field !== undefined);
284
- if (credentialMetadata.length) {
285
- throw new Error(
286
- `memory metadata contains credential-shaped value in: ${credentialMetadata.join(", ")}`,
287
- );
288
- }
289
- const content = redactSecrets(input.content);
290
- // Repo stamp at the single write choke point: gated writes plus viewer edits
291
- // and restore-entry writes all pass through here. Explicit "global" survives;
292
- // an unscoped process (viewer) stamps nothing = global. Session identity wins
293
- // over the module scope so a server hosting several workspaces stamps the
294
- // writing session's repo.
295
- let repo = input.repo;
296
- let repoPath = input.repoPath;
297
- if (repo === undefined) {
298
- // The caller's session when it named one: capture awaits a model call, and
299
- // the last setCurrent before persistence may belong to another session
300
- // entirely (#116). Unnamed writers (tools, viewer, restore) keep the
301
- // ambient binding.
302
- //
303
- // A NAMED session that never resolved a repository is not an unnamed one
304
- // (#152): falling back to the module scope stamped its rows into whatever
305
- // workspace set up last, and with no module scope at all it stamped nothing
306
- // — which every reader calls global. Both outcomes publish private content
307
- // somewhere its owner can no longer see it, so the store refuses the write
308
- // instead of guessing an owner. Tools answer with this message before the
309
- // gate runs; throwing here is what covers every caller, including ones that
310
- // reach the store without a tool.
311
- const target = writeTarget(input.sessionID ?? getCurrent().sid);
312
- if (!target.ok) throw new UnresolvedWriterError(target.sid);
313
- if (target.scope) {
314
- repo = target.scope.key;
315
- repoPath = target.scope.path;
316
- }
317
- }
318
- // Day file chosen before the lock (it IS the lock key). A ts bumped across
319
- // midnight therefore lands under the previous day's name; readers glob every
320
- // file and decay compares ts values, so the grouping is cosmetic.
321
- const file = join(memoryRoot(), `${dateStr()}.logfmt`);
322
- // Locked end to end: seeding ts from a scan another process can race yields
323
- // two rows with the same identity, and an append that lands inside someone
324
- // else's whole-file rewrite is simply not there afterwards.
325
- return withStoreLock(file, async () => {
326
- const since = await fileIdentity(file);
327
- let prior = "";
328
- try { prior = await readFile(file, "utf8"); }
329
- catch (err) { if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; }
330
- const taken = existingTs(prior);
331
- let ts = new Date().toISOString();
332
- let guard = 0;
333
- while (taken.has(ts) && guard++ < 1000) {
334
- ts = new Date(new Date(ts).getTime() + 1).toISOString();
335
- }
336
- const kw = normalizeKeywords(input.kw);
337
- const line = formatLine({
338
- ts,
339
- type: input.type,
340
- scope: input.scope,
341
- content,
342
- issue: input.issue,
343
- tags: input.tags?.length ? input.tags.join(",") : undefined,
344
- kw: kw?.join(","),
345
- status: input.status,
346
- repo,
347
- repoPath,
348
- });
349
- // A lock excludes writers, not readers: an O_APPEND read can end mid-row.
350
- // Publish the complete day file using the read already needed for IDs.
351
- // This costs a whole-file write and can refuse on Windows reader handles;
352
- // the old destination remains intact if publication fails (#198).
353
- await writeAtomic(file, prior + (prior && !prior.endsWith("\n") ? "\n" : "") + line + "\n", since);
354
- return ts;
355
- }, LOCK_WRITE);
356
- }
357
-
358
- export interface SupersedeFields {
359
- superseded_by: string;
360
- reason: string;
361
- symbol?: string;
362
- from?: string;
363
- to?: string;
364
- entity?: string;
365
- }
366
-
367
- // Copy `file` into snapshots/ before a mutation.
368
- async function snapshotBefore(file: string): Promise<void> {
369
- await snapshotFiles([file]);
370
- }
371
-
372
- // Read-modify-write ONE row of a store file: read, rewrite the line, publish
373
- // atomically, all under the store lock, so an append or another rewrite by a
374
- // concurrent session cannot be overwritten by our stale copy. Resolves to null
375
- // when the row is not in this file, otherwise the mutation's outcome.
376
- async function stampRow(
377
- file: string,
378
- ts: string,
379
- mutate: (fields: Fields) => string | null,
380
- ): Promise<boolean | null> {
381
- return withStoreLock(
382
- file,
383
- async () => {
384
- // Identity BEFORE the read: it pins the state `lines` was derived from,
385
- // so writeAtomic can refuse to publish if anything moved the file
386
- // meanwhile (Windows retry path — see logfmt.ts handoverRename).
387
- const since = await fileIdentity(file);
388
- const lines = await readLines(file);
389
- const idx = lines.findIndex((l) => {
390
- const f = parseLine(l);
391
- return f && f.ts === ts;
392
- });
393
- if (idx === -1) return null;
394
- const parsed = parseLine(lines[idx]);
395
- if (!parsed) return false;
396
- const next = mutate(parsed);
397
- if (next === null) return false;
398
- lines[idx] = next;
399
- await snapshotBefore(file);
400
- await writeAtomic(file, lines.join("\n") + "\n", since);
401
- return true;
402
- },
403
- LOCK_WRITE,
404
- );
405
- }
406
-
407
- // Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
408
- // Idempotent: a second call is a no-op, so no double `superseded_by`.
409
- export async function markSuperseded(ts: string, fields: SupersedeFields, durable?: string[]): Promise<boolean> {
410
- return (await markManySupersededReport([{ ts, fields }], durable)).marked.length > 0;
411
- }
412
-
413
- // Batch supersession (#61): one lock acquisition, one read, one snapshot and
414
- // one publish PER FILE touched - N rows retire as one undo point instead of
415
- // N. decay and the gate's drift/canonical loops used to call markSuperseded
416
- // per row, which meant N full read-modify-write cycles, N undo points, and
417
- // N windows where two runs interleave and each re-pays the other's work.
418
- // Idempotence is unchanged: a row already carrying superseded_by is skipped,
419
- // so a repeat run marks nothing and writes nothing. Duplicate ts entries in
420
- // one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
421
- // Returns the number of rows actually marked.
422
- export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[], durable?: string[]): Promise<number> {
423
- return (await markManySupersededReport(entries, durable)).marked.length;
424
- }
425
-
426
- // Same operation, reporting WHICH rows retired rather than how many (#158
427
- // round 3): the write gate needs the ids to keep a durable-mutation ledger,
428
- // because a failed audit line after a persisted retirement must still be able
429
- // to name what actually landed. Skipped-by-the-batch rows (already retired
430
- // out of band) are absent from `marked` — the ledger never claims a retirement
431
- // this call did not perform.
432
- export async function markManySupersededReport(
433
- entries: { ts: string; fields: SupersedeFields }[],
434
- // Updated immediately after EACH publish, even if a later file refuses its
435
- // lock or lock cleanup throws. A rejected promise is not a rollback.
436
- durable?: string[],
437
- ): Promise<{ marked: string[] }> {
438
- if (entries.length === 0) return { marked: [] };
439
- const wanted = new Map<string, SupersedeFields>();
440
- for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
441
- const marked: string[] = [];
442
- for (const file of await memoryFiles()) {
443
- marked.push(
444
- ...(await withStoreLock(
445
- file,
446
- async () => {
447
- // #106: identity BEFORE the read, like every other whole-file
448
- // read-modify-write (#89's contract) - the publish below may retry a
449
- // Windows handover only while the destination still matches this.
450
- const since = await fileIdentity(file);
451
- const lines = await readLines(file);
452
- const ids: string[] = [];
453
- for (let i = 0; i < lines.length; i++) {
454
- const parsed = parseLine(lines[i]);
455
- if (!parsed || typeof parsed.superseded_by === "string") continue;
456
- const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
457
- if (!fields) continue;
458
- // Whole line rewritten, not extended: an old-format line comes out in
459
- // the current format with its values unchanged (as markSuperseded did).
460
- // The one exception is SECRET SCRUB (#128, review probe 4): the
461
- // fields a merge/decay/update copies into the loser's row carry
462
- // caller-authored prose (the rotation note "key ghp_... rotated"),
463
- // and content already scrubs at this same boundary (line 260). The
464
- // durable row must not be the one place a credential survives when
465
- // the evidence line beside it was cleaned.
466
- const clean: SupersedeFields = { ...fields };
467
- for (const k of Object.keys(clean)) {
468
- const v = (clean as unknown as Record<string, unknown>)[k];
469
- if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
470
- }
471
- lines[i] = formatLine({ ...parsed, ...clean });
472
- ids.push(parsed.ts as string);
473
- }
474
- if (ids.length === 0) return [];
475
- await snapshotBefore(file);
476
- await writeAtomic(file, lines.join("\n") + "\n", since);
477
- durable?.push(...ids);
478
- return ids;
479
- },
480
- LOCK_WRITE,
481
- ))
482
- );
483
- }
484
- // A ts that appears in several files (should not exist - append mints unique
485
- // ts) retires in EVERY file here, where the row-by-row loop retired only the
486
- // first; both are conservation-safe, this one is the more honest tombstone.
487
- return { marked };
488
- }
489
-
490
- // Drop a row's supersession markers IN PLACE (snapshot-first), making it active
491
- // again. Used by memory_merge_review: a declared survivor must be recallable
492
- // even when an earlier row — now the loser — had superseded it first.
493
- export async function clearSuperseded(ts: string): Promise<boolean> {
494
- for (const file of await memoryFiles()) {
495
- const outcome = await stampRow(file, ts, (parsed) => {
496
- if (typeof parsed.superseded_by !== "string") return null;
497
- // These five keys are written only by markSuperseded (drift, canonical,
498
- // update and merge_review), never by appendMemory, so they are all part of
499
- // the marker and go with it. Field order round-trips because parseLine
500
- // inserts keys in source order.
501
- for (const key of ["superseded_by", "reason", "symbol", "from", "to", "entity"]) {
502
- delete parsed[key];
503
- }
504
- return formatLine(parsed);
505
- });
506
- if (outcome !== null) return outcome;
507
- }
508
- return false;
509
- }
510
-
511
- export type TargetResolution =
512
- | { status: "ok"; target: Memory }
513
- | { status: "not_found" }
514
- | { status: "ambiguous"; candidates: Memory[] };
515
-
516
- // Score one row against a query: exact row id first, then content.
517
- function targetScore(m: Memory, query: string): number {
518
- const ts = m.ts.toLowerCase();
519
- if (ts === query) return 100;
520
- // A clock fragment ("00:11:25.867") is unique enough to identify a row.
521
- if (query.length >= 8 && ts.includes(query)) return 95;
522
- const content = m.content.toLowerCase();
523
- if (content === query) return 90;
524
- if (content.includes(query)) return 80;
525
- if (query.includes(content)) return 70;
526
- return 0;
527
- }
528
-
529
- // Pick the row an update/merge call means. Without a query the caller keeps the
530
- // legacy "most recent active row of this scope+type" behaviour; with one, a
531
- // miss or a tie fails CLOSED rather than silently rewriting a different row.
532
- export function resolveMemoryTarget(rows: Memory[], query?: string): TargetResolution {
533
- if (!query || !query.trim()) {
534
- const last = rows[rows.length - 1];
535
- return last ? { status: "ok", target: last } : { status: "not_found" };
536
- }
537
- const q = query.trim().toLowerCase();
538
- let best: Memory | undefined;
539
- let bestScore = 0;
540
- const tied: Memory[] = [];
541
- for (const m of rows) {
542
- const score = targetScore(m, q);
543
- if (score > bestScore) {
544
- best = m;
545
- bestScore = score;
546
- tied.length = 0;
547
- tied.push(m);
548
- } else if (score === bestScore && score > 0) {
549
- tied.push(m);
550
- }
551
- }
552
- if (!best) return { status: "not_found" };
553
- if (tied.length > 1) return { status: "ambiguous", candidates: tied };
554
- return { status: "ok", target: best };
555
- }
556
-
557
- export interface DeletedMemory {
558
- memory: Memory;
559
- reason: string;
560
- }
561
-
562
- // Claim a snapshot name with O_EXCL so "never overwrite a snapshot" holds
563
- // across processes, not just inside one: two sessions mutating the same file in
564
- // one millisecond both bump instead of one clobbering the other's still-undoable
565
- // copy. Names are `<epoch-ms>-<original>` because /undo strips the leading stamp
566
- // to find its target, so nothing may go in front of it.
567
- async function claimSnapshot(file: string): Promise<string> {
568
- await ensureDir(snapshotDir());
569
- let stamp = Date.now();
570
- for (;;) {
571
- const snap = join(snapshotDir(), `${stamp}-${basename(file)}`);
572
- try {
573
- const handle = await open(snap, "wx");
574
- await handle.close();
575
- return snap;
576
- } catch (err) {
577
- if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
578
- stamp++;
579
- }
580
- }
581
- }
582
-
583
- // Snapshot-before-mutate: copy each affected file into snapshots/ so /undo can
584
- // restore it. Returns the snapshot paths keyed by original file.
585
- export async function snapshotFiles(files: string[]): Promise<string[]> {
586
- const snaps: string[] = [];
587
- for (const file of files) {
588
- let contents: Buffer;
589
- try {
590
- contents = await readFile(file);
591
- } catch (err) {
592
- if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
593
- throw err;
594
- }
595
- const snap = await claimSnapshot(file);
596
- await Bun.write(snap, contents);
597
- snaps.push(snap);
598
- }
599
- return snaps;
600
- }
601
-
602
- export async function logDeletion(memory: Memory, reason: string): Promise<void> {
603
- await appendLog(
604
- deletionsFile(),
605
- formatLine({
606
- ts: new Date().toISOString(),
607
- action: "deleted",
608
- original_ts: memory.ts,
609
- type: memory.type,
610
- scope: memory.scope,
611
- content: memory.content,
612
- // Origin survives the delete/restore round trip (#129): a restore-entry
613
- // made from this line re-stamps what the row carried. A row with no
614
- // stamp writes no stamp here — the legacy global path, unchanged.
615
- repo: memory.repo,
616
- repoPath: memory.repoPath,
617
- reason: redactSecrets(reason),
618
- }),
619
- );
620
- }
621
-
622
- export interface PruneResult {
623
- deleted: DeletedMemory[];
624
- snapshot: string[];
625
- }
626
-
627
- // Remove matching memories (used by memory_forget), snapshotting first and
628
- // logging every deletion with its reason. Each file is filtered and republished
629
- // under the store lock, so a row another session appended while we were reading
630
- // is not quietly filtered out along with the targets. The reader is the
631
- // caller's captured identity (#127); out-of-plugin callers keep ambient.
632
- export async function prune(
633
- scope: string,
634
- type: string,
635
- reason: string,
636
- reader: Reader = readerForAmbient(),
637
- durable: PruneResult = { deleted: [], snapshot: [] },
638
- ): Promise<PruneResult> {
639
- const { deleted, snapshot } = durable;
640
- for (const file of await memoryFiles()) {
641
- await withStoreLock(
642
- file,
643
- async () => {
644
- const since = await fileIdentity(file);
645
- const lines = await readLines(file);
646
- const kept: string[] = [];
647
- const fileDeleted: DeletedMemory[] = [];
648
- let changed = false;
649
- for (const line of lines) {
650
- const parsed = parseLine(line);
651
- const m = parsed ? toMemory(parsed, file, 0) : null;
652
- // Repo floor: forgetting scope X here must never delete
653
- // another repo's row for scope X — same basename collisions are real
654
- // (a fork next to its upstream).
655
- if (m && m.scope === scope && m.type === type && isVisibleTo(m, reader)) {
656
- fileDeleted.push({ memory: m, reason });
657
- await logDeletion(m, reason);
658
- changed = true;
659
- continue;
660
- }
661
- kept.push(line);
662
- }
663
- if (!changed) return;
664
- snapshot.push(...(await snapshotFiles([file])));
665
- await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
666
- deleted.push(...fileDeleted);
667
- },
668
- LOCK_WRITE,
669
- );
670
- }
671
- // #35: tombstone every forgotten VALUE, keyed on content rather than on the
672
- // row's `ts`, so replaying the source cannot store the fact again.
673
- //
674
- // ONE batched call, not one per row: `memory_forget` deletes by scope+type and
675
- // routinely removes hundreds of rows, and the per-row form issued a store-lock
676
- // create/unlink pair plus a full re-read of the tombstone file for each one.
677
- // Done AFTER the per-file locks are released as well — appending inside the
678
- // loop would nest a second store lock (day file, then rejected.logfmt) inside
679
- // the first, and one consistent order across the codebase is what keeps the
680
- // lock manager from having to reason about nesting at all.
681
- await tombstoneMany(
682
- deleted.map((d) => ({
683
- content: d.memory.content,
684
- scope: d.memory.scope,
685
- type: d.memory.type,
686
- })),
687
- { reason, source: "forget" },
688
- );
689
- return { deleted, snapshot };
690
- }
691
-
692
- export function isActive(m: Memory): boolean {
693
- return !m.superseded_by;
694
- }
695
-
696
- // Quarantine remains durable and reviewable; only model-facing reads withhold it.
697
- export function isInjectable(m: Memory): boolean {
698
- return isActive(m) && !isQuarantined(m);
699
- }
700
-
701
- // Human viewer action only. Preserve identity, origin, and all non-quarantine
702
- // metadata; stampRow snapshots and atomically publishes under the store lock.
703
- export async function releaseQuarantine(ts: string): Promise<"released" | "not_found" | "not_quarantined"> {
704
- for (const file of await memoryFiles()) {
705
- const result = await stampRow(file, ts, (fields) => {
706
- const tags = typeof fields.tags === "string" ? fields.tags.split(",") : [];
707
- if (!tags.includes(QUARANTINE_TAG)) return null;
708
- const scanTags = new Set([QUARANTINE_TAG, ...quarantineReasons({ tags }).map((id) => `quarantine:${id}`)]);
709
- const kept = tags.filter((tag) => !scanTags.has(tag));
710
- if (kept.length) fields.tags = kept.join(",");
711
- else delete fields.tags;
712
- return formatLine(fields);
713
- });
714
- if (result !== null) return result ? "released" : "not_quarantined";
715
- }
716
- return "not_found";
717
- }
718
-
719
- // --- repo visibility ---------------------------------------------------------
720
- // A READER is an immutable caller identity, resolved once at the entry of a
721
- // flow (a hook, a tool call, a viewer route) and carried through every await
722
- // in that flow. Resolution must NOT be deferred to filter time: the module
723
- // global current moves whenever another session's hook or tool dispatches, and
724
- // a store read awaits filesystem I/O — filtering after the await with the
725
- // ambient identity injects the OTHER session's repo (#127).
726
- //
727
- // repo — the caller's session resolved a repository (its own when
728
- // bound; the setup location for an unbound session in a
729
- // single-workspace plugin, exactly the historical semantics).
730
- // global-only — a plugin flow whose caller identity names no repository:
731
- // explicit/legacy global rows ONLY. This is the fail-closed
732
- // answer for an unbound session on a serve host; "unknown"
733
- // is never "everything".
734
- // admin — explicit all-repositories access: the standalone viewer and
735
- // out-of-plugin maintenance callers. Administrative breadth is
736
- // a property of the entry point, never of a missing session.
737
- export type Reader =
738
- | { kind: "repo"; scope: RepoScope }
739
- | { kind: "global-only" }
740
- | { kind: "admin" };
741
-
742
- /** Explicit all-repositories identity (viewer routes, CLI maintenance). */
743
- export const ADMIN_READER: Reader = { kind: "admin" };
744
-
745
- // Reader for a plugin-session flow, resolved from the caller's OWN session id
746
- // captured synchronously at flow entry. Bound session → its repo; unbound →
747
- // global-only. The module scope is NOT a fallback here: in a process that
748
- // loaded more than one plugin instance it belongs to whoever set up LAST,
749
- // which is another workspace (#127's multi-setup gap). Plugin flows bind an
750
- // unbound caller to their OWN setup location at entry (index.ts), so ordinary
751
- // single-workspace sessions resolve through the session map, never here.
752
- export function readerForSession(sid?: unknown): Reader {
753
- const scope = sessionScope(sid);
754
- return scope ? { kind: "repo", scope } : { kind: "global-only" };
755
- }
756
-
757
- // The historical AMBIENT reader: live session, then module scope, and no
758
- // scope at all reads as unpartitioned. Correct only for out-of-plugin callers
759
- // (viewer, scripts, unit tests) with no concurrent sessions; model-facing
760
- // plugin paths carry a Reader instead of using this.
761
- export function readerForAmbient(): Reader {
762
- const scope = repoScopeFor(getCurrent().sid);
763
- return scope ? { kind: "repo", scope } : { kind: "admin" };
764
- }
765
-
766
- // Ambient-style entry points take an optional sid: a real session id resolves
767
- // fail-closed through readerForSession; "?" or absent keeps legacy semantics.
768
- export function readerFromSid(sid?: unknown): Reader {
769
- return typeof sid === "string" && sid !== "" && sid !== "?"
770
- ? readerForSession(sid)
771
- : readerForAmbient();
772
- }
773
-
774
- // The ONLY repo filter every read path uses (injection sinks, recall, list,
775
- // update targeting, prune, decay, gate scope reads). A row is visible when it
776
- // is global (explicit marker OR no stamp — legacy rows and writes by
777
- // processes with no scope, e.g. the viewer), or was written in the reader's
778
- // repo. Keeping it one predicate is what stops the filtering from drifting
779
- // between entry points.
780
- export function isVisibleTo(m: Pick<Memory, "repo" | "repoPath">, reader: Reader): boolean {
781
- if (reader.kind === "admin") return true;
782
- if (!m.repo || m.repo === "global") return true;
783
- if (reader.kind === "global-only") return false;
784
- return m.repo === reader.scope.key || (!!m.repoPath && m.repoPath === reader.scope.path);
785
- }
786
-
787
- export function visibleTo(mems: Memory[], reader: Reader): Memory[] {
788
- return mems.filter((m) => isVisibleTo(m, reader));
789
- }
790
-
791
- // The day-file twin of isVisibleTo for whole-file paths (undo/restore) that
792
- // work on raw logfmt lines instead of parsed rows: the SAME predicate, with the
793
- // rows' rule that a line with no stamp is a legacy row, not a private one —
794
- // which is exactly the rule the evidence lines do NOT share, and the reason
795
- // these are not one function. An unparseable line has no stamp, so it reads
796
- // legacy-global rather than silently vanishing under a restore.
797
- export function lineVisibleTo(line: string, reader: Reader): boolean {
798
- if (reader.kind === "admin") return true;
799
- const fields = parseLine(line);
800
- return isVisibleTo(
801
- {
802
- repo: typeof fields?.repo === "string" ? fields.repo : undefined,
803
- repoPath: typeof fields?.repoPath === "string" ? fields.repoPath : undefined,
804
- },
805
- reader,
806
- );
807
- }
808
-
809
- // The evidence-line twin of isVisibleTo, plus the one rule rows do not need:
810
- // a missing stamp is NOT the same as a global marker. An explicitly
811
- // `repo=global` line is global, and a line with no stamp AND no named
812
- // session (legacy, or an out-of-plugin maintenance write) keeps its
813
- // historical global reading. But a line a NAMED session wrote while its
814
- // repository was unresolvable (evidence.ts) belongs to that session alone —
815
- // visible back to the same session and to the admin surface, never to a
816
- // stranger's memory_evidence. `callerSid` is the reading session's own id
817
- // captured at flow entry; without it the private branch can only fail
818
- // closed (admin sees all, everyone else does not).
819
- export function evidenceVisibleTo(
820
- fields: Record<string, unknown>,
821
- reader: Reader,
822
- callerSid?: unknown,
823
- ): boolean {
824
- if (reader.kind === "admin") return true;
825
- const repo = fields.repo;
826
- if (typeof repo === "string" && repo !== "") {
827
- if (repo === "global") return true;
828
- if (reader.kind === "global-only") return false;
829
- const repoPath = fields.repoPath;
830
- return (
831
- repo === reader.scope.key ||
832
- (typeof repoPath === "string" && !!repoPath && repoPath === reader.scope.path)
833
- );
834
- }
835
- const sid = fields.sid;
836
- if (typeof sid === "string" && sid !== "" && sid !== "?") {
837
- return typeof callerSid === "string" && callerSid === sid;
838
- }
839
- return true;
840
- }
841
-
842
- // Ambient (out-of-plugin) convenience: resolves the reader at CALL time.
843
- // Plugin paths must pass an explicit Reader/sid instead of relying on this.
844
- export function isVisibleHere(m: Memory): boolean {
845
- return isVisibleTo(m, readerForAmbient());
846
- }
847
-
848
- // Rows visible to the current process (active filtering stays with callers).
849
- export function visibleHere(mems: Memory[]): Memory[] {
850
- return mems.filter(isVisibleHere);
851
- }