@staix/agent-mem 0.30.0 → 0.31.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/.claude-plugin/plugin.json +1 -1
- package/README.md +20 -576
- package/package.json +1 -1
- package/src/cli-agent-reads.ts +17 -2
- package/src/cli.ts +109 -11
- package/src/commands-table.ts +10 -2
- package/src/index.ts +1 -0
- package/src/ingest.ts +7 -5
- package/src/memory/candidates.ts +17 -1
- package/src/memory/commands.ts +2 -1
- package/src/memory/config.ts +13 -1
- package/src/memory/decay-review.ts +20 -0
- package/src/memory/doctor.ts +131 -48
- package/src/memory/eval-audit.ts +442 -0
- package/src/memory/eval.ts +66 -0
- package/src/memory/native-roots.ts +28 -0
- package/src/memory/platform.ts +9 -1
- package/src/memory/review-targets.ts +69 -0
- package/src/memory/shard-migration.ts +14 -1
- package/src/memory/shard.ts +4 -0
- package/src/memory/store.ts +4 -2
- package/src/memory/sync-placement-inventory.ts +37 -15
- package/src/memory/sync-placement-transport.ts +5 -2
- package/src/memory/sync-progress.ts +1 -1
- package/src/memory/sync.ts +1 -1
- package/src/memory/use-telemetry.ts +15 -7
- package/src/setup-drift.ts +12 -2
- package/src/setup-owned.ts +42 -0
- package/src/setup.ts +32 -11
- package/src/ui/plugin.ts +25 -10
- package/src/ui/snapshot-cache.ts +24 -11
package/src/memory/doctor.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { Database } from "bun:sqlite";
|
|
|
8
8
|
import { sessionStartBrief, type BriefOptions } from "../session-brief.ts";
|
|
9
9
|
import { openCuratedForRead } from "./curated-read.ts";
|
|
10
10
|
import { pendingSummary } from "./candidate-pending.ts";
|
|
11
|
+
import { inspectNativeRoot, nativeRoots, type NativeRootKind } from "./native-roots.ts";
|
|
11
12
|
import { readCaptureDrops } from "./metrics.ts";
|
|
12
13
|
import { walkShards } from "./catalog.ts";
|
|
13
14
|
import { loadAmemConfig, repoConfigRoot } from "./config.ts";
|
|
@@ -105,32 +106,50 @@ function curatedPresent(home: string, project: string, layout: Layout): boolean
|
|
|
105
106
|
/** What a scratch copy leaves out: databases, locks, repositories, the machine-local capture and work trees, spools and ingest cursors. */
|
|
106
107
|
const SKIP = /\.db(-wal|-shm)?$|\.lock$|\.tmp$|^\.git$|\.git$|^spool$|^ingest$|^readers$/;
|
|
107
108
|
class TooBig extends Error {}
|
|
108
|
-
|
|
109
|
+
// ponytail: at most three complete copy attempts; a future incremental snapshot protocol can reduce retry cost.
|
|
110
|
+
const RECAP_SNAPSHOT_ATTEMPTS = 3;
|
|
111
|
+
export class RecapSourceChangedError extends Error {
|
|
112
|
+
constructor(directory: boolean) {
|
|
113
|
+
super(`recap source ${directory ? "directory " : ""}changed during snapshot after ${RECAP_SNAPSHOT_ATTEMPTS} attempts; wait for memory writes to settle, then retry Recap.`);
|
|
114
|
+
this.name = "RecapSourceChangedError";
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
interface CopyBudget { bytes: number; verify?: (() => void)[]; verifyBytes?: number }
|
|
118
|
+
function retainVerification(budget: CopyBudget, path: string, stamp: string, verify: () => void): void {
|
|
119
|
+
budget.verify!.push(verify);
|
|
120
|
+
// Account for captured path/stamp strings and a conservative per-closure allowance in the provider's cache bound.
|
|
121
|
+
budget.verifyBytes = (budget.verifyBytes ?? 0) + 2 * (Buffer.byteLength(path) + Buffer.byteLength(stamp)) + 512;
|
|
122
|
+
}
|
|
109
123
|
function observedCopy(from: string, to: string, budget: CopyBudget): void {
|
|
110
124
|
budget.bytes += statSync(from).size; if (budget.bytes > COPY_LIMIT_BYTES) throw new TooBig();
|
|
125
|
+
let verifySource: (() => void) | undefined;
|
|
111
126
|
if (budget.verify) {
|
|
112
127
|
const stamp = () => { const s = lstatSync(from, { bigint: true }); if (!s.isFile()) throw Error("recap source is not a plain file"); return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`; };
|
|
113
|
-
const before = stamp();
|
|
128
|
+
const before = stamp(); verifySource = () => { let current: string; try { current = stamp(); } catch { throw Error("recap source changed"); } if (current !== before) throw Error("recap source changed"); };
|
|
129
|
+
retainVerification(budget, from, before, verifySource);
|
|
114
130
|
}
|
|
115
|
-
copyFileSync(from, to);
|
|
131
|
+
try { copyFileSync(from, to); } catch (error) { verifySource?.(); throw error; }
|
|
116
132
|
}
|
|
117
|
-
function observeDirectory(from: string, budget: CopyBudget, keep: (name: string) => boolean): void {
|
|
133
|
+
function observeDirectory(from: string, budget: CopyBudget, keep: (name: string) => boolean): (() => void) | undefined {
|
|
118
134
|
if (!budget.verify) return;
|
|
119
135
|
const stamp = () => { const s = lstatSync(from, { bigint: true }); if (!s.isDirectory()) throw Error("recap source directory changed"); return JSON.stringify([String(s.dev), String(s.ino), readdirSync(from).filter(keep).sort()]); };
|
|
120
|
-
const before = stamp()
|
|
136
|
+
const before = stamp(), verify = () => { let current: string; try { current = stamp(); } catch { throw Error("recap source directory changed"); } if (current !== before) throw Error("recap source directory changed"); };
|
|
137
|
+
retainVerification(budget, from, before, verify); return verify;
|
|
121
138
|
}
|
|
122
139
|
function copyTree(from: string, to: string, budget: CopyBudget, skipNames: ReadonlySet<string> = new Set()): void {
|
|
123
|
-
observeDirectory(from, budget, name => !(SKIP.test(name) && !(basename(from) === "public-prune-objects" && /^[a-f0-9]{40}\.git$/.test(name))) && !skipNames.has(name));
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
140
|
+
const verifyDirectory = observeDirectory(from, budget, name => !(SKIP.test(name) && !(basename(from) === "public-prune-objects" && /^[a-f0-9]{40}\.git$/.test(name))) && !skipNames.has(name));
|
|
141
|
+
try {
|
|
142
|
+
mkdirSync(to, { recursive: true, mode: 0o700 });
|
|
143
|
+
for (const name of readdirSync(from)) {
|
|
144
|
+
const proofObject = basename(from) === "public-prune-objects" && /^[a-f0-9]{40}\.git$/.exec(name)?.[0] === name;
|
|
145
|
+
if (SKIP.test(name) && !proofObject || skipNames.has(name)) continue;
|
|
146
|
+
const source = join(from, name), stat = lstatSync(source);
|
|
147
|
+
if (proofObject && !stat.isFile()) throw new Error("a public prune object is not a plain file");
|
|
148
|
+
if (stat.isSymbolicLink()) throw new Error("the memory home holds a link where a plain file or directory is expected");
|
|
149
|
+
if (stat.isDirectory()) copyTree(source, join(to, name), budget, skipNames);
|
|
150
|
+
else if (stat.isFile()) observedCopy(source, join(to, name), budget);
|
|
151
|
+
}
|
|
152
|
+
} catch (error) { verifyDirectory?.(); throw error; }
|
|
134
153
|
}
|
|
135
154
|
|
|
136
155
|
/** The curated side of the home, without any database: the logs of this project (and its aliases), and the small files that bind them. */
|
|
@@ -175,37 +194,47 @@ function copyWork(options: Pick<DoctorOptions, "home" | "project" | "aliases">,
|
|
|
175
194
|
}
|
|
176
195
|
|
|
177
196
|
/** Reuse doctor's bounded private inputs for an on-demand brief, never a live store or reader lease. */
|
|
178
|
-
export async function withBriefSnapshot<T>(home: string, project: string, read: (inputs: NonNullable<BriefOptions["measureOnly"]>) => Promise<T
|
|
197
|
+
export async function withBriefSnapshot<T>(home: string, project: string, read: (inputs: NonNullable<BriefOptions["measureOnly"]>) => Promise<T>, onValidated?: (validate: () => void, retries: number, verifyBytes: number) => void): Promise<T> {
|
|
179
198
|
const aliases = aliasedKeys(home, project), selection = readSelector(home).revision, layout = layoutOf(home), guard = guardScratch();
|
|
180
|
-
const budget: CopyBudget = { bytes: 0, verify: [] };
|
|
181
199
|
const inputDirectories = [join(home, "projects"), ...(layout === "split" ? [join(home, "user")] : [join(home, "log"), join(home, "local")]),
|
|
182
200
|
...(layout === "generation" ? [join(home, "generations")] : []),
|
|
183
201
|
...[project, ...aliases].flatMap(key => { const dir = shardDir(home, key); return [dir, join(dir, "work"), join(dir, "work", "log")]; })];
|
|
184
202
|
const checkDirectories = () => {
|
|
185
203
|
for (const dir of inputDirectories) { const stat = lstatSync(dir, { throwIfNoEntry: false }); if (stat && !stat.isDirectory()) throw Error("recap input is not a plain directory"); }
|
|
186
204
|
};
|
|
187
|
-
const check = () => {
|
|
205
|
+
const check = (budget: CopyBudget) => {
|
|
188
206
|
checkDirectories();
|
|
189
207
|
if (readSelector(home).revision !== selection || layoutOf(home) !== layout || JSON.stringify(aliasedKeys(home, project)) !== JSON.stringify(aliases)) throw Error("recap binding changed");
|
|
190
208
|
for (const verify of budget.verify!) verify();
|
|
191
209
|
};
|
|
192
210
|
try {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
let curated: MemoryStore | undefined;
|
|
211
|
+
for (let attempt = 0; attempt < RECAP_SNAPSHOT_ATTEMPTS; attempt++) {
|
|
212
|
+
const budget: CopyBudget = { bytes: 0, verify: [] };
|
|
196
213
|
try {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
214
|
+
checkDirectories();
|
|
215
|
+
return await withDoctorPlacementScratch(home, guard.adopt, async scratch => {
|
|
216
|
+
let curated: MemoryStore | undefined;
|
|
217
|
+
try {
|
|
218
|
+
const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
|
|
219
|
+
copyWork(options, workBase, budget);
|
|
220
|
+
if (curatedPresent(home, project, layout)) {
|
|
221
|
+
const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget);
|
|
222
|
+
curated = openCuratedForRead(copy, project);
|
|
223
|
+
if (!curated) throw Error("recap curated snapshot unavailable");
|
|
224
|
+
}
|
|
225
|
+
check(budget);
|
|
226
|
+
const result = await read({ ...(curated ? { curated } : {}), workBase });
|
|
227
|
+
check(budget);
|
|
228
|
+
onValidated?.(() => check(budget), attempt, budget.verifyBytes ?? 0);
|
|
229
|
+
return result;
|
|
230
|
+
} finally { curated?.close(); }
|
|
231
|
+
});
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (!(error instanceof Error) || !["recap source changed", "recap source directory changed"].includes(error.message)) throw error;
|
|
234
|
+
if (attempt + 1 === RECAP_SNAPSHOT_ATTEMPTS) throw new RecapSourceChangedError(error.message === "recap source directory changed");
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
throw Error("recap snapshot unavailable; retry Recap.");
|
|
209
238
|
} catch (error) {
|
|
210
239
|
if (error instanceof TooBig) throw Error("recap snapshot exceeds the 64 MiB copy limit");
|
|
211
240
|
throw error;
|
|
@@ -249,7 +278,7 @@ function duplicatesAndStale(options: DoctorOptions, rows: View[], store: MemoryS
|
|
|
249
278
|
if (!root) stale = skipped("run doctor from inside this project's repository to check its path references");
|
|
250
279
|
else {
|
|
251
280
|
const missing = rows.filter(row => { const paths = row.about.filter(node => node.startsWith("path:")).map(node => node.slice(5)); return paths.length > 0 && paths.every(path => !existsSync(join(root, path))); });
|
|
252
|
-
stale = { status: missing.length ? "attention" : "ok", checked: rows.length, missingReferences: missing.length, ...(missing.length ? { examples: ids(missing.map(row => row.id)) } : {}) };
|
|
281
|
+
stale = { status: missing.length ? "attention" : "ok", checked: rows.length, missingReferences: missing.length, ...(missing.length ? { examples: ids(missing.map(row => row.id)), hint: "The person can inspect these examples with amem show <id> from their own shell." } : {}) };
|
|
253
282
|
}
|
|
254
283
|
return { duplicates, stale };
|
|
255
284
|
}
|
|
@@ -280,36 +309,90 @@ function receiptPhase(home: string, cli: Cli): "applied" | "prepared" | null {
|
|
|
280
309
|
* Per CLI: is a capture hook registered, and when did it last capture. "Registered" is what the setup receipt says (`hookEvidence`): a hook the person removed by hand
|
|
281
310
|
* afterwards still shows as registered until `amem setup <cli> --apply` or `--undo` is run again. A CLI without a receipt is `manual`.
|
|
282
311
|
*/
|
|
312
|
+
type CaptureState = "fresh" | "stale" | "never";
|
|
313
|
+
type MachineState = CaptureState | "unknown";
|
|
314
|
+
type Tally = Map<string, { rows: number; last: string | null }>;
|
|
315
|
+
|
|
316
|
+
function tallyInto(seen: Tally, row: { agent: string; n: number; last: string | null }): void {
|
|
317
|
+
const prior = seen.get(row.agent);
|
|
318
|
+
seen.set(row.agent, { rows: (prior?.rows ?? 0) + row.n, last: prior?.last && prior.last > (row.last ?? "") ? prior.last : row.last });
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** This home's machine id from machine.json, read-only (doctor never creates the identity); undefined when absent or invalid. */
|
|
322
|
+
function localMachineId(home: string): string | undefined {
|
|
323
|
+
try {
|
|
324
|
+
const file = join(home, "machine.json"), stat = lstatSync(file);
|
|
325
|
+
if (!stat.isFile() || stat.size > 4096) return undefined;
|
|
326
|
+
const id = (JSON.parse(readFileSync(file, "utf8")) as { id?: unknown }).id;
|
|
327
|
+
return typeof id === "string" && /^[0-9a-f]{16}$/.test(id) ? id : undefined;
|
|
328
|
+
} catch { return undefined; }
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function stateOf(last: string | null, now: number): CaptureState {
|
|
332
|
+
return last === null ? "never" : now - Date.parse(last) > CAPTURE_STALE_MS ? "stale" : "fresh";
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* The one place a capture hint is chosen (#509 extends it). `trigger` names the state that raised it: the machine-wide one (#510), this project's one
|
|
337
|
+
* (the fallback when another shard could not be read), or a missing setup for a CLI that has never captured anywhere.
|
|
338
|
+
*/
|
|
339
|
+
function captureHint(cli: Cli, registered: boolean, state: CaptureState, trigger: "machine" | "project" | "setup", unsafeRoots: readonly NativeRootKind[] = []): string {
|
|
340
|
+
if (unsafeRoots.length) return `the ${cli} ${unsafeRoots.join(" and ")} root is an unsafe symlink and was skipped: use a directory inside HOME owned by this user without group or world write access, then rerun amem ingest ${cli}`;
|
|
341
|
+
if (trigger === "setup") return cli === "claude" ? "run amem setup claude --apply to register the capture hooks" : `run amem setup ${cli} --apply, or amem ingest ${cli} by hand`;
|
|
342
|
+
const where = trigger === "machine" ? "on this machine (all projects)" : "in this project (other projects could not be read)";
|
|
343
|
+
if (registered && cli === "codex" && state === "never") return `the codex hook is registered but has never captured ${where}: approve it in Codex's /hooks trust review (setup never grants hook trust), then open a session`;
|
|
344
|
+
return `the ${cli} ${registered ? "hook is registered but its capture" : "capture"} is ${state} ${where}: open a session${cli === "claude" ? "" : `, or run amem ingest ${cli}`}`;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Per CLI: this project's state (its shard and aliases, as before) and a machine-wide state over every shard's capture.db (#510).
|
|
349
|
+
* Both come from the same read-only aggregate in one walkShards pass; the machine-wide values are counts and times only, never another project's key, path or rows.
|
|
350
|
+
* An other-shard database that is busy, missing rows table or unreadable makes the machine-wide state `unknown` (not `never`) and is not an error.
|
|
351
|
+
*/
|
|
283
352
|
function captureSection(options: DoctorOptions): Section {
|
|
284
353
|
const keys = [options.project, ...options.aliases];
|
|
285
|
-
const
|
|
286
|
-
|
|
354
|
+
const here: Tally = new Map(), machine: Tally = new Map();
|
|
355
|
+
// Machine-wide means this machine: only capture directories named by this home's machine.json count, read without creating it.
|
|
356
|
+
// Another machine's synced rows must not mask a stale local CLI (#510 AC2). No readable identity: the machine-wide state is unknown.
|
|
357
|
+
const local = localMachineId(options.home);
|
|
358
|
+
let readable = true, othersUnreadable = local === undefined;
|
|
287
359
|
for (const shard of walkShards(options.home)) {
|
|
288
|
-
|
|
360
|
+
const own = keys.includes(shard.key);
|
|
289
361
|
for (const dir of shard.machineDirs) {
|
|
362
|
+
const thisMachine = local !== undefined && basename(dir) === local;
|
|
363
|
+
if (!own && !thisMachine) continue;
|
|
290
364
|
const file = join(dir, "capture.db");
|
|
291
365
|
if (!existsSync(file)) continue;
|
|
292
366
|
let db: Database | undefined;
|
|
293
367
|
try {
|
|
294
368
|
db = new Database(file, { readonly: true }); db.run("PRAGMA busy_timeout = 1000");
|
|
295
369
|
for (const row of db.query("SELECT agent, COUNT(*) AS n, MAX(at) AS last FROM rows GROUP BY agent").all() as { agent: string; n: number; last: string | null }[]) {
|
|
296
|
-
|
|
297
|
-
|
|
370
|
+
if (thisMachine) tallyInto(machine, row);
|
|
371
|
+
if (own) tallyInto(here, row);
|
|
298
372
|
}
|
|
299
|
-
} catch { readable = false; } finally { db?.close(); }
|
|
373
|
+
} catch { if (own) readable = false; if (thisMachine) othersUnreadable = true; } finally { db?.close(); }
|
|
300
374
|
}
|
|
301
375
|
}
|
|
302
376
|
const clis: Record<string, unknown> = {};
|
|
303
377
|
const attention: string[] = [];
|
|
304
378
|
for (const cli of CLIS) {
|
|
305
|
-
const phase = receiptPhase(options.home, cli), registered = phase === "applied", entry =
|
|
306
|
-
const last = entry?.last ?? null,
|
|
307
|
-
const
|
|
308
|
-
// A
|
|
309
|
-
const
|
|
379
|
+
const phase = receiptPhase(options.home, cli), registered = phase === "applied", entry = here.get(cli), wide = machine.get(cli);
|
|
380
|
+
const last = entry?.last ?? null, state = stateOf(last, options.now);
|
|
381
|
+
const wideLast = wide?.last ?? null, wideKnown = stateOf(wideLast, options.now);
|
|
382
|
+
// A fresh row anywhere is definitive; stale or never is only known when every other shard was read.
|
|
383
|
+
const machineState: MachineState = wideKnown === "fresh" || !othersUnreadable ? wideKnown : "unknown";
|
|
384
|
+
// Attention follows the machine-wide state (#510): a registered hook not fresh anywhere, or any CLI whose capture went stale everywhere.
|
|
385
|
+
// When that state is unknown, this project's state decides, as before. A CLI fresh elsewhere but absent here is reported, not flagged.
|
|
386
|
+
const decided: CaptureState = machineState === "unknown" ? state : machineState, trigger = machineState === "unknown" ? "project" : "machine";
|
|
387
|
+
const env = options.env ?? process.env;
|
|
388
|
+
const unsafeRoots = registered && (cli === "codex" || cli === "kimi" || cli === "pi")
|
|
389
|
+
? nativeRoots(cli, env).filter(root => inspectNativeRoot(root.folder, env.HOME?.trim() || undefined).state === "unsafe").map(root => root.kind) : [];
|
|
390
|
+
const needs = unsafeRoots.length > 0 || (registered ? decided !== "fresh" : decided === "stale");
|
|
310
391
|
if (needs) attention.push(cli);
|
|
392
|
+
const unusedHere = state !== "fresh" && machineState === "fresh";
|
|
393
|
+
const hint = needs ? captureHint(cli, registered, decided, trigger, unsafeRoots) : !registered && decided === "never" ? captureHint(cli, registered, decided, "setup") : undefined;
|
|
311
394
|
clis[cli] = { hook: registered ? "registered" : "manual", ...(registered ? { hookEvidence: "setup receipt" } : {}), ...(phase === "prepared" ? { setup: "prepared, not applied" } : {}), capture: state, lastCaptureAt: last, rows: entry?.rows ?? 0,
|
|
312
|
-
|
|
395
|
+
machineCapture: machineState, machineLastCaptureAt: wideLast, machineRows: wide?.rows ?? 0, ...(unusedHere ? { note: "not used in this project" } : {}), ...(hint ? { hint } : {}) };
|
|
313
396
|
}
|
|
314
397
|
return { status: !readable ? "unavailable" : attention.length ? "attention" : "ok", ...(readable ? {} : { reason: "a capture database could not be read" }), clis };
|
|
315
398
|
}
|
|
@@ -541,7 +624,7 @@ function sectionDetail(name: string, detail: Record<string, unknown>, s: Style):
|
|
|
541
624
|
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
542
625
|
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) => {
|
|
543
626
|
const capture = String(row.capture), mark = capture === "fresh" ? s.ok(capture) : capture === "stale" ? s.attention(capture) : s.dim(capture);
|
|
544
|
-
return `${cli.padEnd(7)} hook ${row.hook}${row.setup ? ` (${row.setup})` : ""}, capture ${mark}${row.lastCaptureAt ? ` (last ${row.lastCaptureAt})` : ""}, ${row.rows} rows`;
|
|
627
|
+
return `${cli.padEnd(7)} hook ${row.hook}${row.setup ? ` (${row.setup})` : ""}, capture ${mark}${row.lastCaptureAt ? ` (last ${row.lastCaptureAt})` : ""}, ${row.rows} rows; machine-wide ${row.machineCapture}${row.machineLastCaptureAt ? ` (last ${row.machineLastCaptureAt})` : ""}, ${row.machineRows} rows${row.note ? `, ${row.note}` : ""}`;
|
|
545
628
|
});
|
|
546
629
|
}
|
|
547
630
|
if (name === "cadence") {
|