Skip to content

The agent that grows with you

fix(sessions): make prompt repair evidence-safe

JoaoMarcos447b3dd14768b2
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index a10305f970f..264a9cf41fd 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -974,6 +974,181 @@ def _cmd_repair_routing(db, args):
print(f"\nRepaired {repaired} of {len(adoptable)} session(s).")
+_SKILL_TOOL_NAMES = frozenset({"skills_list", "skill_view", "skill_manage"})
+_SKILLS_INDEX_MARKER = "<available_skills>"
+_SKILLS_GUIDANCE_MARKER = "## Skill Safety"
+_HYGIENE_PIN_TOOLS = frozenset({"memory"})
+
+
+def _repair_prompts_pin_names(row) -> list[str] | None:
+ """Resolve legacy name-list and current versioned tools[] pins to tool names.
+
+ Any malformed or unknown shape is unverifiable and therefore never eligible for automatic
+ repair. Current pins store full tool definitions in a versioned object; older rows may contain
+ a JSON list of names directly.
+ """
+ try:
+ pin = json.loads(row.get("tool_names") or "null")
+ except (TypeError, ValueError):
+ return None
+ tools = pin.get("tools") if isinstance(pin, dict) else pin
+ if not isinstance(tools, list):
+ return None
+ names: list[str] = []
+ for item in tools:
+ if isinstance(item, str):
+ name = item
+ elif isinstance(item, dict):
+ function = item.get("function")
+ name = function.get("name") if isinstance(function, dict) else None
+ else:
+ return None
+ if not isinstance(name, str) or not name:
+ return None
+ names.append(name)
+ return names
+
+
+def _repair_prompts_missing_skills_markers(row) -> bool:
+ prompt = (row.get("system_prompt") or "").strip()
+ return bool(
+ prompt
+ and _SKILLS_INDEX_MARKER not in prompt
+ and _SKILLS_GUIDANCE_MARKER not in prompt
+ )
+
+
+def _repair_prompts_degraded_reason(row) -> str:
+ """Why the stored prompt is provably a reduced-toolset build; '' without sufficient evidence."""
+ if not _repair_prompts_missing_skills_markers(row):
+ return ""
+ pin = _repair_prompts_pin_names(row)
+ if pin is None:
+ return ""
+ names = set(pin)
+ if any(name in names for name in _SKILL_TOOL_NAMES):
+ return "skills index missing while the tools[] pin carries skill tools"
+ if names == _HYGIENE_PIN_TOOLS:
+ return "skills index missing and the tools[] pin is the reduced memory-only set"
+ return ""
+
+
+def _cmd_repair_prompts(db, args):
+ """Report (or clear) stored system prompts degraded to a reduced-toolset build (#122822).
+
+ Automatic repair requires positive tools[] evidence. Rows with missing/malformed pins are
+ reported as unverifiable and never changed by a scan. An explicit session_id remains the
+ operator escape hatch and clears that row regardless of detector evidence.
+ """
+ target = getattr(args, "session_id", None)
+ if target:
+ session_id = db.resolve_session_id(target)
+ if not session_id:
+ print(f"No session matches {target!r}.")
+ return 1
+ rows = [db.get_session(session_id)]
+ else:
+ rows = []
+ offset = 0
+ while True:
+ batch = db.list_sessions_rich(
+ limit=200, offset=offset, include_children=True,
+ include_archived=True, include_hidden=True,
+ )
+ if not batch:
+ break
+ rows.extend(db.get_session(s["id"]) for s in batch)
+ offset += len(batch)
+
+ findings = []
+ unverifiable = []
+ for row in rows:
+ if not row:
+ continue
+ pin = _repair_prompts_pin_names(row)
+ if target:
+ prompt_chars = len(row.get("system_prompt") or "")
+ clear_pin = set(pin or ()) == _HYGIENE_PIN_TOOLS
+ if prompt_chars or clear_pin:
+ findings.append({
+ "id": row["id"],
+ "reason": "targeted clear",
+ "prompt_chars": prompt_chars,
+ "clear_pin": clear_pin,
+ })
+ continue
+
+ reason = _repair_prompts_degraded_reason(row)
+ if reason:
+ findings.append({
+ "id": row["id"],
+ "reason": reason,
+ "prompt_chars": len(row["system_prompt"] or ""),
+ "clear_pin": set(pin or ()) == _HYGIENE_PIN_TOOLS,
+ })
+ elif _repair_prompts_missing_skills_markers(row) and pin is None:
+ unverifiable.append({
+ "id": row["id"],
+ "reason": "skills markers missing but the tools[] pin is unavailable or unreadable",
+ "prompt_chars": len(row["system_prompt"] or ""),
+ })
+
+ apply = bool(getattr(args, "apply", False))
+ as_json = bool(getattr(args, "json", False))
+
+ def _payload(cleared):
+ return {
+ "findings": findings,
+ "unverifiable": unverifiable,
+ "apply": apply,
+ "cleared": cleared,
+ }
+
+ if not findings:
+ if as_json:
+ print(json.dumps(_payload([]), indent=2))
+ else:
+ print("No degraded stored system prompts found.")
+ if unverifiable:
+ print(f"{len(unverifiable)} row(s) lacked enough tools[] evidence and were left unchanged.")
+ return 0
+
+ if not as_json:
+ for finding in findings:
+ suffix = " (tools[] pin cleared too)" if finding["clear_pin"] else ""
+ print(f" {finding['id']} ({finding['prompt_chars']} chars) - {finding['reason']}{suffix}")
+ if unverifiable:
+ print(f"\nSkipped {len(unverifiable)} unverifiable row(s) with no readable tools[] pin.")
+
+ if not apply:
+ if as_json:
+ print(json.dumps(_payload([]), indent=2))
+ else:
+ print(f"\n{len(findings)} stored prompt(s) can be repaired. Re-run with --apply to clear them; "
+ "the next turn rebuilds a healthy prompt (one prefix-cache break per session).")
+ return 0
+
+ # JSON mode is the non-interactive automation surface; --apply is the explicit mutation opt-in.
+ if not as_json and not _confirm_prompt(f"Clear {len(findings)} stored prompt(s)? [y/N] "):
+ print("Aborted - nothing was changed.")
+ return 0
+
+ cleared = []
+ for finding in findings:
+ db.update_system_prompt(finding["id"], None)
+ if finding["clear_pin"]:
+ db.update_session_tool_names(finding["id"], None)
+ cleared.append(finding["id"])
+
+ if as_json:
+ print(json.dumps(_payload(cleared), indent=2))
+ else:
+ print(f"\nCleared {len(cleared)} stored prompt(s); the next turn for each rebuilds and persists "
+ "a healthy prompt.")
+ print("One 'Stored system prompt ... is null' warning per repaired session is expected on that rebuild.")
+ return 0
+
+
def _cmd_stats(db, args):
print(f"Total sessions: {db.session_count()}\nTotal messages: {db.message_count()}")
for src in ("cli", "telegram", "discord", "whatsapp", "slack"):
@@ -1007,7 +1182,7 @@ _DB_HANDLERS = {
"archive": partial(_cmd_prune_or_archive, action="archive"), "unpin": partial(_cmd_pin, pinning=False),
"retitle-skills": _cmd_retitle_skills, "browse": _cmd_browse, "optimize": _cmd_optimize,
"clean-markers": _cmd_clean_markers, "optimize-storage": _cmd_optimize_storage,
- "repair-routing": _cmd_repair_routing, "stats": _cmd_stats,
+ "repair-routing": _cmd_repair_routing, "repair-prompts": _cmd_repair_prompts, "stats": _cmd_stats,
}
diff --git a/hermes_cli/subcommands/sessions.py b/hermes_cli/subcommands/sessions.py
index d56bf4a4183..d17335bb30a 100644
--- a/hermes_cli/subcommands/sessions.py
+++ b/hermes_cli/subcommands/sessions.py
@@ -224,6 +224,20 @@ def build_sessions_parser(subparsers, *, cmd_sessions: Callable) -> None:
"switched on), 'move' them to the default store (a default chat that leaked in), or "
"'report' (default) — the rows themselves cannot tell the two cases apart")
+
+ sessions_repair_prompts = sessions_subparsers.add_parser(
+ "repair-prompts", help="Report or clear stored system prompts degraded to a reduced-toolset build",
+ description="Repair session rows degraded by the pre-#122822 gateway hygiene/compress bug. "
+ "Automatic repair requires positive tools[] evidence; rows without a readable pin are "
+ "reported as unverifiable and never changed by a scan. Clearing a prompt makes the next "
+ "turn rebuild and persist healthy bytes. Reports without touching anything unless --apply "
+ "is given; a session_id explicitly targets one row regardless of detector evidence.")
+ _flag(sessions_repair_prompts, "--apply", help="Clear the verified prompts (default: report only)")
+ _flag(sessions_repair_prompts, "--json",
+ help="Machine-readable output; with --apply, apply without an interactive confirmation")
+ sessions_repair_prompts.add_argument("session_id", nargs="?", default=None,
+ help="Session id (or unique prefix) to clear explicitly, skipping detector evidence")
+
sessions_recover = sessions_subparsers.add_parser(
"recover", help="Rebuild canonical session data into a separate clean database",
description="Offline, non-destructive recovery for a damaged state.db. The "
diff --git a/tests/hermes_cli/test_sessions_repair_prompts.py b/tests/hermes_cli/test_sessions_repair_prompts.py
new file mode 100644
index 00000000000..945ba19e37f
--- /dev/null
+++ b/tests/hermes_cli/test_sessions_repair_prompts.py
@@ -0,0 +1,155 @@
+"""Behavior contracts for hermes sessions repair-prompts (#122822)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import sessions_cmd
+from hermes_cli.sessions_cmd import _cmd_repair_prompts, _repair_prompts_pin_names
+from hermes_state import SessionDB
+
+HEALTHY = (
+ "You are Hermes.\n"
+ "<available_skills>\n dogfood: exploratory QA of web apps\n</available_skills>\n"
+ "## Skill Safety Rule\nReload [SKILL_PRUNED] placeholders with skill_view.\n"
+)
+DEGRADED = "You are Hermes.\n(reduced maintenance build without the skills index)\n"
+
+
+def _tool(name: str) -> dict:
+ return {
+ "type": "function",
+ "function": {
+ "name": name,
+ "description": f"{name} test tool",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+
+
+def _pin(*names: str) -> dict:
+ return {"version": "test-sha", "tools": [_tool(name) for name in names]}
+
+
+def db(tmp_path):
+ session_db = SessionDB(db_path=tmp_path / "state.db")
+ yield session_db
+ session_db.close()
+
+
+def _args(session_id=None, apply=False, json_out=False):
+ return SimpleNamespace(session_id=session_id, apply=apply, json=json_out)
+
+
+def _accept_confirmations(monkeypatch):
+ asked = []
+ monkeypatch.setattr(sessions_cmd, "_confirm_prompt", lambda prompt: asked.append(prompt) or True)
+ return asked
+
+
+def test_pin_reader_accepts_current_versioned_and_legacy_shapes():
+ current = {"tool_names": json.dumps(_pin("memory", "skills_list"))}
+ legacy = {"tool_names": json.dumps(["memory", "skills_list"])}
+ malformed = {"tool_names": json.dumps({"version": "x", "tools": [{"bad": True}]})}
+
+ assert _repair_prompts_pin_names(current) == ["memory", "skills_list"]
+ assert _repair_prompts_pin_names(legacy) == ["memory", "skills_list"]
+ assert _repair_prompts_pin_names(malformed) is None
+
+
+def test_degraded_row_reported_and_cleared_only_with_apply(db, monkeypatch, capsys):
+ degraded = db.create_session("degraded-1", "telegram", system_prompt=DEGRADED)
+ db.update_session_tool_names(degraded, _pin("skills_list", "skill_view", "skill_manage"))
+ healthy = db.create_session("healthy-1", "telegram", system_prompt=HEALTHY)
+
+ assert _cmd_repair_prompts(db, _args()) == 0
+ out = capsys.readouterr().out
+ assert "degraded-1" in out
+ assert "healthy-1" not in out
+ assert db.get_session(degraded)["system_prompt"] == DEGRADED
+
+ asked = _accept_confirmations(monkeypatch)
+ assert _cmd_repair_prompts(db, _args(apply=True)) == 0
+ assert asked
+ assert not (db.get_session(degraded)["system_prompt"] or "")
+ assert db.get_session(healthy)["system_prompt"] == HEALTHY
+
+
+def test_unpinned_row_is_unverifiable_and_apply_json_clears_only_verified(db, monkeypatch, capsys):
+ unverifiable = db.create_session("old-unpinned", "telegram", system_prompt=DEGRADED)
+ verified = db.create_session("verified", "telegram", system_prompt=DEGRADED)
+ db.update_session_tool_names(verified, _pin("skills_list"))
+
+ monkeypatch.setattr(
+ sessions_cmd, "_confirm_prompt",
+ lambda _prompt: pytest.fail("--apply --json must not prompt"),
+ )
+ assert _cmd_repair_prompts(db, _args(apply=True, json_out=True)) == 0
+ payload = json.loads(capsys.readouterr().out)
+
+ assert payload["apply"] is True
+ assert payload["cleared"] == ["verified"]
+ assert [row["id"] for row in payload["unverifiable"]] == ["old-unpinned"]
+ assert db.get_session(unverifiable)["system_prompt"] == DEGRADED
+ assert not (db.get_session(verified)["system_prompt"] or "")
+
+
+def test_reduced_surface_left_alone_memory_only_pin_cleared(db, monkeypatch, capsys):
+ reduced = db.create_session("reduced-1", "telegram", system_prompt=DEGRADED)
+ db.update_session_tool_names(reduced, _pin("todo", "web_search"))
+ empty = db.create_session("empty-pin", "telegram", system_prompt=DEGRADED)
+ db.update_session_tool_names(empty, _pin())
+ memory = db.create_session("memory-only-1", "telegram", system_prompt=DEGRADED)
+ db.update_session_tool_names(memory, _pin("memory"))
+
+ assert _cmd_repair_prompts(db, _args(json_out=True)) == 0
+ payload = json.loads(capsys.readouterr().out)
+ flagged = {finding["id"]: finding for finding in payload["findings"]}
+ assert set(flagged) == {"memory-only-1"}
+ assert flagged["memory-only-1"]["clear_pin"] is True
+
+ _accept_confirmations(monkeypatch)
+ assert _cmd_repair_prompts(db, _args(apply=True)) == 0
+
+ assert db.get_session(reduced)["system_prompt"] == DEGRADED
+ assert db.get_session(empty)["system_prompt"] == DEGRADED
+ memory_row = db.get_session(memory)
+ assert not (memory_row["system_prompt"] or "")
+ assert not (memory_row["tool_names"] or "")
+
+
+def test_positional_target_clears_memory_pin_when_prompt_is_already_null(db, monkeypatch):
+ target = db.create_session("target-null", "telegram")
+ db.update_session_tool_names(target, _pin("memory"))
+ assert not (db.get_session(target)["system_prompt"] or "")
+
+ _accept_confirmations(monkeypatch)
+ assert _cmd_repair_prompts(db, _args(session_id="target-null", apply=True)) == 0
+
+ row = db.get_session(target)
+ assert not (row["system_prompt"] or "")
+ assert not (row["tool_names"] or "")
+
+
+def test_positional_target_clears_exactly_that_row_and_memory_pin(db, monkeypatch, capsys):
+ target = db.create_session("target-1", "telegram", system_prompt=HEALTHY)
+ db.update_session_tool_names(target, _pin("memory"))
+ sibling = db.create_session("sibling-1", "telegram", system_prompt=HEALTHY)
+ db.update_session_tool_names(sibling, _pin("skills_list"))
+
+ assert _cmd_repair_prompts(db, _args(session_id="target")) == 0
+ assert db.get_session(target)["system_prompt"] == HEALTHY
+
+ _accept_confirmations(monkeypatch)
+ assert _cmd_repair_prompts(db, _args(session_id="target", apply=True)) == 0
+ target_row = db.get_session(target)
+ assert not (target_row["system_prompt"] or "")
+ assert not (target_row["tool_names"] or "")
+ assert db.get_session(sibling)["system_prompt"] == HEALTHY
+
+ assert _cmd_repair_prompts(db, _args(session_id="no-such-session", apply=True)) == 1
+ assert "No session matches" in capsys.readouterr().out
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index a2f81b1724a..ce7771ecf48 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1760,6 +1760,7 @@ Subcommands:
| `optimize-storage` | Migrate the full-text search index to the compact v23 external-content layout; on large databases this reclaims a large fraction of `state.db`. |
| `repair` | Repair a malformed `state.db` schema (e.g. `table messages_fts already exists`) so hidden sessions reappear; a backup is made first. |
| `repair-routing` | Re-attach gateway conversations stranded in session rows that lost their routing identity (a chat "jumping back in time" after a restart). Dry-run by default; `--apply` performs the adoptions (stop the gateway first); `--max-gap-seconds N` tunes the contiguity window. Only unambiguous cases are repaired. See [Sessions → Repair Stranded Gateway Sessions](../user-guide/sessions.md#repair-stranded-gateway-sessions). |
+| `repair-prompts` | Report stored system prompts provably degraded by the pre-#122822 maintenance-compaction bug. Report-only by default; `--apply` clears verified rows so the next turn rebuilds them, `--json` is machine-readable (and non-interactive when combined with `--apply`), and an explicit `session_id` targets one row. Rows without a readable tools[] pin are reported as unverifiable and never auto-repaired. See [Sessions → Repair Degraded Stored Prompts](../user-guide/sessions.md#repair-degraded-stored-prompts). |
| `repair-profiles` | Settle session, routing, Telegram-topic and voice-mode state that landed under the wrong profile (rows in another profile's store, labels disagreeing with the session key, parent links crossing profiles, index rows for deleted profiles). Dry-run by default; `--apply` performs the repairs after snapshotting every store (stop the gateway first); `--legacy-main rekey\|move` decides what `agent:main` rows inside a named profile's store are; `--json` for automation. See [Sessions → Repair State Crossed Between Profiles](../user-guide/sessions.md#repair-state-crossed-between-profiles). |
| `recover` | Offline, non-destructive recovery of a damaged `state.db` into a separate clean database. |
| `retitle-skills` | Regenerate titles for sessions opened with a `/skill`, using what the user actually typed; lists changes unless `--apply` is passed. |
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 40c352556ea..a596131291b 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -658,6 +658,47 @@ conversation stays readable via `/resume` and session search either way —
routing is the only thing the repair changes. Back up first
(`cp ~/.hermes/state.db ~/.hermes/state.db.bak`).
+### Repair Degraded Stored Prompts
+
+Older builds affected by #122822 could let gateway hygiene or gateway `/compress`
+persist a detached maintenance agent's reduced-toolset system prompt over the
+live session. After the root fix in PR #122825 is installed, use
+`hermes sessions repair-prompts` to find rows that were already degraded.
+
+The scan is conservative: it only proposes a repair when the stored prompt is
+missing the skills markers **and** the persisted `tools[]` pin proves either
+that skill tools belonged to the session or that the pin is exactly the
+maintenance `memory`-only surface. Older or malformed rows with no readable
+pin are reported as **unverifiable** and are never changed automatically.
+
+```bash
+# Report verified candidates and unverifiable rows; writes nothing
+hermes sessions repair-prompts
+
+# Clear verified degraded prompts after confirmation
+hermes sessions repair-prompts --apply
+
+# Machine-readable report
+hermes sessions repair-prompts --json
+
+# Non-interactive automation: apply and report the ids actually cleared
+hermes sessions repair-prompts --apply --json
+
+# Explicit operator override for one session (id or unique prefix)
+hermes sessions repair-prompts SESSION_ID --apply
+```
+
+A verified memory-only `tools[]` pin is cleared together with the prompt so
+the next live turn can pin the real surface again. Clearing the prompt
+intentionally stores NULL; the next turn rebuilds and persists healthy bytes,
+which causes one expected
+`Stored system prompt ... is null; rebuilding from scratch` warning for each
+repaired session. That warning is the consequence of this explicit repair, not
+evidence of a new corruption.
+
+Run the repair only after the #122822 root fix is present; otherwise a later
+maintenance compaction can degrade the row again.
+
### Repair State Crossed Between Profiles
Every profile owns one `state.db`, and every gateway session key names the