Skip to content

The agent that grows with you

fix(sessions): surface open sessions skipped by prune

fangliquanflq29dfbf2d6a5c
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index 2cb35793d51..714201b6249 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -942,6 +942,17 @@ def cmd_sessions(args, sessions_parser=None):
filters["archived"] = False
candidates = db.list_prune_candidates(**filters)
+ skipped_open = (
+ db.count_open_prune_matches(**filters) if action == "prune" else 0
+ )
+ if skipped_open:
+ suffix = "" if skipped_open == 1 else "s"
+ print(
+ f"Note: {skipped_open} open session{suffix} also match these "
+ "filters but will be skipped because prune only deletes ended "
+ "sessions. Use `hermes sessions delete <id>` to remove one "
+ "explicitly."
+ )
verb = "Delete" if action == "prune" else "Archive"
if not candidates:
print(f"No sessions match ({describe_filters(filters)}).")
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 537f541843a..c9863c49365 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -11852,12 +11852,14 @@ def _prune_sessions(body: SessionPrune):
max_tool_calls=body.max_tool_calls,
archived=None if body.include_archived else False,
)
+ skipped_open = db.count_open_prune_matches(**filters)
if body.dry_run:
rows = db.list_prune_candidates(**filters)
return {
"ok": True,
"removed": 0,
"matched": len(rows),
+ "skipped_open": skipped_open,
# Rows are ordered by last activity, not creation time.
"oldest_last_active": rows[0]["last_active"] if rows else None,
"newest_last_active": rows[-1]["last_active"] if rows else None,
@@ -11885,7 +11887,7 @@ def _prune_sessions(body: SessionPrune):
sessions_dir=sessions_dir if sessions_dir.exists() else None,
**filters,
)
- return {"ok": True, "removed": removed}
+ return {"ok": True, "removed": removed, "skipped_open": skipped_open}
finally:
db.close()
diff --git a/hermes_state.py b/hermes_state.py
index 68011285919..188edd33a41 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -11698,6 +11698,38 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
return [dict(row) for row in cursor.fetchall()]
+ def count_open_prune_matches(
+ self,
+ older_than_days: Optional[float] = None,
+ source: str = None,
+ **filters,
+ ) -> int:
+ """Count open sessions excluded from a matching bulk prune.
+
+ This applies every normal prune filter, but inverts only the
+ ``ended_at`` safety guard. It is visibility-only: callers can explain
+ why an otherwise matching session was skipped without making live
+ sessions eligible for destructive pruning.
+ """
+ if (
+ filters.get("last_active_before") is None
+ and filters.get("started_before") is None
+ and older_than_days is not None
+ ):
+ filters["last_active_before"] = time.time() - (
+ older_than_days * 86400
+ )
+ where, params = self._prune_filter_where(source=source, **filters)
+ ended_guard = "s.ended_at IS NOT NULL"
+ if not where.startswith(ended_guard):
+ raise RuntimeError("prune filter lost its ended-session safety guard")
+ open_where = f"s.ended_at IS NULL{where[len(ended_guard):]}"
+ with self._lock:
+ cursor = self._conn.execute(
+ f"SELECT COUNT(*) FROM sessions s WHERE {open_where}", params
+ )
+ return int(cursor.fetchone()[0])
+
def archive_sessions(
self,
older_than_days: Optional[float] = None,
diff --git a/tests/hermes_cli/test_dashboard_admin_endpoints.py b/tests/hermes_cli/test_dashboard_admin_endpoints.py
index bee6d444f1a..eea2b3c1504 100644
--- a/tests/hermes_cli/test_dashboard_admin_endpoints.py
+++ b/tests/hermes_cli/test_dashboard_admin_endpoints.py
@@ -545,10 +545,36 @@ class TestSessionManagementEndpoints:
assert r.status_code == 200
body = r.json()
assert body["matched"] >= 1
+ assert "skipped_open" in body
assert "oldest_started_at" in body and "newest_started_at" in body
assert "oldest_last_active" in body and "newest_last_active" in body
assert all("last_active" in session for session in body["sessions"])
+ def test_prune_reports_open_sessions_excluded_by_safety_guard(self):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ db.create_session(session_id="sess-old-open", source="skip-test")
+ db._conn.execute(
+ "UPDATE sessions SET started_at = ? WHERE id = ?",
+ (1.0, "sess-old-open"),
+ )
+ db._conn.commit()
+ db.close()
+
+ r = self.client.post(
+ "/api/sessions/prune",
+ json={"older_than_days": 1, "source": "skip-test"},
+ )
+ assert r.status_code == 200
+ body = r.json()
+ assert body["removed"] == 0
+ assert body["skipped_open"] == 1
+
+ db = SessionDB()
+ assert db.get_session("sess-old-open") is not None
+ db.close()
+
class TestSkillsHubSearchEndpoint:
diff --git a/tests/hermes_cli/test_sessions_delete.py b/tests/hermes_cli/test_sessions_delete.py
index 968bcf4be4f..7650a9bbeff 100644
--- a/tests/hermes_cli/test_sessions_delete.py
+++ b/tests/hermes_cli/test_sessions_delete.py
@@ -39,7 +39,7 @@ def test_sessions_delete_accepts_unique_id_prefix(monkeypatch, capsys):
assert "Deleted session '20260315_092437_c9a6ff'." in output
-def _run_prune(monkeypatch, capsys, argv_tail, candidates=None):
+def _run_prune(monkeypatch, capsys, argv_tail, candidates=None, skipped_open=0):
"""Run `hermes sessions prune <argv_tail>` against a FakeDB, capturing
the filter kwargs passed to list_prune_candidates. Auto-confirms."""
import hermes_cli.main as main_mod
@@ -74,6 +74,10 @@ def _run_prune(monkeypatch, capsys, argv_tail, candidates=None):
seen.update(kwargs)
return rows
+ def count_open_prune_matches(self, **kwargs):
+ assert kwargs == seen
+ return skipped_open
+
def prune_sessions(self, **kwargs):
return len(rows)
@@ -108,3 +112,18 @@ def test_sessions_prune_preview_shows_oldest_newest(monkeypatch, capsys):
assert "2 session(s) match" in out
assert f"oldest activity {format_epoch(1_600_000_050.0)}" in out
assert f"newest activity {format_epoch(1_700_000_050.0)}" in out
+
+
+def test_sessions_prune_surfaces_matching_open_sessions(monkeypatch, capsys):
+ _filters, out = _run_prune(
+ monkeypatch,
+ capsys,
+ ["--source", "cron"],
+ candidates=[],
+ skipped_open=2,
+ )
+
+ assert "2 open sessions also match these filters" in out
+ assert "prune only deletes ended sessions" in out
+ assert "hermes sessions delete <id>" in out
+ assert "No sessions match" in out
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index f7aca6465dc..6f03a945b6c 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -1133,6 +1133,26 @@ class TestPruneSessions:
pruned = db.prune_sessions(older_than_days=90)
assert pruned == 0
assert db.get_session("active") is not None
+ assert db.count_open_prune_matches(older_than_days=90) == 1
+
+ def test_open_prune_match_count_applies_other_filters(self, db):
+ db.create_session(session_id="matching-open", source="cron")
+ db.create_session(session_id="other-source", source="cli")
+ db.create_session(session_id="ended", source="cron")
+ db.end_session("ended", "completed")
+ old = time.time() - 200 * 86400
+ db._conn.execute(
+ "UPDATE sessions SET started_at = ? WHERE id IN (?, ?, ?)",
+ (old, "matching-open", "other-source", "ended"),
+ )
+ db._conn.commit()
+
+ assert db.count_open_prune_matches(
+ older_than_days=90, source="cron", archived=False
+ ) == 1
+ assert {row["id"] for row in db.list_prune_candidates(
+ older_than_days=90, source="cron", archived=False
+ )} == {"ended"}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index bd72ff9bf93..55166952158 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -452,11 +452,18 @@ export const api = {
source?: string,
profile = getManagementProfile(),
) =>
- fetchJSON<{ ok: boolean; removed: number }>("/api/sessions/prune", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ older_than_days, source, profile: profile || undefined }),
- }),
+ fetchJSON<{ ok: boolean; removed: number; skipped_open: number }>(
+ "/api/sessions/prune",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ older_than_days,
+ source,
+ profile: profile || undefined,
+ }),
+ },
+ ),
listFiles: (path?: string) => {
const query = path ? `?path=${encodeURIComponent(path)}` : "";
return fetchJSON<ManagedFilesResponse>(`/api/files${query}`);
diff --git a/web/src/lib/session-prune.test.ts b/web/src/lib/session-prune.test.ts
new file mode 100644
index 00000000000..cab7b48e843
--- /dev/null
+++ b/web/src/lib/session-prune.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { formatSessionPruneResult } from "./session-prune";
+
+describe("formatSessionPruneResult", () => {
+ it("reports open sessions skipped by the prune safety guard", () => {
+ expect(formatSessionPruneResult({ removed: 0, skipped_open: 2 })).toBe(
+ "Pruned 0 sessions. Skipped 2 open sessions; prune only removes ended sessions.",
+ );
+ });
+
+ it("keeps the existing success message when nothing was skipped", () => {
+ expect(formatSessionPruneResult({ removed: 1, skipped_open: 0 })).toBe(
+ "Pruned 1 session",
+ );
+ });
+});
\ No newline at end of file
diff --git a/web/src/lib/session-prune.ts b/web/src/lib/session-prune.ts
new file mode 100644
index 00000000000..0031e43f743
--- /dev/null
+++ b/web/src/lib/session-prune.ts
@@ -0,0 +1,11 @@
+interface SessionPruneResult {
+ removed: number;
+ skipped_open: number;
+}
+
+export function formatSessionPruneResult(result: SessionPruneResult): string {
+ const removed = `Pruned ${result.removed} session${result.removed === 1 ? "" : "s"}`;
+ if (!result.skipped_open) return removed;
+
+ return `${removed}. Skipped ${result.skipped_open} open session${result.skipped_open === 1 ? "" : "s"}; prune only removes ended sessions.`;
+}
\ No newline at end of file
diff --git a/web/src/pages/SessionsPage.tsx b/web/src/pages/SessionsPage.tsx
index 8a526f7b327..09140f9e411 100644
--- a/web/src/pages/SessionsPage.tsx
+++ b/web/src/pages/SessionsPage.tsx
@@ -33,6 +33,7 @@ import {
Archive,
} from "lucide-react";
import { api } from "@/lib/api";
+import { formatSessionPruneResult } from "@/lib/session-prune";
import { shouldRefreshSessions } from "@/lib/session-refresh";
import {
importSummary,
@@ -1499,10 +1500,7 @@ export default function SessionsPage() {
setPruning(true);
try {
const resp = await api.pruneSessions(days);
- showToast(
- `Pruned ${resp.removed} session${resp.removed === 1 ? "" : "s"}`,
- "success",
- );
+ showToast(formatSessionPruneResult(resp), "success");
setPruneOpen(false);
loadSessions(0);
setPage(0);