@staix/agent-mem 0.37.0 → 0.39.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/brief-curated.ts +8 -4
- package/src/cli-agent-reads.ts +55 -4
- package/src/cli.ts +222 -93
- package/src/commands-table.ts +332 -171
- package/src/index.ts +5 -0
- package/src/memory/capacity-text.ts +100 -0
- package/src/memory/capacity.ts +1 -57
- package/src/memory/commands.ts +45 -9
- package/src/memory/curated-cache-state.ts +22 -3
- package/src/memory/doctor-text.ts +144 -0
- package/src/memory/doctor.ts +9 -86
- package/src/memory/eval-audit-text.ts +62 -0
- package/src/memory/eval-audit.ts +1 -34
- package/src/memory/eval-text.ts +32 -0
- package/src/memory/eval.ts +1 -14
- package/src/memory/formats.ts +2 -0
- package/src/memory/gc-text.ts +22 -0
- package/src/memory/gc.ts +0 -6
- package/src/memory/generation-index.ts +1 -1
- package/src/memory/index-file.ts +1 -1
- package/src/memory/metrics.ts +18 -10
- package/src/memory/migrate-text.ts +32 -0
- package/src/memory/migrate.ts +0 -29
- package/src/memory/prune-text.ts +29 -0
- package/src/memory/prune.ts +0 -26
- package/src/memory/report-text.ts +233 -0
- package/src/memory/shard-migration-text.ts +40 -0
- package/src/memory/shard-migration.ts +0 -37
- package/src/memory/status-text.ts +72 -29
- package/src/memory/store.ts +112 -17
- package/src/memory/style.ts +98 -1
- package/src/memory/sync-placement-bound.ts +2 -2
- package/src/memory/sync-placement-checkpoint-person.ts +1 -1
- package/src/memory/sync-placement-noop-cache.ts +93 -0
- package/src/memory/sync-placement-refusal-category.ts +18 -0
- package/src/memory/sync-placement-transport.ts +43 -7
- package/src/memory/sync-progress-text.ts +7 -0
- package/src/memory/sync-progress.ts +21 -7
- package/src/memory/sync-screen.ts +13 -0
- package/src/memory/work-lists.ts +6 -4
- package/src/setup-drift.ts +1 -1
- package/src/setup-writer-roots.ts +136 -0
- package/src/setup.ts +122 -159
- package/src/sync-placement-writer-context.ts +8 -3
- package/src/ui/plugin.ts +4 -2
- package/src/work-brief-preparation.ts +28 -0
package/src/index.ts
CHANGED
|
@@ -9,9 +9,11 @@ export type { CuratedDoc, RankedRef } from "./memory/search-fts.ts";
|
|
|
9
9
|
export * from "./memory/shard.ts";
|
|
10
10
|
export * from "./memory/catalog.ts";
|
|
11
11
|
export * from "./memory/capacity.ts";
|
|
12
|
+
export { capacityApplyText, capacitySplitText, capacityText } from "./memory/capacity-text.ts";
|
|
12
13
|
export * from "./memory/lifecycle.ts";
|
|
13
14
|
export * from "./memory/usage.ts";
|
|
14
15
|
export * from "./memory/gc.ts";
|
|
16
|
+
export { gcText } from "./memory/gc-text.ts";
|
|
15
17
|
export * from "./memory/project-export.ts";
|
|
16
18
|
export * from "./memory/project-import.ts";
|
|
17
19
|
export * from "./memory/external-import.ts";
|
|
@@ -38,8 +40,11 @@ export type {
|
|
|
38
40
|
export * from "./memory/ops-contract.ts";
|
|
39
41
|
export * from "./memory/generation.ts";
|
|
40
42
|
export * from "./memory/migrate.ts";
|
|
43
|
+
export { migrationText } from "./memory/migrate-text.ts";
|
|
41
44
|
export * from "./memory/prune.ts";
|
|
45
|
+
export { pruneText } from "./memory/prune-text.ts";
|
|
42
46
|
export * from "./memory/shard-migration.ts";
|
|
47
|
+
export { shardMigrationText } from "./memory/shard-migration-text.ts";
|
|
43
48
|
|
|
44
49
|
export * from "./mcp.ts";
|
|
45
50
|
export * from "./mcp-memory.ts";
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Report } from "@staix/cli-output";
|
|
2
|
+
import { facts, humanBytes, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
3
|
+
import type { CapacityReport } from "./capacity.ts";
|
|
4
|
+
import type { CaptureConfig } from "./capture.ts";
|
|
5
|
+
|
|
6
|
+
const MB = 1048576;
|
|
7
|
+
|
|
8
|
+
/** #592: the human capacity output, kept out of capacity.ts so the write path never imports the output package. */
|
|
9
|
+
interface CapacityRender { columns?: number; style?: Style; next?: string }
|
|
10
|
+
/** The non-JSON rendering of `amem capacity`. */
|
|
11
|
+
export function capacityText(report: CapacityReport, render?: CapacityRender): string {
|
|
12
|
+
if (render) {
|
|
13
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
14
|
+
out.header("amem", "Capacity"); out.section("Capture");
|
|
15
|
+
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`]]);
|
|
16
|
+
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]] : [])]);
|
|
17
|
+
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]]);
|
|
18
|
+
if (report.splitRefused) out.bullet("warn", `Split unavailable: ${report.splitRefused}`);
|
|
19
|
+
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"); }
|
|
20
|
+
out.line(""); out.line(`Summary: 1 capacity proposal, ${report.split.length} shard proposals`);
|
|
21
|
+
return out.render(s.color).join("\n");
|
|
22
|
+
}
|
|
23
|
+
const mb = (n: number): string => `${(n / MB).toFixed(1)} MB`;
|
|
24
|
+
return [
|
|
25
|
+
`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`,
|
|
26
|
+
`disk: ${mb(report.disk.freeBytes)} free of ${mb(report.disk.totalBytes)}; memory: ${mb(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`,
|
|
27
|
+
`metrics: ${report.metrics.samples} samples (hook p95 ${report.metrics.hookP95Ms?.toFixed(1) ?? "?"} ms, search peak ${report.metrics.searchRssMB?.toFixed(1) ?? "?"} MB)`,
|
|
28
|
+
...(report.metrics.mcpPhasePeak ? [`MCP phase peak: ${report.metrics.mcpPhasePeak.phase} ${report.metrics.mcpPhasePeak.rssMB.toFixed(1)} MB (${report.metrics.mcpPhasePeak.shared ? "shared peak" : report.metrics.mcpPhasePeak.peakRaised ? "peak raised" : "not attributed"})`] : []),
|
|
29
|
+
`projected capture in ${report.projected.days} days: ${mb(report.projected.bytes)}`,
|
|
30
|
+
`current: cap ${report.current.capMb} MB, retention ${report.current.retentionDays} days`,
|
|
31
|
+
`proposal: cap ${report.proposal.capMb} MB, retention ${report.proposal.retentionDays} days (${report.proposal.reason})`,
|
|
32
|
+
...(report.splitRefused ? [`split: none proposed (${report.splitRefused})`] : []),
|
|
33
|
+
...(report.split.length ? ["split of the global budget per shard (a proposal: amem capacity apply --split):", ...report.split.map(row => ` ${row.key}: cap ${row.capMb} MB, retention ${row.retentionDays} days (${row.reason})`)] : []),
|
|
34
|
+
].join("\n");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Human-readable `capacity apply` result. JSON output remains the caller's responsibility. */
|
|
38
|
+
export function capacityApplyText(result: {
|
|
39
|
+
preview: { file: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string };
|
|
40
|
+
confirm?: string;
|
|
41
|
+
written?: { cap_mb?: number; retention_days?: number };
|
|
42
|
+
}, s: Style = PLAIN, render?: CapacityRender): string {
|
|
43
|
+
const applied = result.written !== undefined;
|
|
44
|
+
if (render) {
|
|
45
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
46
|
+
out.header("amem", "Capacity apply"); out.section(applied ? "Applied" : "Preview");
|
|
47
|
+
out.bullet(applied ? "ok" : "pending", applied ? "Capacity settings written." : "Capacity settings are ready for review.");
|
|
48
|
+
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]] : [])]);
|
|
49
|
+
if (!applied && render.next) out.next(render.next);
|
|
50
|
+
return out.render(s.color).join("\n");
|
|
51
|
+
}
|
|
52
|
+
return [
|
|
53
|
+
`amem capacity apply: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
54
|
+
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(result.preview.file)}`,
|
|
55
|
+
`${label(s, "ok")} current: ${facts({ cap_mb: result.preview.current.capMb, retention_days: result.preview.current.retentionDays }) || "defaults"}`,
|
|
56
|
+
`${label(s, "attention")} proposed: ${facts({ cap_mb: result.preview.target.capMb, retention_days: result.preview.target.retentionDays })}`,
|
|
57
|
+
`${label(s, "ok")} reason: ${singleLine(result.preview.reason)}`,
|
|
58
|
+
...(applied ? [`${label(s, "ok")} written: ${facts(result.written!) || "no settings reported"}`] : []),
|
|
59
|
+
`Next action: ${applied ? "none" : "re-run the same capacity apply command with --confirm, keeping all other arguments"}`,
|
|
60
|
+
].join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Human-readable `capacity apply --split` result, retaining skipped shard identities. */
|
|
64
|
+
export function capacitySplitText(result:
|
|
65
|
+
| { at: number; split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; skipped: string[]; confirm: string }
|
|
66
|
+
| { split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; written: { key: string; cap_mb: number; retention_days: number }[] },
|
|
67
|
+
s: Style = PLAIN, render?: CapacityRender,
|
|
68
|
+
): string {
|
|
69
|
+
const applied = "written" in result;
|
|
70
|
+
if (render) {
|
|
71
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
72
|
+
out.header("amem", "Capacity split"); out.section(applied ? "Applied" : "Preview");
|
|
73
|
+
out.bullet(applied ? "ok" : "pending", applied ? "Shard settings written." : "Shard settings are ready for review.");
|
|
74
|
+
if (!result.split.length) out.note("No shard settings to change.");
|
|
75
|
+
for (const row of result.split) {
|
|
76
|
+
const written = "written" in result ? result.written.find(item => item.key === row.key) : undefined;
|
|
77
|
+
out.section("Shard");
|
|
78
|
+
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]] : [])]);
|
|
79
|
+
}
|
|
80
|
+
if ("skipped" in result) for (const key of result.skipped) out.bullet("absent", `${key}: no local shard config to write`);
|
|
81
|
+
if (!applied && result.split.length && render.next) out.next(render.next);
|
|
82
|
+
return out.render(s.color).join("\n");
|
|
83
|
+
}
|
|
84
|
+
const rows = result.split.map(row => [
|
|
85
|
+
`${label(s, applied ? "ok" : "attention")} shard: ${singleLine(row.key)}`,
|
|
86
|
+
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(row.dir)}`,
|
|
87
|
+
`${label(s, "ok")} current: ${facts({ cap_mb: row.current.capMb, retention_days: row.current.retentionDays }) || "defaults"}`,
|
|
88
|
+
`${label(s, applied ? "ok" : "attention")} proposed: ${facts({ cap_mb: row.target.capMb, retention_days: row.target.retentionDays })}`,
|
|
89
|
+
`${label(s, "ok")} reason: ${singleLine(row.reason)}`,
|
|
90
|
+
].join("\n"));
|
|
91
|
+
const skipped = "skipped" in result ? result.skipped : [];
|
|
92
|
+
return [
|
|
93
|
+
`amem capacity apply --split: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
94
|
+
...(result.split.length ? [] : [`${label(s, "skipped")} targets: none`]),
|
|
95
|
+
...rows,
|
|
96
|
+
...skipped.map(key => `${label(s, "skipped")} skipped shard: ${singleLine(key)} (no local shard config to write)`),
|
|
97
|
+
...(applied ? result.written.map(row => `${label(s, "ok")} written ${singleLine(row.key)}: ${facts({ cap_mb: row.cap_mb, retention_days: row.retention_days })}`) : []),
|
|
98
|
+
`Next action: ${applied || !result.split.length ? "none" : "re-run the same capacity apply --split command with --confirm, keeping all other arguments"}`,
|
|
99
|
+
].join("\n");
|
|
100
|
+
}
|
package/src/memory/capacity.ts
CHANGED
|
@@ -8,7 +8,7 @@ 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
|
-
|
|
11
|
+
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* #13 R7: the capacity advisor. `capacityReport()` reads this machine's load and proposes capture bounds; the
|
|
@@ -273,61 +273,5 @@ export function capacityReport(opts: {
|
|
|
273
273
|
};
|
|
274
274
|
}
|
|
275
275
|
|
|
276
|
-
/** The non-JSON rendering of `amem capacity`. */
|
|
277
|
-
export function capacityText(report: CapacityReport): string {
|
|
278
|
-
const mb = (n: number): string => `${(n / MB).toFixed(1)} MB`;
|
|
279
|
-
return [
|
|
280
|
-
`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`,
|
|
281
|
-
`disk: ${mb(report.disk.freeBytes)} free of ${mb(report.disk.totalBytes)}; memory: ${mb(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`,
|
|
282
|
-
`metrics: ${report.metrics.samples} samples (hook p95 ${report.metrics.hookP95Ms?.toFixed(1) ?? "?"} ms, search peak ${report.metrics.searchRssMB?.toFixed(1) ?? "?"} MB)`,
|
|
283
|
-
...(report.metrics.mcpPhasePeak ? [`MCP phase peak: ${report.metrics.mcpPhasePeak.phase} ${report.metrics.mcpPhasePeak.rssMB.toFixed(1)} MB (${report.metrics.mcpPhasePeak.shared ? "shared peak" : report.metrics.mcpPhasePeak.peakRaised ? "peak raised" : "not attributed"})`] : []),
|
|
284
|
-
`projected capture in ${report.projected.days} days: ${mb(report.projected.bytes)}`,
|
|
285
|
-
`current: cap ${report.current.capMb} MB, retention ${report.current.retentionDays} days`,
|
|
286
|
-
`proposal: cap ${report.proposal.capMb} MB, retention ${report.proposal.retentionDays} days (${report.proposal.reason})`,
|
|
287
|
-
...(report.splitRefused ? [`split: none proposed (${report.splitRefused})`] : []),
|
|
288
|
-
...(report.split.length ? ["split of the global budget per shard (a proposal: amem capacity apply --split):", ...report.split.map(row => ` ${row.key}: cap ${row.capMb} MB, retention ${row.retentionDays} days (${row.reason})`)] : []),
|
|
289
|
-
].join("\n");
|
|
290
|
-
}
|
|
291
276
|
|
|
292
|
-
/** Human-readable `capacity apply` result. JSON output remains the caller's responsibility. */
|
|
293
|
-
export function capacityApplyText(result: {
|
|
294
|
-
preview: { file: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string };
|
|
295
|
-
confirm?: string;
|
|
296
|
-
written?: { cap_mb?: number; retention_days?: number };
|
|
297
|
-
}, s: Style = PLAIN): string {
|
|
298
|
-
const applied = result.written !== undefined;
|
|
299
|
-
return [
|
|
300
|
-
`amem capacity apply: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
301
|
-
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(result.preview.file)}`,
|
|
302
|
-
`${label(s, "ok")} current: ${facts({ cap_mb: result.preview.current.capMb, retention_days: result.preview.current.retentionDays }) || "defaults"}`,
|
|
303
|
-
`${label(s, "attention")} proposed: ${facts({ cap_mb: result.preview.target.capMb, retention_days: result.preview.target.retentionDays })}`,
|
|
304
|
-
`${label(s, "ok")} reason: ${singleLine(result.preview.reason)}`,
|
|
305
|
-
...(applied ? [`${label(s, "ok")} written: ${facts(result.written!) || "no settings reported"}`] : []),
|
|
306
|
-
`Next action: ${applied ? "none" : "re-run the same capacity apply command with --confirm, keeping all other arguments"}`,
|
|
307
|
-
].join("\n");
|
|
308
|
-
}
|
|
309
277
|
|
|
310
|
-
/** Human-readable `capacity apply --split` result, retaining skipped shard identities. */
|
|
311
|
-
export function capacitySplitText(result:
|
|
312
|
-
| { at: number; split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; skipped: string[]; confirm: string }
|
|
313
|
-
| { 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,
|
|
315
|
-
): string {
|
|
316
|
-
const applied = "written" in result;
|
|
317
|
-
const rows = result.split.map(row => [
|
|
318
|
-
`${label(s, applied ? "ok" : "attention")} shard: ${singleLine(row.key)}`,
|
|
319
|
-
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(row.dir)}`,
|
|
320
|
-
`${label(s, "ok")} current: ${facts({ cap_mb: row.current.capMb, retention_days: row.current.retentionDays }) || "defaults"}`,
|
|
321
|
-
`${label(s, applied ? "ok" : "attention")} proposed: ${facts({ cap_mb: row.target.capMb, retention_days: row.target.retentionDays })}`,
|
|
322
|
-
`${label(s, "ok")} reason: ${singleLine(row.reason)}`,
|
|
323
|
-
].join("\n"));
|
|
324
|
-
const skipped = "skipped" in result ? result.skipped : [];
|
|
325
|
-
return [
|
|
326
|
-
`amem capacity apply --split: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
327
|
-
...(result.split.length ? [] : [`${label(s, "skipped")} targets: none`]),
|
|
328
|
-
...rows,
|
|
329
|
-
...skipped.map(key => `${label(s, "skipped")} skipped shard: ${singleLine(key)} (no local shard config to write)`),
|
|
330
|
-
...(applied ? result.written.map(row => `${label(s, "ok")} written ${singleLine(row.key)}: ${facts({ cap_mb: row.cap_mb, retention_days: row.retention_days })}`) : []),
|
|
331
|
-
`Next action: ${applied || !result.split.length ? "none" : "re-run the same capacity apply --split command with --confirm, keeping all other arguments"}`,
|
|
332
|
-
].join("\n");
|
|
333
|
-
}
|
package/src/memory/commands.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import { PlacementSyncBoundError } from "./sync-placement-bound.ts";
|
|
1
2
|
import { cliAttribution, noteDisplayActor } from "./cli-attribution.ts";
|
|
2
3
|
import { extractNodes, GOAL_STATES, KINDS, MemoryStore, setMachineLabel, type GoalState, type GoalView, type Kind, type Tier, type View } from "./store.ts";
|
|
3
4
|
import { syncMemory, type SyncOptions } from "./sync.ts";
|
|
4
5
|
import { importClaudeMem, type ImportResult, type WorkStateImportResult, type CaptureImportResult } from "./import.ts";
|
|
5
|
-
import {
|
|
6
|
+
import { syncReportText } from "./report-text.ts";
|
|
7
|
+
import { CLI_MEMORY_RENDER, facts, label, memoryDetailText, memoryScoresText, memoryTableText, PLAIN, relativeTime, singleLine, type HumanMemoryRender, type Style } from "./style.ts";
|
|
8
|
+
import { Report } from "@staix/cli-output";
|
|
6
9
|
import { memoryProjectKey, projectChain } from "./project.ts";
|
|
7
10
|
import { recallForViews, recallGraph, recallRows, recallShow } from "./recall.ts";
|
|
8
11
|
import type { GoalPromotionReport } from "./goal-promotion.ts";
|
|
@@ -71,13 +74,26 @@ const fail = (message: string): never => { throw new Error(message); };
|
|
|
71
74
|
|
|
72
75
|
/** A person-facing aggregate receipt; import results and their JSON representation stay untouched. */
|
|
73
76
|
export function claudeMemImportText(notes: ImportResult, work: WorkStateImportResult, capture?: CaptureImportResult,
|
|
74
|
-
options: { captureDays?: number; restart?: boolean } = {}, s: Style = PLAIN): string {
|
|
77
|
+
options: { captureDays?: number; restart?: boolean } = {}, s: Style = PLAIN, render?: { columns?: number; next?: string }): string {
|
|
75
78
|
const more = notes.more || work.more || capture?.more === true;
|
|
76
79
|
const row = (name: string, result: { read: number; added: number; more: boolean }, skipped: number, spooled?: number) =>
|
|
77
80
|
`${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
81
|
const noteSkipped = notes.read - notes.added, workSkipped = work.read - work.added;
|
|
79
82
|
const otherNotes = Math.max(0, noteSkipped - notes.skipped.model - notes.skipped.pii - notes.skipped.secret);
|
|
80
83
|
const duplicateWork = Math.max(0, workSkipped - work.skipped.invalid - work.skipped.policy);
|
|
84
|
+
if (render) {
|
|
85
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
86
|
+
out.header("amem", "Import claude-mem"); out.section("Receipts");
|
|
87
|
+
out.bullet(more || capture?.spooled ? "warn" : "ok", more ? "More rows remain to import." : capture?.spooled ? "Import completed; capture rows are spooled." : "Import completed.");
|
|
88
|
+
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"]]);
|
|
89
|
+
if (capture?.skipped) out.note(`Capture skipped ${capture.skipped} rows (empty, invalid, policy or already imported; no breakdown reported).`);
|
|
90
|
+
if (capture && options.captureDays !== undefined) out.note(`Capture window: last ${options.captureDays} days. Widening --capture-days later requires --restart.`);
|
|
91
|
+
if (options.restart) out.note("Selected cursors replayed from the start; existing receipts prevent duplicates.");
|
|
92
|
+
if (more && render.next) out.next(render.next);
|
|
93
|
+
else if (more) out.bullet("warn", "Some rows remain; inspect --json and rerun without --restart.");
|
|
94
|
+
else if (capture?.spooled) out.note("The next capture write replays rows spooled while the store was busy.");
|
|
95
|
+
return out.render(s.color).join("\n");
|
|
96
|
+
}
|
|
81
97
|
const lines = [`amem import claude-mem: ${more ? s.attention("run again") : s.ok("complete")}`,
|
|
82
98
|
row("notes", notes, noteSkipped),
|
|
83
99
|
` skipped reasons: ${facts({ model: notes.skipped.model, PII: notes.skipped.pii, secret: notes.skipped.secret, "empty/malformed/already imported": otherNotes }) || "none"}`,
|
|
@@ -98,12 +114,15 @@ export function claudeMemImportText(notes: ImportResult, work: WorkStateImportRe
|
|
|
98
114
|
}
|
|
99
115
|
|
|
100
116
|
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)})` : ""}`;
|
|
117
|
+
|
|
101
118
|
function detail(v: View): string[] {
|
|
102
119
|
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
120
|
...(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
121
|
}
|
|
105
122
|
|
|
106
123
|
export async function rawMemoryCommand(args: string[], cwd: string, opts: MemoryCommandOptions): Promise<string> {
|
|
124
|
+
// CLI-only presentation options do not extend the exported host API.
|
|
125
|
+
const internal = (opts as MemoryCommandOptions & { [CLI_MEMORY_RENDER]?: { render: HumanMemoryRender; renderLegacy?: (legacy: string, formatted: string) => string } })[CLI_MEMORY_RENDER];
|
|
107
126
|
const json = args.includes("--json");
|
|
108
127
|
const rest = args.filter((a) => a !== "--json");
|
|
109
128
|
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 +159,7 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
140
159
|
};
|
|
141
160
|
const staleDetail = (view: View): string[] => { const marker = staleMarker(view).trimEnd(); return marker ? [marker] : []; };
|
|
142
161
|
const ready = (rows: readonly View[]) => { try { opts.outputReady?.(rows); } catch { /* optional output metadata cannot fail recall */ } };
|
|
162
|
+
const rendered = (legacy: string, formatted: string) => internal?.renderLegacy ? internal.renderLegacy(legacy, formatted) : formatted;
|
|
143
163
|
const decorated = (view: View) => { const info = staleInfo(view); return { ...view, ...(info.stale ? { stale: true, ...(info.reason ? { staleReason: info.reason } : {}) } : {}) }; };
|
|
144
164
|
if (!["list", "search", "show", "graph"].includes(sub) && (rest.includes("--history") || rest.includes("--as-of"))) fail("history/as-of apply only to memory reads");
|
|
145
165
|
try {
|
|
@@ -175,15 +195,23 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
175
195
|
const emitted = recallForViews(state, rows), publicIds = new Set(rows.map(view => view.id)), allForgotten = q?.trim() ? [] : state.forgotten;
|
|
176
196
|
const forgotten = allForgotten.slice(0, Math.max(0, (limit ? Math.floor(Number(limit)) : 50) - rows.length));
|
|
177
197
|
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
|
-
|
|
198
|
+
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");
|
|
199
|
+
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"));
|
|
200
|
+
return json ? JSON.stringify(result, null, 2) : legacy;
|
|
179
201
|
}
|
|
180
202
|
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
203
|
const counted = opts.readable(store.withDeferredPromotions(() => store.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
|
|
182
204
|
const withheld = all.length - readable.length;
|
|
183
|
-
|
|
205
|
+
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
206
|
? rows.flatMap(view => [`${staleMarker(view)}${one(view)}${foldNote(view)}`, ...(scoreDetails?.has(view.id) ? [`score: ${JSON.stringify(scoreDetails.get(view.id))}`] : [])])
|
|
185
207
|
: rows.map(view => `${staleMarker(view)}${one(view)}${foldNote(view)}`) : ["(nothing)"]),
|
|
186
208
|
...(withheld ? [`(${withheld} withheld: they match a PII pattern; the dashboard shows them)`] : [])].join("\n");
|
|
209
|
+
if (internal?.render) {
|
|
210
|
+
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.`);
|
|
211
|
+
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) : "";
|
|
212
|
+
return rendered(legacy, [table, scores, ...(withheld ? [`${withheld} entries withheld by policy; review them in the dashboard.`] : [])].filter(Boolean).join("\n\n"));
|
|
213
|
+
}
|
|
214
|
+
return legacy;
|
|
187
215
|
}
|
|
188
216
|
case "show": {
|
|
189
217
|
const asOf = flag("--as-of"), history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
|
|
@@ -193,10 +221,12 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
193
221
|
if (shown.state) {
|
|
194
222
|
const rows = opts.readable(shown.state.views), ids = new Set(rows.map(view => view.id)); ready(rows);
|
|
195
223
|
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
|
-
|
|
224
|
+
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");
|
|
225
|
+
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"));
|
|
226
|
+
return json ? JSON.stringify(state, null, 2) : legacy;
|
|
197
227
|
}
|
|
198
228
|
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");
|
|
229
|
+
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
230
|
}
|
|
201
231
|
case "graph": {
|
|
202
232
|
const hops = Number(flag("--hops") ?? 1);
|
|
@@ -233,12 +263,18 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
233
263
|
const realmLines = r.placementRealms?.length ? `\n${r.placementRealms.map(item => `realm ${item.realm === "user" ? "user" : item.realm.slice(0, 16)}: ${item.outcome}${item.publication ? ` (publication ${item.publication})` : ""}`).join("\n")}` : "";
|
|
234
264
|
// #578 Q2: one counts-only line when this sync ran a placement checkpoint.
|
|
235
265
|
const checkpointLine = r.checkpoint ? `\nplacement checkpoint: window ${r.checkpoint.window}, objects ${r.checkpoint.objectsBefore} -> ${r.checkpoint.objectsAfter}` : "";
|
|
236
|
-
if (!r.ok)
|
|
266
|
+
if (!r.ok) {
|
|
267
|
+
const bound = placement?.bound;
|
|
268
|
+
if (internal && cliAttribution()?.actor === "agent" && bound && (r.failure?.cause === "bound" || r.failure?.cause === "checkpoint-refused")) throw new PlacementSyncBoundError(bound);
|
|
269
|
+
fail(`${names.memory} sync: ${r.error}${checkpointLine}${realmLines}`);
|
|
270
|
+
}
|
|
271
|
+
// #590 (task 429): the CLI renders the success report; hosts keep the legacy line below byte for byte.
|
|
272
|
+
const cliSync = (legacy: string) => internal ? rendered(legacy, syncReportText(r, internal.render.style ?? PLAIN, { columns: internal.render.columns ?? 80 })) : legacy;
|
|
237
273
|
if (r.pruneApplication) {
|
|
238
274
|
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}
|
|
275
|
+
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
276
|
}
|
|
241
|
-
return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${checkpointLine}${realmLines}
|
|
277
|
+
return cliSync(`synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${checkpointLine}${realmLines}`);
|
|
242
278
|
}
|
|
243
279
|
case "dedupe": {
|
|
244
280
|
const apply = rest.includes("--apply");
|
|
@@ -9,10 +9,19 @@ export function curatedProfileBinding(base: string, project: string): string {
|
|
|
9
9
|
shards: existsSync(join(base, "shards.json")) ? readShardedSelection(base) : null,
|
|
10
10
|
aliases: aliasedKeys(base, project) });
|
|
11
11
|
}
|
|
12
|
+
export interface CuratedCacheCandidate { project: string; activity: number; warm: boolean }
|
|
13
|
+
|
|
14
|
+
function fileActivity(file: string): number | undefined {
|
|
15
|
+
try {
|
|
16
|
+
const stat = lstatSync(file, { throwIfNoEntry: false });
|
|
17
|
+
if (stat?.isFile()) return stat.mtimeMs;
|
|
18
|
+
} catch { /* An unreadable derived file gives no activity signal. */ }
|
|
19
|
+
}
|
|
20
|
+
|
|
12
21
|
/** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs.
|
|
13
22
|
* #424: `projects` limits removal to those projects' cache directories (an alias resolves to its canonical directory),
|
|
14
23
|
* so one project's write keeps every other project's prebuilt brief. Omitted, every project is invalidated. */
|
|
15
|
-
export function invalidateCuratedCaches(base: string, projects?: readonly string[]): string[] {
|
|
24
|
+
export function invalidateCuratedCaches(base: string, projects?: readonly string[], observe?: { machine: string; now: number; candidate: (candidate: CuratedCacheCandidate) => void }): string[] {
|
|
16
25
|
const invalidated = new Set<string>(), root = join(base, "projects");
|
|
17
26
|
if (!existsSync(root)) return [];
|
|
18
27
|
const only = projects && new Set(projects.flatMap(project => [shardKeyHash(project), shardKeyHash(resolveAlias(base, project))]));
|
|
@@ -22,8 +31,18 @@ export function invalidateCuratedCaches(base: string, projects?: readonly string
|
|
|
22
31
|
if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
|
|
23
32
|
const descriptor = readShardDescriptor(base, hash);
|
|
24
33
|
const machines = join(directory, "machine");
|
|
25
|
-
|
|
26
|
-
|
|
34
|
+
const parent = lstatSync(machines, { throwIfNoEntry: false });
|
|
35
|
+
if (parent && !parent.isDirectory()) continue;
|
|
36
|
+
if (observe && descriptor && shardKeyHash(descriptor.key) === hash && fileActivity(join(directory, "generation.json")) !== undefined) {
|
|
37
|
+
const scope = join(machines, observe.machine);
|
|
38
|
+
const local = lstatSync(scope, { throwIfNoEntry: false });
|
|
39
|
+
if (!local || local.isDirectory()) {
|
|
40
|
+
const lastCurated = fileActivity(join(scope, "brief-curated.json"));
|
|
41
|
+
observe.candidate({ project: descriptor.key, activity: fileActivity(join(scope, "brief-capture.json")) ?? 0,
|
|
42
|
+
warm: lastCurated !== undefined && observe.now - lastCurated < 24 * 60 * 60 * 1000 });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!parent) continue;
|
|
27
46
|
for (const machine of readdirSync(machines)) {
|
|
28
47
|
if (!/^[a-f0-9]{16}$/.test(machine)) continue;
|
|
29
48
|
const scope = join(machines, machine), info = lstatSync(scope);
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { CLIS, type DoctorReport, type Section, type SectionStatus } from "./doctor.ts";
|
|
2
|
+
import { humanBytes, relativeTime, singleLine, wordedFacts, wordedKey, PLAIN, type Style } from "./style.ts";
|
|
3
|
+
import { validPlacementWriterRefusal } from "./sync-placement-refusal-category.ts";
|
|
4
|
+
import { writerRefusalText } from "./sync-progress-text.ts";
|
|
5
|
+
import { attention, reportFrame, stateRows, STATE_WORD, type Finding, type ReportTextOptions } from "./status-text.ts";
|
|
6
|
+
|
|
7
|
+
/** #592: the human doctor report, kept out of doctor.ts so the doctor's checks never import the output package. */
|
|
8
|
+
/** Section order and one-line names for the person-facing report (#125). */
|
|
9
|
+
const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
|
|
10
|
+
duplicates: "duplicate notes", stale: "stale path references", candidates: "review candidates", capture: "capture per CLI", brief: "session brief",
|
|
11
|
+
index: "index equals rebuild", readers: "reader leases", policy: "policy in effect", cadence: "ingest and sync cadence", drops: "recent capture drops",
|
|
12
|
+
writers: "placement writers",
|
|
13
|
+
spool: "pending hook spool",
|
|
14
|
+
setup: "native setup registrations",
|
|
15
|
+
masked: "forgotten or pruned entries (informational)",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* #590 C4: every hint a section emits, as one finding and the complete commands that act on it. `--json` keeps the hint text unchanged;
|
|
20
|
+
* 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.
|
|
21
|
+
* `test/status-doctor-layout.test.ts` checks every hint producer against this table.
|
|
22
|
+
*/
|
|
23
|
+
export const DOCTOR_HINTS: Readonly<Record<string, (section: Record<string, unknown>) => Finding>> = {
|
|
24
|
+
"amem dedupe previews the imported duplicates; amem dedupe --apply reconciles them": () =>
|
|
25
|
+
({ text: "imported duplicate notes can be reconciled", next: ["amem dedupe", "amem dedupe --apply"] }),
|
|
26
|
+
"The person can inspect these examples with amem show <id> from their own shell.": section => {
|
|
27
|
+
const first = Array.isArray(section.examples) ? String(section.examples[0] ?? "") : "";
|
|
28
|
+
// #511 AC3: an agent-marked `show` may withhold these ids, so the finding says where they open.
|
|
29
|
+
return { text: `${section.missingReferences} notes reference paths that no longer exist; open the examples from your own shell`, next: first ? [`amem show ${first}`] : [] };
|
|
30
|
+
},
|
|
31
|
+
"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"] }),
|
|
32
|
+
"a section is partial or unavailable in the brief: see coverage": () => ({ text: "a brief section is partial or unavailable", next: [] }),
|
|
33
|
+
"the brief uses over 90% of its budget": () => ({ text: "the session brief uses over 90% of its budget", next: [] }),
|
|
34
|
+
"a reader lease of a process that is gone is cleared by the next reader; an unreadable one needs a look": () =>
|
|
35
|
+
({ text: "a reader lease is stale or unreadable; the next reader clears a stale one", next: [] }),
|
|
36
|
+
"capture rows were dropped recently (see counts by reason); amem doctor --json keeps the numbers": () =>
|
|
37
|
+
({ text: "capture rows were dropped recently", next: ["amem doctor --json"] }),
|
|
38
|
+
"pending hook spool needs attention: capture can be dropped when both tiers fill; supported orphan recovery is pending": () =>
|
|
39
|
+
({ text: "the hook spool is nearly full; capture is dropped when both tiers fill", next: [] }),
|
|
40
|
+
"sync has failed repeatedly; amem sync --force shows why": () => ({ text: "sync has failed 3 or more times in a row", next: ["amem sync --force"] }),
|
|
41
|
+
"no recent successful sync: run amem sync": () => ({ text: "no recent successful sync", next: ["amem sync"] }),
|
|
42
|
+
"run amem review walk": section => ({ text: `${section.dueWithin7Days} candidates expire within 7 days`, next: ["amem review walk"] }),
|
|
43
|
+
};
|
|
44
|
+
/** Capture hints name a CLI; each maps to a finding and the commands for that CLI. */
|
|
45
|
+
export function captureFinding(cli: string, hint: string): Finding {
|
|
46
|
+
const known = new Set<string>(CLIS);
|
|
47
|
+
const ingest = known.has(cli) && cli !== "claude" ? [`amem ingest ${cli}`] : [];
|
|
48
|
+
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 };
|
|
49
|
+
if (hint.startsWith("run amem setup")) return { text: `${cli}: capture is not set up`, next: known.has(cli) ? [`amem setup ${cli} --apply`, ...ingest] : [] };
|
|
50
|
+
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: [] };
|
|
51
|
+
const state = /capture is (\w+)/.exec(hint)?.[1] ?? "not fresh", where = hint.includes("on this machine") ? "on this machine" : "in this project";
|
|
52
|
+
return { text: `${cli}: capture is ${state} ${where}; open a session`, next: ingest };
|
|
53
|
+
}
|
|
54
|
+
export function hintFinding(name: string, hint: string, section: Record<string, unknown>): Finding {
|
|
55
|
+
const mapped = DOCTOR_HINTS[hint];
|
|
56
|
+
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: [] };
|
|
57
|
+
}
|
|
58
|
+
/** #590 C6: a writer refusal is one finding; each command it names is one `→` line. The fixed refusal text stays in `--json`. */
|
|
59
|
+
export function writerFinding(section: Record<string, unknown>): Finding {
|
|
60
|
+
const reason = String(section.reason ?? "");
|
|
61
|
+
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]);
|
|
62
|
+
return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function sectionFact(name: string, detail: Record<string, unknown>, now: number): string[] {
|
|
66
|
+
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
67
|
+
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) =>
|
|
68
|
+
`${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}` : ""}`);
|
|
69
|
+
}
|
|
70
|
+
if (name === "cadence") {
|
|
71
|
+
const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
|
|
72
|
+
return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
|
|
73
|
+
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${relativeTime(sync.lastOkAt as string | null, now)}, ${sync.failures} failures${sync.due ? ", due" : ""}` : ""}`,
|
|
74
|
+
...(validPlacementWriterRefusal(sync.writerRefusal) ? [`last failure: ${writerRefusalText(sync.writerRefusal)}`] : [])];
|
|
75
|
+
}
|
|
76
|
+
if (name === "drops") {
|
|
77
|
+
if (detail.counts === undefined) return [];
|
|
78
|
+
const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
|
|
79
|
+
return [`${counts.length ? counts.map(([reason, n]) => `${reason.replaceAll("_", " ")} ${n}`).join(", ") : "none"} in the recent metrics tail${detail.malformedLines ? `, ${detail.malformedLines} malformed lines skipped` : ""}`];
|
|
80
|
+
}
|
|
81
|
+
if (name === "spool") {
|
|
82
|
+
if (!detail.active || !detail.reserve) return [];
|
|
83
|
+
const tiers = ["active", "reserve"].map(tierName => {
|
|
84
|
+
const tier = detail[tierName] as { files: number; bytes: number; maxFiles: number; maxBytes: number };
|
|
85
|
+
return `${tierName} ${tier.files} of ${tier.maxFiles} files, ${humanBytes(tier.bytes)} of ${humanBytes(tier.maxBytes)}`;
|
|
86
|
+
});
|
|
87
|
+
const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
|
|
88
|
+
return [`${String(detail.fill).replaceAll("_", " ")}; ${tiers.join("; ")}; ${detail.claimed} claimed${detail.oldestAt ? `, oldest ${relativeTime(String(detail.oldestAt), now)}` : ""}${detail.complete ? "" : " (counts are lower bounds)"}`,
|
|
89
|
+
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
90
|
+
}
|
|
91
|
+
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
92
|
+
const entries = detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[];
|
|
93
|
+
if (!entries.length) return [`${detail.checked ?? 0} registrations match their receipts`];
|
|
94
|
+
return entries.map(item => singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? `, expected ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
95
|
+
}
|
|
96
|
+
if (name === "writers") return typeof detail.writers === "number" ? [`${detail.writers} writers match the active inventory`] : [];
|
|
97
|
+
if (name === "brief" && typeof detail.tokens === "number") {
|
|
98
|
+
const missing = Object.entries((detail.coverage ?? {}) as Record<string, unknown>).filter(([, value]) => value && value !== "complete").map(([key, value]) => `${wordedKey(key)} ${value}`);
|
|
99
|
+
return [`${detail.tokens} of ${detail.budget} tokens${missing.length ? `, coverage: ${missing.join(", ")}` : ""}`];
|
|
100
|
+
}
|
|
101
|
+
if (name === "policy") return [`machine ${detail.machine ?? "none (defaults)"}, repo ${detail.repo ?? "none"}, ${detail.denyPaths} deny paths, ${detail.piiPatterns} PII patterns`];
|
|
102
|
+
if (name === "index") return detail.liveIndex ? [`live index ${detail.liveIndex}, equal to a rebuild`] : [];
|
|
103
|
+
if (name === "readers") return [`${detail.live ?? 0} live, ${detail.stale ?? 0} stale, ${detail.unreadable ?? 0} unreadable`];
|
|
104
|
+
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}` : ""}`,
|
|
105
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
106
|
+
if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
|
|
107
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
|
|
108
|
+
if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
|
|
109
|
+
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` : ""}`];
|
|
110
|
+
const { examples, note: _note, ...rest } = detail;
|
|
111
|
+
const line = wordedFacts(rest);
|
|
112
|
+
return [...(line ? [line] : []), ...(Array.isArray(examples) && examples.length ? [`examples ${examples.map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 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. */
|
|
116
|
+
export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportTextOptions & { now?: number } = {}): string {
|
|
117
|
+
const now = opts.now ?? Date.now();
|
|
118
|
+
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
119
|
+
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
120
|
+
const findings: Finding[] = [];
|
|
121
|
+
for (const [name, item] of entries) {
|
|
122
|
+
if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
|
|
123
|
+
if (item.hint) findings.push(hintFinding(name, item.hint, item));
|
|
124
|
+
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));
|
|
125
|
+
}
|
|
126
|
+
const out = reportFrame(s, "doctor", report.status === "skipped" ? "ok" : STATE_WORD[report.status], opts, report.home);
|
|
127
|
+
out.note(`project ${report.project}`);
|
|
128
|
+
attention(out, findings);
|
|
129
|
+
out.section("Checks", String(entries.length));
|
|
130
|
+
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
131
|
+
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
132
|
+
const rows = entries.flatMap(([name, section]) => {
|
|
133
|
+
const { status, hint: _hint, reason, ...detail } = section;
|
|
134
|
+
const facts = name === "writers" && status === "attention" ? [] : sectionFact(name, detail, now);
|
|
135
|
+
const writerRefusal = name === "writers" && status === "attention";
|
|
136
|
+
const fact = writerRefusal ? `${section.cause} (${section.category} category); see Attention`
|
|
137
|
+
: [...facts, ...(reason ? [singleLine(reason)] : [])].join("; ") || (status === "ok" ? "nothing to report" : SECTION_TITLE[name]);
|
|
138
|
+
return [{ state: status, name, fact }];
|
|
139
|
+
});
|
|
140
|
+
stateRows(out, rows, s);
|
|
141
|
+
if (count("skipped")) { out.line(""); out.note(`${count("skipped")} skipped: nothing to check here`); }
|
|
142
|
+
out.summary({ warnings: count("attention"), unknown: count("unavailable"), ok: count("ok") });
|
|
143
|
+
return out.render(s.color).join("\n");
|
|
144
|
+
}
|