@staix/agent-mem 0.29.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 -574
- package/package.json +3 -2
- package/src/cli-agent-reads.ts +17 -2
- package/src/cli.ts +178 -21
- package/src/commands-table.ts +14 -2
- package/src/index.ts +1 -0
- package/src/ingest.ts +7 -5
- package/src/mcp-memory.ts +36 -8
- package/src/memory/bridge.ts +26 -1
- package/src/memory/candidates.ts +17 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -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 +133 -47
- package/src/memory/eval-audit.ts +442 -0
- package/src/memory/eval.ts +66 -0
- package/src/memory/formats.ts +4 -3
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +173 -14
- 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-bridge.ts +18 -6
- package/src/memory/shard-migration.ts +14 -1
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +4 -0
- package/src/memory/store.ts +4 -2
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +14 -2
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +38 -11
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +129 -26
- package/src/memory/sync-placement-materialize.ts +33 -19
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +18 -1
- package/src/memory/sync-placement-realm-admission.ts +20 -3
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +207 -53
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +14 -0
- package/src/memory/sync-progress.ts +1 -1
- package/src/memory/sync.ts +5 -2
- 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/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +26 -11
- package/src/ui/snapshot-cache.ts +24 -11
package/src/mcp-memory.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { capacityReport } from "./memory/capacity.ts";
|
|
|
14
14
|
import { CaptureStore, type CaptureRow } from "./memory/capture.ts";
|
|
15
15
|
import { hashJSON, readSelector } from "./memory/generation.ts";
|
|
16
16
|
import { memoryHome } from "./memory/home.ts";
|
|
17
|
+
import { appendMetricsLater, createPeakTracker } from "./memory/metrics.ts";
|
|
17
18
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
18
19
|
import { createStandalonePolicy, type StandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
19
20
|
import { configuredPolicyOptions } from "./memory/config.ts";
|
|
@@ -341,17 +342,44 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
|
|
|
341
342
|
};
|
|
342
343
|
const exposed = { ...tools };
|
|
343
344
|
const readTools = ["amem_search", "amem_evidence", "amem_show", "amem_timeline", "amem_graph", "amem_brief", "amem_vault_candidates"] as const;
|
|
345
|
+
// #485: the process peak is monotonic, so a call can be credited with raising it only when no other read call was
|
|
346
|
+
// in flight while it grew; the tracker owns that rule and the observed baseline.
|
|
347
|
+
const peaks = createPeakTracker();
|
|
344
348
|
for (const name of readTools) exposed[name] = async args => {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
349
|
+
// #485: the sample measures the served span, so the clock and the peak window open at entry, before the guard, the
|
|
350
|
+
// policy snapshot and `beginRecallRead()` - whose preparation (an index refresh, a prune) the caller waits for.
|
|
351
|
+
const started = performance.now();
|
|
352
|
+
let window: ReturnType<typeof peaks.begin> | undefined;
|
|
353
|
+
try { window = peaks.begin(); } catch { /* telemetry is an observation, never a precondition */ }
|
|
354
|
+
// One bounded sample per completed call: the tool name, the wall time and the process peak. Never the arguments,
|
|
355
|
+
// the query text, an id or a result. It is handed off, not written: the response is queued first and the write is
|
|
356
|
+
// asynchronous, so telemetry can neither fail, refuse, delay nor block a completed call on disk.
|
|
357
|
+
const recorded = (): void => {
|
|
358
|
+
try {
|
|
359
|
+
const ended = window === undefined ? undefined : peaks.end(window);
|
|
360
|
+
window = undefined;
|
|
361
|
+
if (ended?.peakKB === undefined) return;
|
|
362
|
+
appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "search", tool: name, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised }]);
|
|
363
|
+
} catch { /* a lost telemetry sample is never a failed call */ }
|
|
364
|
+
};
|
|
365
|
+
try {
|
|
366
|
+
fullGuard();
|
|
367
|
+
const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
|
|
368
|
+
const sourceCurrent = store.beginRecallRead();
|
|
352
369
|
if (policyKey(policyOptions()) !== revision) return unavailable();
|
|
370
|
+
const result = await calls.run({ policy: snapshot, revision, configured }, async () => {
|
|
371
|
+
const value = await tools[name](args);
|
|
372
|
+
fullGuard(); sourceCurrent();
|
|
373
|
+
if (policyKey(policyOptions()) !== revision) return unavailable();
|
|
374
|
+
return value;
|
|
375
|
+
});
|
|
376
|
+
recorded();
|
|
353
377
|
return result;
|
|
354
|
-
})
|
|
378
|
+
} catch (error) {
|
|
379
|
+
// A refused or failed call records nothing, but the peak it may have raised still advances the baseline.
|
|
380
|
+
try { if (window !== undefined) peaks.abort(window); } catch { /* nothing recorded, nothing to correct */ }
|
|
381
|
+
throw error;
|
|
382
|
+
}
|
|
355
383
|
};
|
|
356
384
|
return { tools: exposed, close, onEmitted };
|
|
357
385
|
} catch (error) { close(); throw error; }
|
package/src/memory/bridge.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirS
|
|
|
4
4
|
import { basename, dirname, join } from "node:path";
|
|
5
5
|
import { isDeepStrictEqual } from "node:util";
|
|
6
6
|
import { memoryGitArgv, memoryGitEnv, realPath } from "./platform.ts";
|
|
7
|
+
import { drainSteps } from "./sync-placement-yield.ts";
|
|
7
8
|
import { canonicalJSON, fsyncDirectory, readProfileJSON, writeProfileJSON } from "./generation.ts";
|
|
8
9
|
import { OP_CONTRACTS } from "./ops-contract.ts";
|
|
9
10
|
import type { InspectionBound } from "./inspection-bound.ts";
|
|
@@ -193,10 +194,20 @@ export function* completeLines(bytes: Buffer): Generator<Buffer> {
|
|
|
193
194
|
|
|
194
195
|
/** Preserve original IDs; row order and JSON key order never produce duplicate evidence. */
|
|
195
196
|
export function legacyEntries(segments: readonly LegacySegment[], options: { strict?: boolean; onMalformed?: () => void } = {}): Entry[] {
|
|
197
|
+
return drainSteps(legacyEntrySteps(segments, options));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Rows between step boundaries: one row's own canonicalisation and id check is the floor of an uninterrupted stretch. */
|
|
201
|
+
const LEGACY_ENTRY_STEP_LINES = 512;
|
|
202
|
+
|
|
203
|
+
/** #462: the same validation, handing the caller's event loop back every few hundred rows instead of once per read. */
|
|
204
|
+
export function* legacyEntrySteps(segments: readonly LegacySegment[], options: { strict?: boolean; onMalformed?: () => void } = {}): Generator<void, Entry[], void> {
|
|
196
205
|
const rows = new Map<string, Entry>();
|
|
206
|
+
let stepped = 0;
|
|
197
207
|
for (const segment of segments) {
|
|
198
208
|
if (segment.bytes.length !== segment.offset || digest(segment.bytes) !== segment.hash || segment.offset && segment.bytes.at(-1) !== 10) failure();
|
|
199
209
|
for (const bytes of completeLines(segment.bytes)) {
|
|
210
|
+
if (++stepped >= LEGACY_ENTRY_STEP_LINES) { stepped = 0; yield; }
|
|
200
211
|
let row: Entry;
|
|
201
212
|
try {
|
|
202
213
|
let line: string;
|
|
@@ -225,6 +236,13 @@ function inspectArchivedSegment(inspect: LegacySegmentInspector, file: string, c
|
|
|
225
236
|
|
|
226
237
|
/** Raw authoritative inputs only: never constructs a legacy store, opens its index or performs network I/O. */
|
|
227
238
|
function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): LegacySegment[] {
|
|
239
|
+
return drainSteps(snapshotSteps(homeM, options, inspect));
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* #462: the same read, written once as steps so a caller that owns a collector yields between legacy segments instead of
|
|
243
|
+
* inside one call. Every fence, receipt check and row validation stays in the same order.
|
|
244
|
+
*/
|
|
245
|
+
function* snapshotSteps(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): Generator<void, LegacySegment[], void> {
|
|
228
246
|
const root = realPath(homeM);
|
|
229
247
|
directory(root);
|
|
230
248
|
if (inspect && (options.incremental || options.limits)) failure();
|
|
@@ -248,6 +266,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
|
|
|
248
266
|
const machineId = (machine as { id?: unknown } | undefined)?.id;
|
|
249
267
|
if (typeof machineId !== "string" || !/^[a-f0-9]{16}$/.test(machineId)) failure();
|
|
250
268
|
for (const folder of ["log", "local"]) {
|
|
269
|
+
yield;
|
|
251
270
|
const dir = join(root, folder);
|
|
252
271
|
if (!directory(dir, true)) continue;
|
|
253
272
|
for (const name of options.reader ? options.reader.listFiles(dir) : readdirSync(dir).sort()) {
|
|
@@ -255,6 +274,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
|
|
|
255
274
|
const path = `${folder}/${name}`;
|
|
256
275
|
if (!segmentPath(path)) failure();
|
|
257
276
|
if (folder === "local" && name !== `${machineId}.jsonl`) continue;
|
|
277
|
+
yield;
|
|
258
278
|
if (inspect) {
|
|
259
279
|
result.push(inspect(join(dir, name), { source: diskSource, path, local: folder === "local" }, checkpoints.get(`${diskSource}:${path}`)));
|
|
260
280
|
continue;
|
|
@@ -275,6 +295,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
|
|
|
275
295
|
directory(join(archiveDir(root, options.generation, commit), "log"));
|
|
276
296
|
for (const prior of new Set([...(options.previousCommit ? [options.previousCommit] : []), ...[...checkpoints.values()].filter(row => row.source === remoteSource).map(row => row.commit!)])) if (!archivedAncestor(root, options.generation, prior, commit, options.reader?.sourceByteLimit)) failure();
|
|
277
297
|
for (const segment of manifest.segments) {
|
|
298
|
+
yield;
|
|
278
299
|
if (inspect) {
|
|
279
300
|
result.push(inspectArchivedSegment(inspect, join(archiveDir(root, options.generation, commit), segment.path),
|
|
280
301
|
{ source: remoteSource, path: segment.path, local: false, commit }, checkpoints.get(`${remoteSource}:${segment.path}`), segment));
|
|
@@ -298,7 +319,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
|
|
|
298
319
|
const bytes = segment.bytes.subarray(Math.max(0, start - (segment.start ?? 0)));
|
|
299
320
|
return { ...segment, bytes, offset: bytes.length, hash: digest(bytes) };
|
|
300
321
|
});
|
|
301
|
-
|
|
322
|
+
yield* legacyEntrySteps(suffixes, { onMalformed: options.onMalformed });
|
|
302
323
|
return result;
|
|
303
324
|
}
|
|
304
325
|
|
|
@@ -350,6 +371,10 @@ function head(homeM: string, generation: string, maximumArchiveBytes?: number, m
|
|
|
350
371
|
export function readLegacySnapshot(homeM: string, options: LegacySnapshotOptions = {}): LegacySegment[] {
|
|
351
372
|
try { return snapshot(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
|
|
352
373
|
}
|
|
374
|
+
/** #462: the same snapshot as steps, so the transport's capture yields between legacy segments instead of inside one read. */
|
|
375
|
+
export function* legacySnapshotSteps(homeM: string, options: LegacySnapshotOptions = {}): Generator<void, LegacySegment[], void> {
|
|
376
|
+
try { return yield* snapshotSteps(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
|
|
377
|
+
}
|
|
353
378
|
/** Read-only enumeration reuses the legacy frontier checks without retaining source bodies or refreshing an index. */
|
|
354
379
|
export function inspectLegacySnapshot(homeM: string, options: LegacySnapshotOptions, inspect: LegacySegmentInspector): LegacySegment[] {
|
|
355
380
|
return snapshot(homeM, options, inspect);
|
package/src/memory/candidates.ts
CHANGED
|
@@ -27,6 +27,7 @@ export class ConsolidationReviewLimit extends Error {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
export const COUNTER_RETENTION = { count: 10_000, ageMs: 90 * 86400_000 } as const;
|
|
30
|
+
export const UNUSED_INJECTION_REASON = "Unused injection: frequent rendered or delivered notes have no reported citations in the review window.";
|
|
30
31
|
export type CandidateVerdict = "public" | "private" | "pii" | "unknown";
|
|
31
32
|
export interface CandidateTarget { id: string; revision: string }
|
|
32
33
|
/** One capture `Record` row a candidate was derived from: the session hash, its row time and the hash of the stored line. */
|
|
@@ -73,6 +74,7 @@ export interface CandidateAcceptance {
|
|
|
73
74
|
* prove the source, and accepting such a candidate refuses instead of writing memory from a row nobody verified.
|
|
74
75
|
*/
|
|
75
76
|
recordSource?: (project: string, binding: RecordSourceBinding) => "present" | "changed" | "missing";
|
|
77
|
+
unusedEligible?: (view: View) => boolean;
|
|
76
78
|
}
|
|
77
79
|
export interface CandidateAcceptanceResult { candidateId: string; noteId: string; alreadyAccepted: boolean }
|
|
78
80
|
|
|
@@ -436,7 +438,7 @@ export class CandidateStore {
|
|
|
436
438
|
if (candidate.status !== "pending") throw new Error("candidate is rejected or acceptance was interrupted; no automatic replay");
|
|
437
439
|
const data = candidate.input;
|
|
438
440
|
if (data.kind === "model-answer") throw Error("model answers cannot become curated memory; use amem note add to author an independent note");
|
|
439
|
-
if (data.kind === "decay")
|
|
441
|
+
if (data.kind === "decay") return this.acceptDecay(candidate, data, context);
|
|
440
442
|
if (data.kind === "promotion") return this.acceptPromotion(candidate, data, context);
|
|
441
443
|
if (data.kind === "consolidation") return this.acceptConsolidation(candidate, data, context);
|
|
442
444
|
// #368: a Record-derived candidate quotes capture rows. Absent proof, or a row that moved since the queue, refuses
|
|
@@ -490,6 +492,20 @@ export class CandidateStore {
|
|
|
490
492
|
if (!current || current.id !== target.id || candidateTargetRevision(current) !== target.revision) throw new Error("candidate target revision is stale");
|
|
491
493
|
return context.store.withCurrentEntries([target.id], context.project, execute);
|
|
492
494
|
}
|
|
495
|
+
private acceptDecay(candidate: Candidate, data: Extract<CandidateInput, { kind: "decay" }>, context: CandidateAcceptance): CandidateAcceptanceResult {
|
|
496
|
+
if (data.reason !== UNUSED_INJECTION_REASON || !context.unusedEligible) throw Error("decay candidates are listing-only unless proposed for unused injection; use amem decay to review current eligibility");
|
|
497
|
+
return context.store.withCurrentEntries([data.target.id], context.project, () => {
|
|
498
|
+
const target = context.store.get(data.target.id, context.project);
|
|
499
|
+
if (!target || target.tier !== "long" || target.kind === "preference" || target.supersededBy || candidateTargetRevision(target) !== data.target.revision || !context.unusedEligible!(target)) throw Error("decay candidate is no longer eligible; run amem decay --propose again");
|
|
500
|
+
const note: NoteInput = { op: "note", project: target.project, scope: target.scope, tier: target.tier, kind: target.kind, peer: target.peer, source: target.source as NoteInput["source"], about: target.about, text: target.text };
|
|
501
|
+
if (!context.policy(structuredClone(candidate), structuredClone(target), note)) throw Error("decay candidate refused by current policy; review the policy before accepting");
|
|
502
|
+
const replay = this.beginAcceptance(candidate.id, context.project); if (replay) return { candidateId: candidate.id, noteId: replay, alreadyAccepted: true };
|
|
503
|
+
// ponytail: the sidecar receipt and append are not atomic; interrupted acceptance requires inspection, not automatic replay.
|
|
504
|
+
if (!context.store.demote(target.id, context.actor, context.project)) throw Error("decay demotion outcome unavailable; inspect the accepting candidate");
|
|
505
|
+
this.db.query("UPDATE candidates SET status = 'accepted', note_id = ? WHERE id = ? AND project IN (SELECT value FROM json_each(?))").run(target.id, candidate.id, this.scope(context.project));
|
|
506
|
+
return { candidateId: candidate.id, noteId: target.id, alreadyAccepted: false };
|
|
507
|
+
});
|
|
508
|
+
}
|
|
493
509
|
private acceptConsolidation(candidate: Candidate, data: Extract<CandidateInput, { kind: "consolidation" }>, context: CandidateAcceptance): CandidateAcceptanceResult {
|
|
494
510
|
if (typeof context.policyVersion !== "function") throw Error("consolidation requires a policy revision guard");
|
|
495
511
|
const boundStore = context.store, boundProject = context.project, boundActor = context.actor, boundPolicy = context.policy;
|
package/src/memory/capacity.ts
CHANGED
|
@@ -212,8 +212,11 @@ export function capacityReport(opts: {
|
|
|
212
212
|
const samples = opts.inject?.metrics ?? readMetrics(base);
|
|
213
213
|
const hookWalls = samples.filter((s) => s.kind === "hook" && typeof s.wallMs === "number").map((s) => s.wallMs!);
|
|
214
214
|
const hookRss = samples.filter((s) => s.kind === "hook" && typeof s.rssMB === "number").map((s) => s.rssMB!);
|
|
215
|
-
|
|
216
|
-
|
|
215
|
+
// #485: every completed read-tool call appends a `search` sample carrying its tool name; R3's reading is `amem_search`'s.
|
|
216
|
+
// A sample without a tool name counts as a search reading, so a hand-written or pre-#485 sample is still read.
|
|
217
|
+
const searchSamples = samples.filter((s) => s.kind === "search" && (s.tool === undefined || s.tool === "amem_search"));
|
|
218
|
+
const searchWalls = searchSamples.filter((s) => typeof s.wallMs === "number").map((s) => s.wallMs!);
|
|
219
|
+
const searchRss = searchSamples.filter((s) => typeof s.rssMB === "number").map((s) => s.rssMB!);
|
|
217
220
|
const metrics = { samples: samples.length, hookP95Ms: p95(hookWalls), hookRssMB: p95(hookRss), searchP95Ms: p95(searchWalls), searchRssMB: p95(searchRss) };
|
|
218
221
|
|
|
219
222
|
const homeConfig = readCaptureConfigFile(join(base, "capture-config.json"));
|
package/src/memory/catalog.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { readProfileJSON, validGeneration } from "./generation.ts";
|
|
|
8
8
|
import { captureShardStats, readCaptureConfig } from "./capture.ts";
|
|
9
9
|
import { openShardStore } from "./store.ts";
|
|
10
10
|
import { lifecycleResolver, type LifecycleState } from "./lifecycle.ts";
|
|
11
|
+
import { placementSelectorRefusal } from "./sync-placement-guard.ts";
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* #15 D3 (storage part only): the user-level catalog of project shards. `catalog.db` in the memory home is derived
|
|
@@ -35,7 +36,15 @@ const fromRow = (r: CatalogRow): CatalogProject => ({ hash: r.hash, key: r.key,
|
|
|
35
36
|
|
|
36
37
|
/** Interrupted splits expose capture facts, but cannot authorize any curated store open or initialization. */
|
|
37
38
|
function capturedSelection(base: string): boolean {
|
|
38
|
-
|
|
39
|
+
let value: { schema?: unknown; generation?: unknown; phase?: unknown; selectorRevision?: unknown } | undefined, shardError: unknown;
|
|
40
|
+
try { value = readProfileJSON(join(base, "shards.json")) as typeof value; } catch (error) { shardError = error; }
|
|
41
|
+
let profile: { schema?: unknown } | undefined;
|
|
42
|
+
try { profile = readProfileJSON(join(base, "profile.json")) as typeof profile; } catch { /* Legacy selector diagnostics remain with their original reader. */ }
|
|
43
|
+
if (value?.schema === "agent-mem.shards/v3" || profile?.schema === "agent-mem.profile/v3") {
|
|
44
|
+
const refusal = placementSelectorRefusal(base); if (refusal) throw new Error(refusal);
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
if (shardError !== undefined) throw shardError;
|
|
39
48
|
if (value === undefined) return false;
|
|
40
49
|
if (!value || (value.schema !== SHARDED_SCHEMA && value.schema !== SHARDED_V2_SCHEMA) || !validGeneration(value.generation) || (value.phase !== "captured" && value.phase !== "active") || typeof value.selectorRevision !== "string") throw new Error("curated shard selection is unavailable or invalid");
|
|
41
50
|
return value.phase === "captured";
|
package/src/memory/commands.ts
CHANGED
|
@@ -176,7 +176,8 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
176
176
|
case "show": {
|
|
177
177
|
const asOf = flag("--as-of"), history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
|
|
178
178
|
const id = rest[0] ?? fail(`usage: ${names.memory} show <id>`), shown = recallShow(store, project, id, { person: opts.person, history, asOf });
|
|
179
|
-
if (!shown.ids.length) return fail(`no memory entry ${id} (${names.memory} list shows the ids)`);
|
|
179
|
+
if (!shown.ids.length) return cliAttribution()?.actor === "agent" ? fail("Memory operation unavailable or refused; no partial result is shown.") : fail(`no memory entry ${id} (${names.memory} list shows the ids)`);
|
|
180
|
+
if (cliAttribution()?.actor === "agent" && (!shown.entry || !opts.readable([shown.entry]).some(view => view.id === shown.entry!.id))) fail("Memory operation unavailable or refused; no partial result is shown.");
|
|
180
181
|
if (shown.state) {
|
|
181
182
|
const rows = opts.readable(shown.state.views), ids = new Set(rows.map(view => view.id)); ready(rows);
|
|
182
183
|
const state = { ...recallForViews(shown.state, rows), views: rows.map(decorated), relations: shown.state.relations.filter(edge => ids.has(edge.from) && ids.has(edge.to)) };
|
package/src/memory/config.ts
CHANGED
|
@@ -17,10 +17,11 @@ export const CONFIG_FILE = "amem.config.json";
|
|
|
17
17
|
export const REPO_CONFIG_DIR = ".amem";
|
|
18
18
|
export const REPO_CONFIG_FILE = "config";
|
|
19
19
|
const MAX_CONFIG_BYTES = 64 * 1024;
|
|
20
|
-
const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records", "privateRemotes"] as const;
|
|
20
|
+
const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records", "privateRemotes", "review"] as const;
|
|
21
21
|
const REPO_KEYS = ["denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "records"] as const;
|
|
22
22
|
|
|
23
23
|
export interface AmemConfig {
|
|
24
|
+
review?: { recheck_days?: number; unused_rendered?: number; unused_days?: number };
|
|
24
25
|
/** Static SessionStart record instruction; absent means enabled. Repository false only narrows. */
|
|
25
26
|
records?: boolean;
|
|
26
27
|
/** The memory home, when the file moves it (a pointer file: see `configuredHome`). `AMEM_HOME` still wins. Machine file only. */
|
|
@@ -111,6 +112,16 @@ function parseFile(raw: unknown, label: string, keys: readonly string[]): Partia
|
|
|
111
112
|
if (capMb !== undefined) out.capture.capMb = capMb;
|
|
112
113
|
if (retentionDays !== undefined) out.capture.retentionDays = retentionDays;
|
|
113
114
|
}
|
|
115
|
+
if (body.review !== undefined) {
|
|
116
|
+
if (!body.review || typeof body.review !== "object" || Array.isArray(body.review) || Object.keys(body.review).some(key => !["recheck_days", "unused_rendered", "unused_days"].includes(key))) return fail(label, "review takes only recheck_days, unused_rendered and unused_days");
|
|
117
|
+
const rawReview = body.review as Record<string, unknown>;
|
|
118
|
+
const review: NonNullable<AmemConfig["review"]> = {};
|
|
119
|
+
for (const key of ["recheck_days", "unused_rendered", "unused_days"] as const) {
|
|
120
|
+
const value = countOf(rawReview[key], `review.${key}`, label, key === "unused_rendered" ? 1_000_000 : key === "unused_days" ? 90 : 36_500);
|
|
121
|
+
if (value !== undefined) review[key] = value;
|
|
122
|
+
}
|
|
123
|
+
out.review = review;
|
|
124
|
+
}
|
|
114
125
|
return out;
|
|
115
126
|
}
|
|
116
127
|
|
|
@@ -163,6 +174,7 @@ export function loadAmemConfig(base: string, repoRoot?: string): LoadedConfig {
|
|
|
163
174
|
if (denyPaths.length > 64) fail(machinePath, "denyPaths and the repository's denyPaths name more than 64 entries together");
|
|
164
175
|
if (piiPatterns.length > 64) fail(machinePath, "piiPatterns and the repository's piiPatterns name more than 64 entries together");
|
|
165
176
|
const config: AmemConfig = { denyPaths, piiPatterns, capture: { ...(machine?.capture ?? {}) } };
|
|
177
|
+
if (machine?.review !== undefined) config.review = { ...machine.review };
|
|
166
178
|
if (machine?.home !== undefined) config.home = machine.home;
|
|
167
179
|
if (machine?.privateRemotes?.length) config.privateRemotes = machine.privateRemotes;
|
|
168
180
|
if (machine?.records !== undefined || repo?.records !== undefined) config.records = machine?.records !== false && repo?.records !== false;
|
|
@@ -3,7 +3,27 @@ import { lstatSync } from "node:fs";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { hashJSON } from "./generation.ts";
|
|
5
5
|
import { candidateTargetRevision, type CandidateTarget, type Counter } from "./candidates.ts";
|
|
6
|
+
export { UNUSED_INJECTION_REASON } from "./candidates.ts";
|
|
6
7
|
import { MemoryStore, type View } from "./store.ts";
|
|
8
|
+
import { reviewUse, type ReviewSnapshot } from "./review-targets.ts";
|
|
9
|
+
|
|
10
|
+
/** Select proposals only; caller must explicitly queue and accept them. */
|
|
11
|
+
export function unusedInjectionTargets(store: MemoryStore, project: string, snapshot: ReviewSnapshot, options: { now: number; days: number; threshold: number; aliases?: readonly string[]; screen?: (view: View) => boolean; id?: string; exclude?: (target: CandidateTarget) => boolean }): DecayEntry[] {
|
|
12
|
+
const goals = store.goals(project).filter(goal => ["open", "active", "blocked"].includes(goal.state));
|
|
13
|
+
const tasks = new Set(goals.flatMap(goal => goal.links.map(link => link.task))), goalNodes = new Set(goals.map(goal => `goal:${goal.id}`));
|
|
14
|
+
const since = options.now - options.days * 86400_000;
|
|
15
|
+
return store.withDeferredPromotions(() => {
|
|
16
|
+
const rows = options.id ? [store.get(options.id, project)].filter((view): view is View => view !== undefined) : store.list({ project, tier: "long", limit: DECAY_SCAN_LIMIT + 1 });
|
|
17
|
+
if (rows.length > DECAY_SCAN_LIMIT) throw Error("unused-injection scan exceeds 5000 notes; narrow the project before retrying");
|
|
18
|
+
return rows.flatMap(view => {
|
|
19
|
+
if (view.project !== project || view.kind === "preference" || view.supersededBy || view.task && tasks.has(view.task) || view.about.some(node => goalNodes.has(node) || node.startsWith("task:") && tasks.has(node.slice(5))) || options.screen && !options.screen(view)) return [];
|
|
20
|
+
const counts = reviewUse(snapshot, [project, ...options.aliases ?? []], view.id, since);
|
|
21
|
+
if (counts.delivered === null || counts.cited === null || counts.cited !== 0 || Math.max(counts.rendered ?? 0, counts.delivered) < options.threshold) return [];
|
|
22
|
+
const target = { id: view.id, revision: candidateTargetRevision(view) };
|
|
23
|
+
return options.exclude?.(target) ? [] : [{ target, view }];
|
|
24
|
+
}).slice(0, DECAY_PREVIEW_LIMIT);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
7
27
|
|
|
8
28
|
export const DECAY_DEFAULT_DAYS = 90, DECAY_PREVIEW_LIMIT = 64, DECAY_SCAN_LIMIT = 5000;
|
|
9
29
|
export interface DecayEntry { target: CandidateTarget; view: View }
|
package/src/memory/doctor.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { placementRuntimeRefusal, withDoctorPlacementScratch } from "./sync-placement-guard.ts";
|
|
2
|
-
import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync,
|
|
2
|
+
import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
3
3
|
import { indexFileName } from "./index-file.ts";
|
|
4
4
|
import { assertFormatFloor } from "./formats.ts";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -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,39 +194,52 @@ 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
|
-
let scratch: string | undefined, curated: MemoryStore | undefined;
|
|
181
|
-
const budget: CopyBudget = { bytes: 0, verify: [] };
|
|
182
199
|
const inputDirectories = [join(home, "projects"), ...(layout === "split" ? [join(home, "user")] : [join(home, "log"), join(home, "local")]),
|
|
183
200
|
...(layout === "generation" ? [join(home, "generations")] : []),
|
|
184
201
|
...[project, ...aliases].flatMap(key => { const dir = shardDir(home, key); return [dir, join(dir, "work"), join(dir, "work", "log")]; })];
|
|
185
202
|
const checkDirectories = () => {
|
|
186
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"); }
|
|
187
204
|
};
|
|
188
|
-
const check = () => {
|
|
205
|
+
const check = (budget: CopyBudget) => {
|
|
189
206
|
checkDirectories();
|
|
190
207
|
if (readSelector(home).revision !== selection || layoutOf(home) !== layout || JSON.stringify(aliasedKeys(home, project)) !== JSON.stringify(aliases)) throw Error("recap binding changed");
|
|
191
208
|
for (const verify of budget.verify!) verify();
|
|
192
209
|
};
|
|
193
210
|
try {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
211
|
+
for (let attempt = 0; attempt < RECAP_SNAPSHOT_ATTEMPTS; attempt++) {
|
|
212
|
+
const budget: CopyBudget = { bytes: 0, verify: [] };
|
|
213
|
+
try {
|
|
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
|
+
}
|
|
202
236
|
}
|
|
203
|
-
|
|
204
|
-
const result = await read({ ...(curated ? { curated } : {}), workBase });
|
|
205
|
-
check(); return result;
|
|
237
|
+
throw Error("recap snapshot unavailable; retry Recap.");
|
|
206
238
|
} catch (error) {
|
|
207
239
|
if (error instanceof TooBig) throw Error("recap snapshot exceeds the 64 MiB copy limit");
|
|
208
240
|
throw error;
|
|
209
241
|
} finally {
|
|
210
|
-
|
|
242
|
+
guard.release();
|
|
211
243
|
}
|
|
212
244
|
}
|
|
213
245
|
|
|
@@ -246,7 +278,7 @@ function duplicatesAndStale(options: DoctorOptions, rows: View[], store: MemoryS
|
|
|
246
278
|
if (!root) stale = skipped("run doctor from inside this project's repository to check its path references");
|
|
247
279
|
else {
|
|
248
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))); });
|
|
249
|
-
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." } : {}) };
|
|
250
282
|
}
|
|
251
283
|
return { duplicates, stale };
|
|
252
284
|
}
|
|
@@ -277,36 +309,90 @@ function receiptPhase(home: string, cli: Cli): "applied" | "prepared" | null {
|
|
|
277
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
|
|
278
310
|
* afterwards still shows as registered until `amem setup <cli> --apply` or `--undo` is run again. A CLI without a receipt is `manual`.
|
|
279
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
|
+
*/
|
|
280
352
|
function captureSection(options: DoctorOptions): Section {
|
|
281
353
|
const keys = [options.project, ...options.aliases];
|
|
282
|
-
const
|
|
283
|
-
|
|
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;
|
|
284
359
|
for (const shard of walkShards(options.home)) {
|
|
285
|
-
|
|
360
|
+
const own = keys.includes(shard.key);
|
|
286
361
|
for (const dir of shard.machineDirs) {
|
|
362
|
+
const thisMachine = local !== undefined && basename(dir) === local;
|
|
363
|
+
if (!own && !thisMachine) continue;
|
|
287
364
|
const file = join(dir, "capture.db");
|
|
288
365
|
if (!existsSync(file)) continue;
|
|
289
366
|
let db: Database | undefined;
|
|
290
367
|
try {
|
|
291
368
|
db = new Database(file, { readonly: true }); db.run("PRAGMA busy_timeout = 1000");
|
|
292
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 }[]) {
|
|
293
|
-
|
|
294
|
-
|
|
370
|
+
if (thisMachine) tallyInto(machine, row);
|
|
371
|
+
if (own) tallyInto(here, row);
|
|
295
372
|
}
|
|
296
|
-
} catch { readable = false; } finally { db?.close(); }
|
|
373
|
+
} catch { if (own) readable = false; if (thisMachine) othersUnreadable = true; } finally { db?.close(); }
|
|
297
374
|
}
|
|
298
375
|
}
|
|
299
376
|
const clis: Record<string, unknown> = {};
|
|
300
377
|
const attention: string[] = [];
|
|
301
378
|
for (const cli of CLIS) {
|
|
302
|
-
const phase = receiptPhase(options.home, cli), registered = phase === "applied", entry =
|
|
303
|
-
const last = entry?.last ?? null,
|
|
304
|
-
const
|
|
305
|
-
// A
|
|
306
|
-
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");
|
|
307
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;
|
|
308
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,
|
|
309
|
-
|
|
395
|
+
machineCapture: machineState, machineLastCaptureAt: wideLast, machineRows: wide?.rows ?? 0, ...(unusedHere ? { note: "not used in this project" } : {}), ...(hint ? { hint } : {}) };
|
|
310
396
|
}
|
|
311
397
|
return { status: !readable ? "unavailable" : attention.length ? "attention" : "ok", ...(readable ? {} : { reason: "a capture database could not be read" }), clis };
|
|
312
398
|
}
|
|
@@ -538,7 +624,7 @@ function sectionDetail(name: string, detail: Record<string, unknown>, s: Style):
|
|
|
538
624
|
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
539
625
|
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) => {
|
|
540
626
|
const capture = String(row.capture), mark = capture === "fresh" ? s.ok(capture) : capture === "stale" ? s.attention(capture) : s.dim(capture);
|
|
541
|
-
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}` : ""}`;
|
|
542
628
|
});
|
|
543
629
|
}
|
|
544
630
|
if (name === "cadence") {
|