Files
hermes-agent/tests/hermes_cli/test_sqlite3_cli_salvage_gate.py
ethernet 890bbbda1f Merge remote-tracking branch 'origin/main' into ethie/pm-clean
# Conflicts:
#	apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts
#	apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts
#	apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts
#	apps/desktop/e2e/bot-mode-roster-localized.spec.ts
#	apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
#	apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
#	apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts
#	apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts
#	apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts
#	apps/desktop/e2e/bot-roster-user-sections.spec.ts
#	apps/desktop/e2e/bot-routines-pane-narrow.spec.ts
#	apps/desktop/e2e/bot-row-open-recent-session.spec.ts
#	apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts
#	apps/desktop/e2e/group-composer-auto-grow.spec.ts
#	apps/desktop/e2e/group-create-gate-remote-roster.spec.ts
#	apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts
#	apps/desktop/e2e/hosted-room-backend-continuity.spec.ts
#	apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts
#	apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts
#	apps/desktop/e2e/worktree-branch-status.spec.ts
#	apps/desktop/electron/backend-probes.test.ts
#	apps/desktop/electron/connection-apply.test.ts
#	apps/desktop/electron/desktop-electron-pin.test.ts
#	apps/desktop/electron/desktop-uninstall.test.ts
#	apps/desktop/electron/gateway-file-download-transport.test.ts
#	apps/desktop/electron/gateway-stop-before-update.test.ts
#	apps/desktop/electron/github-api-auth.test.ts
#	apps/desktop/electron/registry-primary-profile-scope.test.ts
#	apps/desktop/electron/update-api-check.test.ts
#	apps/desktop/electron/update-handoff-marker.test.ts
#	apps/desktop/electron/venv-blocker-scan.test.ts
#	apps/desktop/scripts/after-extract.test.mjs
#	apps/desktop/scripts/local-pack-publish.test.mjs
#	apps/desktop/scripts/tasks-scroll.test.mjs
#	apps/desktop/src/app/settings/model-settings.test.tsx
#	apps/desktop/src/app/updates-overlay.blockers.test.tsx
#	apps/desktop/src/components/desktop-install-overlay.test.tsx
#	apps/desktop/src/lib/update-copy.test.ts
#	scripts/ci/check_os_marker_fakes.py
#	tests-js/desktop-mac-usage-descriptions.test.ts
#	tests-js/node-engine-alignment.test.ts
#	tests/agent/lsp/test_install_and_lint_fixes.py
#	tests/agent/test_command_token_source.py
#	tests/agent/test_compression_boundary_hook.py
#	tests/agent/test_create_openai_client_ssl_verify.py
#	tests/agent/test_custom_provider_ca_probes.py
#	tests/agent/test_endpoint_blackhole.py
#	tests/agent/test_estimator_parity.py
#	tests/agent/test_in_place_compaction.py
#	tests/agent/test_moa_loop_mode.py
#	tests/agent/test_model_metadata.py
#	tests/agent/test_skill_session_platform_gate.py
#	tests/agent/test_skill_utils.py
#	tests/agent/test_ssl_ca_guard.py
#	tests/computer_use/test_doctor.py
#	tests/cron/test_codex_execution_paths.py
#	tests/cron/test_cron_bot_chat_delivery.py
#	tests/cron/test_cron_script.py
#	tests/cron/test_media_delivery_parity.py
#	tests/cron/test_misfire_catchup.py
#	tests/cron/test_parallel_pool.py
#	tests/cron/test_recurring_eagain_redispatch.py
#	tests/gateway/test_choice_picker.py
#	tests/gateway/test_control_socket_windows_live.py
#	tests/gateway/test_dingtalk.py
#	tests/gateway/test_feishu.py
#	tests/gateway/test_feishu_onboard.py
#	tests/gateway/test_gateway_shutdown.py
#	tests/gateway/test_matrix.py
#	tests/gateway/test_model_command_custom_providers.py
#	tests/gateway/test_reasoning_command.py
#	tests/gateway/test_runtime_footer.py
#	tests/gateway/test_session.py
#	tests/gateway/test_session_hygiene.py
#	tests/gateway/test_status.py
#	tests/gateway/test_teams.py
#	tests/gateway/test_turn_lease.py
#	tests/gateway/test_whatsapp_connect.py
#	tests/hermes_cli/test_approvals_command.py
#	tests/hermes_cli/test_auth_store_lock_concurrent.py
#	tests/hermes_cli/test_backup.py
#	tests/hermes_cli/test_banner_git_state.py
#	tests/hermes_cli/test_certifi_repair.py
#	tests/hermes_cli/test_cmd_update.py
#	tests/hermes_cli/test_compat_manifest_targets.py
#	tests/hermes_cli/test_computer_use_cli.py
#	tests/hermes_cli/test_cpr_local_leak.py
#	tests/hermes_cli/test_dashboard_auth_gate.py
#	tests/hermes_cli/test_dashboard_procs_kill_grace.py
#	tests/hermes_cli/test_desktop_lifecycle_windows_live.py
#	tests/hermes_cli/test_doctor.py
#	tests/hermes_cli/test_doctor_command_install.py
#	tests/hermes_cli/test_fleet_config_migration_windows_live.py
#	tests/hermes_cli/test_gateway.py
#	tests/hermes_cli/test_gateway_platform_gating.py
#	tests/hermes_cli/test_gateway_restart_loop.py
#	tests/hermes_cli/test_gateway_task_probe.py
#	tests/hermes_cli/test_gateway_wsl.py
#	tests/hermes_cli/test_gui_command.py
#	tests/hermes_cli/test_install_cua_driver.py
#	tests/hermes_cli/test_kanban_db.py
#	tests/hermes_cli/test_lazy_command_exports.py
#	tests/hermes_cli/test_lazy_refresh_venv_repair.py
#	tests/hermes_cli/test_linux_desktop_entry.py
#	tests/hermes_cli/test_local_runtime.py
#	tests/hermes_cli/test_local_runtime_updates.py
#	tests/hermes_cli/test_managed_uv.py
#	tests/hermes_cli/test_mcp_reload_confirm_gate.py
#	tests/hermes_cli/test_nous_subscription.py
#	tests/hermes_cli/test_npm_engine.py
#	tests/hermes_cli/test_personality_none.py
#	tests/hermes_cli/test_pet_toggle.py
#	tests/hermes_cli/test_plan_reconciliation_windows_live.py
#	tests/hermes_cli/test_plugin_event_bus.py
#	tests/hermes_cli/test_plugin_manifest_v2.py
#	tests/hermes_cli/test_plugin_packs.py
#	tests/hermes_cli/test_plugins_cmd.py
#	tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py
#	tests/hermes_cli/test_process_identity.py
#	tests/hermes_cli/test_profiles.py
#	tests/hermes_cli/test_profiles_sidebar_cache.py
#	tests/hermes_cli/test_pty_bridge.py
#	tests/hermes_cli/test_resolve_turn_limit.py
#	tests/hermes_cli/test_serve_runtime_inventory.py
#	tests/hermes_cli/test_session_vacuum_config.py
#	tests/hermes_cli/test_set_config_value.py
#	tests/hermes_cli/test_signal_handler_kanban_worker.py
#	tests/hermes_cli/test_slash_confirm_windows.py
#	tests/hermes_cli/test_stale_pid_guard.py
#	tests/hermes_cli/test_startup_fast_guards.py
#	tests/hermes_cli/test_status.py
#	tests/hermes_cli/test_telegram_managed_bot.py
#	tests/hermes_cli/test_tools_config.py
#	tests/hermes_cli/test_update_apply_shallow_count.py
#	tests/hermes_cli/test_update_autostash.py
#	tests/hermes_cli/test_update_concurrent_quarantine.py
#	tests/hermes_cli/test_update_fetch_failure_classifier.py
#	tests/hermes_cli/test_update_fleet_probe_resume_token.py
#	tests/hermes_cli/test_update_handoff_backend_reap.py
#	tests/hermes_cli/test_update_handoff_desktop_rebuild.py
#	tests/hermes_cli/test_update_head_moved_gate.py
#	tests/hermes_cli/test_update_host_obligation.py
#	tests/hermes_cli/test_update_import_guard.py
#	tests/hermes_cli/test_update_interrupted_recovery.py
#	tests/hermes_cli/test_update_inventory.py
#	tests/hermes_cli/test_update_launchd_unloaded_gateway.py
#	tests/hermes_cli/test_update_missing_configured_deps.py
#	tests/hermes_cli/test_update_modified_notice.py
#	tests/hermes_cli/test_update_multiplex_migration_hook.py
#	tests/hermes_cli/test_update_no_gateway_restart.py
#	tests/hermes_cli/test_update_orphan_backend_reap.py
#	tests/hermes_cli/test_update_parked_branch_guard.py
#	tests/hermes_cli/test_update_post_pull_syntax_guard.py
#	tests/hermes_cli/test_update_receipt.py
#	tests/hermes_cli/test_update_self_lock.py
#	tests/hermes_cli/test_update_shim_fail_closed.py
#	tests/hermes_cli/test_update_shim_self_lock.py
#	tests/hermes_cli/test_update_sqlite_remediation.py
#	tests/hermes_cli/test_update_stale_dashboard.py
#	tests/hermes_cli/test_update_stale_virtualenv.py
#	tests/hermes_cli/test_update_venv_health.py
#	tests/hermes_cli/test_update_venv_ownership_preflight.py
#	tests/hermes_cli/test_update_wedged_gateway.py
#	tests/hermes_cli/test_update_yes_flag.py
#	tests/hermes_cli/test_update_zip_two_phase.py
#	tests/hermes_cli/test_urllib_security.py
#	tests/hermes_cli/test_ux_messages_auth_config.py
#	tests/hermes_cli/test_ux_messages_startup.py
#	tests/hermes_cli/test_venv_holder_classifier.py
#	tests/hermes_cli/test_verify_console_scripts.py
#	tests/hermes_cli/test_verify_core_dependencies.py
#	tests/hermes_cli/test_web_server.py
#	tests/hermes_cli/test_web_server_console_ws.py
#	tests/hermes_cli/test_web_server_ws_ping.py
#	tests/hermes_cli/test_web_ui_build.py
#	tests/hermes_state/test_fts_rebuild_admission.py
#	tests/hermes_state/test_hermes_state.py
#	tests/plugins/memory/test_memory_lazy_install.py
#	tests/plugins/test_google_meet_plugin.py
#	tests/plugins/test_langfuse_plugin.py
#	tests/plugins/test_security_guidance_plugin.py
#	tests/plugins/test_transform_llm_output_hook.py
#	tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py
#	tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
#	tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py
#	tests/scripts/install/test_install_clone_throttle_fallback.py
#	tests/scripts/install/test_install_lockfile_churn.py
#	tests/scripts/install/test_install_no_initial_commit.py
#	tests/scripts/install/test_install_sh_browser_install.py
#	tests/scripts/install/test_install_sh_node_prerelease.py
#	tests/scripts/install/test_install_sh_symlink_stomp.py
#	tests/scripts/install/test_install_sh_uv_lock_config.py
#	tests/scripts/install/test_install_unmerged_index.py
#	tests/scripts/test_contributor_map.py
#	tests/scripts/test_run_tests_parallel.py
#	tests/skills/test_competitor_news_monitor_skill.py
#	tests/skills/test_document_to_action_items_skill.py
#	tests/skills/test_google_workspace_setup.py
#	tests/skills/test_google_workspace_setup_deps.py
#	tests/skills/test_grounded_citations_skill.py
#	tests/skills/test_ip_as_logo_skill.py
#	tests/skills/test_live_dashboard_skill.py
#	tests/skills/test_mcp_oauth_remote_gateway_skill.py
#	tests/skills/test_office_document_skills.py
#	tests/skills/test_openclaw_migration.py
#	tests/skills/test_product_price_monitor_skill.py
#	tests/skills/test_scrollcraft_skill.py
#	tests/skills/test_setup_wizard_generator_skill.py
#	tests/skills/test_weekly_review_planning_skill.py
#	tests/test_engines_satisfiable.py
#	tests/test_fast_safe_load.py
#	tests/test_hermes_bootstrap.py
#	tests/test_hermes_constants.py
#	tests/test_hermes_logging.py
#	tests/test_managed_runtime_resolution.py
#	tests/test_model_tools_async_bridge.py
#	tests/test_packaging_build_guard.py
#	tests/test_packaging_metadata.py
#	tests/test_yaml_indent_consistency.py
#	tests/tools/test_approval_timeout_overflow.py
#	tests/tools/test_base_environment.py
#	tests/tools/test_bot_mode_dm.py
#	tests/tools/test_browser_chromium_check.py
#	tests/tools/test_browser_hardening.py
#	tests/tools/test_browser_homebrew_paths.py
#	tests/tools/test_browser_npx_warmup.py
#	tests/tools/test_browser_orphan_reaper.py
#	tests/tools/test_browser_real_profile.py
#	tests/tools/test_browser_use_cli.py
#	tests/tools/test_clipboard.py
#	tests/tools/test_code_execution.py
#	tests/tools/test_code_execution_modes.py
#	tests/tools/test_code_execution_windows_env.py
#	tests/tools/test_computer_use.py
#	tests/tools/test_delegate_liveness_timeout.py
#	tests/tools/test_execute_code_approval_cluster.py
#	tests/tools/test_execution_flag_detection.py
#	tests/tools/test_fal_common.py
#	tests/tools/test_file_operations.py
#	tests/tools/test_file_tools.py
#	tests/tools/test_file_tools_cwd_resolution.py
#	tests/tools/test_file_tools_live.py
#	tests/tools/test_lazy_deps.py
#	tests/tools/test_lazy_deps_durable_target.py
#	tests/tools/test_lazy_deps_managed.py
#	tests/tools/test_local_env_blocklist.py
#	tests/tools/test_local_tempdir.py
#	tests/tools/test_macos_protected_search.py
#	tests/tools/test_mcp_npx_cached_bin.py
#	tests/tools/test_oneshot_completion_linger.py
#	tests/tools/test_process_registry.py
#	tests/tools/test_read_file_schema_gating.py
#	tests/tools/test_skill_improvements.py
#	tests/tools/test_skills_sync.py
#	tests/tools/test_termux_api_detection.py
#	tests/tools/test_tirith_security.py
#	tests/tools/test_transcription_tools.py
#	tests/tools/test_tts_streaming.py
#	tests/tools/test_wake_word.py
#	tests/tui_gateway/test_compute_host_borrowed_lease.py
#	tests/tui_gateway/test_compute_host_turn_protocol.py
#	tests/tui_gateway/test_isolated_orphan_activity.py
#	tests/tui_gateway/test_protocol.py
#	tests/tui_gateway/test_slash_worker_profile_home.py
#	tests/tui_gateway/test_subprocess_encoding.py
#	tests/tui_gateway/test_tui_gateway_server.py
#	ui-tui/src/__tests__/terminalParity.test.ts
#	ui-tui/src/__tests__/termuxComposerLayout.test.ts
#	ui-tui/src/__tests__/textInputFastEcho.test.ts
2026-09-23 07:02:44 -04:00

