@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.
Files changed (49) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/brief-curated.ts +8 -4
  5. package/src/cli-agent-reads.ts +55 -4
  6. package/src/cli.ts +222 -93
  7. package/src/commands-table.ts +332 -171
  8. package/src/index.ts +5 -0
  9. package/src/memory/capacity-text.ts +100 -0
  10. package/src/memory/capacity.ts +1 -57
  11. package/src/memory/commands.ts +45 -9
  12. package/src/memory/curated-cache-state.ts +22 -3
  13. package/src/memory/doctor-text.ts +144 -0
  14. package/src/memory/doctor.ts +9 -86
  15. package/src/memory/eval-audit-text.ts +62 -0
  16. package/src/memory/eval-audit.ts +1 -34
  17. package/src/memory/eval-text.ts +32 -0
  18. package/src/memory/eval.ts +1 -14
  19. package/src/memory/formats.ts +2 -0
  20. package/src/memory/gc-text.ts +22 -0
  21. package/src/memory/gc.ts +0 -6
  22. package/src/memory/generation-index.ts +1 -1
  23. package/src/memory/index-file.ts +1 -1
  24. package/src/memory/metrics.ts +18 -10
  25. package/src/memory/migrate-text.ts +32 -0
  26. package/src/memory/migrate.ts +0 -29
  27. package/src/memory/prune-text.ts +29 -0
  28. package/src/memory/prune.ts +0 -26
  29. package/src/memory/report-text.ts +233 -0
  30. package/src/memory/shard-migration-text.ts +40 -0
  31. package/src/memory/shard-migration.ts +0 -37
  32. package/src/memory/status-text.ts +72 -29
  33. package/src/memory/store.ts +112 -17
  34. package/src/memory/style.ts +98 -1
  35. package/src/memory/sync-placement-bound.ts +2 -2
  36. package/src/memory/sync-placement-checkpoint-person.ts +1 -1
  37. package/src/memory/sync-placement-noop-cache.ts +93 -0
  38. package/src/memory/sync-placement-refusal-category.ts +18 -0
  39. package/src/memory/sync-placement-transport.ts +43 -7
  40. package/src/memory/sync-progress-text.ts +7 -0
  41. package/src/memory/sync-progress.ts +21 -7
  42. package/src/memory/sync-screen.ts +13 -0
  43. package/src/memory/work-lists.ts +6 -4
  44. package/src/setup-drift.ts +1 -1
  45. package/src/setup-writer-roots.ts +136 -0
  46. package/src/setup.ts +122 -159
  47. package/src/sync-placement-writer-context.ts +8 -3
  48. package/src/ui/plugin.ts +4 -2
  49. package/src/work-brief-preparation.ts +28 -0
@@ -19,11 +19,10 @@ 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 { markerCell, paint } from "@staix/cli-output";
23
- import { facts, label, section, PLAIN, singleLine, type Style } from "./style.ts";
24
22
  import { aliasedKeys, shardDir } from "./shard.ts";
25
23
  import type { MemoryStore, View } from "./store.ts";
26
24
  import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
25
+ import { readSyncStatus } from "./sync-progress.ts";
27
26
  import { readSetupDrift } from "../setup-drift.ts";
28
27
  import { readHookSpoolStatus } from "../hook-spool.ts";
29
28
 
