@staix/agent-mem 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,231 @@
1
+ import { Report } from "@staix/cli-output";
2
+ import type { CatalogProject } from "./catalog.ts";
3
+ import type { DecayPlan } from "./decay-review.ts";
4
+ import type { MigrationResult } from "./migrate.ts";
5
+ import type { PrunePlan } from "./prune.ts";
6
+ import type { ShardMigrationResult } from "./shard-migration.ts";
7
+ import type { View } from "./store.ts";
8
+ import type { SyncResult } from "./sync.ts";
9
+ import { renderSyncProgress, type SyncStatusReport } from "./sync-progress.ts";
10
+ import type { UsageReport } from "./usage.ts";
11
+ import { humanBytes, PLAIN, relativeTime, singleLine, wordedKey, type Style } from "./style.ts";
12
+
13
+ /**
14
+ * CLI-only #590 renderers for the report families outside status, doctor, setup and the memory reads (task 429).
15
+ * Never re-exported from `src/index.ts`: the exported renderers they replace on the CLI (migrationText, pruneText, usageText,
16
+ * vaultCandidatesText, renderSyncStatus, ...) stay byte-identical for hosts. Every `→` line is a complete amem command.
17
+ */
18
+ export interface RenderOptions { columns?: number; now?: number }
19
+
20
+ const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
21
+ const frame = (s: Style, name: string, state: string, opts: RenderOptions): Report =>
22
+ new Report(opts.columns ?? 80, s.ascii, { sanitize: singleLine }).header("amem", name, state);
23
+ const done = (report: Report, s: Style) => report.render(s.color).join("\n");
24
+ const shortId = (id: string) => id.slice(0, 8);
25
+
26
+ /** `amem migrate` (generation profile). */
27
+ export function migrateReportText(result: MigrationResult, s: Style = PLAIN, opts: RenderOptions = {}): string {
28
+ const active = result.profile.kind === "generation", needsResume = result.mode === "resume" && !active;
29
+ const state = needsResume ? "needs resume" : result.mode === "dry-run" ? "preview, nothing written" : result.alreadyActive ? "already active" : "done";
30
+ const report = frame(s, "Migration", state, opts);
31
+ report.section("Profile").kv([["Kind", result.profile.kind], ["Generation", result.profile.generation ? shortId(result.profile.generation) : ""],
32
+ ["Home", result.profile.home], ["Directory", result.profile.dir]], 2, { omitEmpty: true });
33
+ if (result.counts) {
34
+ const c = result.counts, groups = (value: Record<string, number>) => Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, n]) => `${k} ${n}`).join(", ");
35
+ report.section("Rows").kv([["Valid", c.validRows], ["Skipped", c.skippedRows], ["Expired", c.expiredRows], ["Eligible", c.eligibleRows],
36
+ ["Tail bytes", c.tailBytes ? humanBytes(c.tailBytes) : ""], ["Operations", groups(c.byOp)], ["Tiers", groups(c.byTier)]], 2, { omitEmpty: true });
37
+ }
38
+ report.section("Effect").note(result.consequence, "value");
39
+ const next = result.mode === "dry-run" && !active ? "amem migrate --apply" : needsResume ? "amem migrate --resume" : result.mode === "deactivate" && active ? "amem migrate --deactivate" : undefined;
40
+ if (next) { report.section("Next"); report.next(next); }
41
+ return done(report, s);
42
+ }
43
+
44
+ /** `amem migrate --shards`. */
45
+ export function shardMigrateReportText(result: ShardMigrationResult, s: Style = PLAIN, opts: RenderOptions = {}): string {
46
+ const c = result.counts, refusals = result.refusals ?? [];
47
+ const flagged = refusals.length > 0 || c.refusedRows > 0 || c.danglingRows > 0;
48
+ const state = flagged ? "needs attention" : result.mode === "dry-run" ? "preview, nothing written" : result.active ? result.alreadyActive ? "already active" : "done" : "needs resume";
49
+ const report = frame(s, "Shard migration", state, opts);
50
+ report.note(`generation ${shortId(result.generation)}`);
51
+ const findings: { text: string; next?: string }[] = [
52
+ ...refusals.map(reason => ({ text: reason })),
53
+ ...(c.refusedRows ? [{ text: `${plural(c.refusedRows, "row")} refused` }] : []),
54
+ ...(c.danglingRows ? [{ text: `${plural(c.danglingRows, "dangling row")}` }] : []),
55
+ ...(c.sharedSupersededByPrivate ? [{ text: `${plural(c.sharedSupersededByPrivate, "shared row")} superseded by a private one` }] : []),
56
+ ...(c.crossPrivateReplacement ? [{ text: `${plural(c.crossPrivateReplacement, "cross-project private replacement")}` }] : []),
57
+ ];
58
+ if (findings.length) { report.section("Attention", String(findings.length)); for (const f of findings) report.bullet("warn", f.text); }
59
+ report.section("Rows").kv(([["Rows", c.rows], ["Skipped", c.skippedRows], ["User", c.userRows], ["Legacy", c.legacyRows], ["Legacy local", c.legacyLocalRows],
60
+ ["Legacy main", c.legacyMainRows], ["Generation", c.generationRows], ["Generation local", c.generationLocalRows], ["Prune", c.pruneRows],
61
+ ["Translated prune", c.translatedPruneRows], ["Tail bytes", c.tailBytes ? humanBytes(c.tailBytes) : ""],
62
+ ["Shards", Object.keys(c.byShard).length], ["Projects", Object.keys(c.byProject).length],
63
+ ["Dead leases removed", result.deadLeasesRemoved?.length ?? 0]] as [string, string | number][]).filter(([, v]) => v !== 0), 2, { omitEmpty: true });
64
+ report.section("Effect").note(result.consequence, "value");
65
+ const next = flagged ? undefined : result.mode === "dry-run" && (!result.active || c.rows > 0) ? "amem migrate --shards --apply"
66
+ : result.mode === "resume" && !result.active ? "amem migrate --shards --resume" : undefined;
67
+ if (next) { report.section("Next"); report.next(next); }
68
+ return done(report, s);
69
+ }
70
+
71
+ /** `amem prune`: the readable preview (never the sealed plan) or the applied rows. */
72
+ export function pruneReportText(result: PrunePlan | { completed: string[] }, s: Style = PLAIN, opts: RenderOptions = {}): string {
73
+ if ("completed" in result) {
74
+ const report = frame(s, "Prune", result.completed.length ? "done" : "nothing to apply", opts);
75
+ if (result.completed.length) { report.section("Completed", String(result.completed.length)); for (const id of result.completed) report.bullet("ok", id); }
76
+ return done(report, s);
77
+ }
78
+ const targets = result.rows.flatMap(row => row.payload.targets.map(target => ({ placement: row.placement, ...target })));
79
+ const report = frame(s, "Prune", targets.length ? "preview, nothing written" : "nothing eligible", opts);
80
+ const now = opts.now ?? Date.now();
81
+ report.note(`project ${result.project}${result.rows.length ? `, cutoff ${relativeTime(result.rows[0]!.payload.cutoff, now)}` : ""}`);
82
+ report.section("Selection").kv([["Eligible", result.counts.eligible], ["Selected", result.counts.selected], ["Local", result.counts.local], ["Synced", result.counts.synced]]);
83
+ if (result.hasMore) report.note("More eligible entries remain beyond this plan.");
84
+ if (targets.length) {
85
+ report.section("Targets", String(targets.length));
86
+ report.table(["Placement", "Entry", "Expired"], targets.map(t => [t.placement, t.id, relativeTime(t.expiredAt, now)]), 1);
87
+ report.section("Next");
88
+ report.note("This preview is not the sealed plan. Save the plan with --json, then apply it (keep --user if you used it):");
89
+ report.next("amem prune --apply --plan <file>");
90
+ }
91
+ return done(report, s);
92
+ }
93
+
94
+ /** `amem decay`: preview, nothing eligible, or the applied revision. */
95
+ export function decayReportText(input: { kind: "preview"; plan: DecayPlan; action: "demote" | "FORGET" } | { kind: "empty" } | { kind: "applied"; action: string; ids: readonly string[]; expiresAt?: string },
96
+ s: Style = PLAIN, opts: RenderOptions = {}): string {
97
+ if (input.kind === "empty") return done(frame(s, "Decay", "nothing eligible to apply", opts), s);
98
+ if (input.kind === "applied") {
99
+ const report = frame(s, "Decay", `${input.action === "forget" ? "forgotten" : "demoted"} ${plural(input.ids.length, "note")}`, opts);
100
+ if (input.expiresAt) report.section("Details").kv([["Expires", relativeTime(input.expiresAt, opts.now ?? Date.now())]]);
101
+ return done(report, s);
102
+ }
103
+ const { plan, action } = input, verb = action === "FORGET" ? "forget" : "demote";
104
+ const report = frame(s, "Decay", `preview, nothing written`, opts);
105
+ report.note(`${plural(plan.entries.length, "note")} older than ${plural(plan.days, "day")} would ${verb === "forget" ? "be forgotten" : "be demoted"}`);
106
+ report.section("Selection").kv([["Notes", plan.entries.length], ["Withheld", plan.withheld], ["Cited, kept", plan.citedExemptions ?? "unknown"],
107
+ ["Citation history", "unknown"], ...(plan.truncated ? [["Truncated", "yes"] as const] : [])]);
108
+ if (plan.entries.length) {
109
+ report.section("Notes", String(plan.entries.length));
110
+ report.table(["ID", "Revision", "Kind", "Title"], plan.entries.map(e => [shortId(e.target.id), String(e.target.revision), e.view.kind, singleLine(e.view.title ?? e.view.text)]), 3);
111
+ report.section("Next");
112
+ report.next(`amem decay --days ${plan.days} --apply --confirm${action === "FORGET" ? " --forget" : ""}`);
113
+ }
114
+ return done(report, s);
115
+ }
116
+
117
+ interface ReplayPlan { records: { cwd: string; project: string | null; class: string }[]; counts: Record<string, number>; digest: string; needsConfirmation: { cwd: string; project: string; count: number }[] }
118
+ /** `amem spool replay` preview: counts and cwd mappings only, never a record body. */
119
+ export function spoolReplayReportText(plan: ReplayPlan, s: Style = PLAIN, opts: RenderOptions = {}): string {
120
+ const report = frame(s, "Spool replay", "preview, nothing written", opts);
121
+ report.note(`plan ${plan.digest.slice(0, 12)}; no record bodies shown`);
122
+ const counts = Object.entries(plan.counts).filter(([, n]) => n > 0);
123
+ if (counts.length) report.section("Records").kv(counts.map(([cls, n]) => [wordedKey(cls).replace(/^./, c => c.toUpperCase()), n]));
124
+ const byCwd = new Map<string, { project: string | null; classes: Map<string, number> }>();
125
+ for (const record of plan.records) {
126
+ const row = byCwd.get(record.cwd) ?? { project: record.project, classes: new Map() };
127
+ row.classes.set(record.class, (row.classes.get(record.class) ?? 0) + 1); byCwd.set(record.cwd, row);
128
+ }
129
+ if (byCwd.size) {
130
+ report.section("Mappings", String(byCwd.size));
131
+ report.table(["Directory", "Project", "Records"], [...byCwd].map(([cwd, row]) => [cwd || "(unreadable record)", row.project ?? "(unresolved)", [...row.classes].map(([c, n]) => `${c} ${n}`).join(", ")]), 0);
132
+ }
133
+ if (plan.needsConfirmation.length) {
134
+ report.section("Attention", String(plan.needsConfirmation.length));
135
+ for (const group of plan.needsConfirmation) report.bullet("warn", `${group.cwd} -> ${group.project}: ${plural(group.count, "record")}; this boot cannot prove the original identity`);
136
+ }
137
+ report.section("Next");
138
+ report.note("Save the preview first: amem spool replay --json > plan.json");
139
+ report.next("amem spool replay --apply --plan plan.json");
140
+ if (plan.needsConfirmation.length) report.next("amem spool replay --apply --plan plan.json --confirm-unverifiable");
141
+ return done(report, s);
142
+ }
143
+
144
+ /** `amem sync` success. A failure stays the thrown refusal text. */
145
+ export function syncReportText(r: SyncResult, s: Style = PLAIN, opts: RenderOptions = {}): string {
146
+ const report = frame(s, "Sync", r.pushed ? "synced and pushed" : "synced", opts);
147
+ const rows: [string, unknown][] = [[r.pruneApplication ? "Transported" : "Visible here", plural(r.entries, "long-term entry").replace("entrys", "entries")]];
148
+ const p = r.placementPublication;
149
+ if (p) rows.push(["Placement", `${p.outcome}, ${p.exported} exported, ${p.withheld} withheld`]);
150
+ if (r.checkpoint) rows.push(["Checkpoint", `window ${r.checkpoint.window}, objects ${r.checkpoint.objectsBefore} -> ${r.checkpoint.objectsAfter}`]);
151
+ const a = r.pruneApplication;
152
+ if (a) rows.push(["Prune proofs", `${a.proofComplete} complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native applied, ${a.held} held`]);
153
+ report.section("Result").kv(rows);
154
+ if (r.placementRealms?.length) {
155
+ report.section("Realms", String(r.placementRealms.length));
156
+ report.table(["Realm", "Outcome", "Publication"], r.placementRealms.map(item => [item.realm === "user" ? "user" : item.realm.slice(0, 16), item.outcome, item.publication === undefined ? "" : String(item.publication)]), 1, { emptyCell: "blank" });
157
+ }
158
+ if (r.warning) { report.section("Attention", "1"); report.bullet("warn", r.warning); }
159
+ return done(report, s);
160
+ }
161
+
162
+ /** `amem sync --status`. */
163
+ export function syncStatusReportText(status: SyncStatusReport, now: number, s: Style = PLAIN, opts: RenderOptions = {}): string {
164
+ const interrupted = status.operations.filter(op => op.state === "interrupted").length;
165
+ const report = frame(s, "Sync status", status.operations.length ? `${plural(status.operations.length, "operation")}${interrupted ? `, ${interrupted} interrupted` : ""}` : "no operation recorded", opts);
166
+ if (status.operations.length) {
167
+ report.section("Operations", String(status.operations.length));
168
+ for (const op of status.operations) {
169
+ // An interrupted operation renders as the running snapshot it was; the owner is gone, so it is never a success.
170
+ const line = renderSyncProgress(op.state === "interrupted" ? { ...op, state: "running" } : op, now).replace(/^amem sync: /, "");
171
+ const marker = op.state === "interrupted" ? "warn" : op.state === "running" ? "pending" : op.state === "succeeded" ? "ok" : op.state === "cancelled" ? "absent" : "fail";
172
+ report.bullet(marker, `${op.operationId}: ${op.state === "interrupted" ? `interrupted in ${line.replace(/; last work progress .*$/, "")}; owner gone ${Math.round(op.lastAliveAgoMs / 1000)}s ago; not a successful sync`
173
+ : op.state === "running" ? `${line}; last alive ${Math.round(op.lastAliveAgoMs / 1000)}s ago` : line}`);
174
+ }
175
+ }
176
+ if (status.malformed) report.note(`${plural(status.malformed, "unreadable status file")} ignored`);
177
+ return done(report, s);
178
+ }
179
+
180
+ /** `amem projects`. */
181
+ export function projectsReportText(rows: readonly CatalogProject[], split: boolean, s: Style = PLAIN, opts: RenderOptions = {}): string {
182
+ const report = frame(s, "Projects", rows.length ? plural(rows.length, "project shard") : "none", opts);
183
+ if (!rows.length) return done(report, s);
184
+ if (!split) report.note("Curated counts are per project only after amem migrate --shards.");
185
+ report.section("Shards", String(rows.length));
186
+ report.table(["Key", "State", "Capture", "Curated", "Disk", "Last"], rows.map(p => [
187
+ `${p.key}${p.local ? " (local)" : ""}${p.aliases.length ? ` +${p.aliases.length}` : ""}`, p.state, `${p.captureRows} rows`,
188
+ split ? p.curatedEntries === null ? "?" : String(p.curatedEntries) : "-", humanBytes(p.diskBytes), relativeTime(p.captureLastAt, opts.now ?? Date.now())]), 0);
189
+ const aliased = rows.filter(p => p.aliases.length);
190
+ if (aliased.length) { report.section("Aliases"); report.kv(aliased.map(p => [p.key, p.aliases.join(", ")])); }
191
+ return done(report, s);
192
+ }
193
+
194
+ /** `amem usage`. */
195
+ export function usageReportText(report_: UsageReport, s: Style = PLAIN, opts: RenderOptions = {}): string {
196
+ const t = report_.totals, report = frame(s, "Usage", plural(t.shards, "project shard"), opts);
197
+ report.section("Totals").kv([["Capture", `${t.captureRows} rows, ${humanBytes(t.captureBytes)}`],
198
+ ["Curated", t.curatedEntries === null ? report_.curatedSplit ? "unavailable" : "unavailable until amem migrate --shards" : `${t.curatedEntries} entries`],
199
+ ["Disk", humanBytes(t.diskBytes)]]);
200
+ if (report_.largest.length) {
201
+ report.section("Largest", String(report_.largest.length));
202
+ report.table(["Key", "Disk", "Capture"], report_.largest.map(p => [`${p.key}${p.state === "active" ? "" : ` (${p.state})`}`, humanBytes(p.diskBytes), `${p.captureRows} rows`]), 0);
203
+ }
204
+ return done(report, s);
205
+ }
206
+
207
+ /** `amem repo status`. */
208
+ export function repoStatusReportText(status: { root: string; file: string; state: string; entries: number; reason?: string; skipped: null | { malformed: number; mismatched: number; duplicate: number; withheld: number } },
209
+ project: string, s: Style = PLAIN, opts: RenderOptions = {}): string {
210
+ const report = frame(s, "Repository log", status.state === "unavailable" ? "unavailable" : plural(status.entries, "entry").replace("entrys", "entries"), opts);
211
+ report.note(`project ${project}`);
212
+ const k = status.skipped;
213
+ report.section("Log").kv([["File", status.file], ["State", status.state], ["Entries", status.entries],
214
+ ["Skipped", k ? [k.malformed && `${k.malformed} malformed`, k.mismatched && `${k.mismatched} id mismatch`, k.duplicate && `${k.duplicate} duplicate`, k.withheld && `${k.withheld} withheld by the screen`].filter(Boolean).join(", ") : ""]], 2, { omitEmpty: true });
215
+ if (status.reason) { report.section("Attention", "1"); report.bullet("warn", status.reason); }
216
+ return done(report, s);
217
+ }
218
+
219
+ /** `amem vault-candidates` (one project or across projects); never a note body. */
220
+ export function vaultReportText(groups: readonly { project: string; candidates: readonly View[] }[], crossed: boolean, s: Style = PLAIN, opts: RenderOptions = {}): string {
221
+ const count = groups.reduce((sum, g) => sum + g.candidates.length, 0);
222
+ const report = frame(s, "Vault candidates", `${count ? plural(count, "candidate") : "none"}${crossed ? ", across projects" : ""}`, opts);
223
+ if (!count) return done(report, s);
224
+ report.section("Candidates", String(count));
225
+ report.table([...(crossed ? ["Project"] : []), "ID", "Kind", "Title"], groups.flatMap(g => g.candidates.map(row =>
226
+ [...(crossed ? [g.project] : []), shortId(row.id), row.kind, singleLine(row.title ?? "(untitled)")])), crossed ? 3 : 2);
227
+ report.section("Next");
228
+ report.note(crossed ? "Open the candidate's source repository, then review it before recording it in your vault:" : "Review a candidate before recording it in your vault:");
229
+ report.next("amem show <id>");
230
+ return done(report, s);
231
+ }
@@ -1,5 +1,5 @@
1
- import { markerCell, paint } from "@staix/cli-output";
2
- import { facts, label, section, PLAIN, type Style } from "./style.ts";
1
+ import { MARKER_COLUMN, MARKERS, Report, markerCell, wrap } from "@staix/cli-output";
2
+ import { humanBytes, singleLine, wordedKey, PLAIN, type Style } from "./style.ts";
3
3
 
