opencode-self-improvement 0.13.1 → 0.14.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/package.json +1 -1
- package/src/gates.ts +42 -32
- package/src/index.ts +125 -47
- package/src/memory.ts +44 -6
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"exports": {
|
package/src/gates.ts
CHANGED
|
@@ -8,10 +8,11 @@ import {
|
|
|
8
8
|
appendMemory,
|
|
9
9
|
loadAll,
|
|
10
10
|
loadScope,
|
|
11
|
-
|
|
11
|
+
markManySuperseded,
|
|
12
12
|
snapshotFiles,
|
|
13
13
|
MAX_CONTENT_CHARS,
|
|
14
14
|
type Memory,
|
|
15
|
+
type SupersedeFields,
|
|
15
16
|
} from "./memory.ts";
|
|
16
17
|
import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
|
|
17
18
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
@@ -357,6 +358,7 @@ export async function runWriteGate(
|
|
|
357
358
|
});
|
|
358
359
|
|
|
359
360
|
let supersededTs: string | undefined;
|
|
361
|
+
const driftPlan: { s: StaleRef; target: string; fields: SupersedeFields }[] = [];
|
|
360
362
|
for (const s of stale) {
|
|
361
363
|
await record("ref_stale", {
|
|
362
364
|
gate: 2,
|
|
@@ -368,27 +370,33 @@ export async function runWriteGate(
|
|
|
368
370
|
chain,
|
|
369
371
|
});
|
|
370
372
|
// Drift-fed supersession is AUTO (provable) and target depends on whether a
|
|
371
|
-
// valid write will land; stale data is neutralized either way.
|
|
373
|
+
// valid write will land; stale data is neutralized either way. One batch
|
|
374
|
+
// publish for the whole set (#61): a row marked out-of-band between the scan
|
|
375
|
+
// and the pass is skipped by the batch (it re-reads under the lock).
|
|
372
376
|
const target = g1.candidateStale ? "<-" : chain;
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
from: s.from,
|
|
378
|
-
to: s.to,
|
|
377
|
+
if (typeof s.memory.superseded_by === "string") continue;
|
|
378
|
+
driftPlan.push({
|
|
379
|
+
s,
|
|
380
|
+
target,
|
|
381
|
+
fields: { superseded_by: target, reason: "drift", symbol: s.symbol, from: s.from, to: s.to },
|
|
379
382
|
});
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
383
|
+
}
|
|
384
|
+
if (driftPlan.length > 0) {
|
|
385
|
+
const markedCount = await markManySuperseded(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
|
|
386
|
+
if (markedCount > 0) {
|
|
387
|
+
for (const p of driftPlan) {
|
|
388
|
+
supersededTs = p.s.memory.ts;
|
|
389
|
+
await record("superseded_by", {
|
|
390
|
+
gate: 2,
|
|
391
|
+
mem: p.s.memory.ts,
|
|
392
|
+
target: p.target,
|
|
393
|
+
reason: "drift",
|
|
394
|
+
symbol: p.s.symbol,
|
|
395
|
+
from: p.s.from,
|
|
396
|
+
to: p.s.to,
|
|
397
|
+
chain,
|
|
398
|
+
});
|
|
399
|
+
}
|
|
392
400
|
}
|
|
393
401
|
}
|
|
394
402
|
|
|
@@ -404,29 +412,31 @@ export async function runWriteGate(
|
|
|
404
412
|
// Any in-scope entry that contradicts the canonical value is neutralized.
|
|
405
413
|
const entitySet = new Set(tokens(canon.entry.entity));
|
|
406
414
|
const valueSet = new Set(tokens(canon.entry.value));
|
|
415
|
+
const target = canon.aligns ? chain : "<-";
|
|
416
|
+
const canonPlan: { ts: string; from: string | undefined }[] = [];
|
|
407
417
|
for (const m of scopeMems) {
|
|
408
418
|
if (m.superseded_by) continue;
|
|
409
419
|
if (tokens(m.content).some((t) => valueSet.has(t))) continue;
|
|
410
420
|
const from = rawTokens(m.content).find(
|
|
411
421
|
(t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()) && !valueSet.has(t.toLowerCase()),
|
|
412
422
|
);
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
if (!supersededTs) supersededTs =
|
|
423
|
+
canonPlan.push({ ts: m.ts, from });
|
|
424
|
+
}
|
|
425
|
+
// One batch publish for the whole neutralization set (#61); rows marked
|
|
426
|
+
// out-of-band since the scan are skipped by the batch (re-read under lock).
|
|
427
|
+
if ((await markManySuperseded(canonPlan.map((p) => ({
|
|
428
|
+
ts: p.ts,
|
|
429
|
+
fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
|
|
430
|
+
})))) > 0) {
|
|
431
|
+
for (const p of canonPlan) {
|
|
432
|
+
if (!supersededTs) supersededTs = p.ts;
|
|
423
433
|
await record("superseded_by", {
|
|
424
434
|
gate: 2,
|
|
425
|
-
mem:
|
|
435
|
+
mem: p.ts,
|
|
426
436
|
target,
|
|
427
437
|
reason: "canonical",
|
|
428
438
|
entity: canon.entry.entity,
|
|
429
|
-
from: from
|
|
439
|
+
from: p.from,
|
|
430
440
|
to: canon.entry.value,
|
|
431
441
|
chain,
|
|
432
442
|
});
|
package/src/index.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
isVisibleHere,
|
|
21
21
|
loadAll,
|
|
22
22
|
malformedCount,
|
|
23
|
+
markManySuperseded,
|
|
23
24
|
markSuperseded,
|
|
24
25
|
resolveMemoryTarget,
|
|
25
26
|
snapshotFiles,
|
|
@@ -185,6 +186,12 @@ function resultMeta(result: unknown): Record<string, unknown> {
|
|
|
185
186
|
|
|
186
187
|
const PLUGIN_ID = "opencode-self-improvement";
|
|
187
188
|
|
|
189
|
+
// Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
|
|
190
|
+
// the shared "auto-capture" provenance tag (src/inject.ts renders it) and add
|
|
191
|
+
// this one so decay/status can tell which trigger wrote them — the same
|
|
192
|
+
// distinction the auto_capture_compaction_* evidence lines carry.
|
|
193
|
+
const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
|
|
194
|
+
|
|
188
195
|
// The setup-time Bun-floor warning fires once per process (setup can run for
|
|
189
196
|
// more than one location).
|
|
190
197
|
let bunFloorChecked = false;
|
|
@@ -644,29 +651,28 @@ const impl = {
|
|
|
644
651
|
}
|
|
645
652
|
// Snapshot-before-mutate: the SAME helper prune() uses in memory.ts,
|
|
646
653
|
// one whole-file copy per affected file, taken before the first
|
|
647
|
-
// mutation.
|
|
648
|
-
// pass guarantees a pre-decay copy exists even if a later
|
|
654
|
+
// mutation. The batch pass snapshots again per file it touches; this
|
|
655
|
+
// pass guarantees a pre-decay copy exists even if a later file fails.
|
|
649
656
|
const snapshot = await snapshotFiles([...new Set(stale.map((m) => m.file))]);
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
}
|
|
657
|
+
// One lock/read/snapshot/publish per file for the whole decay run (#61):
|
|
658
|
+
// N retired rows are one undo point, not N. Idempotent (a no-op on rows
|
|
659
|
+
// already superseded, out-of-band ones skipped under the lock).
|
|
660
|
+
const retired = await markManySuperseded(
|
|
661
|
+
stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })),
|
|
662
|
+
);
|
|
657
663
|
await record(
|
|
658
664
|
"decay_applied",
|
|
659
665
|
{
|
|
660
666
|
days,
|
|
661
|
-
retired
|
|
662
|
-
mem:
|
|
667
|
+
retired,
|
|
668
|
+
mem: stale.map((m) => m.ts).join(",") || "-",
|
|
663
669
|
snapshot: snapshot.join(",") || "-",
|
|
664
670
|
},
|
|
665
671
|
false,
|
|
666
672
|
);
|
|
667
673
|
return {
|
|
668
674
|
content:
|
|
669
|
-
`Decayed ${
|
|
675
|
+
`Decayed ${retired} open thread(s) older than ${days} days ` +
|
|
670
676
|
`(superseded, not deleted; snapshot: ${snapshot[0] ?? "-"}). ` +
|
|
671
677
|
"Recover with memory_undo.",
|
|
672
678
|
};
|
|
@@ -844,6 +850,12 @@ const impl = {
|
|
|
844
850
|
};
|
|
845
851
|
|
|
846
852
|
// ---- hooks (all fail-closed) -------------------------------------------
|
|
853
|
+
// Seam set by the auto-capture wiring below ONLY when the compaction
|
|
854
|
+
// trigger is live (autoCapture on, captureOnCompact not false, valid
|
|
855
|
+
// captureModel). The compaction hook calls it fire-and-forget; undefined
|
|
856
|
+
// means "off". Declared here because the hook registers before capture.
|
|
857
|
+
let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
|
|
858
|
+
|
|
847
859
|
// Bookkeeping: track the active session/tool/call before a tool runs.
|
|
848
860
|
await ctx.tool?.hook("execute.before", (event: any) =>
|
|
849
861
|
guarded("tool.execute.before", async () => {
|
|
@@ -936,7 +948,9 @@ const impl = {
|
|
|
936
948
|
// compaction: the durable-memory anchor is pushed onto the hook's system
|
|
937
949
|
// parts (visible to the summarizer model, which runs AFTER hooks) so the
|
|
938
950
|
// summary preserves the facts. Never sets event.result — that would skip
|
|
939
|
-
// the summarizer call entirely.
|
|
951
|
+
// the summarizer call entirely. Also fires the context-death auto-capture
|
|
952
|
+
// (issue #41, opt-in; see the capture section): the transcript is mined
|
|
953
|
+
// while it still exists, BEFORE the summarizer replaces it.
|
|
940
954
|
await ctx.session?.hook("compaction", (event: any) =>
|
|
941
955
|
guarded("session.compaction (onCompacting)", async () => {
|
|
942
956
|
setCurrent({ sessionID: event?.sessionID });
|
|
@@ -947,6 +961,13 @@ const impl = {
|
|
|
947
961
|
}
|
|
948
962
|
const anchor = await compactionAnchor();
|
|
949
963
|
if (anchor) event?.system?.push?.({ type: "text", text: anchor });
|
|
964
|
+
// Fire-and-forget: a capture model call must never delay the compaction
|
|
965
|
+
// the user is waiting for, and failures stay inside the guarded path.
|
|
966
|
+
// The payload's own messages ride along so the mining sees the
|
|
967
|
+
// pre-compaction transcript even if the store moves under it.
|
|
968
|
+
if (onCompactCapture && typeof event?.sessionID === "string") {
|
|
969
|
+
onCompactCapture(event.sessionID, event.messages);
|
|
970
|
+
}
|
|
950
971
|
}),
|
|
951
972
|
);
|
|
952
973
|
|
|
@@ -1020,22 +1041,27 @@ const impl = {
|
|
|
1020
1041
|
})();
|
|
1021
1042
|
}
|
|
1022
1043
|
|
|
1023
|
-
// ---- opt-in auto-capture
|
|
1044
|
+
// ---- opt-in auto-capture (idle + compaction triggers) ------------------
|
|
1024
1045
|
// Default OFF: capture never reads sessions and never calls a model. (The
|
|
1025
1046
|
// measured-cache listener above does subscribe to the event stream by
|
|
1026
1047
|
// default, but it is zero-model: pure bookkeeping of message usage.) When
|
|
1027
1048
|
// enabled (options.autoCapture === true AND a valid captureModel), each
|
|
1028
|
-
// session.idle event
|
|
1029
|
-
//
|
|
1049
|
+
// session.idle event — and, unless captureOnCompact === false, each
|
|
1050
|
+
// compaction hook call too — runs ONE cheap ctx.generate.text call whose
|
|
1051
|
+
// reply is parsed into candidates that go through the SAME runWriteGate as
|
|
1030
1052
|
// model-authored writes — capture can never bypass the moat, and it only
|
|
1031
|
-
// ever writes through the gate. A per-session cooldown bounds
|
|
1032
|
-
//
|
|
1033
|
-
//
|
|
1053
|
+
// ever writes through the gate. A per-session, per-trigger cooldown bounds
|
|
1054
|
+
// the cost. Compaction-triggered rows carry the CAPTURE_COMPACT_TAG tag and
|
|
1055
|
+
// auto_capture_compaction_* evidence lines, idle rows keep auto_capture_*,
|
|
1056
|
+
// so decay/status — and bench/capture-trigger-compare.ts — can measure
|
|
1057
|
+
// which trigger earns its tokens. Every failure is swallowed: capture must
|
|
1058
|
+
// never be able to break a session.
|
|
1034
1059
|
let captureCleanup: Cleanup | undefined;
|
|
1035
1060
|
if (ctx.options?.autoCapture === true) {
|
|
1036
1061
|
const captureModel =
|
|
1037
1062
|
typeof ctx.options.captureModel === "string" ? ctx.options.captureModel : "";
|
|
1038
1063
|
const captureMax = Number(ctx.options.captureMax) || 3;
|
|
1064
|
+
const captureOnCompact = ctx.options?.captureOnCompact !== false;
|
|
1039
1065
|
const modelRef = parseModelRef(captureModel);
|
|
1040
1066
|
if (!modelRef) {
|
|
1041
1067
|
// Invalid/missing model: skip registering the whole subscription
|
|
@@ -1058,6 +1084,63 @@ const impl = {
|
|
|
1058
1084
|
// setup guard proves it exists, but property narrowing does not survive
|
|
1059
1085
|
// into the closure, and undefined degrades safely (empty transcript).
|
|
1060
1086
|
const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
|
|
1087
|
+
|
|
1088
|
+
// ONE capture pass, shared by both triggers. `seeded` is a transcript
|
|
1089
|
+
// already in hand — the compaction hook carries the PRE-compaction
|
|
1090
|
+
// messages, which is the whole point (Compaction Cliff: one round
|
|
1091
|
+
// retains 53% of exact-wording rules); when it is absent (older host
|
|
1092
|
+
// shapes) or too thin, the session context is read instead, the same
|
|
1093
|
+
// source the idle trigger mines.
|
|
1094
|
+
async function captureSession(
|
|
1095
|
+
sid: string,
|
|
1096
|
+
seeded: string,
|
|
1097
|
+
trigger: "idle" | "compaction",
|
|
1098
|
+
seededMsgs?: unknown,
|
|
1099
|
+
): Promise<void> {
|
|
1100
|
+
// Bind the capturing session so captures stamp (and gate against)
|
|
1101
|
+
// that session's repo, not whatever tool call ran last.
|
|
1102
|
+
setCurrent({ sessionID: sid });
|
|
1103
|
+
let transcript = seeded;
|
|
1104
|
+
let msgs = seededMsgs;
|
|
1105
|
+
if (transcript.length < 200) {
|
|
1106
|
+
msgs = await contextFn({ sessionID: sid });
|
|
1107
|
+
transcript = flattenTranscript(msgs);
|
|
1108
|
+
}
|
|
1109
|
+
if (transcript.length < 200) return; // too thin to mine reliably
|
|
1110
|
+
// #44: how stale is a capture? Distance from the newest message of
|
|
1111
|
+
// the mined transcript to this instant - measured on whatever the
|
|
1112
|
+
// trigger actually mined (the hook payload for compaction, the
|
|
1113
|
+
// session context for idle), so both triggers' lag is comparable.
|
|
1114
|
+
const lagMs = lagSince(msgs);
|
|
1115
|
+
const out = await generateApi.text({
|
|
1116
|
+
model: modelRef,
|
|
1117
|
+
prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
|
|
1118
|
+
});
|
|
1119
|
+
const text = typeof out === "string" ? out : out?.text ?? "";
|
|
1120
|
+
const candidates = parseCandidates(text, captureMax);
|
|
1121
|
+
for (const c of candidates) {
|
|
1122
|
+
const outcome = await runWriteGate(
|
|
1123
|
+
{
|
|
1124
|
+
...c,
|
|
1125
|
+
tags:
|
|
1126
|
+
trigger === "compaction"
|
|
1127
|
+
? ["auto-capture", CAPTURE_COMPACT_TAG]
|
|
1128
|
+
: ["auto-capture"],
|
|
1129
|
+
},
|
|
1130
|
+
gateContext(),
|
|
1131
|
+
);
|
|
1132
|
+
await record(
|
|
1133
|
+
trigger === "compaction"
|
|
1134
|
+
? `auto_capture_compaction_${outcome.action}`
|
|
1135
|
+
: `auto_capture_${outcome.action}`,
|
|
1136
|
+
// A blocked credential-shaped scope must not reach the evidence log either.
|
|
1137
|
+
{ session: sid, trigger, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
|
|
1138
|
+
false,
|
|
1139
|
+
);
|
|
1140
|
+
}
|
|
1141
|
+
await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1061
1144
|
void (async () => {
|
|
1062
1145
|
try {
|
|
1063
1146
|
for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
|
|
@@ -1065,39 +1148,12 @@ const impl = {
|
|
|
1065
1148
|
if (event?.type !== "session.idle") continue;
|
|
1066
1149
|
const sid = event.sessionID ?? event.properties?.sessionID ?? event.data?.sessionID;
|
|
1067
1150
|
if (typeof sid !== "string") continue;
|
|
1068
|
-
// Bind the idle session so captures stamp (and gate against)
|
|
1069
|
-
// that session's repo, not whatever tool call ran last.
|
|
1070
1151
|
setCurrent({ sessionID: sid });
|
|
1071
1152
|
const now = Date.now();
|
|
1072
1153
|
if (now - (lastRun.get(sid) ?? 0) < 5 * 60_000) continue; // 5-min cooldown
|
|
1073
1154
|
lastRun.set(sid, now);
|
|
1074
1155
|
try {
|
|
1075
|
-
|
|
1076
|
-
const transcript = flattenTranscript(msgs);
|
|
1077
|
-
if (transcript.length < 200) continue; // too thin to mine reliably
|
|
1078
|
-
// #44: how stale is a capture? Distance from the last message of
|
|
1079
|
-
// the transcript to this instant. Sessions idle for an hour
|
|
1080
|
-
// produce an hour-old capture, and the surfaces now say so.
|
|
1081
|
-
const lagMs = lagSince(msgs);
|
|
1082
|
-
const out = await generateApi.text({
|
|
1083
|
-
model: modelRef,
|
|
1084
|
-
prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
|
|
1085
|
-
});
|
|
1086
|
-
const text = typeof out === "string" ? out : out?.text ?? "";
|
|
1087
|
-
const candidates = parseCandidates(text, captureMax);
|
|
1088
|
-
for (const c of candidates) {
|
|
1089
|
-
const outcome = await runWriteGate(
|
|
1090
|
-
{ ...c, tags: ["auto-capture"] },
|
|
1091
|
-
gateContext(),
|
|
1092
|
-
);
|
|
1093
|
-
await record(
|
|
1094
|
-
`auto_capture_${outcome.action}`,
|
|
1095
|
-
// A blocked credential-shaped scope must not reach the evidence log either.
|
|
1096
|
-
{ session: sid, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
|
|
1097
|
-
false,
|
|
1098
|
-
);
|
|
1099
|
-
}
|
|
1100
|
-
await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
|
|
1156
|
+
await captureSession(sid, "", "idle");
|
|
1101
1157
|
} catch {
|
|
1102
1158
|
// fail-closed: a broken capture attempt is invisible to the session
|
|
1103
1159
|
}
|
|
@@ -1107,7 +1163,29 @@ const impl = {
|
|
|
1107
1163
|
}
|
|
1108
1164
|
})();
|
|
1109
1165
|
captureCleanup = () => controller.abort();
|
|
1166
|
+
|
|
1167
|
+
// The compaction trigger needs no extra subscription: the session
|
|
1168
|
+
// compaction hook (registered above) calls through this seam. Separate
|
|
1169
|
+
// cooldown map from idle, so measuring a trigger is not confounded by
|
|
1170
|
+
// the other trigger having fired moments ago.
|
|
1171
|
+
if (captureOnCompact) {
|
|
1172
|
+
const lastCompactRun = new Map<string, number>();
|
|
1173
|
+
onCompactCapture = (sid, messages) => {
|
|
1174
|
+
if (controller.signal.aborted) return;
|
|
1175
|
+
const now = Date.now();
|
|
1176
|
+
if (now - (lastCompactRun.get(sid) ?? 0) < 5 * 60_000) return; // 5-min cooldown
|
|
1177
|
+
lastCompactRun.set(sid, now);
|
|
1178
|
+
void guarded("session.compaction (auto-capture)", () =>
|
|
1179
|
+
captureSession(sid, flattenTranscript(messages), "compaction", messages),
|
|
1180
|
+
);
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1110
1183
|
}
|
|
1184
|
+
} else if (ctx.options?.captureOnCompact === true) {
|
|
1185
|
+
// autoCapture is the master switch (zero-token default preserved).
|
|
1186
|
+
console.warn(
|
|
1187
|
+
"[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
|
|
1188
|
+
);
|
|
1111
1189
|
}
|
|
1112
1190
|
// Single cleanup returned by setup: tears down the measured listener and,
|
|
1113
1191
|
// when enabled, the capture subscription. Future teardowns merge in here.
|
package/src/memory.ts
CHANGED
|
@@ -341,15 +341,53 @@ async function stampRow(
|
|
|
341
341
|
// Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
|
|
342
342
|
// Idempotent: a second call is a no-op, so no double `superseded_by`.
|
|
343
343
|
export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
|
|
344
|
+
return (await markManySuperseded([{ ts, fields }])) > 0;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Batch supersession (#61): one lock acquisition, one read, one snapshot and
|
|
348
|
+
// one publish PER FILE touched - N rows retire as one undo point instead of
|
|
349
|
+
// N. decay and the gate's drift/canonical loops used to call markSuperseded
|
|
350
|
+
// per row, which meant N full read-modify-write cycles, N undo points, and
|
|
351
|
+
// N windows where two runs interleave and each re-pays the other's work.
|
|
352
|
+
// Idempotence is unchanged: a row already carrying superseded_by is skipped,
|
|
353
|
+
// so a repeat run marks nothing and writes nothing. Duplicate ts entries in
|
|
354
|
+
// one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
|
|
355
|
+
// Returns the number of rows actually marked.
|
|
356
|
+
export async function markManySuperseded(
|
|
357
|
+
entries: { ts: string; fields: SupersedeFields }[],
|
|
358
|
+
): Promise<number> {
|
|
359
|
+
if (entries.length === 0) return 0;
|
|
360
|
+
const wanted = new Map<string, SupersedeFields>();
|
|
361
|
+
for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
|
|
362
|
+
let marked = 0;
|
|
344
363
|
for (const file of await memoryFiles()) {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
364
|
+
marked += await withStoreLock(
|
|
365
|
+
file,
|
|
366
|
+
async () => {
|
|
367
|
+
const lines = await readLines(file);
|
|
368
|
+
let touched = 0;
|
|
369
|
+
for (let i = 0; i < lines.length; i++) {
|
|
370
|
+
const parsed = parseLine(lines[i]);
|
|
371
|
+
if (!parsed || typeof parsed.superseded_by === "string") continue;
|
|
372
|
+
const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
|
|
373
|
+
if (!fields) continue;
|
|
374
|
+
// Whole line rewritten, not extended: an old-format line comes out in
|
|
375
|
+
// the current format with its values unchanged (as markSuperseded did).
|
|
376
|
+
lines[i] = formatLine({ ...parsed, ...fields });
|
|
377
|
+
touched++;
|
|
378
|
+
}
|
|
379
|
+
if (touched === 0) return 0;
|
|
380
|
+
await snapshotBefore(file);
|
|
381
|
+
await writeAtomic(file, lines.join("\n") + "\n");
|
|
382
|
+
return touched;
|
|
383
|
+
},
|
|
384
|
+
LOCK_WRITE,
|
|
349
385
|
);
|
|
350
|
-
if (outcome !== null) return outcome;
|
|
351
386
|
}
|
|
352
|
-
|
|
387
|
+
// A ts that appears in several files (should not exist - append mints unique
|
|
388
|
+
// ts) retires in EVERY file here, where the row-by-row loop retired only the
|
|
389
|
+
// first; both are conservation-safe, this one is the more honest tombstone.
|
|
390
|
+
return marked;
|
|
353
391
|
}
|
|
354
392
|
|
|
355
393
|
// Drop a row's supersession markers IN PLACE (snapshot-first), making it active
|