@@ -342,7 +341,7 @@ function stateOf(last: string | null, now: number): CaptureState {
342
341
  * The one place a capture hint is chosen (#509 extends it). `trigger` names the state that raised it: the machine-wide one (#510), this project's one
343
342
  * (the fallback when another shard could not be read), or a missing setup for a CLI that has never captured anywhere.
344
343
  */
345
- function captureHint(cli: Cli, registered: boolean, state: CaptureState, trigger: "machine" | "project" | "setup", unsafeRoots: readonly NativeRootKind[] = []): string {
344
+ export function captureHint(cli: Cli, registered: boolean, state: CaptureState, trigger: "machine" | "project" | "setup", unsafeRoots: readonly NativeRootKind[] = []): string {
346
345
  if (unsafeRoots.length) return `the ${cli} ${unsafeRoots.join(" and ")} root is an unsafe symlink and was skipped: use a directory inside HOME owned by this user without group or world write access, then rerun amem ingest ${cli}`;
347
346
  if (trigger === "setup") return cli === "claude" ? "run amem setup claude --apply to register the capture hooks" : `run amem setup ${cli} --apply, or amem ingest ${cli} by hand`;
348
347
  const where = trigger === "machine" ? "on this machine (all projects)" : "in this project (other projects could not be read)";
@@ -498,13 +497,19 @@ function cadenceSection(options: DoctorOptions): Section {
498
497
  const ingest: Record<string, string> = {};
499
498
  for (const cli of CLIS) ingest[cli] = receiptPhase(options.home, cli) === "applied" ? (cli === "claude" ? "hooks" : "session end") : "manual";
500
499
  const remote = remoteConfigured(options.home), state = usableState(readSyncState(options.home), options.now), next = nextSyncAt(state);
500
+ const latest = readSyncStatus(options.home, options.now).operations
501
+ .filter(op => op.state !== "running" && op.state !== "interrupted" && op.lastAliveUnixMs <= options.now)
502
+ .sort((a, b) => b.lastAliveUnixMs - a.lastAliveUnixMs)[0];
503
+ const lastOk = state.lastOkAt === null ? -Infinity : Date.parse(state.lastOkAt);
504
+ const writerRefusal = latest?.state === "failed" && latest.lastAliveUnixMs > lastOk ? latest.writerRefusal : undefined;
501
505
  const command = options.syncCommand ?? "amem sync --if-due";
502
506
  const stale = remote && (state.lastOkAt === null || options.now - Date.parse(state.lastOkAt) > SYNC_STALE_MS || state.failures >= 3);
503
507
  const sync = { remote: remote ? "configured" : "none", lastAttemptAt: state.lastAttemptAt, lastOkAt: state.lastOkAt, failures: state.failures,
504
508
  nextAttemptAt: next === null ? null : new Date(next).toISOString(), due: remote ? syncDue(state, options.now) : false,
509
+ ...(writerRefusal ? { writerRefusal } : {}),
505
510
  ...(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
511
  const manual = CLIS.filter(cli => ingest[cli] === "manual");
507
- return { status: stale ? "attention" : "ok", ingest, ...(manual.length ? { manual } : {}), sync,
512
+ return { status: stale || writerRefusal ? "attention" : "ok", ingest, ...(manual.length ? { manual } : {}), sync,
508
513
  ...(stale ? { hint: state.failures >= 3 ? "sync has failed repeatedly; amem sync --force shows why" : "no recent successful sync: run amem sync" } : {}) };
509
514
  }
510
515
 
@@ -633,85 +638,3 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
633
638
  } finally { curated?.close(); }
634
639
  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
640
  }
636
-
637
- /** Section order and one-line descriptions 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
- function sectionDetail(name: string, detail: Record<string, unknown>, s: Style): string[] {
648
- if (name === "capture" && detail.clis && typeof detail.clis === "object") {
649
- return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) => {
650
- const capture = String(row.capture), mark = capture === "fresh" ? s.ok(capture) : capture === "stale" ? s.attention(capture) : s.dim(capture);
651
- return `${cli.padEnd(7)} hook ${row.hook}${row.setup ? ` (${row.setup})` : ""}, capture ${mark}${row.lastCaptureAt ? ` (last ${row.lastCaptureAt})` : ""}, ${row.rows} rows; machine-wide ${row.machineCapture}${row.machineLastCaptureAt ? ` (last ${row.machineLastCaptureAt})` : ""}, ${row.machineRows} rows${row.note ? `, ${row.note}` : ""}`;
652
- });
653
- }
654
- if (name === "cadence") {
655
- const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
656
- return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
657
- `sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${sync.lastOkAt ?? "never"}, failures ${sync.failures}${sync.due ? ", due" : ""}` : ""}`];
658
- }
659
- if (name === "drops") {
660
- if (detail.counts === undefined) return []; // unavailable: only its reason is shown
661
- const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
662
- return [counts.length ? `${counts.map(([reason, n]) => `${reason.replaceAll("_", " ")} ${n}`).join(", ")} (recent metrics tail)` : "none in the recent metrics tail"].map(line => detail.malformedLines ? `${line}; ${detail.malformedLines} malformed lines skipped` : line);
663
- }
664
- if (name === "spool") {
665
- if (!detail.active || !detail.reserve) return [];
666
- const tiers = ["active", "reserve"].map(name => {
667
- const tier = detail[name] as { files: number; bytes: number; maxFiles: number; maxBytes: number };
668
- return `${name} ${tier.files}/${tier.maxFiles} files, ${tier.bytes}/${tier.maxBytes} bytes`;
669
- });
670
- const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
671
- return [`${detail.fill}; ${tiers.join("; ")}; claimed ${detail.claimed}; oldest ${detail.oldestAt ?? "none observed"}; coverage ${detail.coverage}${detail.complete ? "" : " (counts are lower bounds)"}`,
672
- `native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
673
- }
674
- if (name === "setup" && Array.isArray(detail.entries)) {
675
- return (detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[]).map(item =>
676
- singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? ` -> ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
677
- }
678
- if (name === "writers") return typeof detail.writers === "number"
679
- ? [`${detail.writers} writers measured against the active inventory`]
680
- : detail.reason ? [singleLine(String(detail.reason))] : [];
681
- if (name === "brief" && typeof detail.tokens === "number") return [`${detail.tokens} of ${detail.budget} tokens${detail.coverage ? `, coverage ${facts(detail.coverage as Record<string, unknown>) || "complete"}` : ""}`];
682
- const { examples, ...rest } = detail;
683
- const line = facts(rest);
684
- return [...(line ? [line] : []), ...(Array.isArray(examples) && examples.length ? [`examples ${examples.map(item => Array.isArray(item) ? item.join("=") : String(item)).join(", ")}`] : [])];
685
- }
686
-
687
- /** The person-facing report: overall state, one labelled row per section, then the next actions. `amem doctor --json` keeps the full report. */
688
- export function doctorText(report: DoctorReport, s: Style = PLAIN): string {
689
- const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
690
- const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
691
- const summary = facts({ attention: count("attention"), unavailable: count("unavailable"), skipped: count("skipped") });
692
- const actions: string[] = [];
693
- for (const [name, item] of entries) {
694
- if (item.hint) actions.push(`${name}: ${item.hint}`);
695
- if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) actions.push(`capture ${cli}: ${row.hint}`);
696
- }
697
- const lines = [`${paint([{ role: "header", text: " amem Doctor" }], s.color)}: ${report.status === "ok" ? s.ok(report.status) : report.status === "attention" ? s.attention(report.status) : s.error(report.status)}${summary ? ` (${summary})` : ` (all ${entries.length} checks ok)`}`,
698
- ...(actions.length ? ["", section(s, "Attention"), ...actions.map(action => ` ${paint([{ role: "accent", text: markerCell("next", s.ascii) }], s.color)} ${action}`)] : []),
699
- "", section(s, "Checks"), ` home: ${report.home.path} ${s.dim(`(${report.home.source})`)}`, ` project: ${report.project}`];
700
- const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
701
- entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
702
- for (const [name, section] of entries) {
703
- const { status, hint, reason, ...detail } = section;
704
- lines.push(`${label(s, status)} ${name}: ${s.dim(SECTION_TITLE[name])}`);
705
- for (const line of sectionDetail(name, detail, s)) lines.push(` ${line}`);
706
- if (reason) lines.push(` ${s.dim(`reason: ${reason}`)}`);
707
- }
708
- lines.push("", actions.length ? "Next actions: see Attention" : "Next actions: none");
709
- const counts = [
710
- ...(count("attention") ? [`${paint([{ role: "warning", text: markerCell("warn", s.ascii) }], s.color)} ${count("attention")} warnings`] : []),
711
- ...(count("unavailable") ? [`${paint([{ role: "hint", text: markerCell("unknown", s.ascii) }], s.color)} ${count("unavailable")} unknown`] : []),
712
- ...(count("skipped") ? [`${paint([{ role: "hint", text: markerCell("absent", s.ascii) }], s.color)} ${count("skipped")} skipped`] : []),
713
- ...(count("ok") ? [`${paint([{ role: "success", text: markerCell("ok", s.ascii) }], s.color)} ${count("ok")} ok`] : []),
714
- ];
715
- if (counts.length) lines.push(counts.join(" "));
716
- return lines.join("\n");
717
- }
@@ -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
+ }
@@ -16,6 +16,7 @@ import {
16
16
  import { memoryGitEnv, memoryGitSync, realPath } from "./platform.ts";
17
17
  import type { MemoryStore, View } from "./store.ts";
18
18
 
19
+
19
20
  export interface AuditAnchor { path: string; status: Exclude<AuditAnchorStatus, "none"> }
20
21
  export interface AuditNote {
21
22
  id: string; kind: string; at: string; age: AuditAgeBucket;
@@ -405,38 +406,4 @@ export function auditScore(sheet: AuditSheet): AuditScore {
405
406
  return score;
406
407
  }
407
408
 
408
- /** Human text for `amem eval audit sample`: where the sheet is, and what filling it costs. Content-free, like the score. */
409
- export function auditSheetText(sheet: AuditSheet, file: string): string {
410
- const cells = new Set(sheet.notes.map(note => `${note.kind}/${note.age}`));
411
- const frame = `${sheet.frame}${sheet.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
412
- return [
413
- `audit sample: ${sheet.drawn} of ${frame} ${sheet.project} notes, seed "${sheet.seed}" as of ${sheet.asOf}, ${cells.size} kind/age cells, anchors checked in ${sheet.root}${sheet.withheld ? `, ${sheet.withheld} withheld by the configured policy` : ""}`,
414
- `sheet: ${file} (0600, local only; never synced and never committed)`,
415
- `fill judge_a and judge_b with ${AUDIT_LABELS.join(", ")} (rubric in the sheet header), then run \`amem eval audit score ${file}\``,
416
- ].join("\n");
417
- }
418
409
 
419
- /** Human text for `amem eval audit score`; the JSON is the machine form. */
420
- export function auditScoreText(score: AuditScore): string {
421
- const row = (label: string, counts: Partial<Record<AuditLabel, number>>) => `${label.padEnd(10)} ${AUDIT_LABELS.map(name => String(counts[name] ?? 0).padStart(4)).join(" ")}`;
422
- const frame = `${score.frame}${score.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
423
- const withheld = score.withheld ? `, ${score.withheld} withheld by the configured policy` : "";
424
- 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}`;
425
- // 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.
426
- const strata = new Map<string, Partial<Record<AuditLabel, number>>>();
427
- for (const cell of score.cells) {
428
- const key = `${cell.kind}/${cell.age}/${cell.anchor}`, counts = strata.get(key) ?? {};
429
- counts[cell.label] = cell.count;
430
- strata.set(key, counts);
431
- }
432
- return [
433
- head,
434
- `${"".padEnd(10)} ${AUDIT_LABELS.map(name => name.slice(0, 4).padStart(4)).join(" ")}`,
435
- row("all", score.byLabel),
436
- ...Object.entries(score.byKind).map(([kind, counts]) => row(`kind ${kind}`, counts)),
437
- ...Object.entries(score.byAge).map(([age, counts]) => row(`age ${age}`, counts)),
438
- ...Object.entries(score.byAnchor).map(([anchor, counts]) => row(`anchor ${anchor}`, counts)),
439
- ...strata.entries().map(([key, counts]) => row(`cross ${key}`, counts)),
440
- `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)`,
441
- ].join("\n");
442
- }
@@ -0,0 +1,32 @@
1
+ import { Report } from "@staix/cli-output";
2
+ import { PLAIN, singleLine, type Style } from "./style.ts";
3
+ import type { EvalAggregate, EvalReport } from "./eval.ts";
4
+ const pct = (value: number | null): string => value === null ? " n/a" : value.toFixed(3);
5
+
6
+
7
+ /** #592: the human eval output, kept out of eval.ts so the write path never imports the output package. */
8
+ /** Human text for `amem eval`; the JSON report is the machine form. */
9
+ export function evalText(report: EvalReport, label: string, render?: { columns?: number; style?: Style }): string {
10
+ if (render) {
11
+ const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
12
+ out.header("amem", "Evaluation"); out.section("Results");
13
+ out.kv([["Set", label], ["Engine", report.engine], ["Questions", String(report.all.questions)], ["Answerable", String(report.answerable.questions)], ["All MRR", report.all.mrr === null ? "?" : report.all.mrr.toFixed(3)], ["Answerable MRR", report.answerable.mrr === null ? "?" : report.answerable.mrr.toFixed(3)]]);
14
+ if (report.answerable.questions < report.all.questions) out.note(`${report.all.questions - report.answerable.questions} questions name entries this store does not hold; they score zero in all.`);
15
+ out.section("Cutoffs", String(report.ks.length));
16
+ const number = (value: number | null | undefined) => value == null ? "?" : value.toFixed(3);
17
+ out.table(["K", "ALL RECALL", "ALL HIT", "ANSWERABLE RECALL", "ANSWERABLE HIT"], report.ks.map(k => [String(k), number(report.all.recall[k]), number(report.all.hit[k]), number(report.answerable.recall[k]), number(report.answerable.hit[k])]), 0);
18
+ const missed = report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks));
19
+ if (missed.length) { out.section("Questions to review", String(missed.length)); out.table(["RESULT", "QUESTION"], missed.map(row => [row.rank === null ? "miss" : `rank ${row.rank}`, `${row.answerable ? "" : "not in store: "}${row.q}`]), 1); }
20
+ out.line(""); out.line(`Summary: ${report.all.questions} questions, ${report.answerable.questions} answerable`);
21
+ return out.render(s.color).join("\n");
22
+ }
23
+ const head = (name: string, row: EvalAggregate) => `${name.padEnd(11)} ${String(row.questions).padStart(4)} ${report.ks.map(k => `${pct(row.recall[k] ?? null)}/${pct(row.hit[k] ?? null)}`.padStart(13)).join(" ")} ${pct(row.mrr).padStart(6)}`;
24
+ return [
25
+ `eval: ${label} (${report.engine === "substring" ? "substring fallback" : "ranked store.search, engine " + report.engine}; same ranked search path as default \`amem search\`; \`--filter\` keeps legacy substring matching)`,
26
+ `${"".padEnd(11)} ${"n".padStart(4)} ${report.ks.map(k => `@${k} recall/hit`.padStart(13)).join(" ")} ${"MRR".padStart(6)}`,
27
+ head("all", report.all),
28
+ head("answerable", report.answerable),
29
+ ...(report.answerable.questions < report.all.questions ? [`${report.all.questions - report.answerable.questions} question(s) name an entry this store does not hold (they score 0 in "all")`] : []),
30
+ ...report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks)).map(row => ` ${row.rank === null ? "miss" : `rank ${row.rank}`}${row.answerable ? "" : " (not in store)"}: ${row.q.slice(0, 100)}`),
31
+ ].join("\n");
32
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * F13 (agent-mem#40, AC7): local recall evaluation. A question set is a list of (question, expected entry) pairs; the evaluation replays each question
3
3
  * through a search function and reports recall@k, hit@k and MRR. No model judge, no network, no embedding: a result either is one of the expected
4
- * entries or it is not. This leaf has no imports, so the parser and the arithmetic are testable without a store.
4
+ * entries or it is not. The parser and arithmetic remain testable without a store.
5
5
  *
6
6
  * Two shapes of set:
7
7
  * - self-contained: `entries` are synthetic notes seeded into a throwaway store, and `expect` names them by `key` (the committed fixture is one);
@@ -212,16 +212,3 @@ export function runEval(rank: (question: string) => readonly string[], resolve:
212
212
  return { engine, ks: [...ks], all: aggregate(perQuestion, ks, true), answerable: aggregate(perQuestion.filter(row => row.answerable), ks, false), perQuestion };
213
213
  }
214
214
 
215
- const pct = (value: number | null): string => value === null ? " n/a" : value.toFixed(3);
216
- /** Human text for `amem eval`; the JSON report is the machine form. */
217
- export function evalText(report: EvalReport, label: string): string {
218
- const head = (name: string, row: EvalAggregate) => `${name.padEnd(11)} ${String(row.questions).padStart(4)} ${report.ks.map(k => `${pct(row.recall[k] ?? null)}/${pct(row.hit[k] ?? null)}`.padStart(13)).join(" ")} ${pct(row.mrr).padStart(6)}`;
219
- return [
220
- `eval: ${label} (${report.engine === "substring" ? "substring fallback" : "ranked store.search, engine " + report.engine}; same ranked search path as default \`amem search\`; \`--filter\` keeps legacy substring matching)`,
221
- `${"".padEnd(11)} ${"n".padStart(4)} ${report.ks.map(k => `@${k} recall/hit`.padStart(13)).join(" ")} ${"MRR".padStart(6)}`,
222
- head("all", report.all),
223
- head("answerable", report.answerable),
224
- ...(report.answerable.questions < report.all.questions ? [`${report.all.questions - report.answerable.questions} question(s) name an entry this store does not hold (they score 0 in "all")`] : []),
225
- ...report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks)).map(row => ` ${row.rank === null ? "miss" : `rank ${row.rank}`}${row.answerable ? "" : " (not in store)"}: ${row.q.slice(0, 100)}`),
226
- ].join("\n");
227
- }
@@ -31,6 +31,8 @@ const READER_VERSION: string | undefined = (() => {
31
31
  try { const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")) as { version?: unknown }; return typeof version === "string" && SEMVER.test(version) ? version : undefined; }
32
32
  catch { return undefined; }
33
33
  })();
34
+ /** This release's plain version as read at load, or undefined when unreadable. */
35
+ export function amemReaderVersion(): string | undefined { return READER_VERSION; }
34
36
  const parts = (version: string) => SEMVER.exec(version)!.slice(1, 4).map(Number);
35
37
  /** Compare versions accepted by format-floor records, using their numeric release components. */
36
38
  export function formatVersionBelow(reader: string, floor: string): boolean {
@@ -0,0 +1,22 @@
1
+ import { Report } from "@staix/cli-output";
2
+ import { PLAIN, singleLine, type Style } from "./style.ts";
3
+ import type { GcResult } from "./gc.ts";
4
+
5
+ /** #592: the human gc output, kept out of gc.ts so the write path never imports the output package. */
6
+ /** The non-JSON rendering of `amem gc`. */
7
+ export function gcText(result: GcResult, render?: { columns?: number; style?: Style; next?: string }): string {
8
+ if (render) {
9
+ const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
10
+ out.header("amem", "Capture cleanup"); out.section(result.dryRun ? "Preview" : "Results");
11
+ out.bullet(result.dryRun ? "pending" : "ok", result.dryRun ? "Review the cleanup before confirming." : "Cleanup completed.");
12
+ if (result.shards.length) out.table(["PROJECT", "EXPIRED", "TRIMMED", "STATE"], result.shards.map(row => [row.key, String(row.expired), String(row.trimmed), row.remainingOverCap ? "over cap" : "within cap"]), 0);
13
+ else out.note("No project shards.");
14
+ for (const row of result.skipped) out.bullet("absent", `${row.key}: skipped (${row.reason})`);
15
+ if (render.next && (result.dryRun ? result.shards.some(row => row.expired > 0 || row.remainingOverCap) : result.shards.some(row => row.remainingOverCap))) out.next(render.next);
16
+ out.line(""); out.line(`Summary: ${result.shards.length} shards, ${result.skipped.length} skipped`);
17
+ return out.render(s.color).join("\n");
18
+ }
19
+ const lines = result.shards.map(s => `${s.key}: ${result.dryRun ? `${s.expired} expired row(s) would go` : `${s.expired} expired, ${s.trimmed} trimmed`}${s.remainingOverCap ? "; still over its cap, run gc again" : ""}`);
20
+ for (const s of result.skipped) lines.push(`${s.key}: skipped (${s.reason})`);
21
+ return (lines.length ? lines : ["no project shards"]).join("\n");
22
+ }
package/src/memory/gc.ts CHANGED
@@ -106,9 +106,3 @@ export function runGc(base: string, opts: GcOptions = {}): GcResult {
106
106
 
107
107
  export const GC_MAX_BATCHES_PER_CALL = CAPTURE_EVICT_MAX_BATCHES;
108
108
 
109
- /** The non-JSON rendering of `amem gc`. */
110
- export function gcText(result: GcResult): string {
111
- const lines = result.shards.map(s => `${s.key}: ${result.dryRun ? `${s.expired} expired row(s) would go` : `${s.expired} expired, ${s.trimmed} trimmed`}${s.remainingOverCap ? "; still over its cap, run gc again" : ""}`);
112
- for (const s of result.skipped) lines.push(`${s.key}: skipped (${s.reason})`);
113
- return (lines.length ? lines : ["no project shards"]).join("\n");
114
- }
@@ -351,7 +351,7 @@ export class GenerationIndex {
351
351
  finally { this.fullCapture = false; }
352
352
  const committed = this.options.db.transaction(() => {
353
353
  if (this.frontier() !== before) return false;
354
- for (const table of ["entries", "ops", "edges", "goals", "segments", "heads", ...GENERATION_TABLES, ...(this.profile.foreignPruneFormat ? FOREIGN_TABLES : [])]) this.options.db.run(`DELETE FROM ${table}`);
354
+ for (const table of ["entries", "ops", "edges", "goals", "segments", "heads", "unsettled_tasks", ...GENERATION_TABLES, ...(this.profile.foreignPruneFormat ? FOREIGN_TABLES : [])]) this.options.db.run(`DELETE FROM ${table}`);
355
355
  // The stamp described the tables just deleted, so the rebuild below proves them again instead of trusting it.
356
356
  this.foreignStamp = undefined;
357
357
  this.index(input); return true;
@@ -1,5 +1,5 @@
1
1
  /** Bumped when derived index tables change; each version uses its own file, rebuilt from logs on first open. */
2
- export const INDEX_VERSION = 5; // #466: isolate the persisted foreign-prune stamp from older index writers.
2
+ export const INDEX_VERSION = 6; // #610: keep the derived outstanding-task projection separate from v5 writers.
3
3
  /** The version that released 0.14.0 through 0.18.0 build into the unversioned names below; it keeps them so this release shares their warm index. */
4
4
  const SHARED_INDEX_VERSION = 3;
5
5
 
@@ -55,7 +55,13 @@ export interface RecordVariantMetric {
55
55
  /** All marks are process-local performance.now() milliseconds since the process time origin. */
56
56
  export interface JcodeJournalTiming { scanStartMs?: number; scanEndMs?: number; workStartMs?: number; publishStartMs?: number; publishEndMs?: number; publishTotalMs?: number; workerSpawnStartMs?: number; workerSpawnEndMs?: number; cursorCloseStartMs?: number; cursorCloseEndMs?: number; metricSampleAtMs?: number }
57
57
  export interface TranscriptTiming { killAtMs?: number; reapAtMs?: number; metricSampleAtMs: number }
58
- export interface MetricSample extends RecordVariantMetric { jcodeJournalTiming?: JcodeJournalTiming; transcriptTiming?: TranscriptTiming; at: string; kind: "hook" | "search" | "mcp-phase"; /** #485: the read tool that completed, so a peak can be attributed; never its arguments or result. */ tool?: string; /** #485: the process peak after this call was higher than after any sample before it. */ peakRaised?: boolean; shared?: boolean; brief?: BriefObservation; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
58
+ export type BriefPublicationFailureReason = "source_unavailable" | "binding_changed" | "frontier_changed" | "byte_bound" | "write_failed";
59
+
60
+ export function recordBriefPublicationFailure(base: string, section: "curated" | "work", reason: BriefPublicationFailureReason): void {
61
+ appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "brief-publication", briefPublication: { section, reason } }]);
62
+ }
63
+
64
+ export interface MetricSample extends RecordVariantMetric { jcodeJournalTiming?: JcodeJournalTiming; transcriptTiming?: TranscriptTiming; at: string; kind: "hook" | "search" | "mcp-phase" | "brief-publication"; briefPublication?: { section: "curated" | "work"; reason: BriefPublicationFailureReason }; /** #485: the read tool that completed, so a peak can be attributed; never its arguments or result. */ tool?: string; /** #485: the process peak after this call was higher than after any sample before it. */ peakRaised?: boolean; shared?: boolean; brief?: BriefObservation; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
59
65
  const METRICS_MAX_BYTES = 128 * 1024, METRICS_KEEP = 200, MCP_PHASE_KEEP = 32;
60
66
  // ponytail: reserve 17 KiB for future appends; upgrade to separate bounded files if these windows need larger guarantees.
61
67
  const HOOK_BYTES = 74 * 1024, SEARCH_BYTES = 30 * 1024, PHASE_BYTES = 6 * 1024, OTHER_BYTES = 1024;
@@ -200,14 +206,16 @@ function trimMetrics(file: string): void {
200
206
  * is refused before a byte is written. One worker drains the hand-offs in call order, so the file keeps the order the
201
207
  * calls completed in; a sample still in flight when the process exits is simply lost.
202
208
  */
203
- const pending: { base: string; samples: MetricSample[]; phase: boolean }[] = [];
204
- let draining = false, pendingPhases = 0;
209
+ const pending: { base: string; samples: MetricSample[]; boundedKind?: "mcp-phase" | "brief-publication" }[] = [];
210
+ let draining = false;
211
+ const pendingCounts = { "mcp-phase": 0, "brief-publication": 0 };
205
212
  export function appendMetricsLater(base: string, samples: MetricSample[]): void {
206
- const phase = samples.length > 0 && samples.every(sample => sample.kind === "mcp-phase");
207
- // ponytail: at most 32 outstanding phase writes; a bounded worker queue with per-kind fairness is the upgrade.
208
- if (phase && pendingPhases >= MCP_PHASE_KEEP) return;
209
- if (phase) pendingPhases++;
210
- pending.push({ base, samples, phase });
213
+ const kind = samples[0]?.kind;
214
+ const boundedKind = (kind === "mcp-phase" || kind === "brief-publication") && samples.every(sample => sample.kind === kind) ? kind : undefined;
215
+ // ponytail: at most 32 outstanding writes per metered kind; a worker queue with per-kind fairness is the upgrade.
216
+ if (boundedKind && pendingCounts[boundedKind] >= MCP_PHASE_KEEP) return;
217
+ if (boundedKind) pendingCounts[boundedKind]++;
218
+ pending.push({ base, samples, boundedKind });
211
219
  if (draining) return;
212
220
  draining = true;
213
221
  setImmediate(() => { void drainPending(); });
@@ -217,7 +225,7 @@ async function drainPending(): Promise<void> {
217
225
  while (pending.length) {
218
226
  const next = pending.shift()!;
219
227
  try { await writeSamplesLater(next.base, next.samples); } catch { /* a lost sample is never a failed call */ }
220
- finally { if (next.phase) pendingPhases--; }
228
+ finally { if (next.boundedKind) pendingCounts[next.boundedKind]--; }
221
229
  }
222
230
  draining = false;
223
231
  }
@@ -261,7 +269,7 @@ export function readMetrics(base: string, limit = METRICS_KEEP): MetricSample[]
261
269
  if (!line) continue;
262
270
  try {
263
271
  const s = JSON.parse(line) as MetricSample;
264
- if ((s?.kind === "hook" || s?.kind === "search" || s?.kind === "mcp-phase") && typeof s.at === "string") parsed.push(s);
272
+ if ((s?.kind === "hook" || s?.kind === "search" || s?.kind === "mcp-phase" || s?.kind === "brief-publication") && typeof s.at === "string") parsed.push(s);
265
273
  } catch { /* a malformed line is skipped */ }
266
274
  }
267
275
  return newestPerKind(parsed, limit, sample => sample.kind);
@@ -0,0 +1,32 @@
1
+ import { label, PLAIN, singleLine, type Style } from "./style.ts";
2
+ import type { MigrationResult } from "./migrate.ts";
3
+
4
+ /** #592: the human migrate report, kept out of migrate.ts so the write path never imports the output package. */
5
+ /** Render a migration result for a person; JSON output remains owned by the CLI. */
6
+ export function migrationText(result: MigrationResult, s: Style = PLAIN): string {
7
+ const active = result.profile.kind === "generation";
8
+ const needsResume = result.mode === "resume" && !active;
9
+ const state = needsResume ? "attention" : result.mode === "dry-run" ? "preview" : "complete";
10
+ const groups = (value: Record<string, number>) => Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, count]) => `${singleLine(key)}=${count}`).join(", ");
11
+ const countRows = result.counts ? [
12
+ ["valid", result.counts.validRows], ["skipped", result.counts.skippedRows], ["tailBytes", result.counts.tailBytes],
13
+ ["expired", result.counts.expiredRows], ["eligible", result.counts.eligibleRows],
14
+ ].map(([key, value]) => `${label(s, "ok")} ${key} ${value}`) : [`${label(s, "skipped")} counts not returned for this mode`];
15
+ const operationCounts = result.counts ? groups(result.counts.byOp) : "", tierCounts = result.counts ? groups(result.counts.byTier) : "";
16
+ if (operationCounts) countRows.push(`${label(s, "ok")} operations ${operationCounts}`);
17
+ if (tierCounts) countRows.push(`${label(s, "ok")} tiers ${tierCounts}`);
18
+ let action = "none";
19
+ if (result.mode === "dry-run" && !active) action = "apply migration: amem migrate --apply";
20
+ else if (needsResume) action = "resume migration: amem migrate --resume";
21
+ else if (result.mode === "deactivate" && active) action = "deactivate generation: amem migrate --deactivate";
22
+ const lines = [
23
+ `${s.bold("amem migrate:")} ${state}${result.alreadyActive ? " (already active)" : ""}`,
24
+ `${label(s, "ok")} profile ${result.profile.kind}${result.profile.generation ? ` (generation ${result.profile.generation.slice(0, 8)})` : ""}`,
25
+ `${label(s, "ok")} home ${singleLine(result.profile.home)}`,
26
+ `${label(s, "ok")} current directory ${singleLine(result.profile.dir)}`,
27
+ ...countRows,
28
+ `${label(s, "ok")} effect ${singleLine(result.consequence)}`,
29
+ `Next action: ${action}`,
30
+ ];
31
+ return lines.join("\n");
32
+ }
@@ -6,7 +6,6 @@ import { acquireMutation } from "./mutation.ts";
6
6
  import { canonicalPath, realPath } from "./platform.ts";
7
7
  import { canonicalJSON, fsyncDirectory, generationDescriptor, generationDir, hashJSON, readProfileJSON, readSelector, resolveProfile, validGeneration, withProfileLock, writeProfileJSON, type BoundProfile } from "./generation.ts";
8
8
  import { invalidateCuratedCaches } from "./curated-cache-state.ts";
9
- import { label, PLAIN, singleLine, type Style } from "./style.ts";
10
9
 
11
10
  export interface SourcePrefix extends LegacyCheckpoint { tailBytes: number }
12
11
  interface MigrationJournal {
@@ -231,31 +230,3 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
231
230
  return result;
232
231
  }
233
232
 
234
- /** Render a migration result for a person; JSON output remains owned by the CLI. */
235
- export function migrationText(result: MigrationResult, s: Style = PLAIN): string {
236
- const active = result.profile.kind === "generation";
237
- const needsResume = result.mode === "resume" && !active;
238
- const state = needsResume ? "attention" : result.mode === "dry-run" ? "preview" : "complete";
239
- const groups = (value: Record<string, number>) => Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, count]) => `${singleLine(key)}=${count}`).join(", ");
240
- const countRows = result.counts ? [
241
- ["valid", result.counts.validRows], ["skipped", result.counts.skippedRows], ["tailBytes", result.counts.tailBytes],
242
- ["expired", result.counts.expiredRows], ["eligible", result.counts.eligibleRows],
243
- ].map(([key, value]) => `${label(s, "ok")} ${key} ${value}`) : [`${label(s, "skipped")} counts not returned for this mode`];
244
- const operationCounts = result.counts ? groups(result.counts.byOp) : "", tierCounts = result.counts ? groups(result.counts.byTier) : "";
245
- if (operationCounts) countRows.push(`${label(s, "ok")} operations ${operationCounts}`);
246
- if (tierCounts) countRows.push(`${label(s, "ok")} tiers ${tierCounts}`);
247
- let action = "none";
248
- if (result.mode === "dry-run" && !active) action = "apply migration: amem migrate --apply";
249
- else if (needsResume) action = "resume migration: amem migrate --resume";
250
- else if (result.mode === "deactivate" && active) action = "deactivate generation: amem migrate --deactivate";
251
- const lines = [
252
- `${s.bold("amem migrate:")} ${state}${result.alreadyActive ? " (already active)" : ""}`,
253
- `${label(s, "ok")} profile ${result.profile.kind}${result.profile.generation ? ` (generation ${result.profile.generation.slice(0, 8)})` : ""}`,
254
- `${label(s, "ok")} home ${singleLine(result.profile.home)}`,
255
- `${label(s, "ok")} current directory ${singleLine(result.profile.dir)}`,
256
- ...countRows,
257
- `${label(s, "ok")} effect ${singleLine(result.consequence)}`,
258
- `Next action: ${action}`,
259
- ];
260
- return lines.join("\n");
261
- }
@@ -0,0 +1,29 @@
1
+ import { label, PLAIN, singleLine, type Style } from "./style.ts";
2
+ import type { PrunePlan } from "./prune.ts";
3
+
4
+ /** #592: the human prune report, kept out of prune.ts so the write path never imports the output package. */
5
+ /** Human-readable preview or apply result. A preview is descriptive output, not a serialized sealed plan. */
6
+ export function pruneText(result: PrunePlan | { completed: string[] }, s: Style = PLAIN): string {
7
+ if ("completed" in result) {
8
+ return [
9
+ `amem prune: ${s.ok("complete")}`,
10
+ `${label(s, result.completed.length ? "ok" : "skipped")} completed prune rows: ${result.completed.length}`,
11
+ ...result.completed.map(id => ` ${label(s, "ok")} ${id}`),
12
+ "Next action: none",
13
+ ].join("\n");
14
+ }
15
+ const targetIds = result.rows.flatMap(row => row.payload.targets.map(target => target.id));
16
+ const next = targetIds.length
17
+ ? "save this preview with --json, then amem prune --apply --plan <file>; keep --user if used in the preview"
18
+ : "none; the sealed plan contains no prune rows";
19
+ return [
20
+ `amem prune: ${s.attention("preview")}`,
21
+ `${label(s, "ok")} project: ${singleLine(result.project)}`,
22
+ ...(result.rows.length ? [`${label(s, "ok")} cutoff: ${result.rows[0]!.payload.cutoff}`] : []),
23
+ `${label(s, targetIds.length ? "attention" : "skipped")} selection: eligible ${result.counts.eligible}, selected ${result.counts.selected}, local ${result.counts.local}, synced ${result.counts.synced}`,
24
+ ...(result.hasMore ? ["more eligible entries remain beyond this plan"] : []),
25
+ ...result.rows.flatMap(row => row.payload.targets.map(target => ` ${label(s, "attention")} ${row.placement}: ${target.id} (expired ${target.expiredAt})`)),
26
+ `Next action: ${next}`,
27
+ ...(targetIds.length ? ["The readable preview is not a sealed JSON plan."] : []),
28
+ ].join("\n");
29
+ }
@@ -1,6 +1,5 @@
1
1
  import { canonicalJSON, hashJSON, validGeneration } from "./generation.ts";
2
2
  import { entryId, type Entry, type NoteEntry } from "./store.ts";
3
- import { label, PLAIN, singleLine, type Style } from "./style.ts";
4
3
 
5
4
  export const PRUNE_ROW_MAX_BYTES = 16_384, PRUNE_PLAN_MAX_BYTES = 262_144;
6
5
  export const PRUNE_ROW_MAX_TARGETS = 32, PRUNE_PLAN_MAX_ROWS = 16, PRUNE_PLAN_MAX_TARGETS = 256;
@@ -259,28 +258,3 @@ export function applyPrune(port: PruneStorePort, input: unknown, auth: PruneAuth
259
258
  });
