opencode-self-improvement 0.14.24 → 0.14.26
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 +1 -1
- package/package.json +1 -1
- package/src/gates.ts +82 -43
- package/src/hits.ts +3 -0
- package/src/index.ts +49 -30
- package/src/lock.ts +8 -6
- package/src/logfmt.ts +6 -9
- package/src/memory.ts +35 -7
- package/src/prune.ts +16 -4
- package/src/schema.ts +4 -0
- package/src/tokenize.ts +208 -0
- package/src/tombstones.ts +454 -0
- package/src/viewer/mutate.ts +51 -6
- package/src/viewer/page.html +34 -1
- package/src/viewer/server.ts +27 -5
package/README.md
CHANGED
|
@@ -319,7 +319,7 @@ Use Bun **1.4.4** for development checks, matching CI. `bun run test` and `bun r
|
|
|
319
319
|
| `memory_remember` says blocked | A gate rejected the write: a stale code reference, a cited path that doesn't exist in the repo, overlap with a superseded memory, or an ambiguous claim. The reason is in `memory_evidence`; rephrase against current code and retry. |
|
|
320
320
|
| `invalid arguments to memory_*` | The call didn't match the tool's input schema; nothing was done and the message names the offending fields. Gate blocks look different (`blocked at GATE (…)`). |
|
|
321
321
|
| STORE shows `N malformed` | A daily file has a `ts=` that is not a valid ISO instant (typically a hand-edit). Every reader skips those rows; fix the `ts=` or restore the file with `memory_undo`. |
|
|
322
|
-
| `memory store is busy` |
|
|
322
|
+
| `memory store is busy` | A store write exhausted its 5s lock-wait budget. Appends, rewrites, and restores refuse that mutation rather than proceed unlocked and risk losing another writer's rows. Retry after contention clears. An operation spanning several files or steps may have completed earlier steps; refusal is not a rollback of those steps. If the reply reports `PARTIAL`, inspect the named rows and `memory_evidence` / `memory_undo` before retrying. A lock left by a killed process is taken over after 10s. |
|
|
323
323
|
| Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping; safe to delete while nothing is writing. |
|
|
324
324
|
| `/repo-init` missing from the command list | The self-install couldn't write to `~/.config/opencode/commands/`. Create it and restart, or ask the model to "init memory for this repo" — the same tool. |
|
|
325
325
|
| Init says `Graph: unavailable` | `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.26",
|
|
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
|
@@ -30,6 +30,8 @@ import {
|
|
|
30
30
|
type DriftInfo,
|
|
31
31
|
type LazyTree,
|
|
32
32
|
} from "./resolver.ts";
|
|
33
|
+
import { STOPWORDS, jaccard, rawTokens, tokens } from "./tokenize.ts";
|
|
34
|
+
import { probeRejection } from "./tombstones.ts";
|
|
33
35
|
|
|
34
36
|
export interface WriteCandidate {
|
|
35
37
|
type: string;
|
|
@@ -131,44 +133,9 @@ export type GateOutcome =
|
|
|
131
133
|
| (GateOutcomeFields & { action: "blocked"; reason: string })
|
|
132
134
|
| (GateOutcomeFields & { action: "collapsed" });
|
|
133
135
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
"the",
|
|
138
|
-
"a",
|
|
139
|
-
"an",
|
|
140
|
-
"in",
|
|
141
|
-
"of",
|
|
142
|
-
"to",
|
|
143
|
-
"with",
|
|
144
|
-
"on",
|
|
145
|
-
"and",
|
|
146
|
-
"or",
|
|
147
|
-
"for",
|
|
148
|
-
"is",
|
|
149
|
-
"are",
|
|
150
|
-
]);
|
|
151
|
-
|
|
152
|
-
function tokens(text: string): string[] {
|
|
153
|
-
return text
|
|
154
|
-
.toLowerCase()
|
|
155
|
-
.split(/[^a-z0-9_.]+/)
|
|
156
|
-
.filter((t) => t.length > 0);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// Case-preserving tokens, for reporting asserted values back to the user.
|
|
160
|
-
function rawTokens(text: string): string[] {
|
|
161
|
-
return text.split(/[^A-Za-z0-9_.]+/).filter(Boolean);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function jaccard(a: string[], b: string[]): number {
|
|
165
|
-
const sa = new Set(a);
|
|
166
|
-
const sb = new Set(b);
|
|
167
|
-
let inter = 0;
|
|
168
|
-
for (const t of sa) if (sb.has(t)) inter++;
|
|
169
|
-
const union = sa.size + sb.size - inter;
|
|
170
|
-
return union === 0 ? 0 : inter / union;
|
|
171
|
-
}
|
|
136
|
+
// STOPWORDS, tokens, rawTokens and jaccard now live in tokenize.ts so the
|
|
137
|
+
// rejection sketch (#35) scores similarity with the same definition GATE-3
|
|
138
|
+
// uses. Imported below; behavior is byte-identical to the local copies.
|
|
172
139
|
|
|
173
140
|
// GATE-3 similarity floors. OVERLAP_FLOOR: reworded near-duplicates of any
|
|
174
141
|
// type are merge-review candidates. CONFLICT_OVERLAP_FLOOR: decisions and
|
|
@@ -477,11 +444,10 @@ export async function runWriteGate(
|
|
|
477
444
|
});
|
|
478
445
|
}
|
|
479
446
|
if (driftPlan.length > 0) {
|
|
480
|
-
const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
|
|
447
|
+
const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })), ctx.durable);
|
|
481
448
|
if (marked.length > 0) {
|
|
482
449
|
// Ledger BEFORE the audit lines: what is on disk now stays on disk no
|
|
483
450
|
// matter what the record loop below does (round-3 probe 3).
|
|
484
|
-
ctx.durable?.push(...marked);
|
|
485
451
|
for (const p of driftPlan) {
|
|
486
452
|
supersededTs = p.s.memory.ts;
|
|
487
453
|
await rec("superseded_by", {
|
|
@@ -530,10 +496,10 @@ export async function runWriteGate(
|
|
|
530
496
|
ts: p.ts,
|
|
531
497
|
fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
|
|
532
498
|
})),
|
|
499
|
+
ctx.durable,
|
|
533
500
|
);
|
|
534
501
|
if (canonMarked.length > 0) {
|
|
535
502
|
// Same ledger discipline as the drift batch above.
|
|
536
|
-
ctx.durable?.push(...canonMarked);
|
|
537
503
|
for (const p of canonPlan) {
|
|
538
504
|
if (!supersededTs) supersededTs = p.ts;
|
|
539
505
|
await rec("superseded_by", {
|
|
@@ -551,6 +517,19 @@ export async function runWriteGate(
|
|
|
551
517
|
}
|
|
552
518
|
|
|
553
519
|
// ---- GATE-3: no dupes ----------------------------------------------------
|
|
520
|
+
// #35: a value a human rejected stays rejected. This is the "have we already
|
|
521
|
+
// seen this" gate, and it is the only place a rejection can be enforced
|
|
522
|
+
// before a write becomes durable — but unlike every other check here, it is
|
|
523
|
+
// keyed on the VALUE, not on row identity. The blocklist keys on `ts` and
|
|
524
|
+
// prune deletes the row outright, so re-ingesting the original source (the
|
|
525
|
+
// same transcript through auto-capture, the same export through
|
|
526
|
+
// memory_import) stores a rejected fact again with a fresh `ts`, as if it had
|
|
527
|
+
// never been turned down.
|
|
528
|
+
//
|
|
529
|
+
// Computed here, enforced at GATE-4, so the ordered evidence chain
|
|
530
|
+
// (gate_start → gate1 → gate2 → dedup_*) stays intact for every verdict.
|
|
531
|
+
const probe = await probeRejection(candidate.content);
|
|
532
|
+
const rejection = probe.rejection;
|
|
554
533
|
const conflictProne = candidate.type === "decision" || candidate.type === "preference";
|
|
555
534
|
const active = scopeMems.filter((m) => !m.superseded_by);
|
|
556
535
|
// Exact duplicates are detected against the full scope (a drift-superseded
|
|
@@ -620,7 +599,36 @@ export async function runWriteGate(
|
|
|
620
599
|
overlapScore = Math.round(rival.score * 100) / 100;
|
|
621
600
|
}
|
|
622
601
|
|
|
623
|
-
|
|
602
|
+
// A declined near-match, recorded so the guard is falsifiable in the field:
|
|
603
|
+
// without this line "it never over-blocks a correction" is a claim with no
|
|
604
|
+
// evidence either way, and this is exactly the kind of judgement that needs
|
|
605
|
+
// counting where it happens. Only reached when nothing refused the write.
|
|
606
|
+
if (!rejection && probe.vetoed) {
|
|
607
|
+
await rec("rejection_vetoed", {
|
|
608
|
+
gate: 3,
|
|
609
|
+
survivors: scopeMems.length,
|
|
610
|
+
match_ch: probe.vetoed.tombstone.ch,
|
|
611
|
+
score: probe.vetoed.score,
|
|
612
|
+
differs: probe.vetoed.differs,
|
|
613
|
+
action: "allow_different_fact",
|
|
614
|
+
chain,
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
if (rejection) {
|
|
619
|
+
// The prior rejection's own hash, never the prose: the atlas step-10
|
|
620
|
+
// inversion is a deletion log that reproduces what it deleted.
|
|
621
|
+
await rec("dedup_rejected", {
|
|
622
|
+
gate: 3,
|
|
623
|
+
survivors: scopeMems.length,
|
|
624
|
+
match_ch: rejection.tombstone.ch,
|
|
625
|
+
match_kind: rejection.kind,
|
|
626
|
+
...(rejection.kind === "near" ? { score: rejection.score } : {}),
|
|
627
|
+
rejected_at: rejection.tombstone.rejected_at,
|
|
628
|
+
action: "refuse_previously_rejected",
|
|
629
|
+
chain,
|
|
630
|
+
});
|
|
631
|
+
} else if (collapseMatch) {
|
|
624
632
|
await rec("dedup_collapse", {
|
|
625
633
|
gate: 3,
|
|
626
634
|
survivors: scopeMems.length,
|
|
@@ -670,7 +678,38 @@ export async function runWriteGate(
|
|
|
670
678
|
let blockReason: string | undefined;
|
|
671
679
|
let blockFlags: string[] = [];
|
|
672
680
|
let hint: string | undefined;
|
|
673
|
-
if (
|
|
681
|
+
if (rejection) {
|
|
682
|
+
// First in the chain: every other reason here is a heuristic about the
|
|
683
|
+
// write's shape, and a human already made a decision about this value.
|
|
684
|
+
blockReason = "previously_rejected";
|
|
685
|
+
blockFlags =
|
|
686
|
+
rejection.kind === "exact"
|
|
687
|
+
? [`ch=${rejection.tombstone.ch}`, "exact"]
|
|
688
|
+
: [`ch=${rejection.tombstone.ch}`, `score=${rejection.score}`, "near_match"];
|
|
689
|
+
const when = rejection.tombstone.rejected_at.slice(0, 10) || "an earlier session";
|
|
690
|
+
// Scrubbed here as well as on the way in and on the way out of tombstones():
|
|
691
|
+
// this string goes to the model, and the hint is built from a field a human
|
|
692
|
+
// typed. If the row already came through clean this is a no-op — deleting it
|
|
693
|
+
// changes nothing observable today, which is deliberate: the guarantee lives
|
|
694
|
+
// on the read path (it covers every consumer, the viewer included), and this
|
|
695
|
+
// is the seam where the value becomes a model-facing sentence.
|
|
696
|
+
const why = redactSecrets(rejection.tombstone.reason) || "no reason recorded";
|
|
697
|
+
const tch = rejection.tombstone.ch;
|
|
698
|
+
// The escape-hatch tail is shared by BOTH kinds. An earlier draft put it
|
|
699
|
+
// only on the near-match branch, which left the COMMON case — a byte-exact
|
|
700
|
+
// replay — reported as a dead end with no way to lift it.
|
|
701
|
+
const lift =
|
|
702
|
+
`If this is genuinely a different fact, state it in clearly different terms; ` +
|
|
703
|
+
`if the earlier rejection was wrong, a human can lift it in the viewer ` +
|
|
704
|
+
`(Rejections → un-reject, hash ${tch}) — there is deliberately no tool that ` +
|
|
705
|
+
`lifts a rejection, so a blocked write cannot be re-submitted by the session ` +
|
|
706
|
+
`it was refused.`;
|
|
707
|
+
hint =
|
|
708
|
+
(rejection.kind === "exact"
|
|
709
|
+
? `This exact content was rejected on ${when} (reason: ${why}; hash ${tch}). Nothing was stored. `
|
|
710
|
+
: `Content ${rejection.score} similar to a value rejected on ${when} (reason: ${why}; ` +
|
|
711
|
+
`hash ${tch}) — the same statement reworded counts as the rejected value. Nothing was stored. `) + lift;
|
|
712
|
+
} else if (g1.candidateStale) {
|
|
674
713
|
blockReason = "drift_ref_stale_incoming";
|
|
675
714
|
blockFlags = ["incoming_embeds_pre_drift_ref"];
|
|
676
715
|
} else if (g1.missingPaths.length && !planningObject) {
|
package/src/hits.ts
CHANGED
|
@@ -127,6 +127,9 @@ export async function recordHits(
|
|
|
127
127
|
);
|
|
128
128
|
return true;
|
|
129
129
|
} catch {
|
|
130
|
+
// Fail-closed lock contention can drop this use observation. Decay and
|
|
131
|
+
// consolidation therefore see a best-effort ledger, not proof of non-use;
|
|
132
|
+
// retrieval remains available even when its telemetry cannot be persisted.
|
|
130
133
|
return false; // telemetry never breaks retrieval
|
|
131
134
|
}
|
|
132
135
|
}
|
package/src/index.ts
CHANGED
|
@@ -794,7 +794,7 @@ const impl = {
|
|
|
794
794
|
symbol: target.ts,
|
|
795
795
|
from: target.ts,
|
|
796
796
|
to: survivorTs,
|
|
797
|
-
});
|
|
797
|
+
}, gateDurable);
|
|
798
798
|
if (done) {
|
|
799
799
|
return {
|
|
800
800
|
content:
|
|
@@ -854,8 +854,8 @@ const impl = {
|
|
|
854
854
|
? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
|
|
855
855
|
"Re-running this update reports the duplicate; inspect with memory_evidence."
|
|
856
856
|
: gateDurable.length > 0
|
|
857
|
-
? `memory_update
|
|
858
|
-
`${gateDurable.length}
|
|
857
|
+
? `memory_update PARTIAL: ${msg} No replacement was written, but this call had ALREADY retired ` +
|
|
858
|
+
`${gateDurable.length} row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
|
|
859
859
|
"disk and their audit lines may not all have landed. Re-running this update will not undo " +
|
|
860
860
|
"them — reconcile with memory_evidence / memory_undo before retrying."
|
|
861
861
|
: `memory_update blocked: ${msg} Nothing was written.`,
|
|
@@ -872,6 +872,7 @@ const impl = {
|
|
|
872
872
|
async execute(args, context): Promise<{ content: string }> {
|
|
873
873
|
const { sid } = toolIds(context);
|
|
874
874
|
const res = await pruneMemory(args.scope, args.type, args.reason, sid);
|
|
875
|
+
if (res.error) return { content: `memory_forget PARTIAL: deleted row(s) ${res.deleted.map((d) => d.memory.ts).join(", ")}; stopped: ${res.error}. Rejection tombstones or audit lines may be incomplete. Inspect memory_evidence / memory_undo before retrying.` };
|
|
875
876
|
if (!res.deleted.length) return { content: `No memories found for ${args.type} in ${args.scope}` };
|
|
876
877
|
return { content: `Deleted ${res.deleted.length} ${args.type} memory(s) from ${args.scope}. Audit: ${res.audit}` };
|
|
877
878
|
},
|
|
@@ -985,7 +986,7 @@ const impl = {
|
|
|
985
986
|
editor.add(validated(MergeReviewArgs, {
|
|
986
987
|
name: "memory_merge_review",
|
|
987
988
|
description:
|
|
988
|
-
"Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat.
|
|
989
|
+
"Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, the survivor id names no row in the store, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row. Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
|
|
989
990
|
options: direct,
|
|
990
991
|
async execute(args, context): Promise<{ content: string }> {
|
|
991
992
|
const { sid } = toolIds(context);
|
|
@@ -1008,11 +1009,9 @@ const impl = {
|
|
|
1008
1009
|
// this cannot deadlock against a plain writer; on timeout it fails
|
|
1009
1010
|
// closed with nothing written.
|
|
1010
1011
|
const reader = readerFromSid(sid);
|
|
1011
|
-
//
|
|
1012
|
-
//
|
|
1013
|
-
|
|
1014
|
-
// claiming "nothing was done" is a lie (review probe 5).
|
|
1015
|
-
let mutated = false;
|
|
1012
|
+
// A batch may publish the loser then refuse a later file. The sink
|
|
1013
|
+
// records that publish before the overall promise settles (#197).
|
|
1014
|
+
const mergeDurable: string[] = [];
|
|
1016
1015
|
try {
|
|
1017
1016
|
return await withStoreLock(
|
|
1018
1017
|
join(memoryRoot(), "update-order"),
|
|
@@ -1047,11 +1046,10 @@ const impl = {
|
|
|
1047
1046
|
symbol: args.loser,
|
|
1048
1047
|
from: args.loser,
|
|
1049
1048
|
to: args.survivor,
|
|
1050
|
-
});
|
|
1049
|
+
}, mergeDurable);
|
|
1051
1050
|
if (!ok) {
|
|
1052
1051
|
return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
|
|
1053
1052
|
}
|
|
1054
|
-
mutated = true;
|
|
1055
1053
|
// The survivor may itself have been superseded earlier (e.g. by
|
|
1056
1054
|
// a row this very call just made the loser). Declaring it
|
|
1057
1055
|
// canonical has to make it recallable, so clear its own marker.
|
|
@@ -1089,19 +1087,19 @@ const impl = {
|
|
|
1089
1087
|
);
|
|
1090
1088
|
} catch (err) {
|
|
1091
1089
|
// Before mutation this is the fail-closed lock contract: nothing
|
|
1092
|
-
// written.
|
|
1090
|
+
// written. Once a file published, the loser IS retired —
|
|
1093
1091
|
// the honest report names the completed mutation and the failed
|
|
1094
1092
|
// follow-up (evidence/revive), not a blanket "nothing was done".
|
|
1095
|
-
|
|
1093
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
1094
|
+
if (mergeDurable.length === 0) {
|
|
1096
1095
|
return {
|
|
1097
|
-
content:
|
|
1096
|
+
content: `merge_review blocked: ${why} — nothing was done. Retry.`,
|
|
1098
1097
|
};
|
|
1099
1098
|
}
|
|
1100
|
-
const why = err instanceof Error ? err.message : String(err);
|
|
1101
1099
|
return {
|
|
1102
1100
|
content:
|
|
1103
1101
|
`merge_review PARTIAL: ${args.loser} IS retired on disk (superseded_by ${args.survivor}; ` +
|
|
1104
|
-
`recoverable via memory_undo) but
|
|
1102
|
+
`recoverable via memory_undo) but the remaining operation failed: ${why}. ` +
|
|
1105
1103
|
`The evidence line may be missing; re-running reports the loser already superseded.`,
|
|
1106
1104
|
};
|
|
1107
1105
|
}
|
|
@@ -1211,15 +1209,24 @@ const impl = {
|
|
|
1211
1209
|
// One lock/read/snapshot/publish per file for the whole decay run (#61):
|
|
1212
1210
|
// N retired rows are one undo point, not N. Idempotent (a no-op on rows
|
|
1213
1211
|
// already superseded, out-of-band ones skipped under the lock).
|
|
1214
|
-
const
|
|
1215
|
-
|
|
1216
|
-
|
|
1212
|
+
const durable: string[] = [];
|
|
1213
|
+
let retired: number;
|
|
1214
|
+
try {
|
|
1215
|
+
retired = await markManySuperseded(
|
|
1216
|
+
stale.map((m) => ({ ts: m.ts, fields: { superseded_by: "decay", reason: "decay" } })), durable,
|
|
1217
|
+
);
|
|
1218
|
+
} catch (err) {
|
|
1219
|
+
if (durable.length === 0) throw err;
|
|
1220
|
+
let why = err instanceof Error ? err.message : String(err);
|
|
1221
|
+
await record("decay_applied", { days, retired: durable.length, mem: durable.join(","), snapshot: snapshot.join(","), partial: true, error: why }, false).catch((audit) => { why += `; audit failed: ${String(audit)}`; });
|
|
1222
|
+
return { content: `memory_decay PARTIAL: retired row(s) ${durable.join(", ")}; stopped: ${why}. Recover with memory_undo; inspect memory_evidence before retrying.` };
|
|
1223
|
+
}
|
|
1217
1224
|
await record(
|
|
1218
1225
|
"decay_applied",
|
|
1219
1226
|
{
|
|
1220
1227
|
days,
|
|
1221
1228
|
retired,
|
|
1222
|
-
mem:
|
|
1229
|
+
mem: durable.join(",") || "-",
|
|
1223
1230
|
snapshot: snapshot.join(",") || "-",
|
|
1224
1231
|
},
|
|
1225
1232
|
false,
|
|
@@ -1557,16 +1564,28 @@ const impl = {
|
|
|
1557
1564
|
const text = typeof out === "string" ? out : out?.text ?? "";
|
|
1558
1565
|
const candidates = parseCandidates(text, captureMax);
|
|
1559
1566
|
for (const c of candidates) {
|
|
1560
|
-
const
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1567
|
+
const durable: string[] = [];
|
|
1568
|
+
let outcome: Awaited<ReturnType<typeof runWriteGate>>;
|
|
1569
|
+
try {
|
|
1570
|
+
outcome = await runWriteGate(
|
|
1571
|
+
{
|
|
1572
|
+
...c,
|
|
1573
|
+
tags:
|
|
1574
|
+
trigger === "compaction"
|
|
1575
|
+
? ["auto-capture", CAPTURE_COMPACT_TAG]
|
|
1576
|
+
: ["auto-capture"],
|
|
1577
|
+
},
|
|
1578
|
+
{ ...captureGate, durable },
|
|
1579
|
+
);
|
|
1580
|
+
} catch (err) {
|
|
1581
|
+
// A refused write must not disappear into the hook's fail-soft
|
|
1582
|
+
// wrapper. Preserve any earlier gate retirements in the receipt.
|
|
1583
|
+
await record(durable.length ? "auto_capture_partial" : "auto_capture_refused", {
|
|
1584
|
+
session: sid, trigger, type: c.type, scope: redactSecrets(c.scope),
|
|
1585
|
+
reason: String(err), retired: durable.join(",") || undefined,
|
|
1586
|
+
}, false, sid);
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1570
1589
|
await record(
|
|
1571
1590
|
trigger === "compaction"
|
|
1572
1591
|
? `auto_capture_compaction_${outcome.action}`
|
package/src/lock.ts
CHANGED
|
@@ -48,18 +48,20 @@ export interface LockOptions {
|
|
|
48
48
|
/**
|
|
49
49
|
* What waiting past `timeoutMs` means. "fail" refuses the mutation (for
|
|
50
50
|
* callers where proceeding unlocked could destroy more than it saves, e.g.
|
|
51
|
-
* snapshot restore). "proceed" runs it
|
|
52
|
-
*
|
|
51
|
+
* snapshot restore). The legacy default, "proceed", runs it unlocked and
|
|
52
|
+
* can lose acknowledged writes when another caller rewrites the same file.
|
|
53
|
+
* Store writers must use LOCK_WRITE (or an explicit fail-closed policy).
|
|
53
54
|
*/
|
|
54
55
|
onTimeout?: "proceed" | "fail";
|
|
55
56
|
onEvent?: (event: LockEvent, waitedMs: number) => void;
|
|
56
57
|
}
|
|
57
58
|
|
|
58
|
-
//
|
|
59
|
-
//
|
|
60
|
-
//
|
|
61
|
-
//
|
|
59
|
+
// Every writer of a shared store file must respect exclusion, INCLUDING
|
|
60
|
+
// appenders: an unlocked append inside a holder's read-modify-write window is
|
|
61
|
+
// overwritten by its publish. Refuse at the deadline so the caller can retry;
|
|
62
|
+
// never acknowledge a mutation performed outside the holder's lock (#196).
|
|
62
63
|
export const LOCK_WRITE: LockOptions = {
|
|
64
|
+
onTimeout: "fail",
|
|
63
65
|
onEvent: (event, waitedMs) => {
|
|
64
66
|
void record("store_lock", { event, waited_ms: waitedMs, op: "write" });
|
|
65
67
|
},
|
package/src/logfmt.ts
CHANGED
|
@@ -124,13 +124,10 @@ let tmpSeq = 0;
|
|
|
124
124
|
|
|
125
125
|
export async function writeAtomic(file: string, content: string, since?: string): Promise<void> {
|
|
126
126
|
await ensureDir(dirname(file));
|
|
127
|
-
// Unique PER CALL, not per process:
|
|
128
|
-
//
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
// very temp the anchored publish's ≤2s retry keeps renaming, and the retry
|
|
132
|
-
// would publish THOSE bytes under our success report. One extra leftover
|
|
133
|
-
// per failed attempt is the (unlinkable) price of that safety.
|
|
127
|
+
// Unique PER CALL, not per process: shared store writers now fail closed on
|
|
128
|
+
// lock timeout, but direct/legacy callers can still overlap. A pid-stable
|
|
129
|
+
// name would let one call replace the bytes another call's anchored publish
|
|
130
|
+
// is retrying. Keep separate temps even when the caller holds a lock.
|
|
134
131
|
const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
|
|
135
132
|
try {
|
|
136
133
|
await Bun.write(tmp, content);
|
|
@@ -147,8 +144,8 @@ export async function writeAtomic(file: string, content: string, since?: string)
|
|
|
147
144
|
// while that handle lives. Readers of a small store file cycle their handle on
|
|
148
145
|
// a microsecond scale, so that failure is usually transient and worth a retry
|
|
149
146
|
// window (~2s, well inside the 5s lock budget) — but a retry alone is not safe
|
|
150
|
-
// here. If an
|
|
151
|
-
//
|
|
147
|
+
// here. If an out-of-band or legacy unlocked writer appends into the
|
|
148
|
+
// destination DURING the window, the
|
|
152
149
|
// retried rename publishes our now-stale copy over that row — a slower way to
|
|
153
150
|
// lose exactly what the immediate failure preserved. So the retry runs only
|
|
154
151
|
// while the destination still matches `since`, the identity from before the
|
package/src/memory.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
} from "./logfmt.ts";
|
|
21
21
|
import { withStoreLock, LOCK_WRITE } from "./lock.ts";
|
|
22
22
|
import { blockedTs } from "./blocklist.ts";
|
|
23
|
+
import { tombstoneMany } from "./tombstones.ts";
|
|
23
24
|
import { containsSecret, redactSecrets } from "./secrets.ts";
|
|
24
25
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
25
26
|
|
|
@@ -96,6 +97,9 @@ const RESERVED = new Set([
|
|
|
96
97
|
"deleted.logfmt",
|
|
97
98
|
"canonical.logfmt",
|
|
98
99
|
"blocklist.logfmt",
|
|
100
|
+
// Value-keyed rejection tombstones (#35). Hashes only, never prose — and it
|
|
101
|
+
// must never be ingested as a row, exported, or restored by undo.
|
|
102
|
+
"rejected.logfmt",
|
|
99
103
|
// The use ledger (src/hits.ts): telemetry, not memory. A hit line must never
|
|
100
104
|
// be able to become a row — or to be superseded, exported, or injected.
|
|
101
105
|
HITS_FILENAME,
|
|
@@ -395,8 +399,8 @@ async function stampRow(
|
|
|
395
399
|
|
|
396
400
|
// Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
|
|
397
401
|
// Idempotent: a second call is a no-op, so no double `superseded_by`.
|
|
398
|
-
export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
|
|
399
|
-
return (await markManySupersededReport([{ ts, fields }])).marked.length > 0;
|
|
402
|
+
export async function markSuperseded(ts: string, fields: SupersedeFields, durable?: string[]): Promise<boolean> {
|
|
403
|
+
return (await markManySupersededReport([{ ts, fields }], durable)).marked.length > 0;
|
|
400
404
|
}
|
|
401
405
|
|
|
402
406
|
// Batch supersession (#61): one lock acquisition, one read, one snapshot and
|
|
@@ -408,8 +412,8 @@ export async function markSuperseded(ts: string, fields: SupersedeFields): Promi
|
|
|
408
412
|
// so a repeat run marks nothing and writes nothing. Duplicate ts entries in
|
|
409
413
|
// one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
|
|
410
414
|
// Returns the number of rows actually marked.
|
|
411
|
-
export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[]): Promise<number> {
|
|
412
|
-
return (await markManySupersededReport(entries)).marked.length;
|
|
415
|
+
export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[], durable?: string[]): Promise<number> {
|
|
416
|
+
return (await markManySupersededReport(entries, durable)).marked.length;
|
|
413
417
|
}
|
|
414
418
|
|
|
415
419
|
// Same operation, reporting WHICH rows retired rather than how many (#158
|
|
@@ -420,6 +424,9 @@ export async function markManySuperseded(entries: { ts: string; fields: Supersed
|
|
|
420
424
|
// this call did not perform.
|
|
421
425
|
export async function markManySupersededReport(
|
|
422
426
|
entries: { ts: string; fields: SupersedeFields }[],
|
|
427
|
+
// Updated immediately after EACH publish, even if a later file refuses its
|
|
428
|
+
// lock or lock cleanup throws. A rejected promise is not a rollback.
|
|
429
|
+
durable?: string[],
|
|
423
430
|
): Promise<{ marked: string[] }> {
|
|
424
431
|
if (entries.length === 0) return { marked: [] };
|
|
425
432
|
const wanted = new Map<string, SupersedeFields>();
|
|
@@ -460,6 +467,7 @@ export async function markManySupersededReport(
|
|
|
460
467
|
if (ids.length === 0) return [];
|
|
461
468
|
await snapshotBefore(file);
|
|
462
469
|
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
470
|
+
durable?.push(...ids);
|
|
463
471
|
return ids;
|
|
464
472
|
},
|
|
465
473
|
LOCK_WRITE,
|
|
@@ -619,9 +627,9 @@ export async function prune(
|
|
|
619
627
|
type: string,
|
|
620
628
|
reason: string,
|
|
621
629
|
reader: Reader = readerForAmbient(),
|
|
630
|
+
durable: PruneResult = { deleted: [], snapshot: [] },
|
|
622
631
|
): Promise<PruneResult> {
|
|
623
|
-
const deleted
|
|
624
|
-
const snapshot: string[] = [];
|
|
632
|
+
const { deleted, snapshot } = durable;
|
|
625
633
|
for (const file of await memoryFiles()) {
|
|
626
634
|
await withStoreLock(
|
|
627
635
|
file,
|
|
@@ -629,6 +637,7 @@ export async function prune(
|
|
|
629
637
|
const since = await fileIdentity(file);
|
|
630
638
|
const lines = await readLines(file);
|
|
631
639
|
const kept: string[] = [];
|
|
640
|
+
const fileDeleted: DeletedMemory[] = [];
|
|
632
641
|
let changed = false;
|
|
633
642
|
for (const line of lines) {
|
|
634
643
|
const parsed = parseLine(line);
|
|
@@ -637,7 +646,7 @@ export async function prune(
|
|
|
637
646
|
// another repo's row for scope X — same basename collisions are real
|
|
638
647
|
// (a fork next to its upstream).
|
|
639
648
|
if (m && m.scope === scope && m.type === type && isVisibleTo(m, reader)) {
|
|
640
|
-
|
|
649
|
+
fileDeleted.push({ memory: m, reason });
|
|
641
650
|
await logDeletion(m, reason);
|
|
642
651
|
changed = true;
|
|
643
652
|
continue;
|
|
@@ -647,10 +656,29 @@ export async function prune(
|
|
|
647
656
|
if (!changed) return;
|
|
648
657
|
snapshot.push(...(await snapshotFiles([file])));
|
|
649
658
|
await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
|
|
659
|
+
deleted.push(...fileDeleted);
|
|
650
660
|
},
|
|
651
661
|
LOCK_WRITE,
|
|
652
662
|
);
|
|
653
663
|
}
|
|
664
|
+
// #35: tombstone every forgotten VALUE, keyed on content rather than on the
|
|
665
|
+
// row's `ts`, so replaying the source cannot store the fact again.
|
|
666
|
+
//
|
|
667
|
+
// ONE batched call, not one per row: `memory_forget` deletes by scope+type and
|
|
668
|
+
// routinely removes hundreds of rows, and the per-row form issued a store-lock
|
|
669
|
+
// create/unlink pair plus a full re-read of the tombstone file for each one.
|
|
670
|
+
// Done AFTER the per-file locks are released as well — appending inside the
|
|
671
|
+
// loop would nest a second store lock (day file, then rejected.logfmt) inside
|
|
672
|
+
// the first, and one consistent order across the codebase is what keeps the
|
|
673
|
+
// lock manager from having to reason about nesting at all.
|
|
674
|
+
await tombstoneMany(
|
|
675
|
+
deleted.map((d) => ({
|
|
676
|
+
content: d.memory.content,
|
|
677
|
+
scope: d.memory.scope,
|
|
678
|
+
type: d.memory.type,
|
|
679
|
+
})),
|
|
680
|
+
{ reason, source: "forget" },
|
|
681
|
+
);
|
|
654
682
|
return { deleted, snapshot };
|
|
655
683
|
}
|
|
656
684
|
|
package/src/prune.ts
CHANGED
|
@@ -13,8 +13,15 @@ export async function pruneMemory(
|
|
|
13
13
|
// CALLER's identity, captured at tool entry, not the ambient current the
|
|
14
14
|
// locked file walk may outlive. "?" / undefined keep ambient semantics.
|
|
15
15
|
sid?: string,
|
|
16
|
-
): Promise<PruneResult & { audit: string }> {
|
|
17
|
-
const res =
|
|
16
|
+
): Promise<PruneResult & { audit: string; error?: string }> {
|
|
17
|
+
const res: PruneResult = { deleted: [], snapshot: [] };
|
|
18
|
+
let error: string | undefined;
|
|
19
|
+
try {
|
|
20
|
+
await prune(scope, type, reason, readerFromSid(sid), res);
|
|
21
|
+
} catch (err) {
|
|
22
|
+
if (res.deleted.length === 0) throw err;
|
|
23
|
+
error = err instanceof Error ? err.message : String(err);
|
|
24
|
+
}
|
|
18
25
|
const memTs = res.deleted.map((d) => d.memory.ts).join(",") || "-";
|
|
19
26
|
await record(
|
|
20
27
|
"prune",
|
|
@@ -24,9 +31,14 @@ export async function pruneMemory(
|
|
|
24
31
|
snapshot: res.snapshot[0] ?? "-",
|
|
25
32
|
audit: deletionsFile(),
|
|
26
33
|
tool: "memory_forget",
|
|
34
|
+
partial: error ? true : undefined,
|
|
35
|
+
error,
|
|
27
36
|
},
|
|
28
37
|
true,
|
|
29
38
|
sid,
|
|
30
|
-
)
|
|
31
|
-
|
|
39
|
+
).catch((audit) => {
|
|
40
|
+
if (!error) throw audit;
|
|
41
|
+
error += `; audit failed: ${String(audit)}`;
|
|
42
|
+
});
|
|
43
|
+
return { ...res, audit: deletionsFile(), ...(error ? { error } : {}) };
|
|
32
44
|
}
|
package/src/schema.ts
CHANGED
|
@@ -200,6 +200,10 @@ export const EditBody = z.object({
|
|
|
200
200
|
export const DeleteBody = z.object({ ts: isoTs, reason: z.string() });
|
|
201
201
|
export const BlockBody = z.object({ ts: isoTs, reason: z.string() });
|
|
202
202
|
export const UnblockBody = z.object({ ts: isoTs });
|
|
203
|
+
// #35: lift a value-keyed rejection. `ch` is the 12-hex content hash the gate's
|
|
204
|
+
// block hint names, and the same identifier a `dedup_rejected` evidence line
|
|
205
|
+
// carries — so a human can act on either without reading the store by hand.
|
|
206
|
+
export const UnrejectBody = z.object({ ch: z.string().regex(/^[0-9a-f]{12}$/) });
|
|
203
207
|
// Strict fields by intent: String(body.x ?? "") coercion once let unvalidated
|
|
204
208
|
// POSTs append rows with empty type/scope/content.
|
|
205
209
|
// repo/repoPath (#129): the origin stamp of the DELETED row, replayed from the
|