@staix/agent-mem 0.38.0 → 0.40.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 +2 -1
- package/src/cli.ts +82 -32
- package/src/commands-table.ts +6 -3
- package/src/hooks.ts +4 -0
- package/src/index.ts +5 -0
- package/src/memory/capacity-text.ts +100 -0
- package/src/memory/capacity.ts +0 -92
- package/src/memory/commands.ts +6 -1
- package/src/memory/curated-cache-state.ts +22 -3
- package/src/memory/doctor-text.ts +148 -0
- package/src/memory/doctor.ts +19 -141
- package/src/memory/eval-audit-text.ts +62 -0
- package/src/memory/eval-audit.ts +0 -57
- package/src/memory/eval-text.ts +32 -0
- package/src/memory/eval.ts +0 -28
- package/src/memory/formats.ts +2 -0
- package/src/memory/gc-text.ts +22 -0
- package/src/memory/gc.ts +0 -19
- 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/project-export.ts +9 -4
- package/src/memory/prune-text.ts +29 -0
- package/src/memory/prune.ts +0 -26
- package/src/memory/report-text.ts +2 -0
- package/src/memory/roots.ts +145 -0
- package/src/memory/shard-migration-text.ts +40 -0
- package/src/memory/shard-migration.ts +0 -37
- package/src/memory/status-text.ts +5 -1
- package/src/memory/store.ts +112 -17
- package/src/memory/sync-placement-activation-locks.ts +7 -5
- package/src/memory/sync-placement-advertisement.ts +18 -0
- package/src/memory/sync-placement-bound.ts +2 -2
- package/src/memory/sync-placement-checkpoint-person.ts +2 -2
- package/src/memory/sync-placement-inventory.ts +4 -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 +80 -13
- package/src/memory/sync-placement-writer-renewal.ts +3 -1
- 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/session-brief.ts +16 -2
- package/src/setup-drift.ts +1 -1
- package/src/setup-writer-roots.ts +136 -0
- package/src/setup.ts +8 -118
- package/src/sync-placement-writer-context.ts +9 -4
- package/src/ui/inbox.ts +1 -1
- package/src/ui/plugin.ts +4 -2
- package/src/work-brief-preparation.ts +28 -0
package/src/memory/capacity.ts
CHANGED
|
@@ -8,10 +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
|
-
import { facts, humanBytes, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
12
|
-
import { Report } from "@staix/cli-output";
|
|
13
11
|
|
|
14
|
-
interface CapacityRender { columns?: number; style?: Style; next?: string }
|
|
15
12
|
|
|
16
13
|
/**
|
|
17
14
|
* #13 R7: the capacity advisor. `capacityReport()` reads this machine's load and proposes capture bounds; the
|
|
@@ -276,94 +273,5 @@ export function capacityReport(opts: {
|
|
|
276
273
|
};
|
|
277
274
|
}
|
|
278
275
|
|
|
279
|
-
/** The non-JSON rendering of `amem capacity`. */
|
|
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
|
-
}
|
|
292
|
-
const mb = (n: number): string => `${(n / MB).toFixed(1)} MB`;
|
|
293
|
-
return [
|
|
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`,
|
|
295
|
-
`disk: ${mb(report.disk.freeBytes)} free of ${mb(report.disk.totalBytes)}; memory: ${mb(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`,
|
|
296
|
-
`metrics: ${report.metrics.samples} samples (hook p95 ${report.metrics.hookP95Ms?.toFixed(1) ?? "?"} ms, search peak ${report.metrics.searchRssMB?.toFixed(1) ?? "?"} MB)`,
|
|
297
|
-
...(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"})`] : []),
|
|
298
|
-
`projected capture in ${report.projected.days} days: ${mb(report.projected.bytes)}`,
|
|
299
|
-
`current: cap ${report.current.capMb} MB, retention ${report.current.retentionDays} days`,
|
|
300
|
-
`proposal: cap ${report.proposal.capMb} MB, retention ${report.proposal.retentionDays} days (${report.proposal.reason})`,
|
|
301
|
-
...(report.splitRefused ? [`split: none proposed (${report.splitRefused})`] : []),
|
|
302
|
-
...(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})`)] : []),
|
|
303
|
-
].join("\n");
|
|
304
|
-
}
|
|
305
276
|
|
|
306
|
-
/** Human-readable `capacity apply` result. JSON output remains the caller's responsibility. */
|
|
307
|
-
export function capacityApplyText(result: {
|
|
308
|
-
preview: { file: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string };
|
|
309
|
-
confirm?: string;
|
|
310
|
-
written?: { cap_mb?: number; retention_days?: number };
|
|
311
|
-
}, s: Style = PLAIN, render?: CapacityRender): string {
|
|
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
|
-
}
|
|
321
|
-
return [
|
|
322
|
-
`amem capacity apply: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
323
|
-
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(result.preview.file)}`,
|
|
324
|
-
`${label(s, "ok")} current: ${facts({ cap_mb: result.preview.current.capMb, retention_days: result.preview.current.retentionDays }) || "defaults"}`,
|
|
325
|
-
`${label(s, "attention")} proposed: ${facts({ cap_mb: result.preview.target.capMb, retention_days: result.preview.target.retentionDays })}`,
|
|
326
|
-
`${label(s, "ok")} reason: ${singleLine(result.preview.reason)}`,
|
|
327
|
-
...(applied ? [`${label(s, "ok")} written: ${facts(result.written!) || "no settings reported"}`] : []),
|
|
328
|
-
`Next action: ${applied ? "none" : "re-run the same capacity apply command with --confirm, keeping all other arguments"}`,
|
|
329
|
-
].join("\n");
|
|
330
|
-
}
|
|
331
277
|
|
|
332
|
-
/** Human-readable `capacity apply --split` result, retaining skipped shard identities. */
|
|
333
|
-
export function capacitySplitText(result:
|
|
334
|
-
| { at: number; split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; skipped: string[]; confirm: string }
|
|
335
|
-
| { split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; written: { key: string; cap_mb: number; retention_days: number }[] },
|
|
336
|
-
s: Style = PLAIN, render?: CapacityRender,
|
|
337
|
-
): string {
|
|
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
|
-
}
|
|
353
|
-
const rows = result.split.map(row => [
|
|
354
|
-
`${label(s, applied ? "ok" : "attention")} shard: ${singleLine(row.key)}`,
|
|
355
|
-
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(row.dir)}`,
|
|
356
|
-
`${label(s, "ok")} current: ${facts({ cap_mb: row.current.capMb, retention_days: row.current.retentionDays }) || "defaults"}`,
|
|
357
|
-
`${label(s, applied ? "ok" : "attention")} proposed: ${facts({ cap_mb: row.target.capMb, retention_days: row.target.retentionDays })}`,
|
|
358
|
-
`${label(s, "ok")} reason: ${singleLine(row.reason)}`,
|
|
359
|
-
].join("\n"));
|
|
360
|
-
const skipped = "skipped" in result ? result.skipped : [];
|
|
361
|
-
return [
|
|
362
|
-
`amem capacity apply --split: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
363
|
-
...(result.split.length ? [] : [`${label(s, "skipped")} targets: none`]),
|
|
364
|
-
...rows,
|
|
365
|
-
...skipped.map(key => `${label(s, "skipped")} skipped shard: ${singleLine(key)} (no local shard config to write)`),
|
|
366
|
-
...(applied ? result.written.map(row => `${label(s, "ok")} written ${singleLine(row.key)}: ${facts({ cap_mb: row.cap_mb, retention_days: row.retention_days })}`) : []),
|
|
367
|
-
`Next action: ${applied || !result.split.length ? "none" : "re-run the same capacity apply --split command with --confirm, keeping all other arguments"}`,
|
|
368
|
-
].join("\n");
|
|
369
|
-
}
|
package/src/memory/commands.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
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";
|
|
@@ -262,7 +263,11 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
262
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")}` : "";
|
|
263
264
|
// #578 Q2: one counts-only line when this sync ran a placement checkpoint.
|
|
264
265
|
const checkpointLine = r.checkpoint ? `\nplacement checkpoint: window ${r.checkpoint.window}, objects ${r.checkpoint.objectsBefore} -> ${r.checkpoint.objectsAfter}` : "";
|
|
265
|
-
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
|
+
}
|
|
266
271
|
// #590 (task 429): the CLI renders the success report; hosts keep the legacy line below byte for byte.
|
|
267
272
|
const cliSync = (legacy: string) => internal ? rendered(legacy, syncReportText(r, internal.render.style ?? PLAIN, { columns: internal.render.columns ?? 80 })) : legacy;
|
|
268
273
|
if (r.pruneApplication) {
|
|
@@ -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,148 @@
|
|
|
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
|
+
transition: "project key transition",
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* #590 C4: every hint a section emits, as one finding and the complete commands that act on it. `--json` keeps the hint text unchanged;
|
|
21
|
+
* 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.
|
|
22
|
+
* `test/status-doctor-layout.test.ts` checks every hint producer against this table.
|
|
23
|
+
*/
|
|
24
|
+
export const DOCTOR_HINTS: Readonly<Record<string, (section: Record<string, unknown>) => Finding>> = {
|
|
25
|
+
"amem dedupe previews the imported duplicates; amem dedupe --apply reconciles them": () =>
|
|
26
|
+
({ text: "imported duplicate notes can be reconciled", next: ["amem dedupe", "amem dedupe --apply"] }),
|
|
27
|
+
"The person can inspect these examples with amem show <id> from their own shell.": section => {
|
|
28
|
+
const first = Array.isArray(section.examples) ? String(section.examples[0] ?? "") : "";
|
|
29
|
+
// #511 AC3: an agent-marked `show` may withhold these ids, so the finding says where they open.
|
|
30
|
+
return { text: `${section.missingReferences} notes reference paths that no longer exist; open the examples from your own shell`, next: first ? [`amem show ${first}`] : [] };
|
|
31
|
+
},
|
|
32
|
+
"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"] }),
|
|
33
|
+
"a section is partial or unavailable in the brief: see coverage": () => ({ text: "a brief section is partial or unavailable", next: [] }),
|
|
34
|
+
"the brief uses over 90% of its budget": () => ({ text: "the session brief uses over 90% of its budget", next: [] }),
|
|
35
|
+
"a reader lease of a process that is gone is cleared by the next reader; an unreadable one needs a look": () =>
|
|
36
|
+
({ text: "a reader lease is stale or unreadable; the next reader clears a stale one", next: [] }),
|
|
37
|
+
"capture rows were dropped recently (see counts by reason); amem doctor --json keeps the numbers": () =>
|
|
38
|
+
({ text: "capture rows were dropped recently", next: ["amem doctor --json"] }),
|
|
39
|
+
"pending hook spool needs attention: capture can be dropped when both tiers fill; supported orphan recovery is pending": () =>
|
|
40
|
+
({ text: "the hook spool is nearly full; capture is dropped when both tiers fill", next: [] }),
|
|
41
|
+
"sync has failed repeatedly; amem sync --force shows why": () => ({ text: "sync has failed 3 or more times in a row", next: ["amem sync --force"] }),
|
|
42
|
+
"no recent successful sync: run amem sync": () => ({ text: "no recent successful sync", next: ["amem sync"] }),
|
|
43
|
+
"run amem review walk": section => ({ text: `${section.dueWithin7Days} candidates expire within 7 days`, next: ["amem review walk"] }),
|
|
44
|
+
};
|
|
45
|
+
/** Capture hints name a CLI; each maps to a finding and the commands for that CLI. */
|
|
46
|
+
export function captureFinding(cli: string, hint: string): Finding {
|
|
47
|
+
const known = new Set<string>(CLIS);
|
|
48
|
+
const ingest = known.has(cli) && cli !== "claude" ? [`amem ingest ${cli}`] : [];
|
|
49
|
+
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 };
|
|
50
|
+
if (hint.startsWith("run amem setup")) return { text: `${cli}: capture is not set up`, next: known.has(cli) ? [`amem setup ${cli} --apply`, ...ingest] : [] };
|
|
51
|
+
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: [] };
|
|
52
|
+
const state = /capture is (\w+)/.exec(hint)?.[1] ?? "not fresh", where = hint.includes("on this machine") ? "on this machine" : "in this project";
|
|
53
|
+
return { text: `${cli}: capture is ${state} ${where}; open a session`, next: ingest };
|
|
54
|
+
}
|
|
55
|
+
export function hintFinding(name: string, hint: string, section: Record<string, unknown>): Finding {
|
|
56
|
+
const mapped = DOCTOR_HINTS[hint];
|
|
57
|
+
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: [] };
|
|
58
|
+
}
|
|
59
|
+
/** #590 C6: a writer refusal is one finding; each command it names is one `→` line. The fixed refusal text stays in `--json`. */
|
|
60
|
+
export function writerFinding(section: Record<string, unknown>): Finding {
|
|
61
|
+
const reason = String(section.reason ?? "");
|
|
62
|
+
// #624: the checkpoint renewal comes first. Its saving preview is a subshell, so the finding names the bare checkpoint command; the reason keeps the saving form.
|
|
63
|
+
const commands = [...reason.matchAll(/amem (?:migrate --sync-placement --(?:checkpoint|dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
|
|
64
|
+
return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function sectionFact(name: string, detail: Record<string, unknown>, now: number): string[] {
|
|
68
|
+
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
69
|
+
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) =>
|
|
70
|
+
`${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}` : ""}`);
|
|
71
|
+
}
|
|
72
|
+
if (name === "cadence") {
|
|
73
|
+
const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
|
|
74
|
+
return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
|
|
75
|
+
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${relativeTime(sync.lastOkAt as string | null, now)}, ${sync.failures} failures${sync.due ? ", due" : ""}` : ""}`,
|
|
76
|
+
...(validPlacementWriterRefusal(sync.writerRefusal) ? [`last failure: ${writerRefusalText(sync.writerRefusal)}`] : [])];
|
|
77
|
+
}
|
|
78
|
+
if (name === "drops") {
|
|
79
|
+
if (detail.counts === undefined) return [];
|
|
80
|
+
const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
|
|
81
|
+
return [`${counts.length ? counts.map(([reason, n]) => `${reason.replaceAll("_", " ")} ${n}`).join(", ") : "none"} in the recent metrics tail${detail.malformedLines ? `, ${detail.malformedLines} malformed lines skipped` : ""}`];
|
|
82
|
+
}
|
|
83
|
+
if (name === "spool") {
|
|
84
|
+
if (!detail.active || !detail.reserve) return [];
|
|
85
|
+
const tiers = ["active", "reserve"].map(tierName => {
|
|
86
|
+
const tier = detail[tierName] as { files: number; bytes: number; maxFiles: number; maxBytes: number };
|
|
87
|
+
return `${tierName} ${tier.files} of ${tier.maxFiles} files, ${humanBytes(tier.bytes)} of ${humanBytes(tier.maxBytes)}`;
|
|
88
|
+
});
|
|
89
|
+
const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
|
|
90
|
+
return [`${String(detail.fill).replaceAll("_", " ")}; ${tiers.join("; ")}; ${detail.claimed} claimed${detail.oldestAt ? `, oldest ${relativeTime(String(detail.oldestAt), now)}` : ""}${detail.complete ? "" : " (counts are lower bounds)"}`,
|
|
91
|
+
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
92
|
+
}
|
|
93
|
+
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
94
|
+
const entries = detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[];
|
|
95
|
+
if (!entries.length) return [`${detail.checked ?? 0} registrations match their receipts`];
|
|
96
|
+
return entries.map(item => singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? `, expected ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
97
|
+
}
|
|
98
|
+
if (name === "writers") return typeof detail.writers === "number" ? [`${detail.writers} writers match the active inventory`] : [];
|
|
99
|
+
if (name === "brief" && typeof detail.tokens === "number") {
|
|
100
|
+
const missing = Object.entries((detail.coverage ?? {}) as Record<string, unknown>).filter(([, value]) => value && value !== "complete").map(([key, value]) => `${wordedKey(key)} ${value}`);
|
|
101
|
+
return [`${detail.tokens} of ${detail.budget} tokens${missing.length ? `, coverage: ${missing.join(", ")}` : ""}`];
|
|
102
|
+
}
|
|
103
|
+
if (name === "policy") return [`machine ${detail.machine ?? "none (defaults)"}, repo ${detail.repo ?? "none"}, ${detail.denyPaths} deny paths, ${detail.piiPatterns} PII patterns`];
|
|
104
|
+
if (name === "index") return detail.liveIndex ? [`live index ${detail.liveIndex}, equal to a rebuild`] : [];
|
|
105
|
+
if (name === "readers") return [`${detail.live ?? 0} live, ${detail.stale ?? 0} stale, ${detail.unreadable ?? 0} unreadable`];
|
|
106
|
+
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}` : ""}`,
|
|
107
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
108
|
+
if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
|
|
109
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
|
|
110
|
+
if (name === "transition") return [`was ${detail.previousKey}${typeof detail.previousCuratedNotes === "number" ? ` (${detail.previousCuratedNotes} curated notes)` : ""}, now ${detail.key}; see Attention`];
|
|
111
|
+
if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
|
|
112
|
+
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` : ""}`];
|
|
113
|
+
const { examples, note: _note, ...rest } = detail;
|
|
114
|
+
const line = wordedFacts(rest);
|
|
115
|
+
return [...(line ? [line] : []), ...(Array.isArray(examples) && examples.length ? [`examples ${examples.map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 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. */
|
|
119
|
+
export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportTextOptions & { now?: number } = {}): string {
|
|
120
|
+
const now = opts.now ?? Date.now();
|
|
121
|
+
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
122
|
+
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
123
|
+
const findings: Finding[] = [];
|
|
124
|
+
for (const [name, item] of entries) {
|
|
125
|
+
if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
|
|
126
|
+
if (name === "transition") findings.push({ text: `this directory resolved to ${item.previousKey} before and to ${item.key} now`, next: [String(item.aliasCommand), String(item.keepCommand)] });
|
|
127
|
+
if (item.hint) findings.push(hintFinding(name, item.hint, item));
|
|
128
|
+
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));
|
|
129
|
+
}
|
|
130
|
+
const out = reportFrame(s, "doctor", report.status === "skipped" ? "ok" : STATE_WORD[report.status], opts, report.home);
|
|
131
|
+
out.note(`project ${report.project}`);
|
|
132
|
+
attention(out, findings);
|
|
133
|
+
out.section("Checks", String(entries.length));
|
|
134
|
+
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
135
|
+
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
136
|
+
const rows = entries.flatMap(([name, section]) => {
|
|
137
|
+
const { status, hint: _hint, reason, ...detail } = section;
|
|
138
|
+
const facts = name === "writers" && status === "attention" ? [] : sectionFact(name, detail, now);
|
|
139
|
+
const writerRefusal = name === "writers" && status === "attention";
|
|
140
|
+
const fact = writerRefusal ? `${section.cause} (${section.category} category); see Attention`
|
|
141
|
+
: [...facts, ...(reason ? [singleLine(reason)] : [])].join("; ") || (status === "ok" ? "nothing to report" : SECTION_TITLE[name]);
|
|
142
|
+
return [{ state: status, name, fact }];
|
|
143
|
+
});
|
|
144
|
+
stateRows(out, rows, s);
|
|
145
|
+
if (count("skipped")) { out.line(""); out.note(`${count("skipped")} skipped: nothing to check here`); }
|
|
146
|
+
out.summary({ warnings: count("attention"), unknown: count("unavailable"), ok: count("ok") });
|
|
147
|
+
return out.render(s.color).join("\n");
|
|
148
|
+
}
|
package/src/memory/doctor.ts
CHANGED
|
@@ -19,11 +19,11 @@ 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 { 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
22
|
import { aliasedKeys, shardDir } from "./shard.ts";
|
|
23
|
+
import { curatedCount, projectTransition, transitionKey, transitionNotice } from "./roots.ts";
|
|
25
24
|
import type { MemoryStore, View } from "./store.ts";
|
|
26
25
|
import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
|
|
26
|
+
import { readSyncStatus } from "./sync-progress.ts";
|
|
27
27
|
import { readSetupDrift } from "../setup-drift.ts";
|
|
28
28
|
import { readHookSpoolStatus } from "../hook-spool.ts";
|
|
29
29
|
|
|
@@ -78,6 +78,8 @@ export interface DoctorReport {
|
|
|
78
78
|
setup?: Section;
|
|
79
79
|
/** #551, additive: present on a placement home only - the writer verification the next sync performs. */
|
|
80
80
|
writers?: Section;
|
|
81
|
+
/** #581, additive: present only when this working root last resolved to a different, unjoined key. Read-only. */
|
|
82
|
+
transition?: Section;
|
|
81
83
|
};
|
|
82
84
|
}
|
|
83
85
|
|
|
@@ -92,6 +94,13 @@ function maskedSection(curated: MemoryStore | undefined): { masked?: Section } {
|
|
|
92
94
|
if (!forgets && !prunes) return {};
|
|
93
95
|
return { masked: { status: "ok", forgets, prunes, note: "masked entries stay in the local log and in sync history; see docs/purge.md" } };
|
|
94
96
|
}
|
|
97
|
+
/** #581: a read of roots.jsonl and aliases.jsonl only; doctor never writes a root line. */
|
|
98
|
+
function transitionSection(options: DoctorOptions): { transition?: Section } {
|
|
99
|
+
try {
|
|
100
|
+
const transition = projectTransition(options.home, options.cwd, transitionKey(options.cwd), key => curatedCount(options.home, key, shardDir));
|
|
101
|
+
return transition ? { transition: { status: "attention", ...transition, notice: transitionNotice(transition) } } : {};
|
|
102
|
+
} catch { return {}; }
|
|
103
|
+
}
|
|
95
104
|
const ids = (list: string[]): string[] => list.slice(0, MAX_IDS).map(id => id.slice(0, 8));
|
|
96
105
|
const regularDir = (path: string): boolean => { try { const stat = lstatSync(path); return stat.isDirectory() && !stat.isSymbolicLink(); } catch { return false; } };
|
|
97
106
|
const regularFile = (path: string): boolean => { try { const stat = lstatSync(path); return stat.isFile() && !stat.isSymbolicLink(); } catch { return false; } };
|
|
@@ -498,13 +507,19 @@ function cadenceSection(options: DoctorOptions): Section {
|
|
|
498
507
|
const ingest: Record<string, string> = {};
|
|
499
508
|
for (const cli of CLIS) ingest[cli] = receiptPhase(options.home, cli) === "applied" ? (cli === "claude" ? "hooks" : "session end") : "manual";
|
|
500
509
|
const remote = remoteConfigured(options.home), state = usableState(readSyncState(options.home), options.now), next = nextSyncAt(state);
|
|
510
|
+
const latest = readSyncStatus(options.home, options.now).operations
|
|
511
|
+
.filter(op => op.state !== "running" && op.state !== "interrupted" && op.lastAliveUnixMs <= options.now)
|
|
512
|
+
.sort((a, b) => b.lastAliveUnixMs - a.lastAliveUnixMs)[0];
|
|
513
|
+
const lastOk = state.lastOkAt === null ? -Infinity : Date.parse(state.lastOkAt);
|
|
514
|
+
const writerRefusal = latest?.state === "failed" && latest.lastAliveUnixMs > lastOk ? latest.writerRefusal : undefined;
|
|
501
515
|
const command = options.syncCommand ?? "amem sync --if-due";
|
|
502
516
|
const stale = remote && (state.lastOkAt === null || options.now - Date.parse(state.lastOkAt) > SYNC_STALE_MS || state.failures >= 3);
|
|
503
517
|
const sync = { remote: remote ? "configured" : "none", lastAttemptAt: state.lastAttemptAt, lastOkAt: state.lastOkAt, failures: state.failures,
|
|
504
518
|
nextAttemptAt: next === null ? null : new Date(next).toISOString(), due: remote ? syncDue(state, options.now) : false,
|
|
519
|
+
...(writerRefusal ? { writerRefusal } : {}),
|
|
505
520
|
...(remote ? { schedule: `run \`${command}\` from your own shell (for example a zshexit or bash EXIT trap): it needs a terminal like every mutating command; amem registers no sync hook and runs nothing between sessions` } : {}) };
|
|
506
521
|
const manual = CLIS.filter(cli => ingest[cli] === "manual");
|
|
507
|
-
return { status: stale ? "attention" : "ok", ingest, ...(manual.length ? { manual } : {}), sync,
|
|
522
|
+
return { status: stale || writerRefusal ? "attention" : "ok", ingest, ...(manual.length ? { manual } : {}), sync,
|
|
508
523
|
...(stale ? { hint: state.failures >= 3 ? "sync has failed repeatedly; amem sync --force shows why" : "no recent successful sync: run amem sync" } : {}) };
|
|
509
524
|
}
|
|
510
525
|
|
|
@@ -628,145 +643,8 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
|
|
|
628
643
|
try {
|
|
629
644
|
await tick();
|
|
630
645
|
const writers = await writersSection(options);
|
|
631
|
-
sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...(writers ? { writers } : {}), ...maskedSection(curated) };
|
|
646
|
+
sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...(writers ? { writers } : {}), ...maskedSection(curated), ...transitionSection(options) };
|
|
632
647
|
await tick(); // a signal that arrived during the last synchronous stage is handled while the guard is still installed
|
|
633
648
|
} finally { curated?.close(); }
|
|
634
649
|
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
650
|
}
|
|
636
|
-
|
|
637
|
-
/** Section order and one-line names for the person-facing report (#125). */
|
|
638
|
-
const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
|
|
639
|
-
duplicates: "duplicate notes", stale: "stale path references", candidates: "review candidates", capture: "capture per CLI", brief: "session brief",
|
|
640
|
-
index: "index equals rebuild", readers: "reader leases", policy: "policy in effect", cadence: "ingest and sync cadence", drops: "recent capture drops",
|
|
641
|
-
writers: "placement writers",
|
|
642
|
-
spool: "pending hook spool",
|
|
643
|
-
setup: "native setup registrations",
|
|
644
|
-
masked: "forgotten or pruned entries (informational)",
|
|
645
|
-
};
|
|
646
|
-
|
|
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[] {
|
|
695
|
-
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
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}` : ""}`);
|
|
698
|
-
}
|
|
699
|
-
if (name === "cadence") {
|
|
700
|
-
const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
|
|
701
|
-
return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
|
|
702
|
-
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${relativeTime(sync.lastOkAt as string | null, now)}, ${sync.failures} failures${sync.due ? ", due" : ""}` : ""}`];
|
|
703
|
-
}
|
|
704
|
-
if (name === "drops") {
|
|
705
|
-
if (detail.counts === undefined) return [];
|
|
706
|
-
const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
|
|
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` : ""}`];
|
|
708
|
-
}
|
|
709
|
-
if (name === "spool") {
|
|
710
|
-
if (!detail.active || !detail.reserve) 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)}`;
|
|
714
|
-
});
|
|
715
|
-
const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
|
|
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)"}`,
|
|
717
|
-
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
718
|
-
}
|
|
719
|
-
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
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}`));
|
|
723
|
-
}
|
|
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();
|
|
746
|
-
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
747
|
-
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
748
|
-
const findings: Finding[] = [];
|
|
749
|
-
for (const [name, item] of entries) {
|
|
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));
|
|
753
|
-
}
|
|
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));
|
|
758
|
-
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
759
|
-
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
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");
|
|
772
|
-
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Report } from "@staix/cli-output";
|
|
2
|
+
import { PLAIN, relativeTime, singleLine, type Style } from "./style.ts";
|
|
3
|
+
import { AUDIT_LABELS, type AuditLabel } from "./eval.ts";
|
|
4
|
+
import type { AuditSheet, AuditScore } from "./eval-audit.ts";
|
|
5
|
+
|
|
6
|
+
/** #592: the human eval-audit output, kept out of eval-audit.ts so the write path never imports the output package. */
|
|
7
|
+
interface AuditRender { columns?: number; style?: Style; now?: number }
|
|
8
|
+
/** Human text for `amem eval audit sample`: where the sheet is, and what filling it costs. Content-free, like the score. */
|
|
9
|
+
export function auditSheetText(sheet: AuditSheet, file: string, render?: AuditRender): string {
|
|
10
|
+
const cells = new Set(sheet.notes.map(note => `${note.kind}/${note.age}`));
|
|
11
|
+
const frame = `${sheet.frame}${sheet.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
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", "Audit sample"); out.section("Sheet");
|
|
15
|
+
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)]]);
|
|
16
|
+
out.note("The sheet is mode 0600, local only; never synced or committed.");
|
|
17
|
+
out.note(`Fill both judge columns using ${AUDIT_LABELS.join(", ")}; the rubric is in the sheet.`);
|
|
18
|
+
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.");
|
|
19
|
+
else out.next(`amem eval audit score '${file.replaceAll("'", "'\\''")}'`);
|
|
20
|
+
return out.render(s.color).join("\n");
|
|
21
|
+
}
|
|
22
|
+
return [
|
|
23
|
+
`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` : ""}`,
|
|
24
|
+
`sheet: ${file} (0600, local only; never synced and never committed)`,
|
|
25
|
+
`fill judge_a and judge_b with ${AUDIT_LABELS.join(", ")} (rubric in the sheet header), then run \`amem eval audit score ${file}\``,
|
|
26
|
+
].join("\n");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Human text for `amem eval audit score`; the JSON is the machine form. */
|
|
30
|
+
export function auditScoreText(score: AuditScore, render?: AuditRender): string {
|
|
31
|
+
const row = (label: string, counts: Partial<Record<AuditLabel, number>>) => `${label.padEnd(10)} ${AUDIT_LABELS.map(name => String(counts[name] ?? 0).padStart(4)).join(" ")}`;
|
|
32
|
+
const frame = `${score.frame}${score.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
33
|
+
const withheld = score.withheld ? `, ${score.withheld} withheld by the configured policy` : "";
|
|
34
|
+
const head = `audit score: project ${score.project}, ${score.drawn} of ${frame} notes, seed "${score.seed}" as of ${score.asOf}, ${score.labelled} labelled, ${score.unlabelled} not${withheld}`;
|
|
35
|
+
// The joint cells are printed as one line per kind/age/anchor stratum, so a reader sees which label fills each intersection instead of three marginals.
|
|
36
|
+
const strata = new Map<string, Partial<Record<AuditLabel, number>>>();
|
|
37
|
+
for (const cell of score.cells) {
|
|
38
|
+
const key = `${cell.kind}/${cell.age}/${cell.anchor}`, counts = strata.get(key) ?? {};
|
|
39
|
+
counts[cell.label] = cell.count;
|
|
40
|
+
strata.set(key, counts);
|
|
41
|
+
}
|
|
42
|
+
if (render) {
|
|
43
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
44
|
+
out.header("amem", "Audit score"); out.section("Summary");
|
|
45
|
+
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)]]);
|
|
46
|
+
out.section("Labels");
|
|
47
|
+
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])];
|
|
48
|
+
out.table(["GROUP", ...AUDIT_LABELS], rows.map(([name, counts]) => [name, ...AUDIT_LABELS.map(label => String(counts[label] ?? 0))]), 0);
|
|
49
|
+
out.line(""); out.line(`Summary: ${score.labelled} labelled, ${score.unlabelled} unlabelled`);
|
|
50
|
+
return out.render(s.color).join("\n");
|
|
51
|
+
}
|
|
52
|
+
return [
|
|
53
|
+
head,
|
|
54
|
+
`${"".padEnd(10)} ${AUDIT_LABELS.map(name => name.slice(0, 4).padStart(4)).join(" ")}`,
|
|
55
|
+
row("all", score.byLabel),
|
|
56
|
+
...Object.entries(score.byKind).map(([kind, counts]) => row(`kind ${kind}`, counts)),
|
|
57
|
+
...Object.entries(score.byAge).map(([age, counts]) => row(`age ${age}`, counts)),
|
|
58
|
+
...Object.entries(score.byAnchor).map(([anchor, counts]) => row(`anchor ${anchor}`, counts)),
|
|
59
|
+
...strata.entries().map(([key, counts]) => row(`cross ${key}`, counts)),
|
|
60
|
+
`kappa ${score.agreement.kappa === null ? "n/a (needs both judge columns, and more than one label between them)" : score.agreement.kappa.toFixed(3)} over ${score.agreement.pairs} doubly labelled note(s)`,
|
|
61
|
+
].join("\n");
|
|
62
|
+
}
|