@staix/agent-mem 0.37.0 → 0.38.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 +1 -1
- package/package.json +1 -1
- package/src/cli-agent-reads.ts +54 -4
- package/src/cli.ts +166 -69
- package/src/commands-table.ts +332 -171
- package/src/memory/capacity.ts +40 -4
- package/src/memory/commands.ts +39 -8
- package/src/memory/doctor.ts +106 -51
- package/src/memory/eval-audit.ts +26 -2
- package/src/memory/eval.ts +17 -2
- package/src/memory/gc.ts +14 -1
- package/src/memory/report-text.ts +231 -0
- package/src/memory/status-text.ts +72 -29
- package/src/memory/style.ts +98 -1
- package/src/setup.ts +119 -43
package/src/memory/capacity.ts
CHANGED
|
@@ -8,7 +8,10 @@ export { appendMetrics, readMetrics, metricsPath, type MetricSample } from "./me
|
|
|
8
8
|
import { walkShards } from "./catalog.ts";
|
|
9
9
|
import { lifecycleResolver } from "./lifecycle.ts";
|
|
10
10
|
import { captureShardGrowth, captureShardStats, readCaptureConfigFile, CAPTURE_DEFAULT_CAP_MB, CAPTURE_DEFAULT_RETENTION_DAYS, type CaptureConfig } from "./capture.ts";
|
|
11
|
-
import { facts, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
11
|
+
import { facts, humanBytes, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
12
|
+
import { Report } from "@staix/cli-output";
|
|
13
|
+
|
|
14
|
+
interface CapacityRender { columns?: number; style?: Style; next?: string }
|
|
12
15
|
|
|
13
16
|
/**
|
|
14
17
|
* #13 R7: the capacity advisor. `capacityReport()` reads this machine's load and proposes capture bounds; the
|
|
@@ -274,7 +277,18 @@ export function capacityReport(opts: {
|
|
|
274
277
|
}
|
|
275
278
|
|
|
276
279
|
/** The non-JSON rendering of `amem capacity`. */
|
|
277
|
-
export function capacityText(report: CapacityReport): string {
|
|
280
|
+
export function capacityText(report: CapacityReport, render?: CapacityRender): string {
|
|
281
|
+
if (render) {
|
|
282
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
283
|
+
out.header("amem", "Capacity"); out.section("Capture");
|
|
284
|
+
out.kv([["Rows", String(report.capture.rows)], ["Size", humanBytes(report.capture.bytes)], ["Shards", String(report.capture.shards)], ["Growth", `${report.capture.rowsPerDay.toFixed(1)} rows/day, ${humanBytes(report.capture.bytesPerDay)}/day`]]);
|
|
285
|
+
out.section("Resources"); out.kv([["Disk", `${humanBytes(report.disk.freeBytes)} free of ${humanBytes(report.disk.totalBytes)}`], ["Memory", `${humanBytes(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`], ["Samples", String(report.metrics.samples)], ["Hook p95", report.metrics.hookP95Ms === null ? "?" : `${report.metrics.hookP95Ms.toFixed(1)} ms`], ["Search peak", report.metrics.searchRssMB === null ? "?" : `${report.metrics.searchRssMB.toFixed(1)} MiB`], ...(report.metrics.mcpPhasePeak ? [["MCP phase peak", `${report.metrics.mcpPhasePeak.phase}: ${report.metrics.mcpPhasePeak.rssMB.toFixed(1)} MiB (${report.metrics.mcpPhasePeak.shared ? "shared peak" : report.metrics.mcpPhasePeak.peakRaised ? "peak raised" : "not attributed"})`] as [string, string]] : [])]);
|
|
286
|
+
out.section("Proposal"); out.kv([["Projected", `${humanBytes(report.projected.bytes)} in ${report.projected.days} days`], ["Current", `${report.current.capMb} MiB, ${report.current.retentionDays} days`], ["Proposed", `${report.proposal.capMb} MiB, ${report.proposal.retentionDays} days`], ["Reason", report.proposal.reason]]);
|
|
287
|
+
if (report.splitRefused) out.bullet("warn", `Split unavailable: ${report.splitRefused}`);
|
|
288
|
+
if (report.split.length) { out.section("Shard proposals", String(report.split.length)); out.table(["PROJECT", "CAP", "RETENTION", "REASON"], report.split.map(row => [row.key, `${row.capMb} MiB`, `${row.retentionDays} days`, row.reason]), 3); out.next("amem capacity apply --split"); }
|
|
289
|
+
out.line(""); out.line(`Summary: 1 capacity proposal, ${report.split.length} shard proposals`);
|
|
290
|
+
return out.render(s.color).join("\n");
|
|
291
|
+
}
|
|
278
292
|
const mb = (n: number): string => `${(n / MB).toFixed(1)} MB`;
|
|
279
293
|
return [
|
|
280
294
|
`capture: ${report.capture.rows} rows, ${mb(report.capture.bytes)} in ${report.capture.shards} shard(s), +${report.capture.rowsPerDay.toFixed(1)} rows/day, +${mb(report.capture.bytesPerDay)}/day`,
|
|
@@ -294,8 +308,16 @@ export function capacityApplyText(result: {
|
|
|
294
308
|
preview: { file: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string };
|
|
295
309
|
confirm?: string;
|
|
296
310
|
written?: { cap_mb?: number; retention_days?: number };
|
|
297
|
-
}, s: Style = PLAIN): string {
|
|
311
|
+
}, s: Style = PLAIN, render?: CapacityRender): string {
|
|
298
312
|
const applied = result.written !== undefined;
|
|
313
|
+
if (render) {
|
|
314
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
315
|
+
out.header("amem", "Capacity apply"); out.section(applied ? "Applied" : "Preview");
|
|
316
|
+
out.bullet(applied ? "ok" : "pending", applied ? "Capacity settings written." : "Capacity settings are ready for review.");
|
|
317
|
+
out.kv([["File", result.preview.file], ["Current", result.preview.current.capMb === undefined && result.preview.current.retentionDays === undefined ? "defaults" : `${result.preview.current.capMb ?? "?"} MiB, ${result.preview.current.retentionDays ?? "?"} days`], ["Proposed", `${result.preview.target.capMb} MiB, ${result.preview.target.retentionDays} days`], ["Reason", result.preview.reason], ...(result.written ? [["Written", `${result.written.cap_mb ?? "?"} MiB, ${result.written.retention_days ?? "?"} days`] as [string, string]] : [])]);
|
|
318
|
+
if (!applied && render.next) out.next(render.next);
|
|
319
|
+
return out.render(s.color).join("\n");
|
|
320
|
+
}
|
|
299
321
|
return [
|
|
300
322
|
`amem capacity apply: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
301
323
|
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(result.preview.file)}`,
|
|
@@ -311,9 +333,23 @@ export function capacityApplyText(result: {
|
|
|
311
333
|
export function capacitySplitText(result:
|
|
312
334
|
| { at: number; split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; skipped: string[]; confirm: string }
|
|
313
335
|
| { split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; written: { key: string; cap_mb: number; retention_days: number }[] },
|
|
314
|
-
s: Style = PLAIN,
|
|
336
|
+
s: Style = PLAIN, render?: CapacityRender,
|
|
315
337
|
): string {
|
|
316
338
|
const applied = "written" in result;
|
|
339
|
+
if (render) {
|
|
340
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
341
|
+
out.header("amem", "Capacity split"); out.section(applied ? "Applied" : "Preview");
|
|
342
|
+
out.bullet(applied ? "ok" : "pending", applied ? "Shard settings written." : "Shard settings are ready for review.");
|
|
343
|
+
if (!result.split.length) out.note("No shard settings to change.");
|
|
344
|
+
for (const row of result.split) {
|
|
345
|
+
const written = "written" in result ? result.written.find(item => item.key === row.key) : undefined;
|
|
346
|
+
out.section("Shard");
|
|
347
|
+
out.kv([["Project", row.key], ["File", row.dir], ["Current", row.current.capMb === undefined && row.current.retentionDays === undefined ? "defaults" : `${row.current.capMb ?? "?"} MiB, ${row.current.retentionDays ?? "?"} days`], ["Proposed", `${row.target.capMb} MiB, ${row.target.retentionDays} days`], ["Reason", row.reason], ...(written ? [["Written", `${written.cap_mb ?? "?"} MiB, ${written.retention_days ?? "?"} days`] as [string, string]] : [])]);
|
|
348
|
+
}
|
|
349
|
+
if ("skipped" in result) for (const key of result.skipped) out.bullet("absent", `${key}: no local shard config to write`);
|
|
350
|
+
if (!applied && result.split.length && render.next) out.next(render.next);
|
|
351
|
+
return out.render(s.color).join("\n");
|
|
352
|
+
}
|
|
317
353
|
const rows = result.split.map(row => [
|
|
318
354
|
`${label(s, applied ? "ok" : "attention")} shard: ${singleLine(row.key)}`,
|
|
319
355
|
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(row.dir)}`,
|
package/src/memory/commands.ts
CHANGED
|
@@ -2,7 +2,9 @@ import { cliAttribution, noteDisplayActor } from "./cli-attribution.ts";
|
|
|
2
2
|
import { extractNodes, GOAL_STATES, KINDS, MemoryStore, setMachineLabel, type GoalState, type GoalView, type Kind, type Tier, type View } from "./store.ts";
|
|
3
3
|
import { syncMemory, type SyncOptions } from "./sync.ts";
|
|
4
4
|
import { importClaudeMem, type ImportResult, type WorkStateImportResult, type CaptureImportResult } from "./import.ts";
|
|
5
|
-
import {
|
|
5
|
+
import { syncReportText } from "./report-text.ts";
|
|
6
|
+
import { CLI_MEMORY_RENDER, facts, label, memoryDetailText, memoryScoresText, memoryTableText, PLAIN, relativeTime, singleLine, type HumanMemoryRender, type Style } from "./style.ts";
|
|
7
|
+
import { Report } from "@staix/cli-output";
|
|
6
8
|
import { memoryProjectKey, projectChain } from "./project.ts";
|
|
7
9
|
import { recallForViews, recallGraph, recallRows, recallShow } from "./recall.ts";
|
|
8
10
|
import type { GoalPromotionReport } from "./goal-promotion.ts";
|
|
@@ -71,13 +73,26 @@ const fail = (message: string): never => { throw new Error(message); };
|
|
|
71
73
|
|
|
72
74
|
/** A person-facing aggregate receipt; import results and their JSON representation stay untouched. */
|
|
73
75
|
export function claudeMemImportText(notes: ImportResult, work: WorkStateImportResult, capture?: CaptureImportResult,
|
|
74
|
-
options: { captureDays?: number; restart?: boolean } = {}, s: Style = PLAIN): string {
|
|
76
|
+
options: { captureDays?: number; restart?: boolean } = {}, s: Style = PLAIN, render?: { columns?: number; next?: string }): string {
|
|
75
77
|
const more = notes.more || work.more || capture?.more === true;
|
|
76
78
|
const row = (name: string, result: { read: number; added: number; more: boolean }, skipped: number, spooled?: number) =>
|
|
77
79
|
`${label(s, result.more || (spooled ?? 0) > 0 ? "attention" : "ok")} ${name}: ${facts({ read: String(result.read), added: String(result.added), skipped: String(skipped), spooled: spooled === undefined ? "n/a" : String(spooled) })}${result.more ? "; more remain" : ""}`;
|
|
78
80
|
const noteSkipped = notes.read - notes.added, workSkipped = work.read - work.added;
|
|
79
81
|
const otherNotes = Math.max(0, noteSkipped - notes.skipped.model - notes.skipped.pii - notes.skipped.secret);
|
|
80
82
|
const duplicateWork = Math.max(0, workSkipped - work.skipped.invalid - work.skipped.policy);
|
|
83
|
+
if (render) {
|
|
84
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
85
|
+
out.header("amem", "Import claude-mem"); out.section("Receipts");
|
|
86
|
+
out.bullet(more || capture?.spooled ? "warn" : "ok", more ? "More rows remain to import." : capture?.spooled ? "Import completed; capture rows are spooled." : "Import completed.");
|
|
87
|
+
out.kv([["Notes", `read ${notes.read}, added ${notes.added}, skipped ${noteSkipped}${notes.more ? "; more remain" : ""}`], ["Note skips", `model ${notes.skipped.model}, personal data ${notes.skipped.pii}, secret ${notes.skipped.secret}, other ${otherNotes}`], ["Work lists", `read ${work.read}, added ${work.added}, skipped ${workSkipped}${work.more ? "; more remain" : ""}`], ["Work skips", `invalid ${work.skipped.invalid}, policy ${work.skipped.policy}, already imported ${duplicateWork}`], ["Capture", capture ? `read ${capture.read}, added ${capture.added}, skipped ${capture.skipped}, spooled ${capture.spooled}${capture.more ? "; more remain" : ""}` : "not requested"]]);
|
|
88
|
+
if (capture?.skipped) out.note(`Capture skipped ${capture.skipped} rows (empty, invalid, policy or already imported; no breakdown reported).`);
|
|
89
|
+
if (capture && options.captureDays !== undefined) out.note(`Capture window: last ${options.captureDays} days. Widening --capture-days later requires --restart.`);
|
|
90
|
+
if (options.restart) out.note("Selected cursors replayed from the start; existing receipts prevent duplicates.");
|
|
91
|
+
if (more && render.next) out.next(render.next);
|
|
92
|
+
else if (more) out.bullet("warn", "Some rows remain; inspect --json and rerun without --restart.");
|
|
93
|
+
else if (capture?.spooled) out.note("The next capture write replays rows spooled while the store was busy.");
|
|
94
|
+
return out.render(s.color).join("\n");
|
|
95
|
+
}
|
|
81
96
|
const lines = [`amem import claude-mem: ${more ? s.attention("run again") : s.ok("complete")}`,
|
|
82
97
|
row("notes", notes, noteSkipped),
|
|
83
98
|
` skipped reasons: ${facts({ model: notes.skipped.model, PII: notes.skipped.pii, secret: notes.skipped.secret, "empty/malformed/already imported": otherNotes }) || "none"}`,
|
|
@@ -98,12 +113,15 @@ export function claudeMemImportText(notes: ImportResult, work: WorkStateImportRe
|
|
|
98
113
|
}
|
|
99
114
|
|
|
100
115
|
const one = (v: View) => `${v.id.slice(0, 8)} ${v.at.slice(0, 16).replace("T", " ")} ${v.tier.padEnd(5)} ${v.kind.padEnd(8)} ${v.peer.padEnd(8)} ${v.scope === "shared" ? "shared " : ""}${`${v.title ? `${v.title}: ` : ""}${v.text}`.replace(/\s+/g, " ").slice(0, 100)}${v.supersededBy ? ` (superseded by ${v.supersededBy.slice(0, 8)})` : ""}`;
|
|
116
|
+
|
|
101
117
|
function detail(v: View): string[] {
|
|
102
118
|
return [`${v.id} ${v.kind}, ${v.tier}-term${v.expiresAt ? ` until ${v.expiresAt}` : ""}, ${v.scope}`, `by ${v.peer} on machine ${v.machine}, ${v.at}, project ${v.project}${v.task ? `, task ${v.task}` : ""}`,
|
|
103
119
|
...(cliAttribution() ? [`actor: ${noteDisplayActor(v.peer)}, peer: ${v.peer}`] : []), ...(v.promotedFrom ? [`promoted from ${v.promotedFrom}`] : []), ...(v.supersededBy ? [`superseded by ${v.supersededBy}`] : []), ...(v.about.length ? [`about: ${v.about.join(", ")}`] : []), "", ...(v.title ? [v.title] : []), v.text];
|
|
104
120
|
}
|
|
105
121
|
|
|
106
122
|
export async function rawMemoryCommand(args: string[], cwd: string, opts: MemoryCommandOptions): Promise<string> {
|
|
123
|
+
// CLI-only presentation options do not extend the exported host API.
|
|
124
|
+
const internal = (opts as MemoryCommandOptions & { [CLI_MEMORY_RENDER]?: { render: HumanMemoryRender; renderLegacy?: (legacy: string, formatted: string) => string } })[CLI_MEMORY_RENDER];
|
|
107
125
|
const json = args.includes("--json");
|
|
108
126
|
const rest = args.filter((a) => a !== "--json");
|
|
109
127
|
const flag = (name: string) => { const i = rest.indexOf(name); if (i < 0) return undefined; const v = rest[i + 1] ?? fail(`${name} needs a value`); rest.splice(i, 2); return v; };
|
|
@@ -140,6 +158,7 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
140
158
|
};
|
|
141
159
|
const staleDetail = (view: View): string[] => { const marker = staleMarker(view).trimEnd(); return marker ? [marker] : []; };
|
|
142
160
|
const ready = (rows: readonly View[]) => { try { opts.outputReady?.(rows); } catch { /* optional output metadata cannot fail recall */ } };
|
|
161
|
+
const rendered = (legacy: string, formatted: string) => internal?.renderLegacy ? internal.renderLegacy(legacy, formatted) : formatted;
|
|
143
162
|
const decorated = (view: View) => { const info = staleInfo(view); return { ...view, ...(info.stale ? { stale: true, ...(info.reason ? { staleReason: info.reason } : {}) } : {}) }; };
|
|
144
163
|
if (!["list", "search", "show", "graph"].includes(sub) && (rest.includes("--history") || rest.includes("--as-of"))) fail("history/as-of apply only to memory reads");
|
|
145
164
|
try {
|
|
@@ -175,15 +194,23 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
175
194
|
const emitted = recallForViews(state, rows), publicIds = new Set(rows.map(view => view.id)), allForgotten = q?.trim() ? [] : state.forgotten;
|
|
176
195
|
const forgotten = allForgotten.slice(0, Math.max(0, (limit ? Math.floor(Number(limit)) : 50) - rows.length));
|
|
177
196
|
const result = { at: state.at, entries: rows.map(decorated), forgotten, relations: state.relations.filter(edge => publicIds.has(edge.from) && publicIds.has(edge.to)), incomplete: emitted.incomplete || readable.length > rows.length || forgotten.length < allForgotten.length, notices: emitted.notices };
|
|
178
|
-
|
|
197
|
+
const legacy = [`retained memory as of ${state.at}`, ...result.notices, ...rows.map(view => `${staleMarker(view)}${one(view)}${view.expiresAt && Date.parse(view.expiresAt) <= Date.parse(state.at) ? ` (expired at ${view.expiresAt})` : ""}`), ...forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(result.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
|
|
198
|
+
if (!json && internal?.render) return rendered(legacy, [memoryTableText([...rows.map(view => { const marker = staleMarker(view); return { id: view.id, kind: view.kind, tier: view.tier, peer: view.peer, scope: view.scope, at: view.at, text: `${view.title ? `${view.title}: ` : ""}${view.text}`, flags: [...(view.expiresAt && Date.parse(view.expiresAt) <= Date.parse(state.at) ? ["(expired)"] : []), ...(marker ? [marker.trim()] : []), ...(view.supersededBy ? [`superseded by ${view.supersededBy.slice(0, 8)}`] : [])] }; }), ...forgotten.map(row => ({ id: row.id, kind: "forgotten", at: row.at, text: "No retained text" }))], "Retained memory", internal?.render, `retained memory as of ${relativeTime(state.at, internal?.render.now ?? Date.now())}.`), ...result.notices.map(singleLine), ...(result.incomplete ? ["Retained state is incomplete."] : [])].join("\n"));
|
|
199
|
+
return json ? JSON.stringify(result, null, 2) : legacy;
|
|
179
200
|
}
|
|
180
201
|
if (json) return JSON.stringify(rows.map(view => ({ ...view, ...(folded.has(view.id) ? { folded: folded.get(view.id) } : {}), ...(opts.explainSearch && scoreDetails?.has(view.id) ? { scoreDetails: scoreDetails.get(view.id) } : {}) })), null, 2);
|
|
181
202
|
const counted = opts.readable(store.withDeferredPromotions(() => store.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
|
|
182
203
|
const withheld = all.length - readable.length;
|
|
183
|
-
|
|
204
|
+
const legacy = [`memory for ${project} on machine ${store.machine.label}: ${counted.filter(view => view.tier === "long").length} long-term, ${counted.filter(view => view.tier === "short").length} short-term`, ...(rows.length ? opts.explainSearch
|
|
184
205
|
? rows.flatMap(view => [`${staleMarker(view)}${one(view)}${foldNote(view)}`, ...(scoreDetails?.has(view.id) ? [`score: ${JSON.stringify(scoreDetails.get(view.id))}`] : [])])
|
|
185
206
|
: rows.map(view => `${staleMarker(view)}${one(view)}${foldNote(view)}`) : ["(nothing)"]),
|
|
186
207
|
...(withheld ? [`(${withheld} withheld: they match a PII pattern; the dashboard shows them)`] : [])].join("\n");
|
|
208
|
+
if (internal?.render) {
|
|
209
|
+
const table = memoryTableText(rows.map(view => { const marker = staleMarker(view); return { id: view.id, kind: view.kind, tier: view.tier, peer: view.peer, scope: view.scope, at: view.at, text: `${view.title ? `${view.title}: ` : ""}${view.text}`, flags: [...(marker ? [marker.trim()] : []), ...(folded.has(view.id) ? [`+${folded.get(view.id)} same task`] : []), ...(view.supersededBy ? [`superseded by ${view.supersededBy.slice(0, 8)}`] : [])] }; }), sub === "search" ? "Search" : "Memory", internal?.render, `Project ${project}; machine ${store.machine.label}; ${counted.filter(view => view.tier === "long").length} long-term, ${counted.filter(view => view.tier === "short").length} short-term.`);
|
|
210
|
+
const scores = opts.explainSearch ? memoryScoresText(rows.flatMap(view => scoreDetails?.has(view.id) ? [{ id: view.id, details: scoreDetails.get(view.id)! as unknown as Record<string, unknown> }] : []), internal?.render) : "";
|
|
211
|
+
return rendered(legacy, [table, scores, ...(withheld ? [`${withheld} entries withheld by policy; review them in the dashboard.`] : [])].filter(Boolean).join("\n\n"));
|
|
212
|
+
}
|
|
213
|
+
return legacy;
|
|
187
214
|
}
|
|
188
215
|
case "show": {
|
|
189
216
|
const asOf = flag("--as-of"), history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
|
|
@@ -193,10 +220,12 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
193
220
|
if (shown.state) {
|
|
194
221
|
const rows = opts.readable(shown.state.views), ids = new Set(rows.map(view => view.id)); ready(rows);
|
|
195
222
|
const state = { ...recallForViews(shown.state, rows), views: rows.map(decorated), relations: shown.state.relations.filter(edge => ids.has(edge.from) && ids.has(edge.to)) };
|
|
196
|
-
|
|
223
|
+
const legacy = [`retained memory as of ${state.at}`, ...state.notices, ...rows.flatMap(view => [...staleDetail(view), ...detail(view)]), ...state.forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(state.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
|
|
224
|
+
if (!json && internal?.render) return rendered(legacy, [...state.notices.map(singleLine), ...rows.map(view => memoryDetailText(view, { ...internal?.render, ...(cliAttribution() ? { actor: noteDisplayActor(view.peer) } : {}) })), ...state.forgotten.map(row => `Forgotten ${singleLine(row.id)}; no retained text.`), ...(state.incomplete ? ["Retained state is incomplete."] : [])].join("\n"));
|
|
225
|
+
return json ? JSON.stringify(state, null, 2) : legacy;
|
|
197
226
|
}
|
|
198
227
|
const view = need(shown.entry, id); if (!opts.readable([view]).length) fail(`${view.id.slice(0, 8)} is withheld: it matches a PII pattern (the dashboard shows it)`);
|
|
199
|
-
ready([view]); return json ? JSON.stringify(view, null, 2) : [...staleDetail(view), ...detail(view)].join("\n");
|
|
228
|
+
ready([view]); return json ? JSON.stringify(view, null, 2) : internal?.render ? rendered([...staleDetail(view), ...detail(view)].join("\n"), [ ...staleDetail(view), memoryDetailText(view, { ...internal?.render, ...(cliAttribution() ? { actor: noteDisplayActor(view.peer) } : {}) }) ].join("\n")) : [...staleDetail(view), ...detail(view)].join("\n");
|
|
200
229
|
}
|
|
201
230
|
case "graph": {
|
|
202
231
|
const hops = Number(flag("--hops") ?? 1);
|
|
@@ -234,11 +263,13 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
234
263
|
// #578 Q2: one counts-only line when this sync ran a placement checkpoint.
|
|
235
264
|
const checkpointLine = r.checkpoint ? `\nplacement checkpoint: window ${r.checkpoint.window}, objects ${r.checkpoint.objectsBefore} -> ${r.checkpoint.objectsAfter}` : "";
|
|
236
265
|
if (!r.ok) fail(`${names.memory} sync: ${r.error}${checkpointLine}${realmLines}`);
|
|
266
|
+
// #590 (task 429): the CLI renders the success report; hosts keep the legacy line below byte for byte.
|
|
267
|
+
const cliSync = (legacy: string) => internal ? rendered(legacy, syncReportText(r, internal.render.style ?? PLAIN, { columns: internal.render.columns ?? 80 })) : legacy;
|
|
237
268
|
if (r.pruneApplication) {
|
|
238
269
|
const a = r.pruneApplication;
|
|
239
|
-
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}
|
|
270
|
+
return cliSync(`synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`);
|
|
240
271
|
}
|
|
241
|
-
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${checkpointLine}${realmLines}
|
|
272
|
+
return cliSync(`synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${checkpointLine}${realmLines}`);
|
|
242
273
|
}
|
|
243
274
|
case "dedupe": {
|
|
244
275
|
const apply = rest.includes("--apply");
|
package/src/memory/doctor.ts
CHANGED
|
@@ -19,8 +19,8 @@ import { readSelector } from "./generation.ts";
|
|
|
19
19
|
import { processLiveness, withGitTimeout } from "./platform.ts";
|
|
20
20
|
import { endLikeSignal, STOP_SIGNALS } from "./sync-cadence.ts";
|
|
21
21
|
import { boundRepoRoot } from "./repo-scope.ts";
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
22
|
+
import { humanBytes, relativeTime, singleLine, wordedFacts, wordedKey, PLAIN, type Style } from "./style.ts";
|
|
23
|
+
import { attention, reportFrame, stateRows, STATE_WORD, type Finding, type ReportTextOptions } from "./status-text.ts";
|
|
24
24
|
import { aliasedKeys, shardDir } from "./shard.ts";
|
|
25
25
|
import type { MemoryStore, View } from "./store.ts";
|
|
26
26
|
import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
|
|
@@ -342,7 +342,7 @@ function stateOf(last: string | null, now: number): CaptureState {
|
|
|
342
342
|
* 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
|
|
343
343
|
* (the fallback when another shard could not be read), or a missing setup for a CLI that has never captured anywhere.
|
|
344
344
|
*/
|
|
345
|
-
function captureHint(cli: Cli, registered: boolean, state: CaptureState, trigger: "machine" | "project" | "setup", unsafeRoots: readonly NativeRootKind[] = []): string {
|
|
345
|
+
export function captureHint(cli: Cli, registered: boolean, state: CaptureState, trigger: "machine" | "project" | "setup", unsafeRoots: readonly NativeRootKind[] = []): string {
|
|
346
346
|
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}`;
|
|
347
347
|
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`;
|
|
348
348
|
const where = trigger === "machine" ? "on this machine (all projects)" : "in this project (other projects could not be read)";
|
|
@@ -634,7 +634,7 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
|
|
|
634
634
|
return { schema: DOCTOR_SCHEMA, status: worst(Object.values(sections).map(section => section.status)), home: { path: options.home, source: options.homeSource }, project: options.project, sections };
|
|
635
635
|
}
|
|
636
636
|
|
|
637
|
-
/** Section order and one-line
|
|
637
|
+
/** Section order and one-line names for the person-facing report (#125). */
|
|
638
638
|
const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
|
|
639
639
|
duplicates: "duplicate notes", stale: "stale path references", candidates: "review candidates", capture: "capture per CLI", brief: "session brief",
|
|
640
640
|
index: "index equals rebuild", readers: "reader leases", policy: "policy in effect", cadence: "ingest and sync cadence", drops: "recent capture drops",
|
|
@@ -644,74 +644,129 @@ const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
|
|
|
644
644
|
masked: "forgotten or pruned entries (informational)",
|
|
645
645
|
};
|
|
646
646
|
|
|
647
|
-
|
|
647
|
+
/**
|
|
648
|
+
* #590 C4: every hint a section emits, as one finding and the complete commands that act on it. `--json` keeps the hint text unchanged;
|
|
649
|
+
* only the human report reads this table. A hint missing from it renders as a finding with no `→`, never as text with an embedded command.
|
|
650
|
+
* `test/status-doctor-layout.test.ts` checks every hint producer against this table.
|
|
651
|
+
*/
|
|
652
|
+
export const DOCTOR_HINTS: Readonly<Record<string, (section: Record<string, unknown>) => Finding>> = {
|
|
653
|
+
"amem dedupe previews the imported duplicates; amem dedupe --apply reconciles them": () =>
|
|
654
|
+
({ text: "imported duplicate notes can be reconciled", next: ["amem dedupe", "amem dedupe --apply"] }),
|
|
655
|
+
"The person can inspect these examples with amem show <id> from their own shell.": section => {
|
|
656
|
+
const first = Array.isArray(section.examples) ? String(section.examples[0] ?? "") : "";
|
|
657
|
+
// #511 AC3: an agent-marked `show` may withhold these ids, so the finding says where they open.
|
|
658
|
+
return { text: `${section.missingReferences} notes reference paths that no longer exist; open the examples from your own shell`, next: first ? [`amem show ${first}`] : [] };
|
|
659
|
+
},
|
|
660
|
+
"the index differs from a rebuild of the logs: run amem rebuild": () => ({ text: "the index differs from a rebuild of the logs", next: ["amem rebuild"] }),
|
|
661
|
+
"a section is partial or unavailable in the brief: see coverage": () => ({ text: "a brief section is partial or unavailable", next: [] }),
|
|
662
|
+
"the brief uses over 90% of its budget": () => ({ text: "the session brief uses over 90% of its budget", next: [] }),
|
|
663
|
+
"a reader lease of a process that is gone is cleared by the next reader; an unreadable one needs a look": () =>
|
|
664
|
+
({ text: "a reader lease is stale or unreadable; the next reader clears a stale one", next: [] }),
|
|
665
|
+
"capture rows were dropped recently (see counts by reason); amem doctor --json keeps the numbers": () =>
|
|
666
|
+
({ text: "capture rows were dropped recently", next: ["amem doctor --json"] }),
|
|
667
|
+
"pending hook spool needs attention: capture can be dropped when both tiers fill; supported orphan recovery is pending": () =>
|
|
668
|
+
({ text: "the hook spool is nearly full; capture is dropped when both tiers fill", next: [] }),
|
|
669
|
+
"sync has failed repeatedly; amem sync --force shows why": () => ({ text: "sync has failed 3 or more times in a row", next: ["amem sync --force"] }),
|
|
670
|
+
"no recent successful sync: run amem sync": () => ({ text: "no recent successful sync", next: ["amem sync"] }),
|
|
671
|
+
"run amem review walk": section => ({ text: `${section.dueWithin7Days} candidates expire within 7 days`, next: ["amem review walk"] }),
|
|
672
|
+
};
|
|
673
|
+
/** Capture hints name a CLI; each maps to a finding and the commands for that CLI. */
|
|
674
|
+
export function captureFinding(cli: string, hint: string): Finding {
|
|
675
|
+
const known = new Set<string>(CLIS);
|
|
676
|
+
const ingest = known.has(cli) && cli !== "claude" ? [`amem ingest ${cli}`] : [];
|
|
677
|
+
if (hint.startsWith(`the ${cli} `) && hint.includes("unsafe symlink")) return { text: `${cli}: a native session root is an unsafe symlink and was skipped`, next: ingest };
|
|
678
|
+
if (hint.startsWith("run amem setup")) return { text: `${cli}: capture is not set up`, next: known.has(cli) ? [`amem setup ${cli} --apply`, ...ingest] : [] };
|
|
679
|
+
if (hint.includes("/hooks trust review")) return { text: "codex: the hook is registered but has never captured; approve it in the Codex /hooks trust review", next: [] };
|
|
680
|
+
const state = /capture is (\w+)/.exec(hint)?.[1] ?? "not fresh", where = hint.includes("on this machine") ? "on this machine" : "in this project";
|
|
681
|
+
return { text: `${cli}: capture is ${state} ${where}; open a session`, next: ingest };
|
|
682
|
+
}
|
|
683
|
+
export function hintFinding(name: string, hint: string, section: Record<string, unknown>): Finding {
|
|
684
|
+
const mapped = DOCTOR_HINTS[hint];
|
|
685
|
+
return mapped ? mapped(section) : { text: `${SECTION_TITLE[name as keyof typeof SECTION_TITLE] ?? name}: ${hint.replace(/[:;,]?\s*(?:run |see |use )?\bamem [a-z].*$/, "").replace(/[:;,]\s*$/, "").trim() || "needs a look"}`, next: [] };
|
|
686
|
+
}
|
|
687
|
+
/** #590 C6: a writer refusal is one finding; each command it names is one `→` line. The fixed refusal text stays in `--json`. */
|
|
688
|
+
export function writerFinding(section: Record<string, unknown>): Finding {
|
|
689
|
+
const reason = String(section.reason ?? "");
|
|
690
|
+
const commands = [...reason.matchAll(/amem (?:migrate --sync-placement --(?:dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
|
|
691
|
+
return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function sectionFact(name: string, detail: Record<string, unknown>, now: number): string[] {
|
|
648
695
|
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
649
|
-
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) =>
|
|
650
|
-
|
|
651
|
-
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}` : ""}`;
|
|
652
|
-
});
|
|
696
|
+
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) =>
|
|
697
|
+
`${cli} hook ${row.hook}${row.setup ? ` (${row.setup})` : ""}, capture ${row.capture}${row.lastCaptureAt ? ` ${relativeTime(String(row.lastCaptureAt), now)}` : ""}, ${row.rows} rows; machine-wide ${row.machineCapture ?? "unknown"}${row.machineLastCaptureAt ? ` ${relativeTime(String(row.machineLastCaptureAt), now)}` : ""}${row.note ? `, ${row.note}` : ""}`);
|
|
653
698
|
}
|
|
654
699
|
if (name === "cadence") {
|
|
655
700
|
const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
|
|
656
701
|
return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
|
|
657
|
-
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${sync.lastOkAt
|
|
702
|
+
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${relativeTime(sync.lastOkAt as string | null, now)}, ${sync.failures} failures${sync.due ? ", due" : ""}` : ""}`];
|
|
658
703
|
}
|
|
659
704
|
if (name === "drops") {
|
|
660
|
-
if (detail.counts === undefined) return [];
|
|
705
|
+
if (detail.counts === undefined) return [];
|
|
661
706
|
const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
|
|
662
|
-
return [counts.length ?
|
|
707
|
+
return [`${counts.length ? counts.map(([reason, n]) => `${reason.replaceAll("_", " ")} ${n}`).join(", ") : "none"} in the recent metrics tail${detail.malformedLines ? `, ${detail.malformedLines} malformed lines skipped` : ""}`];
|
|
663
708
|
}
|
|
664
709
|
if (name === "spool") {
|
|
665
710
|
if (!detail.active || !detail.reserve) return [];
|
|
666
|
-
const tiers = ["active", "reserve"].map(
|
|
667
|
-
const tier = detail[
|
|
668
|
-
return `${
|
|
711
|
+
const tiers = ["active", "reserve"].map(tierName => {
|
|
712
|
+
const tier = detail[tierName] as { files: number; bytes: number; maxFiles: number; maxBytes: number };
|
|
713
|
+
return `${tierName} ${tier.files} of ${tier.maxFiles} files, ${humanBytes(tier.bytes)} of ${humanBytes(tier.maxBytes)}`;
|
|
669
714
|
});
|
|
670
715
|
const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
|
|
671
|
-
return [`${detail.fill}; ${tiers.join("; ")};
|
|
716
|
+
return [`${String(detail.fill).replaceAll("_", " ")}; ${tiers.join("; ")}; ${detail.claimed} claimed${detail.oldestAt ? `, oldest ${relativeTime(String(detail.oldestAt), now)}` : ""}${detail.complete ? "" : " (counts are lower bounds)"}`,
|
|
672
717
|
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
673
718
|
}
|
|
674
719
|
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
675
|
-
|
|
676
|
-
|
|
720
|
+
const entries = detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[];
|
|
721
|
+
if (!entries.length) return [`${detail.checked ?? 0} registrations match their receipts`];
|
|
722
|
+
return entries.map(item => singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? `, expected ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
677
723
|
}
|
|
678
|
-
if (name === "writers") return typeof detail.writers === "number"
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
724
|
+
if (name === "writers") return typeof detail.writers === "number" ? [`${detail.writers} writers match the active inventory`] : [];
|
|
725
|
+
if (name === "brief" && typeof detail.tokens === "number") {
|
|
726
|
+
const missing = Object.entries((detail.coverage ?? {}) as Record<string, unknown>).filter(([, value]) => value && value !== "complete").map(([key, value]) => `${wordedKey(key)} ${value}`);
|
|
727
|
+
return [`${detail.tokens} of ${detail.budget} tokens${missing.length ? `, coverage: ${missing.join(", ")}` : ""}`];
|
|
728
|
+
}
|
|
729
|
+
if (name === "policy") return [`machine ${detail.machine ?? "none (defaults)"}, repo ${detail.repo ?? "none"}, ${detail.denyPaths} deny paths, ${detail.piiPatterns} PII patterns`];
|
|
730
|
+
if (name === "index") return detail.liveIndex ? [`live index ${detail.liveIndex}, equal to a rebuild`] : [];
|
|
731
|
+
if (name === "readers") return [`${detail.live ?? 0} live, ${detail.stale ?? 0} stale, ${detail.unreadable ?? 0} unreadable`];
|
|
732
|
+
if (name === "duplicates" && typeof detail.notes === "number") return [`${detail.notes} notes, ${detail.identicalGroups ?? 0} identical groups, ${detail.importedGroups ?? 0} imported groups${detail.truncated ? `, ${detail.truncated}` : ""}`,
|
|
733
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
734
|
+
if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
|
|
735
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
|
|
736
|
+
if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
|
|
737
|
+
if (name === "candidates") return [`${detail.count ?? 0} pending${detail.unshown ? `, ${detail.unshown} never shown` : ""}${detail.oldestExpiresInDays !== null && detail.oldestExpiresInDays !== undefined ? `, oldest expires in ${detail.oldestExpiresInDays} d` : ""}`];
|
|
738
|
+
const { examples, note: _note, ...rest } = detail;
|
|
739
|
+
const line = wordedFacts(rest);
|
|
740
|
+
return [...(line ? [line] : []), ...(Array.isArray(examples) && examples.length ? [`examples ${examples.map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** The person-facing report (#125, #590): state, findings with their commands, one row per check, then the summary. `amem doctor --json` keeps the full report. */
|
|
744
|
+
export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportTextOptions & { now?: number } = {}): string {
|
|
745
|
+
const now = opts.now ?? Date.now();
|
|
689
746
|
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
690
747
|
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
691
|
-
const
|
|
692
|
-
const actions: string[] = [];
|
|
748
|
+
const findings: Finding[] = [];
|
|
693
749
|
for (const [name, item] of entries) {
|
|
694
|
-
if (item.
|
|
695
|
-
if (
|
|
750
|
+
if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
|
|
751
|
+
if (item.hint) findings.push(hintFinding(name, item.hint, item));
|
|
752
|
+
if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) findings.push(captureFinding(cli, row.hint));
|
|
696
753
|
}
|
|
697
|
-
const
|
|
698
|
-
|
|
699
|
-
|
|
754
|
+
const out = reportFrame(s, "doctor", report.status === "skipped" ? "ok" : STATE_WORD[report.status], opts, report.home);
|
|
755
|
+
out.note(`project ${report.project}`);
|
|
756
|
+
attention(out, findings);
|
|
757
|
+
out.section("Checks", String(entries.length));
|
|
700
758
|
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
701
759
|
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
702
|
-
|
|
703
|
-
const { status, hint, reason, ...detail } = section;
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
];
|
|
715
|
-
if (counts.length) lines.push(counts.join(" "));
|
|
716
|
-
return lines.join("\n");
|
|
760
|
+
const rows = entries.flatMap(([name, section]) => {
|
|
761
|
+
const { status, hint: _hint, reason, ...detail } = section;
|
|
762
|
+
const facts = name === "writers" && status === "attention" ? [] : sectionFact(name, detail, now);
|
|
763
|
+
const writerRefusal = name === "writers" && status === "attention";
|
|
764
|
+
const fact = writerRefusal ? `${section.cause} (${section.category} category); see Attention`
|
|
765
|
+
: [...facts, ...(reason ? [singleLine(reason)] : [])].join("; ") || (status === "ok" ? "nothing to report" : SECTION_TITLE[name]);
|
|
766
|
+
return [{ state: status, name, fact }];
|
|
767
|
+
});
|
|
768
|
+
stateRows(out, rows, s);
|
|
769
|
+
if (count("skipped")) { out.line(""); out.note(`${count("skipped")} skipped: nothing to check here`); }
|
|
770
|
+
out.summary({ warnings: count("attention"), unknown: count("unavailable"), ok: count("ok") });
|
|
771
|
+
return out.render(s.color).join("\n");
|
|
717
772
|
}
|
package/src/memory/eval-audit.ts
CHANGED
|
@@ -15,6 +15,10 @@ import {
|
|
|
15
15
|
} from "./eval.ts";
|
|
16
16
|
import { memoryGitEnv, memoryGitSync, realPath } from "./platform.ts";
|
|
17
17
|
import type { MemoryStore, View } from "./store.ts";
|
|
18
|
+
import { Report } from "@staix/cli-output";
|
|
19
|
+
import { PLAIN, relativeTime, singleLine, type Style } from "./style.ts";
|
|
20
|
+
|
|
21
|
+
interface AuditRender { columns?: number; style?: Style; now?: number }
|
|
18
22
|
|
|
19
23
|
export interface AuditAnchor { path: string; status: Exclude<AuditAnchorStatus, "none"> }
|
|
20
24
|
export interface AuditNote {
|
|
@@ -406,9 +410,19 @@ export function auditScore(sheet: AuditSheet): AuditScore {
|
|
|
406
410
|
}
|
|
407
411
|
|
|
408
412
|
/** Human text for `amem eval audit sample`: where the sheet is, and what filling it costs. Content-free, like the score. */
|
|
409
|
-
export function auditSheetText(sheet: AuditSheet, file: string): string {
|
|
413
|
+
export function auditSheetText(sheet: AuditSheet, file: string, render?: AuditRender): string {
|
|
410
414
|
const cells = new Set(sheet.notes.map(note => `${note.kind}/${note.age}`));
|
|
411
415
|
const frame = `${sheet.frame}${sheet.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
416
|
+
if (render) {
|
|
417
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
418
|
+
out.header("amem", "Audit sample"); out.section("Sheet");
|
|
419
|
+
out.kv([["Project", sheet.project], ["Drawn", `${sheet.drawn} of ${frame}`], ["Seed", sheet.seed], ["Measured", relativeTime(sheet.asOf, render.now ?? Date.now())], ["Groups", String(cells.size)], ["Root", sheet.root], ["File", file], ["Withheld", String(sheet.withheld)]]);
|
|
420
|
+
out.note("The sheet is mode 0600, local only; never synced or committed.");
|
|
421
|
+
out.note(`Fill both judge columns using ${AUDIT_LABELS.join(", ")}; the rubric is in the sheet.`);
|
|
422
|
+
if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(file)) out.bullet("warn", "The sheet path contains control characters; inspect --json and pass the exact path to the score command.");
|
|
423
|
+
else out.next(`amem eval audit score '${file.replaceAll("'", "'\\''")}'`);
|
|
424
|
+
return out.render(s.color).join("\n");
|
|
425
|
+
}
|
|
412
426
|
return [
|
|
413
427
|
`audit sample: ${sheet.drawn} of ${frame} ${sheet.project} notes, seed "${sheet.seed}" as of ${sheet.asOf}, ${cells.size} kind/age cells, anchors checked in ${sheet.root}${sheet.withheld ? `, ${sheet.withheld} withheld by the configured policy` : ""}`,
|
|
414
428
|
`sheet: ${file} (0600, local only; never synced and never committed)`,
|
|
@@ -417,7 +431,7 @@ export function auditSheetText(sheet: AuditSheet, file: string): string {
|
|
|
417
431
|
}
|
|
418
432
|
|
|
419
433
|
/** Human text for `amem eval audit score`; the JSON is the machine form. */
|
|
420
|
-
export function auditScoreText(score: AuditScore): string {
|
|
434
|
+
export function auditScoreText(score: AuditScore, render?: AuditRender): string {
|
|
421
435
|
const row = (label: string, counts: Partial<Record<AuditLabel, number>>) => `${label.padEnd(10)} ${AUDIT_LABELS.map(name => String(counts[name] ?? 0).padStart(4)).join(" ")}`;
|
|
422
436
|
const frame = `${score.frame}${score.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
423
437
|
const withheld = score.withheld ? `, ${score.withheld} withheld by the configured policy` : "";
|
|
@@ -429,6 +443,16 @@ export function auditScoreText(score: AuditScore): string {
|
|
|
429
443
|
counts[cell.label] = cell.count;
|
|
430
444
|
strata.set(key, counts);
|
|
431
445
|
}
|
|
446
|
+
if (render) {
|
|
447
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
448
|
+
out.header("amem", "Audit score"); out.section("Summary");
|
|
449
|
+
out.kv([["Project", score.project], ["Drawn", `${score.drawn} of ${frame}`], ["Seed", score.seed], ["Measured", relativeTime(score.asOf, render.now ?? Date.now())], ["Labelled", String(score.labelled)], ["Unlabelled", String(score.unlabelled)], ["Withheld", String(score.withheld)], ["Kappa", score.agreement.kappa === null ? "? (needs both judges and more than one label)" : score.agreement.kappa.toFixed(3)], ["Judge pairs", String(score.agreement.pairs)]]);
|
|
450
|
+
out.section("Labels");
|
|
451
|
+
const rows: [string, Partial<Record<AuditLabel, number>>][] = [["all", score.byLabel], ...Object.entries(score.byKind).map(([kind, counts]): [string, Partial<Record<AuditLabel, number>>] => [`kind ${kind}`, counts]), ...Object.entries(score.byAge).map(([age, counts]): [string, Partial<Record<AuditLabel, number>>] => [`age ${age}`, counts]), ...Object.entries(score.byAnchor).map(([anchor, counts]): [string, Partial<Record<AuditLabel, number>>] => [`anchor ${anchor}`, counts]), ...[...strata.entries()].map(([key, counts]): [string, Partial<Record<AuditLabel, number>>] => [`cross ${key}`, counts])];
|
|
452
|
+
out.table(["GROUP", ...AUDIT_LABELS], rows.map(([name, counts]) => [name, ...AUDIT_LABELS.map(label => String(counts[label] ?? 0))]), 0);
|
|
453
|
+
out.line(""); out.line(`Summary: ${score.labelled} labelled, ${score.unlabelled} unlabelled`);
|
|
454
|
+
return out.render(s.color).join("\n");
|
|
455
|
+
}
|
|
432
456
|
return [
|
|
433
457
|
head,
|
|
434
458
|
`${"".padEnd(10)} ${AUDIT_LABELS.map(name => name.slice(0, 4).padStart(4)).join(" ")}`,
|
package/src/memory/eval.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* F13 (agent-mem#40, AC7): local recall evaluation. A question set is a list of (question, expected entry) pairs; the evaluation replays each question
|
|
3
3
|
* through a search function and reports recall@k, hit@k and MRR. No model judge, no network, no embedding: a result either is one of the expected
|
|
4
|
-
* entries or it is not.
|
|
4
|
+
* entries or it is not. The parser and arithmetic remain testable without a store.
|
|
5
5
|
*
|
|
6
6
|
* Two shapes of set:
|
|
7
7
|
* - self-contained: `entries` are synthetic notes seeded into a throwaway store, and `expect` names them by `key` (the committed fixture is one);
|
|
8
8
|
* - the person's own: no `entries`, `expect` holds real entry ids (or `mem:<id>`, or a prefix of 8 or more hex characters) and the bound project's store is searched.
|
|
9
9
|
*/
|
|
10
|
+
import { Report } from "@staix/cli-output";
|
|
11
|
+
import { PLAIN, singleLine, type Style } from "./style.ts";
|
|
10
12
|
export const EVAL_SCHEMA = "amem.eval/v1";
|
|
11
13
|
export const MAX_QUESTIONS = 500, MAX_ENTRIES = 200, MAX_QUESTION_CHARS = 500, MAX_EXPECT = 20, MAX_ENTRY_CHARS = 4000, MAX_SET_BYTES = 1024 * 1024, MAX_K = 100;
|
|
12
14
|
export const DEFAULT_KS: readonly number[] = [1, 5, 10];
|
|
@@ -214,7 +216,20 @@ export function runEval(rank: (question: string) => readonly string[], resolve:
|
|
|
214
216
|
|
|
215
217
|
const pct = (value: number | null): string => value === null ? " n/a" : value.toFixed(3);
|
|
216
218
|
/** Human text for `amem eval`; the JSON report is the machine form. */
|
|
217
|
-
export function evalText(report: EvalReport, label: string): string {
|
|
219
|
+
export function evalText(report: EvalReport, label: string, render?: { columns?: number; style?: Style }): string {
|
|
220
|
+
if (render) {
|
|
221
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
222
|
+
out.header("amem", "Evaluation"); out.section("Results");
|
|
223
|
+
out.kv([["Set", label], ["Engine", report.engine], ["Questions", String(report.all.questions)], ["Answerable", String(report.answerable.questions)], ["All MRR", report.all.mrr === null ? "?" : report.all.mrr.toFixed(3)], ["Answerable MRR", report.answerable.mrr === null ? "?" : report.answerable.mrr.toFixed(3)]]);
|
|
224
|
+
if (report.answerable.questions < report.all.questions) out.note(`${report.all.questions - report.answerable.questions} questions name entries this store does not hold; they score zero in all.`);
|
|
225
|
+
out.section("Cutoffs", String(report.ks.length));
|
|
226
|
+
const number = (value: number | null | undefined) => value == null ? "?" : value.toFixed(3);
|
|
227
|
+
out.table(["K", "ALL RECALL", "ALL HIT", "ANSWERABLE RECALL", "ANSWERABLE HIT"], report.ks.map(k => [String(k), number(report.all.recall[k]), number(report.all.hit[k]), number(report.answerable.recall[k]), number(report.answerable.hit[k])]), 0);
|
|
228
|
+
const missed = report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks));
|
|
229
|
+
if (missed.length) { out.section("Questions to review", String(missed.length)); out.table(["RESULT", "QUESTION"], missed.map(row => [row.rank === null ? "miss" : `rank ${row.rank}`, `${row.answerable ? "" : "not in store: "}${row.q}`]), 1); }
|
|
230
|
+
out.line(""); out.line(`Summary: ${report.all.questions} questions, ${report.answerable.questions} answerable`);
|
|
231
|
+
return out.render(s.color).join("\n");
|
|
232
|
+
}
|
|
218
233
|
const head = (name: string, row: EvalAggregate) => `${name.padEnd(11)} ${String(row.questions).padStart(4)} ${report.ks.map(k => `${pct(row.recall[k] ?? null)}/${pct(row.hit[k] ?? null)}`.padStart(13)).join(" ")} ${pct(row.mrr).padStart(6)}`;
|
|
219
234
|
return [
|
|
220
235
|
`eval: ${label} (${report.engine === "substring" ? "substring fallback" : "ranked store.search, engine " + report.engine}; same ranked search path as default \`amem search\`; \`--filter\` keeps legacy substring matching)`,
|
package/src/memory/gc.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { join } from "node:path";
|
|
|
4
4
|
import { CAPTURE_EVICT_MAX_BATCHES, CaptureStore, captureShardStats, readCaptureConfig } from "./capture.ts";
|
|
5
5
|
import { walkShards } from "./catalog.ts";
|
|
6
6
|
import { lifecycleResolver } from "./lifecycle.ts";
|
|
7
|
+
import { Report } from "@staix/cli-output";
|
|
8
|
+
import { PLAIN, singleLine, type Style } from "./style.ts";
|
|
7
9
|
|
|
8
10
|
/**
|
|
9
11
|
* #15 T5 / D3: `amem gc`. Applies each shard's own R6 bounds (its retention window and size cap, the shard config over the home default) across every
|
|
@@ -107,7 +109,18 @@ export function runGc(base: string, opts: GcOptions = {}): GcResult {
|
|
|
107
109
|
export const GC_MAX_BATCHES_PER_CALL = CAPTURE_EVICT_MAX_BATCHES;
|
|
108
110
|
|
|
109
111
|
/** The non-JSON rendering of `amem gc`. */
|
|
110
|
-
export function gcText(result: GcResult): string {
|
|
112
|
+
export function gcText(result: GcResult, render?: { columns?: number; style?: Style; next?: string }): string {
|
|
113
|
+
if (render) {
|
|
114
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
115
|
+
out.header("amem", "Capture cleanup"); out.section(result.dryRun ? "Preview" : "Results");
|
|
116
|
+
out.bullet(result.dryRun ? "pending" : "ok", result.dryRun ? "Review the cleanup before confirming." : "Cleanup completed.");
|
|
117
|
+
if (result.shards.length) out.table(["PROJECT", "EXPIRED", "TRIMMED", "STATE"], result.shards.map(row => [row.key, String(row.expired), String(row.trimmed), row.remainingOverCap ? "over cap" : "within cap"]), 0);
|
|
118
|
+
else out.note("No project shards.");
|
|
119
|
+
for (const row of result.skipped) out.bullet("absent", `${row.key}: skipped (${row.reason})`);
|
|
120
|
+
if (render.next && (result.dryRun ? result.shards.some(row => row.expired > 0 || row.remainingOverCap) : result.shards.some(row => row.remainingOverCap))) out.next(render.next);
|
|
121
|
+
out.line(""); out.line(`Summary: ${result.shards.length} shards, ${result.skipped.length} skipped`);
|
|
122
|
+
return out.render(s.color).join("\n");
|
|
123
|
+
}
|
|
111
124
|
const lines = result.shards.map(s => `${s.key}: ${result.dryRun ? `${s.expired} expired row(s) would go` : `${s.expired} expired, ${s.trimmed} trimmed`}${s.remainingOverCap ? "; still over its cap, run gc again" : ""}`);
|
|
112
125
|
for (const s of result.skipped) lines.push(`${s.key}: skipped (${s.reason})`);
|
|
113
126
|
return (lines.length ? lines : ["no project shards"]).join("\n");
|