4
4
  /** The `amem status` object as the CLI builds it; `amem status --json` prints it unchanged. */
5
5
  export interface StatusView {
@@ -11,38 +11,81 @@ export interface StatusView {
11
11
  deadLeasesRemoved?: { lease: string; at: string }[]; refusals?: string[];
12
12
  }
13
13
 
14
- /** Person-facing `amem status` (#125): overall state, the effective home and policy, the counts that matter, then next actions. Zero counters are summarized, never listed. */
15
- export function statusText(status: StatusView, s: Style = PLAIN): string {
16
- const actions: string[] = [], warnings: string[] = [];
14
+ /** Human rendering options (#590): `--verbose` history lines, the wrap width and the version in the context line. */
15
+ export interface ReportTextOptions { verbose?: boolean; columns?: number; version?: string }
16
+
17
+ /** One `⚠` finding and the complete commands that act on it (#590 C4); a finding without a known fix has none. */
18
+ export interface Finding { text: string; next: readonly string[] }
19
+
20
+ type State = "ok" | "attention" | "unavailable";
21
+ // #590 S2: one word per state in the header, the rows and the summary line (`⚠ 2 warnings ? 1 unknown ✓ 8 ok`).
22
+ export const STATE_WORD: Record<State, string> = { ok: "ok", attention: "warning", unavailable: "unknown" };
23
+ const MARKER: Record<State, "ok" | "warn" | "unknown"> = { ok: "ok", attention: "warn", unavailable: "unknown" };
24
+
25
+ /** Shared report frame for status and doctor: one header line with the state, one context line, then sections. */
26
+ export function reportFrame(s: Style, name: string, state: string, opts: ReportTextOptions, home: { path: string; source: string }): Report {
27
+ const report = new Report(opts.columns, s.ascii, { sanitize: singleLine });
28
+ report.header("amem", name, state);
29
+ report.note(`${opts.version ? `amem ${opts.version}, ` : ""}home ${home.path} (${home.source})`);
30
+ return report;
31
+ }
32
+ /** `⚠` rows, each followed by its `→` commands. */
33
+ export function attention(report: Report, findings: readonly Finding[]): void {
34
+ if (!findings.length) return;
35
+ report.section("Attention", String(findings.length));
36
+ for (const finding of findings) { report.bullet("warn", finding.text); for (const command of finding.next) report.next(command); }
37
+ }
38
+ /** A state row: marker, padded state word, padded name, then the fact; a wrapped fact continues under itself (#590 S1, S2). */
39
+ export function stateRows(report: Report, rows: readonly { state: State | "skipped"; name: string; fact: string }[], s: Style): void {
40
+ const words = rows.map(row => row.state === "skipped" ? "skipped" : STATE_WORD[row.state]);
41
+ const wordWidth = Math.max(...words.map(word => word.length)), nameWidth = Math.max(...rows.map(row => row.name.length + 1));
42
+ const lead = 2 + MARKER_COLUMN + 1 + wordWidth + 2 + nameWidth + 2;
43
+ rows.forEach((row, index) => {
44
+ const marker = row.state === "skipped" ? "absent" : MARKER[row.state];
45
+ const lines = wrap(singleLine(row.fact), report.columns === undefined ? undefined : Math.max(10, report.columns - lead), 0);
46
+ report.append([[{ text: " " }, { text: markerCell(marker, s.ascii), role: MARKERS[marker].role }, { text: " " },
47
+ { text: words[index]!.padEnd(wordWidth), role: MARKERS[marker].role }, { text: " " }, { text: `${row.name}:`.padEnd(nameWidth), role: "key" }, { text: " " }, { text: lines[0] ?? "" }],
48
+ ...lines.slice(1).map(line => [{ text: " ".repeat(lead) + line }])]);
49
+ });
50
+ }
51
+
52
+ const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
53
+
54
+ /** Person-facing `amem status` (#125, #590): overall state, findings with their commands, then the memory facts. */
55
+ export function statusText(status: StatusView, s: Style = PLAIN, opts: ReportTextOptions = {}): string {
56
+ const findings: Finding[] = [];
17
57
  const candidates = status.candidates;
18
- let candidateLine: string, candidateState: "ok" | "attention" | "unavailable";
19
- if ("unavailable" in candidates) { candidateState = "unavailable"; candidateLine = candidates.unavailable; warnings.push(candidates.unavailable); }
58
+ let candidateFact: string, candidateState: State;
59
+ if ("unavailable" in candidates) { candidateState = "unavailable"; candidateFact = candidates.unavailable; }
20
60
  else {
21
61
  candidateState = candidates.dueWithin7Days ? "attention" : "ok";
22
- candidateLine = candidates.count ? `${candidates.count} pending${candidates.unshown ? ` (${candidates.unshown} never shown)` : ""}${candidates.oldestExpiresInDays !== null ? `, oldest expires in ${candidates.oldestExpiresInDays} days` : ""}` : "none pending";
23
- if (candidates.warning) actions.push(candidates.warning);
24
- else if (candidates.count) actions.push("review pending candidates: amem review walk");
62
+ candidateFact = candidates.count ? `${candidates.count} pending${candidates.unshown ? `, ${candidates.unshown} never shown` : ""}${candidates.oldestExpiresInDays !== null ? `, oldest expires in ${candidates.oldestExpiresInDays} d` : ""}` : "none pending";
63
+ if (candidates.dueWithin7Days) findings.push({ text: `${plural(candidates.dueWithin7Days, "candidate")} expire within 7 days`, next: ["amem review walk"] });
25
64
  }
26
65
  const refusals = status.refusals ?? [];
27
66
  const interrupted = status.phase === "captured" && !status.active; // authoring refuses until activation (generation-index.ts)
28
- const migrationState: "ok" | "attention" = refusals.length || status.pending.rows || interrupted ? "attention" : "ok";
29
- if (interrupted) actions.push("a shard migration stopped after capture and authoring is refused until it activates: amem migrate --shards --resume");
30
- if (refusals.length) warnings.push(...refusals.map(reason => `migration refusal: ${reason}`));
31
- if (status.pending.rows && !interrupted) actions.push(`${status.pending.rows} old-layout rows wait for the shard migration: amem migrate --shards --resume carries them (amem migrate --shards --dry-run previews first)`);
32
- const overall = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" ? "attention" : "ok";
67
+ const migrationState: State = refusals.length || status.pending.rows || interrupted ? "attention" : "ok";
68
+ if (interrupted) findings.push({ text: "a shard migration stopped after capture; authoring is refused until it activates", next: ["amem migrate --shards --resume"] });
69
+ for (const reason of refusals) findings.push({ text: `migration refusal: ${reason}`, next: [] });
70
+ if (status.pending.rows && !interrupted) findings.push({ text: `${plural(status.pending.rows, "old-layout row")} wait for the shard migration`, next: ["amem migrate --shards --dry-run", "amem migrate --shards --resume"] });
71
+ const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" ? "attention" : "ok";
33
72
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
34
- const pendingCounts = facts(Object.fromEntries(Object.entries(status.pending).filter(([key]) => !key.endsWith("Ids"))));
35
- const lines = [
36
- `${paint([{ role: "header", text: " amem Status" }], s.color)}: ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
37
- ...(warnings.length || actions.length ? ["", section(s, "Attention"), ...warnings.map(warning => ` ${s.attention(markerCell("warn", s.ascii))} ${warning}`), ...actions.map(action => ` ${paint([{ role: "accent", text: markerCell("next", s.ascii) }], s.color)} ${action}`)] : []),
38
- "", section(s, "Memory"),
39
- ` home: ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
40
- `${label(s, "ok")} policy: machine ${machine ?? "none (defaults)"}, repo ${repo ?? "none"}; ${denyPaths} deny paths, ${piiPatterns} PII patterns${facts(limits) ? `; ${facts(limits)}` : ""}`,
41
- `${label(s, candidateState)} candidates: ${candidateLine}`,
42
- `${label(s, migrationState)} layout: ${status.active ? `shards active${status.generation ? ` (generation ${status.generation.slice(0, 8)})` : ""}` : status.phase ? `shard migration ${status.phase}${interrupted ? ", not active" : ""}` : "single home"}; ${pendingCounts ? `pending ${pendingCounts}` : "no pending old-layout appends"}`,
43
- ...(status.deadLeasesRemoved?.length ? [` ${s.dim(`${status.deadLeasesRemoved.length} dead reader leases removed`)}`] : []),
44
- "", actions.length ? "Next actions: see Attention" : "Next actions: none",
45
- s.dim("Full report: amem status --json; health checks: amem doctor"),
46
- ];
47
- return lines.join("\n");
73
+ const limitFacts = Object.entries(limits).filter(([, value]) => value !== undefined && value !== null)
74
+ .map(([key, value]) => typeof value === "number" && key.endsWith("Bytes") ? `${wordedKey(key)} ${humanBytes(value)}`
75
+ : typeof value === "object" ? `${wordedKey(key)} ${Array.isArray(value) ? value.length : Object.keys(value as object).length} set` : `${wordedKey(key)} ${String(value)}`);
76
+ const pendingFacts = Object.entries(status.pending).filter(([key, value]) => !key.endsWith("Ids") && value !== 0 && value !== undefined && value !== null)
77
+ .map(([key, value]) => typeof value === "object" ? plural(Object.keys(value as object).length, wordedKey(key).replace(/^by /, "")) : key.endsWith("Bytes") && typeof value === "number" ? `${wordedKey(key)} ${humanBytes(value)}` : `${wordedKey(key)} ${String(value)}`)
78
+ .filter(fact => !/^0 /.test(fact));
79
+ const layout = status.active ? `shards active${status.generation ? `, generation ${status.generation.slice(0, 8)}` : ""}` : status.phase ? `shard migration ${status.phase}${interrupted ? ", not active" : ""}` : "single home";
80
+
81
+ const report = reportFrame(s, "status", STATE_WORD[overall], opts, status.home);
82
+ attention(report, findings);
83
+ report.section("Memory");
84
+ stateRows(report, [
85
+ { state: "ok", name: "policy", fact: `machine ${machine ?? "none (defaults)"}, repo ${repo ?? "none"}, ${plural(denyPaths, "deny path")}, ${plural(piiPatterns, "PII pattern")}${limitFacts.length ? `, ${limitFacts.join(", ")}` : ""}` },
86
+ { state: candidateState, name: "candidates", fact: candidateFact },
87
+ { state: migrationState, name: "layout", fact: `${layout}; ${pendingFacts.length ? `pending ${pendingFacts.join(", ")}` : "no pending old-layout appends"}` },
88
+ ], s);
89
+ if (opts.verbose && status.deadLeasesRemoved?.length) report.note(`${status.deadLeasesRemoved.length} dead reader leases removed during the last migration`);
90
+ return report.render(s.color).join("\n");
48
91
  }
@@ -3,7 +3,9 @@
3
3
  * Color is decoration only: every caller also prints a textual label, so plain output carries the same facts.
4
4
  * JSON output never passes through this module.
5
5
  */
6
- import { MARKERS, SECTION_MARKER, SGR_RESET, cellWidth, markerCell, paint, type MarkerName } from "@staix/cli-output";
6
+ import { MARKERS, SECTION_MARKER, SGR_RESET, cellWidth, markerCell, paint, Report, type MarkerName } from "@staix/cli-output";
7
+
8
+ import type { View } from "./store.ts";
7
9
 
8
10
  export interface Style {
9
11
  readonly color: boolean;
@@ -65,9 +67,104 @@ export function label(s: Style, state: "ok" | "attention" | "skipped" | "unavail
65
67
  return ` ${paint([{ role: MARKERS[marker].role, text }], s.color)}`;
66
68
  }
67
69
 
70
+ /** #590 C2: a past or future ISO time relative to `now` ("just now", "5 min ago", "3 h ago", "2 d ago", "in 4 d"); `--json` keeps the exact value. */
71
+ export function relativeTime(iso: string | null | undefined, now: number): string {
72
+ if (!iso) return "never";
73
+ const at = Date.parse(iso);
74
+ if (!Number.isFinite(at)) return "unknown time";
75
+ const delta = now - at, abs = Math.abs(delta), minute = 60_000, hour = 60 * minute, day = 24 * hour;
76
+ if (abs < minute) return "just now";
77
+ const amount = abs < hour ? `${Math.floor(abs / minute)} min` : abs < day ? `${Math.floor(abs / hour)} h` : `${Math.floor(abs / day)} d`;
78
+ return delta >= 0 ? `${amount} ago` : `in ${amount}`;
79
+ }
80
+
81
+ /** #590 C3: a byte count in binary units ("812 B", "5.7 KiB", "2.0 MiB"). */
82
+ export function humanBytes(bytes: number): string {
83
+ if (!Number.isFinite(bytes) || bytes < 1024) return `${Math.max(0, Math.round(bytes))} B`;
84
+ const units = ["KiB", "MiB", "GiB", "TiB"];
85
+ let value = bytes / 1024, unit = 0;
86
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
87
+ return `${value.toFixed(1)} ${units[unit]}`;
88
+ }
89
+
90
+ /** #590 C1: `identicalGroups` -> `identical groups`, `cap_mb` -> `cap mb`; human rows never print a raw key. */
91
+ export const wordedKey = (key: string): string => key.replace(/_/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
92
+
93
+ /** #590 C1: worded "label value" pairs without JSON; zero, empty and null values are left out, as in `facts`. */
94
+ export function wordedFacts(values: Record<string, unknown>): string {
95
+ return Object.entries(values).filter(([, value]) => value !== 0 && value !== null && value !== undefined && value !== false && value !== ""
96
+ && !(Array.isArray(value) && value.length === 0) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value as object).length === 0))
97
+ .map(([key, value]) => `${wordedKey(key)} ${typeof value === "object" && !Array.isArray(value) ? wordedFacts(value as Record<string, unknown>) : Array.isArray(value) ? value.join(", ") : value === true ? "yes" : String(value)}`).join(", ");
98
+ }
99
+
68
100
  /** "key value" pairs, leaving out zero, empty and null values; returns "" when nothing material is left. */
69
101
  export function facts(values: Record<string, unknown>): string {
70
102
  return Object.entries(values).filter(([, value]) => value !== 0 && value !== null && value !== undefined && value !== false && value !== ""
71
103
  && !(Array.isArray(value) && value.length === 0) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value as object).length === 0))
72
104
  .map(([key, value]) => `${key} ${typeof value === "object" ? Array.isArray(value) ? value.join(", ") : JSON.stringify(value) : String(value)}`).join(", ");
73
105
  }