260
259
  }
261
260
 
262
- /** Human-readable preview or apply result. A preview is descriptive output, not a serialized sealed plan. */
263
- export function pruneText(result: PrunePlan | { completed: string[] }, s: Style = PLAIN): string {
264
- if ("completed" in result) {
265
- return [
266
- `amem prune: ${s.ok("complete")}`,
267
- `${label(s, result.completed.length ? "ok" : "skipped")} completed prune rows: ${result.completed.length}`,
268
- ...result.completed.map(id => ` ${label(s, "ok")} ${id}`),
269
- "Next action: none",
270
- ].join("\n");
271
- }
272
- const targetIds = result.rows.flatMap(row => row.payload.targets.map(target => target.id));
273
- const next = targetIds.length
274
- ? "save this preview with --json, then amem prune --apply --plan <file>; keep --user if used in the preview"
275
- : "none; the sealed plan contains no prune rows";
276
- return [
277
- `amem prune: ${s.attention("preview")}`,
278
- `${label(s, "ok")} project: ${singleLine(result.project)}`,
279
- ...(result.rows.length ? [`${label(s, "ok")} cutoff: ${result.rows[0]!.payload.cutoff}`] : []),
280
- `${label(s, targetIds.length ? "attention" : "skipped")} selection: eligible ${result.counts.eligible}, selected ${result.counts.selected}, local ${result.counts.local}, synced ${result.counts.synced}`,
281
- ...(result.hasMore ? ["more eligible entries remain beyond this plan"] : []),
282
- ...result.rows.flatMap(row => row.payload.targets.map(target => ` ${label(s, "attention")} ${row.placement}: ${target.id} (expired ${target.expiredAt})`)),
283
- `Next action: ${next}`,
284
- ...(targetIds.length ? ["The readable preview is not a sealed JSON plan."] : []),
285
- ].join("\n");
286
- }