Skip to content

Commit a89e6e0

Browse files
fix(cli): summarize cleanup dry-run by label (#93565)
Merged via squash. Prepared head SHA: b0dd1d0 Co-authored-by: AgentArcLab <[email protected]> Co-authored-by: vincentkoc <[email protected]> Reviewed-by: @vincentkoc
1 parent 08ff253 commit a89e6e0

3 files changed

Lines changed: 149 additions & 1 deletion

File tree

‎docs/cli/sessions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ openclaw sessions cleanup --json
122122
- Cleanup also prunes unreferenced primary transcripts, compaction checkpoints, and trajectory sidecars older than `session.maintenance.pruneAfter`; files still referenced by `sessions.json` are preserved.
123123

124124
- `--dry-run`: preview how many entries would be pruned/capped without writing.
125-
- In text mode, dry-run prints a per-session action table (`Action`, `Key`, `Age`, `Model`, `Flags`) so you can see what would be kept vs removed.
125+
- In text mode, dry-run prints a per-session action table (`Action`, `Key`, `Age`, `Model`, `Flags`) plus a summary grouped by session label so you can see what would be kept vs removed.
126126
- `--enforce`: apply maintenance even when `session.maintenance.mode` is `warn`.
127127
- `--fix-missing`: remove entries whose transcript files are missing or header-only/empty, even if they would not normally age/count out yet.
128128
- `--fix-dm-scope`: when `session.dmScope` is `main`, retire stale peer-keyed direct-DM rows left behind by earlier `per-peer`, `per-channel-peer`, or `per-account-channel-peer` routing. Use `--dry-run` first; applying the cleanup removes those rows from `sessions.json` and preserves their transcripts as deleted archives.

‎src/commands/sessions-cleanup.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,104 @@ describe("sessionsCleanupCommand", () => {
503503
expect(stalePruneLines.length).toBeGreaterThan(0);
504504
});
505505

506+
it("renders a dry-run summary grouped by session label", async () => {
507+
mocks.enforceSessionDiskBudget.mockResolvedValue(null);
508+
mocks.runSessionsCleanup.mockResolvedValue({
509+
mode: "warn",
510+
previewResults: [
511+
{
512+
summary: {
513+
agentId: "main",
514+
storePath: "/resolved/sessions.json",
515+
mode: "warn",
516+
dryRun: true,
517+
beforeCount: 7,
518+
afterCount: 3,
519+
missing: 0,
520+
dmScopeRetired: 0,
521+
pruned: 3,
522+
capped: 1,
523+
unreferencedArtifacts: {
524+
scannedFiles: 0,
525+
removedFiles: 0,
526+
freedBytes: 0,
527+
olderThanMs: 604800000,
528+
},
529+
diskBudget: null,
530+
wouldMutate: true,
531+
},
532+
beforeStore: {
533+
cronKept: {
534+
sessionId: "cron-kept",
535+
updatedAt: 4,
536+
model: "test:opus",
537+
label: "Cron: daily-commit",
538+
},
539+
cronPruned: {
540+
sessionId: "cron-pruned",
541+
updatedAt: 3,
542+
model: "test:opus",
543+
label: "Cron: daily-commit",
544+
},
545+
directKept: {
546+
sessionId: "direct-kept",
547+
updatedAt: 2,
548+
model: "test:opus",
549+
},
550+
directCapped: {
551+
sessionId: "direct-capped",
552+
updatedAt: 1,
553+
model: "test:opus",
554+
},
555+
literalUnlabeled: {
556+
sessionId: "literal-unlabeled",
557+
updatedAt: 1,
558+
model: "test:opus",
559+
label: "Unlabeled",
560+
},
561+
unsafePruned: {
562+
sessionId: "unsafe-pruned",
563+
updatedAt: 1,
564+
model: "test:opus",
565+
label: "\u001b[31mAlert\nInjected",
566+
},
567+
malformedLabelPruned: {
568+
sessionId: "malformed-label-pruned",
569+
updatedAt: 1,
570+
model: "test:opus",
571+
label: {} as unknown as string,
572+
},
573+
},
574+
missingKeys: new Set<string>(),
575+
staleKeys: new Set(["cronPruned", "unsafePruned", "malformedLabelPruned"]),
576+
cappedKeys: new Set(["directCapped"]),
577+
budgetEvictedKeys: new Set<string>(),
578+
dmScopeRetiredKeys: new Set<string>(),
579+
},
580+
],
581+
appliedSummaries: [],
582+
});
583+
584+
const { runtime, logs } = makeRuntime();
585+
await sessionsCleanupCommand(
586+
{
587+
dryRun: true,
588+
},
589+
runtime,
590+
);
591+
592+
expectLogsToInclude(logs, "Summary by Label:");
593+
const summaryLogs = logs.slice(logs.indexOf("Summary by Label:") + 1);
594+
expectLogsToInclude(logs, "Cron: daily-commit 1 kept, 1 pruned");
595+
expect(summaryLogs.find((line) => line.includes("(unlabeled)"))).toContain("1 kept, 2 pruned");
596+
expect(summaryLogs.find((line) => line.includes("Unlabeled"))).toContain("1 kept, 0 pruned");
597+
expect(summaryLogs.find((line) => line.includes("Alert\\nInjected"))).toContain(
598+
"0 kept, 1 pruned",
599+
);
600+
expect(logs.join("\n")).not.toContain("\u001b[31m");
601+
expectLogsToInclude(logs, "Total: 3 kept, 4 pruned");
602+
});
603+
506604
it("returns grouped JSON for --all-agents dry-runs", async () => {
507605
mocks.resolveSessionStoreTargets.mockReturnValue([
508606
{ agentId: "main", storePath: "/resolved/main-sessions.json" },

‎src/commands/sessions-cleanup.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* It can delegate cleanup to a live gateway or run local store maintenance,
55
* with dry-run tables that explain every planned pruning action.
66
*/
7+
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
78
import { isRich, theme } from "../../packages/terminal-core/src/theme.js";
89
import { getRuntimeConfig } from "../config/config.js";
910
import {
@@ -35,6 +36,13 @@ const ACTION_PAD = 16;
3536

3637
type SessionCleanupActionRow = ReturnType<typeof toSessionDisplayRows>[number] & {
3738
action: ReturnType<typeof resolveSessionCleanupAction>;
39+
label?: string;
40+
};
41+
42+
type SessionCleanupLabelSummary = {
43+
label: string;
44+
kept: number;
45+
pruned: number;
3846
};
3947

4048
function formatCleanupActionCell(
@@ -75,6 +83,7 @@ function buildActionRows(params: {
7583
// action labels as the cleanup engine without mutating the preview store.
7684
return toSessionDisplayRows(params.beforeStore).map((row) =>
7785
Object.assign({}, row, {
86+
label: params.beforeStore[row.key]?.label,
7887
action: resolveSessionCleanupAction({
7988
key: row.key,
8089
missingKeys: params.missingKeys,
@@ -87,6 +96,46 @@ function buildActionRows(params: {
8796
);
8897
}
8998

99+
function buildLabelSummaries(actionRows: SessionCleanupActionRow[]): SessionCleanupLabelSummary[] {
100+
const summaryByLabel = new Map<string, SessionCleanupLabelSummary>();
101+
for (const actionRow of actionRows) {
102+
const rawLabel = typeof actionRow.label === "string" ? actionRow.label.trim() : "";
103+
const label = sanitizeTerminalText(rawLabel) || "(unlabeled)";
104+
let summary = summaryByLabel.get(label);
105+
if (!summary) {
106+
summary = { label, kept: 0, pruned: 0 };
107+
summaryByLabel.set(label, summary);
108+
}
109+
if (actionRow.action === "keep") {
110+
summary.kept += 1;
111+
} else {
112+
summary.pruned += 1;
113+
}
114+
}
115+
return [...summaryByLabel.values()].toSorted((a, b) => a.label.localeCompare(b.label));
116+
}
117+
118+
function renderLabelSummaries(params: {
119+
actionRows: SessionCleanupActionRow[];
120+
runtime: RuntimeEnv;
121+
}) {
122+
const summaries = buildLabelSummaries(params.actionRows);
123+
if (summaries.length === 0) {
124+
return;
125+
}
126+
const labelPad = Math.max(...summaries.map((summary) => summary.label.length));
127+
const totalKept = summaries.reduce((total, summary) => total + summary.kept, 0);
128+
const totalPruned = summaries.reduce((total, summary) => total + summary.pruned, 0);
129+
params.runtime.log("");
130+
params.runtime.log("Summary by Label:");
131+
for (const summary of summaries) {
132+
params.runtime.log(
133+
`${summary.label.padEnd(labelPad)} ${summary.kept} kept, ${summary.pruned} pruned`,
134+
);
135+
}
136+
params.runtime.log(`Total: ${totalKept} kept, ${totalPruned} pruned`);
137+
}
138+
90139
function renderStoreDryRunPlan(params: {
91140
cfg: OpenClawConfig;
92141
summary: SessionCleanupSummary;
@@ -141,6 +190,7 @@ function renderStoreDryRunPlan(params: {
141190
].join(" ");
142191
params.runtime.log(line.trimEnd());
143192
}
193+
renderLabelSummaries({ actionRows: params.actionRows, runtime: params.runtime });
144194
}
145195

146196
function renderAppliedSummaries(params: {

0 commit comments

Comments
 (0)