106
+
107
+ export const CLI_MEMORY_RENDER = Symbol("cli-memory-render");
108
+ export interface HumanMemoryRow { id: string; kind: string; at: string; text: string; project?: string; tier?: string; peer?: string; scope?: string; flags?: readonly string[] }
109
+ export interface HumanMemoryRender { columns?: number; style?: Style; now?: number; actor?: "person" | "agent" }
110
+ type HumanRender = HumanMemoryRender;
111
+ function clipCells(value: string, limit: number): string {
112
+ const text = singleLine(value).replace(/\s+/g, " ").trim();
113
+ if (cellWidth(text) <= limit) return text;
114
+ let out = "";
115
+ for (const { segment } of new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text)) {
116
+ if (cellWidth(out + segment + "...") > limit) break;
117
+ out += segment;
118
+ }
119
+ return out.trimEnd() + "...";
120
+ }
121
+
122
+ /** Render only rows already selected and screened by the caller. */
123
+ export function memoryTableText(rows: readonly HumanMemoryRow[], title: string, render: HumanRender = {}, context?: string): string {
124
+ const width = Math.max(20, render.columns ?? 80), s = render.style ?? PLAIN, report = new Report(width, s.ascii, { sanitize: singleLine });
125
+ const tier = (row: HumanMemoryRow) => row.tier ? `${row.tier}${row.scope === "shared" ? "*" : ""}` : undefined;
126
+ const details = (row: HumanMemoryRow): string[] => [tier(row), row.peer, ...(row.flags ?? [])].filter((value): value is string => !!value);
127
+ report.header("amem", title); if (context) report.line(context); report.section("Entries", String(rows.length));
128
+ if (!rows.length) report.line(" No entries.");
129
+ else if (width < 65) report.table(["ID", "TEXT"], rows.flatMap(row => [[displayMemoryId(row.id, 12), clipCells(`${row.project ? `${row.project}: ` : ""}${row.text}`, Math.max(3, width - 18))], ...details(row).map(detail => ["", detail])]), 1, { widths: [12, Math.max(3, width - 18)], emptyCell: "blank" });
130
+ else if (rows.some(row => row.project)) {
131
+ const textWidth = Math.max(3, width - 54);
132
+ report.table(["PROJECT", "ID", "KIND", "WHEN", "TEXT"], rows.flatMap(row => [[clipCells(row.project ?? "", 16), displayMemoryId(row.id, 12), clipCells(row.kind, 8), clipCells(relativeTime(row.at, render.now ?? Date.now()), 8), clipCells(row.text, textWidth)], ...details(row).map(detail => ["", "", "", "", detail])]), 4, { widths: [16, 12, 8, 8, textWidth], emptyCell: "blank" });
133
+ }
134
+ else {
135
+ const textWidth = Math.max(3, width - 59);
136
+ report.table(["ID", "KIND", "TIER", "PEER", "WHEN", "TEXT"], rows.flatMap(row => [[displayMemoryId(row.id, 13), clipCells(row.kind, 10), clipCells(tier(row) ?? "-", 6), clipCells(row.peer ?? "-", 8), clipCells(relativeTime(row.at, render.now ?? Date.now()), 10), clipCells(row.text, textWidth)], ...(row.flags ?? []).map(flag => ["", "", "", "", "", flag])]), 5, { widths: [13, 10, 6, 8, 10, textWidth], emptyCell: "blank" });
137
+ }
138
+ if (rows.some(row => row.tier && row.scope === "shared")) report.note("* marks shared scope.");
139
+ if (rows.length) report.note("Full text: amem show <id> or --json.");
140
+ return report.render(s.color).join("\n");
141
+ }
142
+
143
+ function displayMemoryId(id: string, limit: number): string {
144
+ return /^(?:repo:)?[a-f0-9]{16,}$/.test(id) ? id.slice(0, limit) : clipCells(id, limit);
145
+ }
146
+
147
+ export function memoryRecordText(row: HumanMemoryRow, render: HumanRender = {}, fields: readonly (readonly [string, string])[] = []): string {
148
+ const s = render.style ?? PLAIN, report = new Report(render.columns ?? 80, s.ascii, { sanitize: text => text.replace(/[\p{Cf}\p{Zl}\p{Zp}]/gu, " ") });
149
+ report.header("amem", "Memory"); report.section("Entry");
150
+ report.kv([["ID", row.id], ["Kind", row.kind], ["When", relativeTime(row.at, render.now ?? Date.now())], ...fields]);
151
+ report.section("Text"); report.line(row.text);
152
+ return report.render(s.color).join("\n");
153
+ }
154
+
155
+ export function memoryScoresText(rows: readonly { id: string; details: Record<string, unknown> }[], render: HumanRender = {}): string {
156
+ if (!rows.length) return "";
157
+ const s = render.style ?? PLAIN, report = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
158
+ report.section("Scores");
159
+ report.kv(rows.map(row => [displayMemoryId(row.id, 16), Object.entries(row.details).map(([key, value]) => `${wordedKey(key)} ${value === null || value === undefined ? "-" : String(value)}`).join(", ")]));
160
+ return report.render(s.color).join("\n");
161
+ }
162
+
163
+ export function memoryDetailText(view: View, render: HumanRender = {}): string {
164
+ const s = render.style ?? PLAIN, report = new Report(render.columns ?? 80, s.ascii, { sanitize: text => text.replace(/[\p{Cf}\p{Zl}\p{Zp}]/gu, " ") });
165
+ const stale = view as View & { stale?: boolean; staleReason?: string };
166
+ report.header("amem", "Memory"); report.section("Entry");
167
+ report.kv([["ID", view.id], ["Kind", view.kind], ["Tier", view.tier], ["When", relativeTime(view.at, render.now ?? Date.now())], ["Peer", view.peer], ["Scope", view.scope], ["Project", view.project], ["Machine", view.machine], ...(render.actor ? [["Actor", render.actor] as [string, string]] : []), ...(stale.stale ? [["Stale", stale.staleReason?.replace(/_/g, " ") ?? "yes"] as [string, string]] : []), ...(view.task ? [["Task", view.task] as [string, string]] : []), ...(view.expiresAt ? [["Expires", relativeTime(view.expiresAt, render.now ?? Date.now())] as [string, string]] : []), ...(view.promotedFrom ? [["Promoted from", view.promotedFrom] as [string, string]] : []), ...(view.supersededBy ? [["Superseded by", view.supersededBy] as [string, string]] : []), ...(view.about.length ? [["About", view.about.join(", ")] as [string, string]] : [])]);
168
+ report.section("Text"); if (view.title) report.line(view.title); report.line(view.text);
169
+ return report.render(s.color).join("\n");
170
+ }