312 lines
12 KiB
Python

"""#100368 regression: the corruption guidance must not direct a WAL-reset-
vulnerable sqlite3 CLI at a live Hermes database.
Field forensics (issue #100368, maintainer round 2 + the isolated reproducer
in its comments): when a shell with SQLite's WAL-reset opener bug (fixed
3.51.3+ / backports 3.50.7 / 3.44.6 — Debian/Ubuntu system CLIs 3.45.1 /
3.46.1 are in the vulnerable band) opens a live state.db whose writer's DMS
lock has been cancelled, it unlinks the live -wal/-shm pair and splits the
store into two concurrent generations. Both generations report
``integrity_check ok`` while an old-generation acknowledged write is lost.
Hermes' own corruption banners used to instruct exactly that command
(`sqlite3 ~/.hermes/state.db ".recover"`). The fix routes operators to
`hermes sessions recover --source ...`, whose lane snapshots the damaged
bundle before any shell touches it, and refuses a WAL-reset-vulnerable
sqlite3 CLI for the page-level salvage lane even on the snapshot.
"""
from __future__ import annotations
import argparse
import sqlite3
from pathlib import Path
from unittest.mock import patch
import pytest
from hermes_cli.session_lost_and_found import (
_parse_sqlite3_cli_version,
_wal_reset_vulnerable,
find_sqlite3_cli,
find_sqlite3_cli_refusal,
)
from hermes_cli.sqlite_runtime import is_sqlite_wal_reset_vulnerable
LIVE_DB_SALVAGE_COMMAND = 'sqlite3 ~/.hermes/state.db ".recover"'
# ---------------------------------------------------------------------------
# The version gate itself
# ---------------------------------------------------------------------------
class TestWalResetVersionGate:
@pytest.mark.parametrize(
"version",
[(3, 45, 1), (3, 46, 1), (3, 44, 5), (3, 50, 4), (3, 51, 2), (3, 8, 0)],
)
def test_vulnerable_versions(self, version):
assert _wal_reset_vulnerable(version) is True
@pytest.mark.parametrize(
"version",
[
(3, 44, 6),
(3, 44, 7),
(3, 50, 7),
(3, 50, 8),
(3, 51, 3),
(3, 51, 4),
(3, 52, 0),
(3, 53, 1),
(4, 0, 0),
],
)
def test_fixed_versions(self, version):
assert _wal_reset_vulnerable(version) is False
def test_gate_mirrors_library_gate(self):
"""The salvage gate must agree with the shared runtime gate so the
embedded library and the salvage shell can never disagree."""
versions = [
(3, 44, 5),
(3, 44, 6),
(3, 45, 1),
(3, 50, 4),
(3, 50, 7),
(3, 51, 2),
(3, 51, 3),
(3, 53, 1),
]
for version in versions:
assert _wal_reset_vulnerable(version) == (
is_sqlite_wal_reset_vulnerable(version)
), f"salvage gate disagrees with the runtime gate at {version}"
# ---------------------------------------------------------------------------
# find_sqlite3_cli refuses unsafe shells and explains why
# ---------------------------------------------------------------------------
class TestFindSqlite3CliRefusal:
def test_missing_binary_refusal(self, monkeypatch):
monkeypatch.setattr(
"hermes_cli.session_lost_and_found.shutil.which", lambda _: None
)
assert find_sqlite3_cli() is None
assert find_sqlite3_cli_refusal()["reason"] == "missing"
def test_no_dbpage_refusal(self, monkeypatch):
monkeypatch.setattr(
"hermes_cli.session_lost_and_found.shutil.which",
lambda _: "/usr/bin/sqlite3",
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._cli_supports_recover",
lambda _: False,
)
assert find_sqlite3_cli() is None
assert find_sqlite3_cli_refusal()["reason"] == "no_dbpage"
def test_wal_reset_vulnerable_refusal(self, monkeypatch):
"""A .recover-capable but WAL-reset-vulnerable CLI must be refused.
This is the Debian/Ubuntu shape from the #100368 incident: the
system sqlite3 (3.45.1) has sqlite_dbpage, so the capability probe
passes, while the WAL-reset opener bug is still present.
"""
monkeypatch.setattr(
"hermes_cli.session_lost_and_found.shutil.which",
lambda _: "/usr/bin/sqlite3",
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._cli_supports_recover",
lambda _: True,
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._parse_sqlite3_cli_version",
lambda _: (3, 45, 1),
)
assert find_sqlite3_cli() is None
refusal = find_sqlite3_cli_refusal()
assert refusal["reason"] == "wal_reset_vulnerable"
assert refusal["version"] == "3.45.1"
assert "WAL-reset" in refusal["detail"]
def test_fixed_capable_cli_accepted(self, monkeypatch):
monkeypatch.setattr(
"hermes_cli.session_lost_and_found.shutil.which",
lambda _: "/usr/local/bin/sqlite3",
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._cli_supports_recover",
lambda _: True,
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._parse_sqlite3_cli_version",
lambda _: (3, 51, 3),
)
assert find_sqlite3_cli() == "/usr/local/bin/sqlite3"
assert find_sqlite3_cli_refusal() == {}
def test_unparsable_version_still_usable(self, monkeypatch):
"""A CLI whose version line cannot be parsed is not refused on
version grounds alone (the salvage lane runs against a snapshot
copy, not the live file)."""
monkeypatch.setattr(
"hermes_cli.session_lost_and_found.shutil.which",
lambda _: "/usr/bin/sqlite3",
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._cli_supports_recover",
lambda _: True,
)
monkeypatch.setattr(
"hermes_cli.session_lost_and_found._parse_sqlite3_cli_version",
lambda _: None,
)
assert find_sqlite3_cli() == "/usr/bin/sqlite3"
class TestParseSqlite3CliVersion:
def test_parses_modern_output(self):
class Probe:
returncode = 0
stdout = b"3.51.4 2026-XX-XX 12:34:56\n"
with patch(
"hermes_cli.session_lost_and_found.subprocess.run",
return_value=Probe(),
):
assert _parse_sqlite3_cli_version("x") == (3, 51, 4)
def test_unexecutable_returns_none(self):
with patch(
"hermes_cli.session_lost_and_found.subprocess.run",
side_effect=OSError("no such file"),
):
assert _parse_sqlite3_cli_version("x") is None
# ---------------------------------------------------------------------------
# The operator-facing guidance never names the live DB
# ---------------------------------------------------------------------------
class TestGuidanceNeverNamesLiveDb:
def test_run_agent_corrupt_explanation(self):
from run_agent import AIAgent
explanation = AIAgent._format_turn_completion_explanation(
"session_persistence_failed", "corrupt"
)
assert LIVE_DB_SALVAGE_COMMAND not in explanation
assert "hermes sessions recover --source" in explanation
assert "--inspect-only" in explanation
assert "--output recovered-state.db" in explanation
assert ".recover" in explanation # the warning still names the hazard
def test_repair_budget_error_names_safe_lane(self, tmp_path: Path):
import hermes_state_repair as hermes_state # helper lives in the split-out repair module
message = hermes_state._persistent_repair_exhausted_error(
tmp_path / "state.db"
)
assert "Manual recovery required" in message
assert "sessions recover --source" in message
assert "--inspect-only" in message
assert "--output recovered-state.db" in message
# The old shape embedded the live path straight into a raw sqlite3
# command: `sqlite3 {db_path} ".recover"`.
assert ".recover\"`" not in message
assert "do NOT" in message
# ---------------------------------------------------------------------------
# The emitted command satisfies the real CLI contract
# ---------------------------------------------------------------------------
# The reviewer's blocker on the first iteration of this fix: the banners
# printed `hermes sessions recover --source <db>` — which cmd_sessions
# rejects with exit 2 ("--output is required unless --inspect-only is
# used") before any snapshot is taken. These tests dispatch the EXACT argv
# shapes the banners emit through the real parser + cmd_sessions, so a
# guidance string can never again pass a source-substring test while the
# command it prints deterministically fails.
class TestEmittedCommandsSatisfyCliContract:
"""Every `sessions recover` argv the guidance prints must be accepted
by the real CLI contract — the reviewer's blocker on the first
iteration of this fix was exactly this: the banners printed
`hermes sessions recover --source <db>`, which cmd_sessions rejects
with exit 2 ("--output is required unless --inspect-only is used")
before any snapshot is taken.
These tests dispatch the EXACT argv shapes the banners emit through
the real `cmd_sessions` (the same function `hermes` main() hands the
parsed namespace to), so a guidance string can never again pass a
source-substring test while the command it prints deterministically
fails.
"""
@staticmethod
def _namespace(source: Path, **overrides) -> "argparse.Namespace":
"""The namespace hermes main() produces for `sessions recover`.
Mirrors the registrations in hermes_cli/main.py (sessions_recover
subparser): --source, --output, --inspect-only, --work-dir,
--chunk-size (default 1000), --allow-partial, --report.
"""
fields = dict(
sessions_action="recover",
source=source,
output=None,
inspect_only=False,
work_dir=None,
chunk_size=1000,
allow_partial=False,
report=None,
)
fields.update(overrides)
return argparse.Namespace(**fields)
def test_old_v1_shape_is_still_rejected(self, tmp_path):
"""Guard the test's own premise: the bare `--source <db>` shape the
v1 banner printed (neither --inspect-only nor --output) is rejected
with rc 2 by the real dispatcher."""
import hermes_cli.sessions_cmd as sc
rc = sc.cmd_sessions(self._namespace(tmp_path / "state.db"))
assert rc == 2
def test_inspect_stage_dispatches_past_gate(self, tmp_path):
"""`--inspect-only` (stage 1 of the emitted sequence) must pass
the contract gate and reach actual inspection work (rc 0/1, not
the gate's 2)."""
import hermes_cli.sessions_cmd as sc
source = tmp_path / "state.db"
conn = sqlite3.connect(str(source))
try:
conn.execute("CREATE TABLE t (x)")
conn.commit()
finally:
conn.close()
rc = sc.cmd_sessions(
self._namespace(source, inspect_only=True)
)
assert rc != 2, "--inspect-only shape must pass the contract gate"
def test_output_stage_dispatches_past_gate(self, tmp_path):
"""`--output recovered-state.db` (stage 2) must pass the contract
gate and reach actual recovery work (rc 0/1, not the gate's 2)."""
import hermes_cli.sessions_cmd as sc
source = tmp_path / "state.db"
conn = sqlite3.connect(str(source))
try:
conn.execute("CREATE TABLE t (x)")
conn.commit()
finally:
conn.close()
rc = sc.cmd_sessions(
self._namespace(source, output=tmp_path / "recovered-state.db")
)
assert rc != 2, "--output shape must pass the contract gate"