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.
- package/package.json +2 -2
- package/src/capture/candidates.ts +110 -0
- package/src/capture/lag.ts +18 -0
- package/src/capture/prompt.ts +50 -0
- package/src/capture/transcript.ts +59 -0
- package/src/{triggers.ts → capture/triggers.ts} +6 -5
- package/src/{command.ts → command/ensure.ts} +2 -2
- package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
- package/src/consolidate/render.ts +30 -0
- package/src/core/cmp-ts.ts +16 -0
- package/src/core/config/budgets.ts +28 -0
- package/src/{config.ts → core/config/paths.ts} +1 -30
- package/src/core/logfmt/format.ts +82 -0
- package/src/{logfmt.ts → core/logfmt/publish.ts} +3 -92
- package/src/core/logfmt/read.ts +15 -0
- package/src/{state.ts → core/state.ts} +1 -1
- package/src/core/time.ts +6 -0
- package/src/{evidence.ts → evidence/record.ts} +7 -5
- package/src/{gates.ts → gate/gate.ts} +19 -21
- package/src/{resolver.ts → gate/resolver.ts} +1 -1
- package/src/{hits.ts → hits/ledger.ts} +8 -6
- package/src/index.ts +64 -943
- package/src/init/detect.ts +144 -0
- package/src/init/format.ts +25 -0
- package/src/init/run.ts +188 -0
- package/src/inject/anchor.ts +43 -0
- package/src/{attribution.ts → inject/attribution.ts} +2 -2
- package/src/inject/budget.ts +78 -0
- package/src/inject/digest.ts +89 -0
- package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
- package/src/inject/format.ts +32 -0
- package/src/inject/pull.ts +52 -0
- package/src/inject/version.ts +31 -0
- package/src/portable/decay.ts +20 -0
- package/src/portable/export.ts +194 -0
- package/src/portable/import.ts +173 -0
- package/src/recall/relevant.ts +72 -0
- package/src/recall/score.ts +106 -0
- package/src/recall/shared-terms.ts +15 -0
- package/src/status/format.ts +58 -0
- package/src/status/metrics.ts +65 -0
- package/src/status/payload.ts +143 -0
- package/src/status/report.ts +202 -0
- package/src/status/write.ts +102 -0
- package/src/{blocklist.ts → store/blocklist.ts} +4 -2
- package/src/store/files/append.ts +176 -0
- package/src/store/files/deletions.ts +31 -0
- package/src/store/files/load.ts +106 -0
- package/src/store/files/prune.ts +81 -0
- package/src/store/files/snapshots.ts +88 -0
- package/src/store/files/supersede.ts +123 -0
- package/src/store/files/target.ts +36 -0
- package/src/{lock.ts → store/lock.ts} +1 -1
- package/src/store/model/memory.ts +91 -0
- package/src/store/model/predicates.ts +12 -0
- package/src/store/model/visibility.ts +140 -0
- package/src/{prune.ts → store/prune.ts} +4 -3
- package/src/store/quarantine/release.ts +24 -0
- package/src/store/tombstones/rejection.ts +93 -0
- package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
- package/src/{undo.ts → store/undo.ts} +6 -3
- package/src/tools/consolidate.ts +42 -0
- package/src/tools/decay.ts +83 -0
- package/src/tools/deps.ts +27 -0
- package/src/tools/evidence.ts +48 -0
- package/src/tools/export.ts +27 -0
- package/src/tools/forget.ts +23 -0
- package/src/tools/import.ts +57 -0
- package/src/tools/init.ts +30 -0
- package/src/tools/list.ts +36 -0
- package/src/tools/merge-review.ts +138 -0
- package/src/tools/recall.ts +72 -0
- package/src/tools/registry.ts +40 -0
- package/src/tools/remember.ts +49 -0
- package/src/{schema.ts → tools/schema.ts} +3 -3
- package/src/tools/status-tool.ts +59 -0
- package/src/tools/undo.ts +57 -0
- package/src/tools/update.ts +342 -0
- package/src/{tui.tsx → tui/panel.tsx} +7 -17
- package/src/viewer/mutate.ts +15 -15
- package/src/viewer/server.ts +10 -8
- package/tsconfig.json +2 -2
- package/tui.ts +1 -1
- package/src/capture.ts +0 -222
- package/src/init.ts +0 -333
- package/src/inject.ts +0 -471
- package/src/memory.ts +0 -851
- package/src/portable.ts +0 -379
- package/src/status.ts +0 -536
- /package/src/{sessions.ts → core/lru.ts} +0 -0
- /package/src/{runtime.ts → core/runtime.ts} +0 -0
- /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
- /package/src/{types.ts → core/types.ts} +0 -0
- /package/src/{host.ts → identity/host-events.ts} +0 -0
- /package/src/{repokey.ts → identity/repokey.ts} +0 -0
- /package/src/{containment.ts → store/containment.ts} +0 -0
- /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
- /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
- /package/src/{secrets.ts → store/secrets.ts} +0 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// append — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
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
|
+
import { formatLine, parseLine } from "../../core/logfmt/format.ts"
|
|
9
|
+
import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts";
|
|
10
|
+
import { withStoreLock, LOCK_WRITE } from "../lock.ts";
|
|
11
|
+
import { containsSecret, redactSecrets } from "../secrets.ts";
|
|
12
|
+
import { flattenMemoryText } from "../sanitize.ts";
|
|
13
|
+
import { MAX_CONTENT_CHARS, type MemoryStatus, normalizeKeywords } from "../model/memory.ts";
|
|
14
|
+
|
|
15
|
+
export interface AppendMemoryInput {
|
|
16
|
+
type: string;
|
|
17
|
+
scope: string;
|
|
18
|
+
content: string;
|
|
19
|
+
issue?: string;
|
|
20
|
+
tags?: string[];
|
|
21
|
+
/** Retrieval keywords (#40); normalised and capped by appendMemory. */
|
|
22
|
+
kw?: string[];
|
|
23
|
+
status?: MemoryStatus;
|
|
24
|
+
// "global" for explicit cross-project writes; imports may carry a validated
|
|
25
|
+
// same-repo origin stamp (see portable.ts). Any missing value is resolved by
|
|
26
|
+
// appendMemory against the live repo scope.
|
|
27
|
+
repo?: string;
|
|
28
|
+
repoPath?: string;
|
|
29
|
+
// Which session the write belongs to, when the caller knows it (the gate
|
|
30
|
+
// threads it from GateContext, #116). Preferred over the ambient current.
|
|
31
|
+
sessionID?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ts values already in `file`. An appended row's ts is "now", so the only rows
|
|
35
|
+
// it can collide with are ones this same file received in the same millisecond;
|
|
36
|
+
// scanning just it keeps the locked section to one read of one file. (A row
|
|
37
|
+
// hand-placed with today's ts in another day's file is outside this promise.)
|
|
38
|
+
function existingTs(text: string): Set<string> {
|
|
39
|
+
const set = new Set<string>();
|
|
40
|
+
for (const line of text.split("\n")) {
|
|
41
|
+
const f = parseLine(line);
|
|
42
|
+
if (f && typeof f.ts === "string") set.add(f.ts);
|
|
43
|
+
}
|
|
44
|
+
return set;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// #152: the store's answer to a write whose owner it cannot determine. Thrown
|
|
48
|
+
// from the one place that knows what an owner is (the stamp resolution below),
|
|
49
|
+
// so no caller — gate, import, capture, or a future one — can quietly persist
|
|
50
|
+
// an ownerless row. `unresolvedWriteMessage` is the same text the model-facing
|
|
51
|
+
// tools return, kept here so the two can never drift.
|
|
52
|
+
export function unresolvedWriteMessage(sid: string): string {
|
|
53
|
+
return (
|
|
54
|
+
`Write refused: session ${sid} has no resolvable repository, so nothing was stored. ` +
|
|
55
|
+
`A memory with no owner must not be stamped into another repository or published as a ` +
|
|
56
|
+
`global row. Retry from a session in the project you mean, or pass global:true for a ` +
|
|
57
|
+
`deliberate cross-project memory.`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class UnresolvedWriterError extends Error {
|
|
62
|
+
/** The named-but-unresolved session whose write was refused. */
|
|
63
|
+
sid: string;
|
|
64
|
+
constructor(sid: string) {
|
|
65
|
+
super(unresolvedWriteMessage(sid));
|
|
66
|
+
this.name = "UnresolvedWriterError";
|
|
67
|
+
this.sid = sid;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Append a durable memory. GATE-4 promotions and the viewer's edit/restore-entry
|
|
72
|
+
// paths all call this single write choke point.
|
|
73
|
+
export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
74
|
+
// Absolute floor: every write SHOULD arrive through the gate,
|
|
75
|
+
// which rejects invalid input politely; viewer writes do not, so enforce the
|
|
76
|
+
// same storage rules here before anything reaches disk.
|
|
77
|
+
if (typeof input.content !== "string") throw new Error("memory content must be a string");
|
|
78
|
+
if (input.content.length > MAX_CONTENT_CHARS) {
|
|
79
|
+
throw new Error(`memory content exceeds ${MAX_CONTENT_CHARS} chars (${input.content.length})`);
|
|
80
|
+
}
|
|
81
|
+
for (const [field, value] of [
|
|
82
|
+
["type", input.type],
|
|
83
|
+
["scope", input.scope],
|
|
84
|
+
["issue", input.issue],
|
|
85
|
+
] as const) {
|
|
86
|
+
if (value !== undefined && flattenMemoryText(value) !== value) {
|
|
87
|
+
throw new Error(`memory ${field} must not contain control characters`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (input.tags?.some((tag) => flattenMemoryText(tag) !== tag)) {
|
|
91
|
+
throw new Error("memory tags must not contain control characters");
|
|
92
|
+
}
|
|
93
|
+
// Keywords are indexed, never rendered, but they still live on the row's
|
|
94
|
+
// single line, so the same control-character floor applies.
|
|
95
|
+
if (input.kw?.some((k) => typeof k !== "string" || flattenMemoryText(k) !== k)) {
|
|
96
|
+
throw new Error("memory keywords must not contain control characters");
|
|
97
|
+
}
|
|
98
|
+
const credentialMetadata = [
|
|
99
|
+
containsSecret(input.scope) ? "scope" : undefined,
|
|
100
|
+
input.tags?.some(containsSecret) ? "tags" : undefined,
|
|
101
|
+
input.kw?.some(containsSecret) ? "kw" : undefined,
|
|
102
|
+
containsSecret(input.issue) ? "issue" : undefined,
|
|
103
|
+
].filter((field): field is string => field !== undefined);
|
|
104
|
+
if (credentialMetadata.length) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
`memory metadata contains credential-shaped value in: ${credentialMetadata.join(", ")}`,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
const content = redactSecrets(input.content);
|
|
110
|
+
// Repo stamp at the single write choke point: gated writes plus viewer edits
|
|
111
|
+
// and restore-entry writes all pass through here. Explicit "global" survives;
|
|
112
|
+
// an unscoped process (viewer) stamps nothing = global. Session identity wins
|
|
113
|
+
// over the module scope so a server hosting several workspaces stamps the
|
|
114
|
+
// writing session's repo.
|
|
115
|
+
let repo = input.repo;
|
|
116
|
+
let repoPath = input.repoPath;
|
|
117
|
+
if (repo === undefined) {
|
|
118
|
+
// The caller's session when it named one: capture awaits a model call, and
|
|
119
|
+
// the last setCurrent before persistence may belong to another session
|
|
120
|
+
// entirely (#116). Unnamed writers (tools, viewer, restore) keep the
|
|
121
|
+
// ambient binding.
|
|
122
|
+
//
|
|
123
|
+
// A NAMED session that never resolved a repository is not an unnamed one
|
|
124
|
+
// (#152): falling back to the module scope stamped its rows into whatever
|
|
125
|
+
// workspace set up last, and with no module scope at all it stamped nothing
|
|
126
|
+
// — which every reader calls global. Both outcomes publish private content
|
|
127
|
+
// somewhere its owner can no longer see it, so the store refuses the write
|
|
128
|
+
// instead of guessing an owner. Tools answer with this message before the
|
|
129
|
+
// gate runs; throwing here is what covers every caller, including ones that
|
|
130
|
+
// reach the store without a tool.
|
|
131
|
+
const target = writeTarget(input.sessionID ?? getCurrent().sid);
|
|
132
|
+
if (!target.ok) throw new UnresolvedWriterError(target.sid);
|
|
133
|
+
if (target.scope) {
|
|
134
|
+
repo = target.scope.key;
|
|
135
|
+
repoPath = target.scope.path;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Day file chosen before the lock (it IS the lock key). A ts bumped across
|
|
139
|
+
// midnight therefore lands under the previous day's name; readers glob every
|
|
140
|
+
// file and decay compares ts values, so the grouping is cosmetic.
|
|
141
|
+
const file = join(memoryRoot(), `${dateStr()}.logfmt`);
|
|
142
|
+
// Locked end to end: seeding ts from a scan another process can race yields
|
|
143
|
+
// two rows with the same identity, and an append that lands inside someone
|
|
144
|
+
// else's whole-file rewrite is simply not there afterwards.
|
|
145
|
+
return withStoreLock(file, async () => {
|
|
146
|
+
const since = await fileIdentity(file);
|
|
147
|
+
let prior = "";
|
|
148
|
+
try { prior = await readFile(file, "utf8"); }
|
|
149
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; }
|
|
150
|
+
const taken = existingTs(prior);
|
|
151
|
+
let ts = new Date().toISOString();
|
|
152
|
+
let guard = 0;
|
|
153
|
+
while (taken.has(ts) && guard++ < 1000) {
|
|
154
|
+
ts = new Date(new Date(ts).getTime() + 1).toISOString();
|
|
155
|
+
}
|
|
156
|
+
const kw = normalizeKeywords(input.kw);
|
|
157
|
+
const line = formatLine({
|
|
158
|
+
ts,
|
|
159
|
+
type: input.type,
|
|
160
|
+
scope: input.scope,
|
|
161
|
+
content,
|
|
162
|
+
issue: input.issue,
|
|
163
|
+
tags: input.tags?.length ? input.tags.join(",") : undefined,
|
|
164
|
+
kw: kw?.join(","),
|
|
165
|
+
status: input.status,
|
|
166
|
+
repo,
|
|
167
|
+
repoPath,
|
|
168
|
+
});
|
|
169
|
+
// A lock excludes writers, not readers: an O_APPEND read can end mid-row.
|
|
170
|
+
// Publish the complete day file using the read already needed for IDs.
|
|
171
|
+
// This costs a whole-file write and can refuse on Windows reader handles;
|
|
172
|
+
// the old destination remains intact if publication fails (#198).
|
|
173
|
+
await writeAtomic(file, prior + (prior && !prior.endsWith("\n") ? "\n" : "") + line + "\n", since);
|
|
174
|
+
return ts;
|
|
175
|
+
}, LOCK_WRITE);
|
|
176
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// deletions — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { deletionsFile } from "../../core/config/paths.ts";
|
|
3
|
+
import { formatLine } from "../../core/logfmt/format.ts"
|
|
4
|
+
import { appendLog } from "../../core/logfmt/publish.ts";
|
|
5
|
+
import { redactSecrets } from "../secrets.ts";
|
|
6
|
+
import { type Memory } from "../model/memory.ts";
|
|
7
|
+
|
|
8
|
+
export interface DeletedMemory {
|
|
9
|
+
memory: Memory;
|
|
10
|
+
reason: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function logDeletion(memory: Memory, reason: string): Promise<void> {
|
|
14
|
+
await appendLog(
|
|
15
|
+
deletionsFile(),
|
|
16
|
+
formatLine({
|
|
17
|
+
ts: new Date().toISOString(),
|
|
18
|
+
action: "deleted",
|
|
19
|
+
original_ts: memory.ts,
|
|
20
|
+
type: memory.type,
|
|
21
|
+
scope: memory.scope,
|
|
22
|
+
content: memory.content,
|
|
23
|
+
// Origin survives the delete/restore round trip (#129): a restore-entry
|
|
24
|
+
// made from this line re-stamps what the row carried. A row with no
|
|
25
|
+
// stamp writes no stamp here — the legacy global path, unchanged.
|
|
26
|
+
repo: memory.repo,
|
|
27
|
+
repoPath: memory.repoPath,
|
|
28
|
+
reason: redactSecrets(reason),
|
|
29
|
+
}),
|
|
30
|
+
);
|
|
31
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// load — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
// Durable memory store engine. Reproduces the opencode-memory logfmt format
|
|
3
|
+
// (MIT, github.com/shuans/opencode-memory; license retained under
|
|
4
|
+
// vendor/opencode-memory/LICENSE) and extends it with the fields the write-gate
|
|
5
|
+
// needs: supersession markers, snapshots and audited deletion.
|
|
6
|
+
import { existsSync } from "node:fs";
|
|
7
|
+
import { open } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { HITS_FILENAME, memoryRoot } from "../../core/config/paths.ts";
|
|
10
|
+
import { parseLine } from "../../core/logfmt/format.ts"
|
|
11
|
+
import { readLines } from "../../core/logfmt/read.ts";
|
|
12
|
+
import { blockedTs } from "../blocklist.ts";
|
|
13
|
+
import { ISO_TS_RE, type Memory, malformedWarnedFiles } from "../model/memory.ts";
|
|
14
|
+
import { type Reader, isVisibleTo, readerForAmbient } from "../model/visibility.ts";
|
|
15
|
+
|
|
16
|
+
const RESERVED = new Set([
|
|
17
|
+
"deletions.logfmt",
|
|
18
|
+
"deleted.logfmt",
|
|
19
|
+
"canonical.logfmt",
|
|
20
|
+
"blocklist.logfmt",
|
|
21
|
+
// Value-keyed rejection tombstones (#35). Hashes only, never prose — and it
|
|
22
|
+
// must never be ingested as a row, exported, or restored by undo.
|
|
23
|
+
"rejected.logfmt",
|
|
24
|
+
// The use ledger (src/hits.ts): telemetry, not memory. A hit line must never
|
|
25
|
+
// be able to become a row — or to be superseded, exported, or injected.
|
|
26
|
+
HITS_FILENAME,
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
let malformedRows = 0;
|
|
30
|
+
|
|
31
|
+
/** Rows skipped as malformed by the most recent store read (approximate, in-process). */
|
|
32
|
+
export function malformedCount(): number {
|
|
33
|
+
return malformedRows;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function toMemory(fields: Record<string, unknown>, file: string, index: number): Memory | null {
|
|
37
|
+
const ts = fields.ts;
|
|
38
|
+
const type = fields.type;
|
|
39
|
+
const scope = fields.scope;
|
|
40
|
+
if (typeof ts !== "string" || typeof type !== "string") return null;
|
|
41
|
+
if (typeof scope !== "string") return null;
|
|
42
|
+
if (!ISO_TS_RE.test(ts) || Number.isNaN(Date.parse(ts))) {
|
|
43
|
+
malformedRows++;
|
|
44
|
+
if (!malformedWarnedFiles.has(file)) {
|
|
45
|
+
malformedWarnedFiles.add(file);
|
|
46
|
+
console.warn(
|
|
47
|
+
`[memory] malformed row skipped in ${file} (ts is not an ISO instant): ${JSON.stringify(ts.slice(0, 48))}`,
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
ts,
|
|
54
|
+
type,
|
|
55
|
+
scope,
|
|
56
|
+
content: typeof fields.content === "string" ? fields.content : "",
|
|
57
|
+
issue: typeof fields.issue === "string" ? fields.issue : undefined,
|
|
58
|
+
tags: typeof fields.tags === "string" ? fields.tags.split(",") : undefined,
|
|
59
|
+
kw: typeof fields.kw === "string" && fields.kw
|
|
60
|
+
? fields.kw.split(",").map((k) => k.trim()).filter((k) => k.length > 0)
|
|
61
|
+
: undefined,
|
|
62
|
+
superseded_by: typeof fields.superseded_by === "string" ? fields.superseded_by : undefined,
|
|
63
|
+
reason: typeof fields.reason === "string" ? fields.reason : undefined,
|
|
64
|
+
status:
|
|
65
|
+
fields.status === "open" || fields.status === "settled" ? fields.status : undefined,
|
|
66
|
+
repo: typeof fields.repo === "string" ? fields.repo : undefined,
|
|
67
|
+
repoPath: typeof fields.repoPath === "string" ? fields.repoPath : undefined,
|
|
68
|
+
file,
|
|
69
|
+
index,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function memoryFiles(): Promise<string[]> {
|
|
74
|
+
const root = memoryRoot();
|
|
75
|
+
// Bun.Glob.scan throws ENOENT on a missing root; a fresh store must read as
|
|
76
|
+
// empty so the system-digest hook never throws (it runs on every request,
|
|
77
|
+
// including the compaction model call).
|
|
78
|
+
if (!existsSync(root)) return [];
|
|
79
|
+
const glob = new Bun.Glob("*.logfmt");
|
|
80
|
+
const files: string[] = [];
|
|
81
|
+
for await (const f of glob.scan(root)) {
|
|
82
|
+
if (!RESERVED.has(f)) files.push(join(root, f));
|
|
83
|
+
}
|
|
84
|
+
return files.sort();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function loadAll(): Promise<Memory[]> {
|
|
88
|
+
malformedRows = 0; // per-load telemetry: the most recent read wins
|
|
89
|
+
const blocked = await blockedTs();
|
|
90
|
+
const out: Memory[] = [];
|
|
91
|
+
for (const file of await memoryFiles()) {
|
|
92
|
+
const lines = await readLines(file);
|
|
93
|
+
lines.forEach((line, index) => {
|
|
94
|
+
const m = toMemory(parseLine(line) ?? {}, file, index);
|
|
95
|
+
if (m && !blocked.has(m.ts)) out.push(m);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function loadScope(scope: string, reader: Reader = readerForAmbient()): Promise<Memory[]> {
|
|
102
|
+
// Gate dedup/stale reads are repo-scoped: a row from another repo must not
|
|
103
|
+
// collapse or supersede a write here. The reader is the CALLER's identity,
|
|
104
|
+
// resolved at flow entry — not whatever current says after this await.
|
|
105
|
+
return (await loadAll()).filter((m) => m.scope === scope && isVisibleTo(m, reader));
|
|
106
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// prune — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { join, basename } from "node:path";
|
|
3
|
+
import { parseLine } from "../../core/logfmt/format.ts"
|
|
4
|
+
import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts"
|
|
5
|
+
import { readLines } from "../../core/logfmt/read.ts";
|
|
6
|
+
import { withStoreLock, LOCK_WRITE } from "../lock.ts";
|
|
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";
|
|
11
|
+
import { type Reader, isVisibleTo, readerForAmbient } from "../model/visibility.ts";
|
|
12
|
+
|
|
13
|
+
export interface PruneResult {
|
|
14
|
+
deleted: DeletedMemory[];
|
|
15
|
+
snapshot: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Remove matching memories (used by memory_forget), snapshotting first and
|
|
19
|
+
// logging every deletion with its reason. Each file is filtered and republished
|
|
20
|
+
// under the store lock, so a row another session appended while we were reading
|
|
21
|
+
// is not quietly filtered out along with the targets. The reader is the
|
|
22
|
+
// caller's captured identity (#127); out-of-plugin callers keep ambient.
|
|
23
|
+
export async function prune(
|
|
24
|
+
scope: string,
|
|
25
|
+
type: string,
|
|
26
|
+
reason: string,
|
|
27
|
+
reader: Reader = readerForAmbient(),
|
|
28
|
+
durable: PruneResult = { deleted: [], snapshot: [] },
|
|
29
|
+
): Promise<PruneResult> {
|
|
30
|
+
const { deleted, snapshot } = durable;
|
|
31
|
+
for (const file of await memoryFiles()) {
|
|
32
|
+
await withStoreLock(
|
|
33
|
+
file,
|
|
34
|
+
async () => {
|
|
35
|
+
const since = await fileIdentity(file);
|
|
36
|
+
const lines = await readLines(file);
|
|
37
|
+
const kept: string[] = [];
|
|
38
|
+
const fileDeleted: DeletedMemory[] = [];
|
|
39
|
+
let changed = false;
|
|
40
|
+
for (const line of lines) {
|
|
41
|
+
const parsed = parseLine(line);
|
|
42
|
+
const m = parsed ? toMemory(parsed, file, 0) : null;
|
|
43
|
+
// Repo floor: forgetting scope X here must never delete
|
|
44
|
+
// another repo's row for scope X — same basename collisions are real
|
|
45
|
+
// (a fork next to its upstream).
|
|
46
|
+
if (m && m.scope === scope && m.type === type && isVisibleTo(m, reader)) {
|
|
47
|
+
fileDeleted.push({ memory: m, reason });
|
|
48
|
+
await logDeletion(m, reason);
|
|
49
|
+
changed = true;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
kept.push(line);
|
|
53
|
+
}
|
|
54
|
+
if (!changed) return;
|
|
55
|
+
snapshot.push(...(await snapshotFiles([file])));
|
|
56
|
+
await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
|
|
57
|
+
deleted.push(...fileDeleted);
|
|
58
|
+
},
|
|
59
|
+
LOCK_WRITE,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
// #35: tombstone every forgotten VALUE, keyed on content rather than on the
|
|
63
|
+
// row's `ts`, so replaying the source cannot store the fact again.
|
|
64
|
+
//
|
|
65
|
+
// ONE batched call, not one per row: `memory_forget` deletes by scope+type and
|
|
66
|
+
// routinely removes hundreds of rows, and the per-row form issued a store-lock
|
|
67
|
+
// create/unlink pair plus a full re-read of the tombstone file for each one.
|
|
68
|
+
// Done AFTER the per-file locks are released as well — appending inside the
|
|
69
|
+
// loop would nest a second store lock (day file, then rejected.logfmt) inside
|
|
70
|
+
// the first, and one consistent order across the codebase is what keeps the
|
|
71
|
+
// lock manager from having to reason about nesting at all.
|
|
72
|
+
await tombstoneMany(
|
|
73
|
+
deleted.map((d) => ({
|
|
74
|
+
content: d.memory.content,
|
|
75
|
+
scope: d.memory.scope,
|
|
76
|
+
type: d.memory.type,
|
|
77
|
+
})),
|
|
78
|
+
{ reason, source: "forget" },
|
|
79
|
+
);
|
|
80
|
+
return { deleted, snapshot };
|
|
81
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// snapshots — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { open, readFile } from "node:fs/promises";
|
|
3
|
+
import { join, basename } from "node:path";
|
|
4
|
+
import { snapshotDir } from "../../core/config/paths.ts";
|
|
5
|
+
import { parseLine, type Fields } from "../../core/logfmt/format.ts"
|
|
6
|
+
import { ensureDir, fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts"
|
|
7
|
+
import { readLines } from "../../core/logfmt/read.ts";
|
|
8
|
+
import { withStoreLock, LOCK_WRITE } from "../lock.ts";
|
|
9
|
+
|
|
10
|
+
// Copy `file` into snapshots/ before a mutation.
|
|
11
|
+
export async function snapshotBefore(file: string): Promise<void> {
|
|
12
|
+
await snapshotFiles([file]);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Read-modify-write ONE row of a store file: read, rewrite the line, publish
|
|
16
|
+
// atomically, all under the store lock, so an append or another rewrite by a
|
|
17
|
+
// concurrent session cannot be overwritten by our stale copy. Resolves to null
|
|
18
|
+
// when the row is not in this file, otherwise the mutation's outcome.
|
|
19
|
+
export async function stampRow(
|
|
20
|
+
file: string,
|
|
21
|
+
ts: string,
|
|
22
|
+
mutate: (fields: Fields) => string | null,
|
|
23
|
+
): Promise<boolean | null> {
|
|
24
|
+
return withStoreLock(
|
|
25
|
+
file,
|
|
26
|
+
async () => {
|
|
27
|
+
// Identity BEFORE the read: it pins the state `lines` was derived from,
|
|
28
|
+
// so writeAtomic can refuse to publish if anything moved the file
|
|
29
|
+
// meanwhile (Windows retry path — see logfmt.ts handoverRename).
|
|
30
|
+
const since = await fileIdentity(file);
|
|
31
|
+
const lines = await readLines(file);
|
|
32
|
+
const idx = lines.findIndex((l) => {
|
|
33
|
+
const f = parseLine(l);
|
|
34
|
+
return f && f.ts === ts;
|
|
35
|
+
});
|
|
36
|
+
if (idx === -1) return null;
|
|
37
|
+
const parsed = parseLine(lines[idx]);
|
|
38
|
+
if (!parsed) return false;
|
|
39
|
+
const next = mutate(parsed);
|
|
40
|
+
if (next === null) return false;
|
|
41
|
+
lines[idx] = next;
|
|
42
|
+
await snapshotBefore(file);
|
|
43
|
+
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
44
|
+
return true;
|
|
45
|
+
},
|
|
46
|
+
LOCK_WRITE,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Claim a snapshot name with O_EXCL so "never overwrite a snapshot" holds
|
|
51
|
+
// across processes, not just inside one: two sessions mutating the same file in
|
|
52
|
+
// one millisecond both bump instead of one clobbering the other's still-undoable
|
|
53
|
+
// copy. Names are `<epoch-ms>-<original>` because /undo strips the leading stamp
|
|
54
|
+
// to find its target, so nothing may go in front of it.
|
|
55
|
+
async function claimSnapshot(file: string): Promise<string> {
|
|
56
|
+
await ensureDir(snapshotDir());
|
|
57
|
+
let stamp = Date.now();
|
|
58
|
+
for (;;) {
|
|
59
|
+
const snap = join(snapshotDir(), `${stamp}-${basename(file)}`);
|
|
60
|
+
try {
|
|
61
|
+
const handle = await open(snap, "wx");
|
|
62
|
+
await handle.close();
|
|
63
|
+
return snap;
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
66
|
+
stamp++;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Snapshot-before-mutate: copy each affected file into snapshots/ so /undo can
|
|
72
|
+
// restore it. Returns the snapshot paths keyed by original file.
|
|
73
|
+
export async function snapshotFiles(files: string[]): Promise<string[]> {
|
|
74
|
+
const snaps: string[] = [];
|
|
75
|
+
for (const file of files) {
|
|
76
|
+
let contents: Buffer;
|
|
77
|
+
try {
|
|
78
|
+
contents = await readFile(file);
|
|
79
|
+
} catch (err) {
|
|
80
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
const snap = await claimSnapshot(file);
|
|
84
|
+
await Bun.write(snap, contents);
|
|
85
|
+
snaps.push(snap);
|
|
86
|
+
}
|
|
87
|
+
return snaps;
|
|
88
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// supersede — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { formatLine, parseLine } from "../../core/logfmt/format.ts"
|
|
4
|
+
import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts"
|
|
5
|
+
import { readLines } from "../../core/logfmt/read.ts";
|
|
6
|
+
import { withStoreLock, LOCK_WRITE } from "../lock.ts";
|
|
7
|
+
import { redactSecrets } from "../secrets.ts";
|
|
8
|
+
import { appendMemory } from "./append.ts";
|
|
9
|
+
import { memoryFiles } from "./load.ts";
|
|
10
|
+
import { snapshotBefore, stampRow } from "./snapshots.ts";
|
|
11
|
+
|
|
12
|
+
export interface SupersedeFields {
|
|
13
|
+
superseded_by: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
symbol?: string;
|
|
16
|
+
from?: string;
|
|
17
|
+
to?: string;
|
|
18
|
+
entity?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
|
|
22
|
+
// Idempotent: a second call is a no-op, so no double `superseded_by`.
|
|
23
|
+
export async function markSuperseded(ts: string, fields: SupersedeFields, durable?: string[]): Promise<boolean> {
|
|
24
|
+
return (await markManySupersededReport([{ ts, fields }], durable)).marked.length > 0;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Batch supersession (#61): one lock acquisition, one read, one snapshot and
|
|
28
|
+
// one publish PER FILE touched - N rows retire as one undo point instead of
|
|
29
|
+
// N. decay and the gate's drift/canonical loops used to call markSuperseded
|
|
30
|
+
// per row, which meant N full read-modify-write cycles, N undo points, and
|
|
31
|
+
// N windows where two runs interleave and each re-pays the other's work.
|
|
32
|
+
// Idempotence is unchanged: a row already carrying superseded_by is skipped,
|
|
33
|
+
// so a repeat run marks nothing and writes nothing. Duplicate ts entries in
|
|
34
|
+
// one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
|
|
35
|
+
// Returns the number of rows actually marked.
|
|
36
|
+
export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[], durable?: string[]): Promise<number> {
|
|
37
|
+
return (await markManySupersededReport(entries, durable)).marked.length;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Same operation, reporting WHICH rows retired rather than how many (#158
|
|
41
|
+
// round 3): the write gate needs the ids to keep a durable-mutation ledger,
|
|
42
|
+
// because a failed audit line after a persisted retirement must still be able
|
|
43
|
+
// to name what actually landed. Skipped-by-the-batch rows (already retired
|
|
44
|
+
// out of band) are absent from `marked` — the ledger never claims a retirement
|
|
45
|
+
// this call did not perform.
|
|
46
|
+
export async function markManySupersededReport(
|
|
47
|
+
entries: { ts: string; fields: SupersedeFields }[],
|
|
48
|
+
// Updated immediately after EACH publish, even if a later file refuses its
|
|
49
|
+
// lock or lock cleanup throws. A rejected promise is not a rollback.
|
|
50
|
+
durable?: string[],
|
|
51
|
+
): Promise<{ marked: string[] }> {
|
|
52
|
+
if (entries.length === 0) return { marked: [] };
|
|
53
|
+
const wanted = new Map<string, SupersedeFields>();
|
|
54
|
+
for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
|
|
55
|
+
const marked: string[] = [];
|
|
56
|
+
for (const file of await memoryFiles()) {
|
|
57
|
+
marked.push(
|
|
58
|
+
...(await withStoreLock(
|
|
59
|
+
file,
|
|
60
|
+
async () => {
|
|
61
|
+
// #106: identity BEFORE the read, like every other whole-file
|
|
62
|
+
// read-modify-write (#89's contract) - the publish below may retry a
|
|
63
|
+
// Windows handover only while the destination still matches this.
|
|
64
|
+
const since = await fileIdentity(file);
|
|
65
|
+
const lines = await readLines(file);
|
|
66
|
+
const ids: string[] = [];
|
|
67
|
+
for (let i = 0; i < lines.length; i++) {
|
|
68
|
+
const parsed = parseLine(lines[i]);
|
|
69
|
+
if (!parsed || typeof parsed.superseded_by === "string") continue;
|
|
70
|
+
const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
|
|
71
|
+
if (!fields) continue;
|
|
72
|
+
// Whole line rewritten, not extended: an old-format line comes out in
|
|
73
|
+
// the current format with its values unchanged (as markSuperseded did).
|
|
74
|
+
// The one exception is SECRET SCRUB (#128, review probe 4): the
|
|
75
|
+
// fields a merge/decay/update copies into the loser's row carry
|
|
76
|
+
// caller-authored prose (the rotation note "key ghp_... rotated"),
|
|
77
|
+
// and content already scrubs at this same boundary (line 260). The
|
|
78
|
+
// durable row must not be the one place a credential survives when
|
|
79
|
+
// the evidence line beside it was cleaned.
|
|
80
|
+
const clean: SupersedeFields = { ...fields };
|
|
81
|
+
for (const k of Object.keys(clean)) {
|
|
82
|
+
const v = (clean as unknown as Record<string, unknown>)[k];
|
|
83
|
+
if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
|
|
84
|
+
}
|
|
85
|
+
lines[i] = formatLine({ ...parsed, ...clean });
|
|
86
|
+
ids.push(parsed.ts as string);
|
|
87
|
+
}
|
|
88
|
+
if (ids.length === 0) return [];
|
|
89
|
+
await snapshotBefore(file);
|
|
90
|
+
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
91
|
+
durable?.push(...ids);
|
|
92
|
+
return ids;
|
|
93
|
+
},
|
|
94
|
+
LOCK_WRITE,
|
|
95
|
+
))
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
// A ts that appears in several files (should not exist - append mints unique
|
|
99
|
+
// ts) retires in EVERY file here, where the row-by-row loop retired only the
|
|
100
|
+
// first; both are conservation-safe, this one is the more honest tombstone.
|
|
101
|
+
return { marked };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Drop a row's supersession markers IN PLACE (snapshot-first), making it active
|
|
105
|
+
// again. Used by memory_merge_review: a declared survivor must be recallable
|
|
106
|
+
// even when an earlier row — now the loser — had superseded it first.
|
|
107
|
+
export async function clearSuperseded(ts: string): Promise<boolean> {
|
|
108
|
+
for (const file of await memoryFiles()) {
|
|
109
|
+
const outcome = await stampRow(file, ts, (parsed) => {
|
|
110
|
+
if (typeof parsed.superseded_by !== "string") return null;
|
|
111
|
+
// These five keys are written only by markSuperseded (drift, canonical,
|
|
112
|
+
// update and merge_review), never by appendMemory, so they are all part of
|
|
113
|
+
// the marker and go with it. Field order round-trips because parseLine
|
|
114
|
+
// inserts keys in source order.
|
|
115
|
+
for (const key of ["superseded_by", "reason", "symbol", "from", "to", "entity"]) {
|
|
116
|
+
delete parsed[key];
|
|
117
|
+
}
|
|
118
|
+
return formatLine(parsed);
|
|
119
|
+
});
|
|
120
|
+
if (outcome !== null) return outcome;
|
|
121
|
+
}
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// target — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
import { type Memory, targetScore } from "../model/memory.ts";
|
|
4
|
+
|
|
5
|
+
export type TargetResolution =
|
|
6
|
+
| { status: "ok"; target: Memory }
|
|
7
|
+
| { status: "not_found" }
|
|
8
|
+
| { status: "ambiguous"; candidates: Memory[] };
|
|
9
|
+
|
|
10
|
+
// Pick the row an update/merge call means. Without a query the caller keeps the
|
|
11
|
+
// legacy "most recent active row of this scope+type" behaviour; with one, a
|
|
12
|
+
// miss or a tie fails CLOSED rather than silently rewriting a different row.
|
|
13
|
+
export function resolveMemoryTarget(rows: Memory[], query?: string): TargetResolution {
|
|
14
|
+
if (!query || !query.trim()) {
|
|
15
|
+
const last = rows[rows.length - 1];
|
|
16
|
+
return last ? { status: "ok", target: last } : { status: "not_found" };
|
|
17
|
+
}
|
|
18
|
+
const q = query.trim().toLowerCase();
|
|
19
|
+
let best: Memory | undefined;
|
|
20
|
+
let bestScore = 0;
|
|
21
|
+
const tied: Memory[] = [];
|
|
22
|
+
for (const m of rows) {
|
|
23
|
+
const score = targetScore(m, q);
|
|
24
|
+
if (score > bestScore) {
|
|
25
|
+
best = m;
|
|
26
|
+
bestScore = score;
|
|
27
|
+
tied.length = 0;
|
|
28
|
+
tied.push(m);
|
|
29
|
+
} else if (score === bestScore && score > 0) {
|
|
30
|
+
tied.push(m);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (!best) return { status: "not_found" };
|
|
34
|
+
if (tied.length > 1) return { status: "ambiguous", candidates: tied };
|
|
35
|
+
return { status: "ok", target: best };
|
|
36
|
+
}
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
// the middle of a rewrite.
|
|
24
24
|
import { mkdir, open, stat, unlink } from "node:fs/promises";
|
|
25
25
|
import { basename, dirname } from "node:path";
|
|
26
|
-
import { record } from "
|
|
26
|
+
import { record } from "../evidence/record.ts";
|
|
27
27
|
|
|
28
28
|
const LOCK_SUFFIX = ".lock";
|
|
29
29
|
// A lock older than this belongs to a process that died holding it.
|