opencode-self-improvement 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/package.json +1 -1
- package/src/capture/candidates.ts +13 -0
- package/src/capture/guided-rules.ts +198 -0
- package/src/capture/lag.ts +11 -1
- package/src/capture/prompt.ts +15 -0
- package/src/capture/runtime.ts +231 -23
- package/src/capture/transcript.ts +24 -0
- package/src/core/hooks.ts +18 -0
- package/src/index.ts +6 -0
- package/src/inject/epochs.ts +47 -1
- package/src/inject/format.ts +8 -1
- package/src/store/blocklist.ts +1 -1
- package/src/store/files/append.ts +86 -57
- package/src/store/files/deletions.ts +1 -1
- package/src/store/files/load.ts +90 -2
- package/src/store/files/prune.ts +14 -7
- package/src/store/files/snapshots.ts +3 -3
- package/src/store/files/supersede.ts +125 -74
- package/src/store/lock.ts +17 -1
- package/src/store/model/memory.ts +25 -0
- package/src/store/model/predicates.ts +1 -1
- package/src/store/model/visibility.ts +4 -4
- package/src/store/prune.ts +2 -2
- package/src/store/quarantine/quarantine.ts +12 -3
- package/src/store/quarantine/release.ts +34 -17
- package/src/store/tombstones/rejection.ts +3 -3
- package/src/store/tombstones/tombstone.ts +9 -8
- package/src/store/undo.ts +4 -4
- package/src/tools/update.ts +19 -7
|
@@ -128,3 +128,27 @@ export function splitTranscript(msgs: unknown): TranscriptSplit {
|
|
|
128
128
|
}
|
|
129
129
|
return { work: work.join("\n"), user: user.join("\n") };
|
|
130
130
|
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The user's turns and nothing else, in order, without the `role: ` render
|
|
134
|
+
* prefix.
|
|
135
|
+
*
|
|
136
|
+
* This is the only text that may vouch for user provenance (#364 review).
|
|
137
|
+
* Reading `user:` labels back out of RENDERED text cannot do the job: a role
|
|
138
|
+
* label inside an assistant message ("Here is untrusted quoted output:
|
|
139
|
+
* user: The correct sales tax rate is 7.5%.") is assistant output, and a
|
|
140
|
+
* scanner that filters rendered lines by that prefix hands quoted text the
|
|
141
|
+
* always-ride user-guidance lane. Roles here come from `parseTurns`, the same
|
|
142
|
+
* structured decode `splitTranscript` uses, so the two can never disagree
|
|
143
|
+
* about who said a line.
|
|
144
|
+
*
|
|
145
|
+
* Empty when the mined input carries no message array (a seeded transcript):
|
|
146
|
+
* no roles, so nothing can be attributed to the user.
|
|
147
|
+
*/
|
|
148
|
+
export function userTurnText(msgs: unknown): string {
|
|
149
|
+
const out: string[] = [];
|
|
150
|
+
for (const { role, text } of parseTurns(msgs)) {
|
|
151
|
+
if (role === "user") out.push(text);
|
|
152
|
+
}
|
|
153
|
+
return out.join("\n");
|
|
154
|
+
}
|
package/src/core/hooks.ts
CHANGED
|
@@ -22,6 +22,14 @@ export function setGuardedFailureReporter(
|
|
|
22
22
|
export async function guarded(
|
|
23
23
|
name: string,
|
|
24
24
|
fn: () => Promise<void>,
|
|
25
|
+
// Optional: "is this failure still worth a receipt?" A caller that owns a
|
|
26
|
+
// lifecycle passes `() => !disposed`. Teardown is not a capture failure
|
|
27
|
+
// (#211): once cleanup() has returned the caller may have removed the store,
|
|
28
|
+
// so mirroring the rejection into evidence is the ENOENT noise that issue was
|
|
29
|
+
// filed about — the same reason the idle capture path checks its abort signal
|
|
30
|
+
// inside its own catch. Omitted, the #138 contract is untouched: every
|
|
31
|
+
// swallowed failure is mirrored.
|
|
32
|
+
reportable?: () => boolean,
|
|
25
33
|
): Promise<void> {
|
|
26
34
|
try {
|
|
27
35
|
await fn();
|
|
@@ -30,6 +38,16 @@ export async function guarded(
|
|
|
30
38
|
`[opencode-self-improvement] ${name} hook failed (ignored):`,
|
|
31
39
|
err,
|
|
32
40
|
);
|
|
41
|
+
// The console line is the primary trace and stays either way; only the
|
|
42
|
+
// store write is gated. A predicate that throws reports, so a broken
|
|
43
|
+
// predicate can never turn a swallowed failure into a throw.
|
|
44
|
+
let report = true;
|
|
45
|
+
try {
|
|
46
|
+
report = reportable?.() !== false;
|
|
47
|
+
} catch {
|
|
48
|
+
// unknown state reports, as before
|
|
49
|
+
}
|
|
50
|
+
if (!report) return;
|
|
33
51
|
// Report AFTER the warn, and await the reporter so a caller that awaits
|
|
34
52
|
// guarded() can observe the evidence line; any reporter failure is itself
|
|
35
53
|
// swallowed — the console line is the primary trace, evidence the mirror.
|
package/src/index.ts
CHANGED
|
@@ -263,6 +263,12 @@ const impl = {
|
|
|
263
263
|
instanceDir,
|
|
264
264
|
gateContext,
|
|
265
265
|
guarded,
|
|
266
|
+
// Fix A (FINDINGS 2026-11-08 §4b): guided promotion moves every tracked
|
|
267
|
+
// epoch, so a late guided row enters the hint lane on each session's
|
|
268
|
+
// next request instead of waiting for a request that happens to notice.
|
|
269
|
+
onGuidedPromoted: async () => {
|
|
270
|
+
await sessions.refreshAll();
|
|
271
|
+
},
|
|
266
272
|
});
|
|
267
273
|
onCompactCapture = capture.onCompactCapture;
|
|
268
274
|
const captureCleanup = capture.cleanup;
|
package/src/inject/epochs.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { captureEvidenceContext, record } from "../evidence/record.ts";
|
|
|
9
9
|
import { capToBudget, injectedRows } from "./budget.ts";
|
|
10
10
|
import { systemDigest } from "./digest.ts";
|
|
11
11
|
import { storeVersion } from "./version.ts";
|
|
12
|
-
import { selectRelevant } from "../recall/relevant.ts";
|
|
12
|
+
import { isUserGuided, selectRelevant } from "../recall/relevant.ts";
|
|
13
13
|
import {
|
|
14
14
|
attributeSession,
|
|
15
15
|
deriveMemoryRefs,
|
|
@@ -171,6 +171,14 @@ export function createInjectionEpochs({
|
|
|
171
171
|
prefix: string;
|
|
172
172
|
rode: Memory[];
|
|
173
173
|
refs: MemoryRefs;
|
|
174
|
+
/** Guided rows the selector put in the block (pre-budget), by ts. */
|
|
175
|
+
guidedIds: string[];
|
|
176
|
+
/** Guided rows that survived the budget, by ts. */
|
|
177
|
+
guidedRodeIds: string[];
|
|
178
|
+
/** Guided rows visible to this reader in the store. */
|
|
179
|
+
guidedSeen: number;
|
|
180
|
+
/** A CONFLICT line rendered in this block. */
|
|
181
|
+
conflict: boolean;
|
|
174
182
|
}> => {
|
|
175
183
|
const parts: string[] = [];
|
|
176
184
|
await systemDigest(
|
|
@@ -211,12 +219,24 @@ export function createInjectionEpochs({
|
|
|
211
219
|
const prefix = [...parts, block].join("\u0000");
|
|
212
220
|
// Ledger terms/identities belong to the stored rows, but coverage refs
|
|
213
221
|
// must describe only the text the model actually received.
|
|
222
|
+
// Stage telemetry (mystery 2): split the hint channel's journey into the
|
|
223
|
+
// three links a miss can die at — visible in the store (guidedSeen),
|
|
224
|
+
// selected into the block (guidedIds), survived the budget (guidedRodeIds)
|
|
225
|
+
// — so an L6h wire miss joins to exactly one cause from the evidence log.
|
|
226
|
+
const guidedSeen = mems.filter(isUserGuided).length;
|
|
227
|
+
const guidedIds = sel.selected.filter(isUserGuided).map((m) => m.ts);
|
|
228
|
+
const guidedRodeIds = rode.filter(isUserGuided).map((m) => m.ts);
|
|
229
|
+
const conflict = block.includes("CONFLICT (");
|
|
214
230
|
return {
|
|
215
231
|
parts,
|
|
216
232
|
block,
|
|
217
233
|
prefix,
|
|
218
234
|
rode,
|
|
219
235
|
refs: deriveMemoryRefs(rode.map((m) => sel.rendered.get(m) ?? m)),
|
|
236
|
+
guidedIds,
|
|
237
|
+
guidedRodeIds,
|
|
238
|
+
guidedSeen,
|
|
239
|
+
conflict,
|
|
220
240
|
};
|
|
221
241
|
};
|
|
222
242
|
const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
|
|
@@ -305,6 +325,20 @@ export function createInjectionEpochs({
|
|
|
305
325
|
session: sid,
|
|
306
326
|
reason,
|
|
307
327
|
chars: built.block.length,
|
|
328
|
+
// Hint-channel attribution (mystery 2): a wire miss is one grep away.
|
|
329
|
+
// guidedSeen=0 -> capture never wrote the row. guidedSeen>0 with the
|
|
330
|
+
// id absent from `guided` -> the cap (newest-first, 3) dropped it.
|
|
331
|
+
// In `guided` but absent from `guidedRode` -> capToBudget dropped it.
|
|
332
|
+
// In `guidedRode` yet absent from the wire -> render/transport, or a
|
|
333
|
+
// paraphrased needle (now impossible for rows carrying `orig=true`).
|
|
334
|
+
...(built.guidedSeen ? { guidedSeen: built.guidedSeen } : {}),
|
|
335
|
+
...(built.guidedIds.length
|
|
336
|
+
? { guided: built.guidedIds.join(",") }
|
|
337
|
+
: {}),
|
|
338
|
+
...(built.guidedRodeIds.length
|
|
339
|
+
? { guidedRode: built.guidedRodeIds.join(",") }
|
|
340
|
+
: {}),
|
|
341
|
+
...(built.conflict ? { conflict: true } : {}),
|
|
308
342
|
},
|
|
309
343
|
false,
|
|
310
344
|
sid,
|
|
@@ -374,6 +408,18 @@ export function createInjectionEpochs({
|
|
|
374
408
|
latestPrompt.set(sid, text);
|
|
375
409
|
await refreshEpoch(sid);
|
|
376
410
|
},
|
|
411
|
+
// Fix A (FINDINGS 2026-11-08 §4b): a guided row promoted AFTER a session
|
|
412
|
+
// froze its bytes could never enter the hint lane — the bench's run 5
|
|
413
|
+
// lost the lane to a capture that landed 9 minutes into pass 2, and the
|
|
414
|
+
// epoch only moves on a request that happens to notice. Recompute every
|
|
415
|
+
// tracked epoch on guided promotion so the NEXT request of every session
|
|
416
|
+
// carries the row and the epoch_recompute line records it. Bounded:
|
|
417
|
+
// guided rows are rare (cap 3), the refresh pre-check early-returns for
|
|
418
|
+
// any session whose visible rows did not move, and an untracked session
|
|
419
|
+
// is a map miss.
|
|
420
|
+
refreshAll(): Promise<void[]> {
|
|
421
|
+
return Promise.all([...epoch.keys()].map((sid) => refreshEpoch(sid)));
|
|
422
|
+
},
|
|
377
423
|
deliver,
|
|
378
424
|
invalidate(sid: string): void {
|
|
379
425
|
epoch.delete(sid);
|
package/src/inject/format.ts
CHANGED
|
@@ -28,5 +28,12 @@ export function formatMemory(m: Memory): string {
|
|
|
28
28
|
const type = flattenMemoryText(m.type);
|
|
29
29
|
const scope = flattenMemoryText(m.scope);
|
|
30
30
|
const content = flattenMemoryText(m.content);
|
|
31
|
-
|
|
31
|
+
// Verbatim user utterance (mystery 2): rendered so the user's exact words
|
|
32
|
+
// reach the next session's request bytes even when the distilled content
|
|
33
|
+
// paraphrases them. Stored after a substring check, so this is quotation,
|
|
34
|
+
// not generation.
|
|
35
|
+
const quote = m.original
|
|
36
|
+
? ` (user said: "${flattenMemoryText(m.original)}")`
|
|
37
|
+
: "";
|
|
38
|
+
return `- [${date}]${tag}${src} ${type}/${scope}: ${content}${quote}`;
|
|
32
39
|
}
|
package/src/store/blocklist.ts
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
writeAtomic,
|
|
14
14
|
} from "../core/logfmt/publish.ts";
|
|
15
15
|
import { readLines } from "../core/logfmt/read.ts";
|
|
16
|
-
import {
|
|
16
|
+
import { LOCK_WRITE, withStoreLock } from "./lock.ts";
|
|
17
17
|
import { redactSecrets } from "./secrets.ts";
|
|
18
18
|
|
|
19
19
|
const BLOCKLIST_FILENAME = "blocklist.logfmt";
|
|
@@ -2,20 +2,21 @@
|
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { memoryRoot } from "../../core/config/paths.ts";
|
|
5
|
-
import { dateStr } from "../../core/time.ts";
|
|
6
|
-
import { writeTarget } from "../../identity/repokey.ts";
|
|
7
|
-
import { getCurrent } from "../../core/state.ts";
|
|
8
5
|
import { formatLine, parseLine } from "../../core/logfmt/format.ts";
|
|
9
6
|
import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
7
|
+
import { getCurrent } from "../../core/state.ts";
|
|
8
|
+
import { dateStr } from "../../core/time.ts";
|
|
9
|
+
import { writeTarget } from "../../identity/repokey.ts";
|
|
10
|
+
import { LOCK_WRITE, withStoreLock } from "../lock.ts";
|
|
13
11
|
import {
|
|
14
12
|
MAX_CONTENT_CHARS,
|
|
15
13
|
type MemoryStatus,
|
|
16
14
|
normalizeConflictFields,
|
|
17
15
|
normalizeKeywords,
|
|
16
|
+
normalizeOriginal,
|
|
18
17
|
} from "../model/memory.ts";
|
|
18
|
+
import { flattenMemoryText } from "../sanitize.ts";
|
|
19
|
+
import { containsSecret, redactSecrets } from "../secrets.ts";
|
|
19
20
|
|
|
20
21
|
export interface AppendMemoryInput {
|
|
21
22
|
type: string;
|
|
@@ -33,6 +34,11 @@ export interface AppendMemoryInput {
|
|
|
33
34
|
ref?: string;
|
|
34
35
|
claim?: string;
|
|
35
36
|
klass?: "spec" | "behavior";
|
|
37
|
+
/**
|
|
38
|
+
* Verbatim user utterance behind a guided row (see model/memory.ts).
|
|
39
|
+
* Normalised by appendMemory; junk drops the field only.
|
|
40
|
+
*/
|
|
41
|
+
original?: string;
|
|
36
42
|
// "global" for explicit cross-project writes; imports may carry a validated
|
|
37
43
|
// same-repo origin stamp (see portable.ts). Any missing value is resolved by
|
|
38
44
|
// appendMemory against the live repo scope.
|
|
@@ -154,55 +160,78 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
154
160
|
repoPath = target.scope.path;
|
|
155
161
|
}
|
|
156
162
|
}
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
//
|
|
160
|
-
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
163
|
+
// The day file is chosen before the lock because it IS the lock key. A
|
|
164
|
+
// colliding ts is bumped inside that lock, and the bump can cross UTC midnight
|
|
165
|
+
// — which #215 made more than cosmetic: a supersede addresses a row by the day
|
|
166
|
+
// its own ts names, so a row filed under another day is a second, unreachable
|
|
167
|
+
// address for the same identity (two files can then hold the same ts). So when
|
|
168
|
+
// the bumped ts leaves the day, hand the row to the file it names and take that
|
|
169
|
+
// file's lock instead. The loop releases before it re-acquires — never two
|
|
170
|
+
// locks at once — and is bounded only so a pathological store cannot spin.
|
|
171
|
+
let day = dateStr();
|
|
172
|
+
let carryTs: string | undefined;
|
|
173
|
+
for (let attempt = 0; ; attempt++) {
|
|
174
|
+
const file = join(memoryRoot(), `${day}.logfmt`);
|
|
175
|
+
// Locked end to end: seeding ts from a scan another process can race yields
|
|
176
|
+
// two rows with the same identity, and an append that lands inside someone
|
|
177
|
+
// else's whole-file rewrite is simply not there afterwards.
|
|
178
|
+
const outcome = await withStoreLock(
|
|
179
|
+
file,
|
|
180
|
+
async (): Promise<{
|
|
181
|
+
moved?: string;
|
|
182
|
+
bumped?: string;
|
|
183
|
+
ts?: string;
|
|
184
|
+
}> => {
|
|
185
|
+
const since = await fileIdentity(file);
|
|
186
|
+
let prior = "";
|
|
187
|
+
try {
|
|
188
|
+
prior = await readFile(file, "utf8");
|
|
189
|
+
} catch (err) {
|
|
190
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
191
|
+
}
|
|
192
|
+
const taken = existingTs(prior);
|
|
193
|
+
let ts = carryTs ?? new Date().toISOString();
|
|
194
|
+
let guard = 0;
|
|
195
|
+
while (taken.has(ts) && guard++ < 1000) {
|
|
196
|
+
ts = new Date(new Date(ts).getTime() + 1).toISOString();
|
|
197
|
+
}
|
|
198
|
+
const ownDay = ts.slice(0, 10);
|
|
199
|
+
// Carry the bumped identity with the move: re-reading the clock in the
|
|
200
|
+
// new file would hand back the PREVIOUS day's instant and file it under
|
|
201
|
+
// the next day — the same lie in the other direction.
|
|
202
|
+
if (ownDay !== day && attempt < 3) return { moved: ownDay, bumped: ts };
|
|
203
|
+
const kw = normalizeKeywords(input.kw);
|
|
204
|
+
const conflict = normalizeConflictFields(input);
|
|
205
|
+
const original = normalizeOriginal(input.original);
|
|
206
|
+
const line = formatLine({
|
|
207
|
+
ts,
|
|
208
|
+
type: input.type,
|
|
209
|
+
scope: input.scope,
|
|
210
|
+
content,
|
|
211
|
+
issue: input.issue,
|
|
212
|
+
tags: input.tags?.length ? input.tags.join(",") : undefined,
|
|
213
|
+
kw: kw?.join(","),
|
|
214
|
+
status: input.status,
|
|
215
|
+
...conflict,
|
|
216
|
+
...(original ? { original } : {}),
|
|
217
|
+
repo,
|
|
218
|
+
repoPath,
|
|
219
|
+
});
|
|
220
|
+
// A lock excludes writers, not readers: an O_APPEND read can end mid-row.
|
|
221
|
+
// Publish the complete day file using the read already needed for IDs.
|
|
222
|
+
// This costs a whole-file write and can refuse on Windows reader handles;
|
|
223
|
+
// the old destination remains intact if publication fails (#198).
|
|
224
|
+
await writeAtomic(
|
|
225
|
+
file,
|
|
226
|
+
prior + (prior && !prior.endsWith("\n") ? "\n" : "") + line + "\n",
|
|
227
|
+
since,
|
|
228
|
+
);
|
|
229
|
+
return { ts };
|
|
230
|
+
},
|
|
231
|
+
LOCK_WRITE,
|
|
232
|
+
);
|
|
233
|
+
if (outcome.ts !== undefined) return outcome.ts;
|
|
234
|
+
day = outcome.moved as string;
|
|
235
|
+
carryTs = outcome.bumped;
|
|
236
|
+
}
|
|
208
237
|
}
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import { deletionsFile } from "../../core/config/paths.ts";
|
|
3
3
|
import { formatLine } from "../../core/logfmt/format.ts";
|
|
4
4
|
import { appendLog } from "../../core/logfmt/publish.ts";
|
|
5
|
+
import type { Memory } from "../model/memory.ts";
|
|
5
6
|
import { redactSecrets } from "../secrets.ts";
|
|
6
|
-
import { type Memory } from "../model/memory.ts";
|
|
7
7
|
|
|
8
8
|
export interface DeletedMemory {
|
|
9
9
|
memory: Memory;
|
package/src/store/files/load.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// needs: supersession markers, snapshots and audited deletion.
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
7
7
|
import { open } from "node:fs/promises";
|
|
8
|
-
import { join } from "node:path";
|
|
8
|
+
import { basename, join } from "node:path";
|
|
9
9
|
import { HITS_FILENAME, memoryRoot } from "../../core/config/paths.ts";
|
|
10
10
|
import { parseLine } from "../../core/logfmt/format.ts";
|
|
11
11
|
import { readLines } from "../../core/logfmt/read.ts";
|
|
@@ -16,8 +16,8 @@ import {
|
|
|
16
16
|
malformedWarnedFiles,
|
|
17
17
|
} from "../model/memory.ts";
|
|
18
18
|
import {
|
|
19
|
-
type Reader,
|
|
20
19
|
isVisibleTo,
|
|
20
|
+
type Reader,
|
|
21
21
|
readerForAmbient,
|
|
22
22
|
} from "../model/visibility.ts";
|
|
23
23
|
|
|
@@ -88,6 +88,10 @@ export function toMemory(
|
|
|
88
88
|
fields.klass === "spec" || fields.klass === "behavior"
|
|
89
89
|
? fields.klass
|
|
90
90
|
: undefined,
|
|
91
|
+
original:
|
|
92
|
+
typeof fields.original === "string" && fields.original
|
|
93
|
+
? fields.original
|
|
94
|
+
: undefined,
|
|
91
95
|
reason: typeof fields.reason === "string" ? fields.reason : undefined,
|
|
92
96
|
status:
|
|
93
97
|
fields.status === "open" || fields.status === "settled"
|
|
@@ -114,6 +118,90 @@ export async function memoryFiles(): Promise<string[]> {
|
|
|
114
118
|
return files.sort();
|
|
115
119
|
}
|
|
116
120
|
|
|
121
|
+
/**
|
|
122
|
+
* The day file a row's own ts names, as a `YYYY-MM-DD.logfmt` basename, or null
|
|
123
|
+
* when the string is not an ISO instant. `appendMemory` mints ts at write time
|
|
124
|
+
* and appends to that same day file, so for every row the plugin wrote the ts
|
|
125
|
+
* date IS the file date (#215).
|
|
126
|
+
*/
|
|
127
|
+
export function dayFileName(ts: string): string | null {
|
|
128
|
+
const m = /^(\d{4}-\d{2}-\d{2})T/.exec(ts);
|
|
129
|
+
return m ? `${m[1]}.logfmt` : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Day files ordered so the ones these ts values name come first (#215). A
|
|
134
|
+
* single-row mutation that stops as soon as it has SEEN the row then locks one
|
|
135
|
+
* file instead of one per day of store age — the cost that made supersing a row
|
|
136
|
+
* 25x a full read on a 30-day store.
|
|
137
|
+
*
|
|
138
|
+
* The mapping is a hint, never a proof: a store edited outside the plugin can
|
|
139
|
+
* hold a row in a file its ts does not name. Callers must keep walking the rest
|
|
140
|
+
* of the list until they find the row, which is the behaviour this replaced.
|
|
141
|
+
*/
|
|
142
|
+
export async function filesOrderedFor(tsValues: string[]): Promise<string[]> {
|
|
143
|
+
const all = await memoryFiles();
|
|
144
|
+
const names = new Set<string>();
|
|
145
|
+
for (const ts of tsValues) {
|
|
146
|
+
const name = dayFileName(ts);
|
|
147
|
+
if (name) names.add(name);
|
|
148
|
+
}
|
|
149
|
+
if (!names.size) return all;
|
|
150
|
+
const near: string[] = [];
|
|
151
|
+
const rest: string[] = [];
|
|
152
|
+
for (const file of all) {
|
|
153
|
+
(names.has(basename(file)) ? near : rest).push(file);
|
|
154
|
+
}
|
|
155
|
+
return [...near, ...rest];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The day BEFORE `YYYY-MM-DD`, UTC. Month and year boundaries included: the
|
|
160
|
+
* only caller uses it to name a file that may hold a row appended a millisecond
|
|
161
|
+
* before midnight.
|
|
162
|
+
*/
|
|
163
|
+
export function previousDayName(day: string): string {
|
|
164
|
+
return new Date(new Date(`${day}T12:00:00.000Z`).getTime() - 86_400_000)
|
|
165
|
+
.toISOString()
|
|
166
|
+
.slice(0, 10);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The day files that could hold a copy of `ts` — the addresses a single-row
|
|
171
|
+
* mutation must try before it may report success (#373 review).
|
|
172
|
+
*
|
|
173
|
+
* Two files, at most. The one the ts names, plus the previous day's file ONLY
|
|
174
|
+
* when a text scan finds the identity in it: `appendMemory` used to pick the
|
|
175
|
+
* file from the clock and bump a colliding ts inside the lock, so a row whose ts
|
|
176
|
+
* is one millisecond past midnight could be filed under the day before it. That
|
|
177
|
+
* is the only way the plugin can write a row outside its own day, so the
|
|
178
|
+
* neighbour scan is complete, and scanning (not locking) keeps the ordinary
|
|
179
|
+
* single-row mutation at ONE lock.
|
|
180
|
+
*
|
|
181
|
+
* Reading without a lock is sound because this only decides what to lock next:
|
|
182
|
+
* every mutation re-reads under the lock it takes.
|
|
183
|
+
*
|
|
184
|
+
* Empty for a ts that is not an ISO instant — the caller then sweeps, as before.
|
|
185
|
+
*/
|
|
186
|
+
export async function filesHoldingTs(
|
|
187
|
+
ts: string,
|
|
188
|
+
present?: Set<string>,
|
|
189
|
+
): Promise<string[]> {
|
|
190
|
+
const name = dayFileName(ts);
|
|
191
|
+
if (!name) return [];
|
|
192
|
+
const have =
|
|
193
|
+
present ?? new Set((await memoryFiles()).map((f) => basename(f)));
|
|
194
|
+
const out: string[] = [];
|
|
195
|
+
if (have.has(name)) out.push(join(memoryRoot(), name));
|
|
196
|
+
const prev = `${previousDayName(name.slice(0, 10))}.logfmt`;
|
|
197
|
+
if (have.has(prev)) {
|
|
198
|
+
const file = join(memoryRoot(), prev);
|
|
199
|
+
const text = await Bun.file(file).text();
|
|
200
|
+
if (text.includes(`ts=${ts}`)) out.push(file);
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
|
|
117
205
|
export async function loadAll(): Promise<Memory[]> {
|
|
118
206
|
malformedRows = 0; // per-load telemetry: the most recent read wins
|
|
119
207
|
const blocked = await blockedTs();
|
package/src/store/files/prune.ts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
// prune — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
-
import {
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
3
|
import { parseLine } from "../../core/logfmt/format.ts";
|
|
4
4
|
import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts";
|
|
5
5
|
import { readLines } from "../../core/logfmt/read.ts";
|
|
6
|
-
import {
|
|
7
|
-
import { tombstoneMany } from "../tombstones/tombstone.ts";
|
|
8
|
-
import { type DeletedMemory, logDeletion } from "./deletions.ts";
|
|
9
|
-
import { memoryFiles, toMemory } from "./load.ts";
|
|
10
|
-
import { snapshotFiles } from "./snapshots.ts";
|
|
6
|
+
import { LOCK_WRITE, withStoreLock } from "../lock.ts";
|
|
11
7
|
import {
|
|
12
|
-
type Reader,
|
|
13
8
|
isVisibleTo,
|
|
9
|
+
type Reader,
|
|
14
10
|
readerForAmbient,
|
|
15
11
|
} from "../model/visibility.ts";
|
|
12
|
+
import { tombstoneMany } from "../tombstones/tombstone.ts";
|
|
13
|
+
import { type DeletedMemory, logDeletion } from "./deletions.ts";
|
|
14
|
+
import { memoryFiles, toMemory } from "./load.ts";
|
|
15
|
+
import { snapshotFiles } from "./snapshots.ts";
|
|
16
16
|
|
|
17
17
|
export interface PruneResult {
|
|
18
18
|
deleted: DeletedMemory[];
|
|
@@ -45,6 +45,13 @@ export async function prune(
|
|
|
45
45
|
bookkeepingError = bookkeepingError ? `${bookkeepingError}; ${msg}` : msg;
|
|
46
46
|
};
|
|
47
47
|
try {
|
|
48
|
+
// #215 narrowed the ts-addressed write paths (supersede, clearSuperseded,
|
|
49
|
+
// releaseQuarantine) to the day file the row's own ts names. This one keeps
|
|
50
|
+
// the full sweep on purpose: a forget is addressed by scope/type, not by ts,
|
|
51
|
+
// so the only way to know which files match is to look — and a pre-pass that
|
|
52
|
+
// skipped a file would let a row appended during the forget survive it. The
|
|
53
|
+
// per-file body re-reads under the lock precisely so "deleted" means deleted;
|
|
54
|
+
// a forget is a user action, not a per-write path, so it pays the sweep.
|
|
48
55
|
for (const file of await memoryFiles()) {
|
|
49
56
|
const fileDeleted: DeletedMemory[] = [];
|
|
50
57
|
await withStoreLock(
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
// snapshots — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
2
|
import { open, readFile } from "node:fs/promises";
|
|
3
|
-
import {
|
|
3
|
+
import { basename, join } from "node:path";
|
|
4
4
|
import { snapshotDir } from "../../core/config/paths.ts";
|
|
5
|
-
import {
|
|
5
|
+
import { type Fields, parseLine } from "../../core/logfmt/format.ts";
|
|
6
6
|
import {
|
|
7
7
|
ensureDir,
|
|
8
8
|
fileIdentity,
|
|
9
9
|
writeAtomic,
|
|
10
10
|
} from "../../core/logfmt/publish.ts";
|
|
11
11
|
import { readLines } from "../../core/logfmt/read.ts";
|
|
12
|
-
import {
|
|
12
|
+
import { LOCK_WRITE, withStoreLock } from "../lock.ts";
|
|
13
13
|
|
|
14
14
|
// Copy `file` into snapshots/ before a mutation.
|
|
15
15
|
export async function snapshotBefore(file: string): Promise<void> {
|