← Back to Pull requests

feat(cli,tui): OSC 7577 program resume (salvage of #160297) #160797

Merged
kshitijk4poor merged 32 files (2048 lines) on Nov 27, 2026 20:07 UTC
View on GitHub
kshitijk4poor kshitijk4poor commented on Nov 27, 2026 14:57 UTC
Author

Salvage of #160297 by @freqyfreqy (opened 2026-11-26): OSC 7577 Program Resume, so a terminal that supports it can restart Hermes in a pane with the session it was showing. Their commit is kept as-is with authorship (contributor email mapped in the first commit); two follow-up commits fix what review found.

What it does


Hermes reports the pane's resume command (hermes -p PROFILE --cli|--tui [--resume ID]) to the terminal, authenticated with the terminal's OSC7577_TOKEN, and clears it when the user ends Hermes. Classic CLI, gateway chat and the Ink TUI all report. display.program_resume: false turns it off. Nothing changes without a token.

Fixes on top of the contributor commit


Python (classic CLI, gateway chat, launcher):
  • One ProgramResumeReporter instead of two copies of the bookkeeping; writes ordered under a lock (the SIGCONT re-report runs on a thread).

  • The command reaches the same home: -p NAME only when the profile resolves to this home; nothing for a HERMES_HOME outside the profiles root, a custom root (Docker /opt/data, HERMES_DATA_DIR_SUFFIX) or a named gateway (HERMES_TUI_GATEWAY_URL), where a fresh launch would open another store.

  • --safe-mode / --ignore-user-config launches repeat the flag and report only with a saved session (a bare restart would need the explicit model again). Gateway chat takes the flag from its args.

  • --resume ID only once the session store holds the row.

  • Clear only on a user quit (/quit, Ctrl+D; in gateway chat Ctrl+D on an empty line is now a /quit binding). Signals, terminal loss, an exception, a bare EOF and the /update relaunch keep the record. Both clients report again after SIGCONT.

  • The token leaves os.environ in load_hermes_dotenv (every entry point's first env step, before secret-source commands run), so no child inherits it; it is handed only to the Node TUI and the /update relaunch. This replaces per-call-site stripping.
  • TUI:

  • --resume ID only for a session the gateway confirmed saved: an inline turn's prompt.submit streaming answer, or a resume with stored history. Token usage, a built agent or a pending submit no longer count.

  • Clear on exit only after a user quit (die() or SIGINT); /update, a crash, a signal and a dead output stream keep it.

  • Bypass flag carried in the launcher's prefix; SIGCONT re-reports; runtime opt-out clears a reported record.
  • Validation


  • Unit: tests/hermes_cli/test_program_resume.py (44), test_terminal_notify.py (13), test_agent_env_advertisement.py (3); TUI programResume.test.ts + submissionCore.test.ts (34); tsc, eslint, ruff, scripts/check. Every new guard was mutation-checked (test fails with the guard removed).

  • Live, real CLI under a PTY with a synthetic token and a fake LLM server (gateway-backed --cli): start, first turn, Ctrl+D clear, terminal loss / SIGTERM / SIGHUP keep, SIGSTOP+SIGCONT re-report, --safe-mode reports --safe-mode --resume ID, setting off / no token / custom root report nothing, !env shows no OSC7577_TOKEN. The Ink TUI was checked at the launcher hand-off (token + prefix to node), not interactively.

  • /new then /quit hangs in this harness on this branch and on main alike (pre-existing, not touched here).
  • Known limitations


  • Gateway row writes that fail (other than disk-full) are logged and the turn continues, and a context with no store counts as saved; in those cases the TUI can report --resume for a session the restart cannot find. A proper fix needs the gateway to attest the row in its response (a contract change), left out of this PR.

  • Shared-gateway TUI sessions and compute-host turns report the bare command until a resume shows stored history; an empty saved session resumed in the TUI reports the bare command.

  • Gateway chat treats a snapshot with messages as saved without a store lookup.

  • In a bypass launch, switching to an unsaved session clears the old record rather than keep a command that would restore the previous conversation.
  • Closes #160297 once merged.

    Diff: 2048 lines (+2025 / -23) across 32 files Reviewer: kshitijk4poor Review duration: 309m
    All Vouch review confidence checks passed
    Residual risk 0.13 = Change Risk (0.86) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 2048 lines diff across 32 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 5 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    12 items
    github-actions[bot] github-actions[bot] commented on Nov 27, 2026 14:58 UTC
    Bot

    <!-- hermes-ci-review-bot -->

    ૮ >ﻌ< ა ci review

    <sub>ran on fab095c — fix(cli): resume a source launch through this install's own </sub>

    ℹ️ Info

    CI caches · View report · View job

    35 / 35 cache hits (0 misses)
    5278.56 MiB restored
    0 B not restored.

    <details>
    <summary>per-job cache results</summary>

    <h3>hits</h3>

    <table><thead><tr><th>Job</th><th>Step</th><th>Logs</th><th>Restored</th><th>Δ vs main</th></tr></thead><tbody>
    <tr><td>OS-specific tests / Windows-only tests (arm64, 1/2)</td><td>Set up native ARM64 build dependencies / Cache ARM64 OpenSSL development files</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584973#step:3:1">view step</a></td><td>26.23 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / Windows-only tests (arm64, 1/2)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584973#step:4:1">view step</a></td><td>222.58 MiB</td><td>unknown</td></tr>
    <tr><td>OS-specific tests / Windows-only tests (arm64, 1/2)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584973#step:4:1">view step</a></td><td>856.03 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / Windows-only tests (arm64, 2/2)</td><td>Set up native ARM64 build dependencies / Cache ARM64 OpenSSL development files</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584852#step:3:1">view step</a></td><td>26.23 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / Windows-only tests (arm64, 2/2)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584852#step:4:1">view step</a></td><td>222.58 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / Windows-only tests (arm64, 2/2)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584852#step:4:1">view step</a></td><td>856.03 MiB</td><td>+0 B</td></tr>
    <tr><td>JS &amp; TS checks / JS &amp; TS checks</td><td>Set up the locked JS build toolchain / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608582935#step:4:1">view step</a></td><td>155.42 MiB</td><td>unknown</td></tr>
    <tr><td>JS &amp; TS checks / JS &amp; TS checks</td><td>Set up the locked JS build toolchain / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608582935#step:4:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>JS &amp; TS checks / JS &amp; TS checks</td><td>Set up the locked JS build toolchain / Restore node dependency downloads</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608582935#step:4:1">view step</a></td><td>180.90 MiB</td><td>+0 B</td></tr>
    <tr><td>JS &amp; TS checks / JS &amp; TS checks</td><td>Restore node_modules</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608582935#step:6:1">view step</a></td><td>262.53 MiB</td><td>+0 B</td></tr>
    <tr><td>Docs Site / docs-site-checks</td><td>Set up the locked site toolchain / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608583001#step:4:1">view step</a></td><td>155.42 MiB</td><td>unknown</td></tr>
    <tr><td>Docs Site / docs-site-checks</td><td>Install website dependencies / Restore node dependency downloads</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608583001#step:5:1">view step</a></td><td>71.71 MiB</td><td>unknown</td></tr>
    <tr><td>Repository guards / Repository guards</td><td>Run ./.github/actions/setup-pm / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608583256#step:36:1">view step</a></td><td>155.42 MiB</td><td>+0 B</td></tr>
    <tr><td>Repository guards / Repository guards</td><td>Run ./.github/actions/setup-pm / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608583256#step:36:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>Repository guards / Repository guards</td><td>Run ./.github/actions/setup-pm / Restore node dependency downloads</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608583256#step:36:1">view step</a></td><td>180.90 MiB</td><td>+0 B</td></tr>
    <tr><td>Python tests / Run tests (2/3)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584347#step:5:1">view step</a></td><td>154.96 MiB</td><td>+0 B</td></tr>
    <tr><td>Python tests / Run tests (2/3)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584347#step:5:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>Python tests / Run tests (2/3)</td><td>Run tests</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584347#step:8:1">view step</a></td><td>0.10 MiB</td><td>-35 B</td></tr>
    <tr><td>Remote terminal backends / SSH + Docker backends (real sshd, real daemon)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584349#step:6:1">view step</a></td><td>83.14 MiB</td><td>unknown</td></tr>
    <tr><td>Remote terminal backends / SSH + Docker backends (real sshd, real daemon)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584349#step:6:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>Python tests / Run tests (1/3)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584448#step:5:1">view step</a></td><td>154.96 MiB</td><td>unknown</td></tr>
    <tr><td>Python tests / Run tests (1/3)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584448#step:5:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>Python tests / Run tests (1/3)</td><td>Run tests</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584448#step:8:1">view step</a></td><td>0.10 MiB</td><td>+73 B</td></tr>
    <tr><td>Python tests / Run tests (3/3)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584480#step:5:1">view step</a></td><td>154.96 MiB</td><td>unknown</td></tr>
    <tr><td>Python tests / Run tests (3/3)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584480#step:5:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>Python tests / Run tests (3/3)</td><td>Run tests</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584480#step:8:1">view step</a></td><td>0.10 MiB</td><td>+0 B</td></tr>
    <tr><td>Catalog tests / Catalog tests</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584487#step:4:1">view step</a></td><td>83.14 MiB</td><td>unknown</td></tr>
    <tr><td>Catalog tests / Catalog tests</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584487#step:4:1">view step</a></td><td>43.14 MiB</td><td>+0 B</td></tr>
    <tr><td>Python lints / Python lints</td><td>Run ./.github/actions/setup-pm / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608585452#step:4:1">view step</a></td><td>83.14 MiB</td><td>unknown</td></tr>
    <tr><td>OS-specific tests / macOS-only tests (1/2)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584838#step:5:1">view step</a></td><td>107.86 MiB</td><td>unknown</td></tr>
    <tr><td>OS-specific tests / macOS-only tests (1/2)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584838#step:5:1">view step</a></td><td>167.62 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / macOS-only tests (2/2)</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584889#step:5:1">view step</a></td><td>107.86 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / macOS-only tests (2/2)</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584889#step:5:1">view step</a></td><td>167.62 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / Windows-only tests</td><td>Set up locked Python and test dependencies / Restore verified PM tools without saving</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584919#step:5:1">view step</a></td><td>236.13 MiB</td><td>+0 B</td></tr>
    <tr><td>OS-specific tests / Windows-only tests</td><td>Set up locked Python and test dependencies / Restore uv dependency downloads and builds</td><td><a href="https://github.com/NousResearch/hermes-agent/actions/runs/46029206395/job/140608584919#step:5:1">view step</a></td><td>102.91 MiB</td><td>+0 B</td></tr>
    </tbody></table>

    <h3>misses</h3>

    none

    <p>Compressed archive bytes. Not-restored bytes use the main-size reference; missing sizes remain unknown.</p>

    </details>

    ---

    debug info

    <details>
    <summary>CI timings</summary>

    CI timings · View report · View job

    Wall time 6m43s vs 6m22s (+5.5%). 8 job(s) slower, 7 faster, 1 unchanged.

  • Python lints / Python lints: +39.0s

  • OS-specific tests / macOS-only tests (1/2): -38.0s

  • OS-specific tests / Windows-only tests: -38.0s

  • JS & TS checks / JS & TS checks: -33.0s

  • OS-specific tests / Windows-only tests (arm64, 2/2): -31.0s
  • </details>

    greptile-apps[bot] greptile-apps[bot] commented on Nov 27, 2026 15:12 UTC
    Bot

    <!-- greptile_summary -->

    <h2><ruby><rp>Confidence Score: 5/5 · The PR appears safe to merge; all previous findings are addressed, with no new actionable issues found.</rp></ruby><a href="https://app.greptile.com/api/retrigger?id=121868037&amp;sig=1c437e45ff179afa82d48d29eda84cdf786774cd03b9f3f8b68910a316b33965"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a><a href="https://app.greptile.com/-/switch-tenant?tenant=nous-research&amp;next=%2FNousResearch%2Fhermes-agent%2Fpull%2F160797&amp;utm_source=greptile_review&amp;utm_medium=github&amp;utm_campaign=view_in_greptile"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img alt="View in Greptile" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2" align="right"></picture></a>Confidence Score: 5/5</h2>

    [Medium impact] The PR appears safe to merge; all previous findings are addressed, with no new actionable issues found.

    <details><summary><h3>Summary</h3></summary>

    Adds authenticated OSC 7577 resume reports across the classic CLI, gateway chat, and Ink TUI.

  • CLI chat can reopen the right profile and saved session after a terminal restart.

  • The Ink TUI keeps its terminal restart command in step with the saved session.

  • Hermes authenticates restart reports and keeps the pane token out of child environments.

  • </details>

    <details open><summary><h3>Diagram</h3></summary>

    %%{init: {'theme': 'neutral'}}%%
    flowchart TD
      Launch[Start Hermes with pane token] --> Command[Build install-bound resume command]
      Command --> Report[Report command to terminal]
      Saved[Session is saved] --> Resume[Add --resume and session ID]
      Resume --> Report
      Report --> Quit{Why did Hermes exit?}
      Quit -->|User quit| Clear[Clear terminal record]
      Quit -->|Signal, crash, or relaunch| Keep[Keep terminal record]
    

    </details>

    <!-- greptile_confidence_score:5 -->

    <sub>Reviews (3) · Last reviewed commit: "fix(cli): resume a source launch through..." · Reviewed by Greptile</sub>

    greptile-apps[bot] greptile-apps[bot] commented on code on Nov 27, 2026 15:12 UTC
    Code Review
    hermes_cli/program_resume.py:1
    @@ -0,0 +1,187 @@
    +"""OSC 7577 Program Resume reporting for the interactive CLI surfaces.
    +
    +``terminal_notify`` encodes the sequences. This module decides which command brings Hermes back and
    +keeps one pane's record in step with it: report when the command changes, clear when the user ends
    +Hermes, keep the record when the terminal goes away.
    +"""
    +
    +from __future__ import annotations
    +
    +import logging
    +import sys
    +import threading
    +from collections.abc import Callable, Sequence
    +from contextlib import suppress
    +from functools import lru_cache
    +
    +from hermes_cli.terminal_notify import (
    +    _is_valid_osc7577_argv0,
    +    osc7577_token,
    +    program_resume_clear_sequence,
    +    program_resume_sequence,
    +)
    +
    +logger = logging.getLogger(__name__)
    +
    +_ENCODE_ERRORS = (TypeError, ValueError, UnicodeError)
    +
    +
    +def _entrypoint() -> list[str]:
    +    """argv[0]: the launcher this process came from, or this interpreter for ``python -m`` and source runs
    +    (``resolve_hermes_bin`` would otherwise fall back to whichever ``hermes`` is on PATH)."""
    +    if not sys.argv[0].lower().endswith((".py", ".pyc")):
    +        from hermes_cli.relaunch import resolve_hermes_bin
    +
    +        bin_path = resolve_hermes_bin()
    +        if bin_path and _is_valid_osc7577_argv0(bin_path):
    +            return [bin_path]
    +    return [sys.executable, "-m", "hermes_cli.main"]

    <a href=""><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> Source launches cannot restart

    If Hermes was started from a source checkout that relies on PYTHONPATH, this fallback saves a command that loses the checkout path in a fresh terminal. Replaying sys.executable -m hermes_cli.main outside the checkout then fails with ModuleNotFoundError instead of reopening the chat. PM's development environment supports this launch setup.

    Use an install-bound command, such as installation_command(), rather than relying on the old shell's environment.

    <details><summary>Prompt To Fix With AI</summary>

    `

    This is a comment left during a code review.
    Path: hermes_cli/program_resume.py
    Line: 38
    
    Comment:
    **Source launches cannot restart**
    
    If Hermes was started from a source checkout that relies on `PYTHONPATH`, this fallback saves a command that loses the checkout path in a fresh terminal. Replaying `sys.executable -m hermes_cli.main` outside the checkout then fails with `ModuleNotFoundError` instead of reopening the chat. PM's development environment supports this launch setup.
    
    Use an install-bound command, such as `installation_command()`, rather than relying on the old shell's environment.
    
    ---
    
    For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
    
    `
    </details>

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

    greptile-apps[bot] greptile-apps[bot] commented on code on Nov 27, 2026 15:12 UTC
    Code Review
    hermes_cli/config_defaults.py:1
    @@ -835,7 +835,7 @@
             "tui_agents_nudge": True,
             "bell_on_complete": False,
             "bell_on_prompt": False,   # bell when a blocking prompt opens (clarify/approval/sudo)
    -        "program_status": True,    # OSC 7501 idle/working/blocked/done/error for terminals that track it
    +        "program_status": True, "program_resume": True,  # OSC 7501 status & OSC 7577 resume reports

    <a href=""><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> The opt-out lacks coverage

    The CLI guide requires each new config key to have a test that writes a temporary config.yaml and checks behavior through the real loader. The new program_resume test replaces load_user_config_effective with a lambda, so it does not meet that requirement.

    Before merging, add a file-backed opt-out test that loads display.program_resume: false and checks that no report is written.

    Context Used: hermes_cli/AGENTS.md (source)

    <details><summary>Prompt To Fix With AI</summary>

    `

    This is a comment left during a code review.
    Path: hermes_cli/config_defaults.py
    Line: 838
    
    Comment:
    **The opt-out lacks coverage**
    
    The CLI guide requires each new config key to have a test that writes a temporary `config.yaml` and checks behavior through the real loader. The new `program_resume` test replaces `load_user_config_effective` with a lambda, so it does not meet that requirement.
    
    Before merging, add a file-backed opt-out test that loads `display.program_resume: false` and checks that no report is written.
    
    **Context Used:** hermes_cli/AGENTS.md ([source](https://github.com/nousresearch/hermes-agent/blob/main/hermes_cli/AGENTS.md))
    
    ---
    
    For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
    
    `
    </details>

    greptile-apps[bot] greptile-apps[bot] commented on code on Nov 27, 2026 15:12 UTC
    Code Review
    tests/hermes_cli/test_program_resume.py:1
    @@ -0,0 +1,549 @@
    +"""ProgramResumeReporter: one pane's OSC 7577 record (hermes_cli/program_resume.py)."""
    +
    +import base64
    +
    +import os
    +
    +import pytest
    +
    +from hermes_cli.program_resume import ProgramResumeReporter
    +
    +_TOKEN = "dummy-token-replace-me"
    +
    +
    +def _argv(seq: str) -> list[str]:
    +    body = seq[len("\x1b]7577;") : -2]
    +    part = next(p for p in body.split(":") if p.startswith("argv="))
    +    return [base64.b64decode(item).decode() for item in part[len("argv=") :].split(",")]
    +
    +
    +@pytest.fixture(autouse=True)
    +def _no_claimed_token(monkeypatch):
    +    from hermes_cli import terminal_notify
    +
    +    monkeypatch.setattr(terminal_notify, "_claimed_osc7577_token", None)
    +
    +
    +@pytest.fixture(autouse=True)
    +def _stock_hermes_root(monkeypatch):
    +    """The profiles live under ~/.hermes (no custom root): the tests' HERMES_HOME is a temp dir."""
    +    from pathlib import Path
    +
    +    import hermes_constants
    +
    +    monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: Path.home() / ".hermes")
    +
    +
    +@pytest.fixture
    +def written(monkeypatch):
    +    monkeypatch.setenv("OSC7577_TOKEN", _TOKEN)
    +    return []
    +
    +
    +@pytest.fixture(autouse=True)
    +def _fresh_resume_prefix():
    +    from hermes_cli import program_resume
    +
    +    program_resume._cached_prefix.cache_clear()
    +    yield
    +    program_resume._cached_prefix.cache_clear()
    +
    +
    +def _resume_env(monkeypatch, *, profile="default", argv0="/usr/local/bin/hermes", bin_path="/usr/local/bin/hermes"):
    +    import hermes_cli.profiles as profiles_mod
    +    import hermes_cli.relaunch as relaunch_mod
    +    from hermes_cli import program_resume
    +
    +    program_resume._cached_prefix.cache_clear()
    +    monkeypatch.setattr("sys.argv", [argv0])
    +    monkeypatch.setattr(relaunch_mod, "resolve_hermes_bin", lambda: bin_path)
    +    monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: profile)
    +    # get_active_profile_name says "custom" for a home outside the profiles root, unless a profile has that name.
    +    monkeypatch.setattr(profiles_mod, "profile_matches_home", lambda name, home=None: name != "custom")
    +    for name in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG"):
    +        monkeypatch.delenv(name, raising=False)
    +    return program_resume
    +
    +
    +def test_resume_argv_pins_the_profile_and_surface(monkeypatch):
    +    pr = _resume_env(monkeypatch)
    +    assert pr.resume_argv(None, "cli") == ("/usr/local/bin/hermes", "-p", "default", "--cli")
    +    assert pr.resume_argv("sess-1", "cli") == ("/usr/local/bin/hermes", "-p", "default", "--cli", "--resume", "sess-1")
    +
    +    pr = _resume_env(monkeypatch, profile="work")
    +    assert pr.resume_argv("sess-2", "tui", "--tui-native", "--dev") == (
    +        "/usr/local/bin/hermes", "-p", "work", "--tui", "--tui-native", "--dev", "--resume", "sess-2"
    +    )
    +
    +
    +def test_resume_argv_names_a_profile_called_custom(monkeypatch):
    +    import hermes_cli.profiles as profiles_mod
    +
    +    pr = _resume_env(monkeypatch, profile="custom")
    +    monkeypatch.setattr(profiles_mod, "profile_matches_home", lambda name, home=None: True)
    +    assert pr.resume_argv("s", "cli") == ("/usr/local/bin/hermes", "-p", "custom", "--cli", "--resume", "s")
    +
    +
    +def test_bypass_launch_repeats_its_flag_and_reports_only_a_saved_session(monkeypatch):
    +    pr = _resume_env(monkeypatch)
    +    monkeypatch.setenv("HERMES_SAFE_MODE", "1")
    +    monkeypatch.setenv("HERMES_IGNORE_USER_CONFIG", "1")
    +    assert pr.resume_argv(None, "cli") is None  # restarted bare it needs its explicit model back
    +    assert pr.resume_argv("s", "cli") == ("/usr/local/bin/hermes", "-p", "default", "--cli", "--safe-mode", "--resume", "s")
    +
    +    pr = _resume_env(monkeypatch)
    +    monkeypatch.setenv("HERMES_IGNORE_USER_CONFIG", "1")
    +    assert pr.resume_argv("s", "tui")[-3:] == ("--ignore-user-config", "--resume", "s")
    +
    +
    +def test_resume_argv_uses_this_interpreter_for_source_runs_and_bad_launchers(monkeypatch):
    +    import sys
    +
    +    pr = _resume_env(monkeypatch, argv0="/src/hermes/hermes_cli/main.py")
    +    assert pr.resume_argv("s", "cli")[:3] == (sys.executable, "-m", "hermes_cli.main")
    +    pr = _resume_env(monkeypatch, bin_path="./relative-hermes")
    +    assert pr.resume_argv("s", "cli")[:3] == (sys.executable, "-m", "hermes_cli.main")
    +
    +
    +def test_resume_argv_is_none_when_no_command_reaches_this_home(monkeypatch):
    +    import hermes_cli.profiles as profiles_mod
    +
    +    pr = _resume_env(monkeypatch, profile="custom")
    +    assert pr.resume_argv("s", "cli") is None
    +
    +    def _boom():
    +        raise OSError("unreadable home")
    +
    +    pr = _resume_env(monkeypatch)
    +    monkeypatch.setattr(profiles_mod, "get_active_profile_name", _boom)
    +    assert pr.resume_argv("s", "cli") is None
    +
    +
    +class _Store:
    +    def __init__(self, saved=(), error=None):
    +        self.saved, self.error = set(saved), error
    +
    +    def get_session(self, session_id):
    +        if self.error:
    +            raise self.error
    +        return {"id": session_id} if session_id in self.saved else None
    +
    +
    +def test_gateway_chat_view_reports_once_saved_and_never_when_finite(written, monkeypatch):
    +    from hermes_cli.gateway_chat_view import GatewayChatView
    +
    +    from hermes_cli import terminal_notify
    +
    +    monkeypatch.setattr(terminal_notify, "write_tty", written.append)
    +    monkeypatch.setattr("sys.stdout.isatty", lambda: True)
    +    _resume_env(monkeypatch)
    +
    +    class _DummyClient:
    +        pass
    +
    +    import hermes_cli.gateway_session_store as store_mod
    +
    +    store = _Store()
    +    monkeypatch.setattr(store_mod, "session_store", lambda: store)
    +    view = GatewayChatView(_DummyClient(), {"stored_session_id": "gw-1", "info": {"lazy": False, "title": "t"}},
    +                           program_resume=True)
    +    view._sync_program_resume()
    +    assert _argv(written[-1]) == ["/usr/local/bin/hermes", "-p", "default", "--cli"]
    +
    +    store.saved.add("gw-1")  # the store now holds its row
    +    view._sync_program_resume()
    +    assert _argv(written[-1]) == ["/usr/local/bin/hermes", "-p", "default", "--cli", "--resume", "gw-1"]
    +
    +    view._clear_program_resume()
    +    assert ":clear=1:mac=" in written[-1]
    +
    +    before_finite = len(written)
    +    finite_view = GatewayChatView(_DummyClient(), {"stored_session_id": "gw-2", "info": {"lazy": False}},
    +                                  program_resume=True)
    +    finite_view.finite = True
    +    finite_view._sync_program_resume()
    +    assert len(written) == before_finite
    +
    +
    +def test_reports_once_per_command_and_again_when_forced(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.sync(("hermes", "--cli"))
    +    assert [_argv(s) for s in written] == [["hermes", "--cli"]]
    +    reporter.sync(("hermes", "--cli"), force=True)
    +    reporter.sync(("hermes", "--cli", "--resume", "s1"))
    +    assert [_argv(s) for s in written[1:]] == [["hermes", "--cli"], ["hermes", "--cli", "--resume", "s1"]]
    +
    +
    +def test_unreportable_command_clears_the_earlier_record(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.sync(("hermes", "--cli", "--resume", "bad\nid"))
    +    assert ":clear=1:mac=" in written[-1]
    +    reporter.sync(("hermes", "--cli", "--resume", "bad\nid"))
    +    assert len(written) == 2  # nothing left to clear
    +    assert not reporter.reported
    +
    +
    +def test_clear_sends_once_and_closes(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.clear()
    +    assert written == []  # nothing reported, nothing to clear
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.clear()
    +    reporter.clear()
    +    reporter.sync(("hermes", "--cli"))
    +    assert len(written) == 2 and ":clear=1:mac=" in written[1]
    +
    +
    +def test_keep_closes_without_clearing(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.keep()
    +    reporter.clear()
    +    reporter.sync(("hermes", "--tui"))
    +    assert len(written) == 1
    +    assert not reporter.active
    +
    +
    +def test_silent_without_a_token(monkeypatch):
    +    monkeypatch.delenv("OSC7577_TOKEN", raising=False)
    +    written = []
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.clear()
    +    assert written == [] and not reporter.active
    +
    +
    +def test_gateway_chat_view_honours_the_opt_out(written, monkeypatch):
    +    from hermes_cli import terminal_notify
    +    from hermes_cli.gateway_chat_view import GatewayChatView
    +
    +    _resume_env(monkeypatch)
    +    monkeypatch.setattr(terminal_notify, "write_tty", written.append)
    +    monkeypatch.setattr("sys.stdout.isatty", lambda: True)
    +
    +    snapshot = {"stored_session_id": "gw-1", "messages": [{"role": "user"}]}
    +    GatewayChatView(object(), snapshot)._sync_program_resume()
    +    assert written == []  # program_resume defaults off: gateway_chat passes the launch's setting
    +
    +    GatewayChatView(object(), snapshot, program_resume=True)._sync_program_resume()
    +    assert _argv(written[-1]) == ["/usr/local/bin/hermes", "-p", "default", "--cli", "--resume", "gw-1"]
    +
    +
    +def test_program_resume_enabled_reads_the_token_and_setting(written, monkeypatch):
    +    from argparse import Namespace
    +
    +    import hermes_cli.config_effective as effective
    +    from hermes_cli import gateway_chat
    +
    +    for name in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG"):
    +        monkeypatch.delenv(name, raising=False)
    +    monkeypatch.setattr(effective, "load_user_config_effective", lambda path: {"display": {"program_resume": False}})
    +    assert gateway_chat.program_resume_enabled(Namespace()) is False
    +    assert gateway_chat.program_resume_enabled(Namespace(safe_mode=True)) is True  # reads no profile: the default
    +
    +    monkeypatch.delenv("OSC7577_TOKEN")
    +    assert gateway_chat.program_resume_enabled(Namespace(safe_mode=True)) is False
    +
    +
    +def _launch_tui_env(monkeypatch, *, profile):
    +    import sys
    +    from pathlib import Path
    +
    +    import hermes_cli.main as main_mod
    +    import hermes_cli.profiles as profiles_mod
    +    from hermes_cli import main_tui_launch, program_resume
    +
    +    program_resume._cached_prefix.cache_clear()
    +    monkeypatch.setattr(main_mod, "_has_any_provider_configured", lambda: True)
    +    monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: profile)
    +    monkeypatch.setattr(profiles_mod, "profile_matches_home", lambda name, home=None: name != "custom")
    +    monkeypatch.setenv("HERMES_PYTHON", sys.executable)
    +    captured = {}
    +    monkeypatch.setattr(main_tui_launch, "_make_tui_argv",
    +                        lambda tui_dir, tui_dev, notices=None: (["node", "dist/entry.js"], Path(".")))
    +    monkeypatch.setattr(main_mod.subprocess, "call", lambda argv, cwd=None, env=None: captured.update(env=env) or 1)
    +    with pytest.raises(SystemExit):
    +        main_mod._launch_tui()
    +    program_resume._cached_prefix.cache_clear()
    +    return captured["env"]
    +
    +
    +def test_tui_launch_hands_the_token_only_with_a_reachable_resume_command(written, monkeypatch):
    +    env = _launch_tui_env(monkeypatch, profile="work")
    +    assert env["OSC7577_TOKEN"] == _TOKEN
    +    assert '"-p", "work", "--tui"' in env["HERMES_TUI_RESUME_ARGV"]
    +
    +    assert "HERMES_TUI_RESUME_SESSION_ONLY" not in env
    +
    +    env = _launch_tui_env(monkeypatch, profile="custom")
    +    assert "OSC7577_TOKEN" not in env
    +    assert "HERMES_TUI_RESUME_ARGV" not in env and "HERMES_TUI_OWNER_PID" not in env
    +
    +    monkeypatch.setenv("HERMES_SAFE_MODE", "1")
    +    monkeypatch.setenv("HERMES_MODEL", "test/model")  # a bypass launch names its model
    +    env = _launch_tui_env(monkeypatch, profile="work")
    +    assert env["HERMES_TUI_RESUME_SESSION_ONLY"] == "1"
    +    assert '"--tui", "--safe-mode"' in env["HERMES_TUI_RESUME_ARGV"]
    +
    +
    +def test_tui_launch_without_a_token_resolves_nothing(monkeypatch):
    +    from hermes_cli import program_resume
    +
    +    monkeypatch.delenv("OSC7577_TOKEN", raising=False)
    +    calls = []
    +    monkeypatch.setattr(program_resume, "_profile_args", lambda: calls.append(1) or ["-p", "default"])
    +    env = _launch_tui_env(monkeypatch, profile="default")
    +    assert calls == []
    +    assert "HERMES_TUI_RESUME_ARGV" not in env and "HERMES_TUI_OWNER_PID" not in env
    +
    +
    +def test_session_saved_separates_no_row_from_unreadable():
    +    from hermes_cli.program_resume import session_saved
    +
    +    class _Store:
    +        def __init__(self, row=None, error=None):
    +            self.row, self.error = row, error
    +
    +        def get_session(self, session_id):
    +            if self.error:
    +                raise self.error
    +            return self.row
    +
    +    assert session_saved(_Store(row={"id": "s"}), "s") is True
    +    assert session_saved(_Store(), "s") is False
    +    assert session_saved(_Store(error=OSError("locked")), "s") is False
    +    assert session_saved(None, "s") is False
    +
    +
    +# Same table as ui-tui/src/__tests__/programResume.test.ts ("argv[0] rules match the Python reporter").
    +ARGV0_CASES = [
    +    ("/usr/local/bin/hermes", True),
    +    ("hermes", True),
    +    ("C:\\Program Files\\hermes.exe", True),
    +    ("c:/hermes/hermes.exe", True),
    +    ("\\\\server\\share\\hermes.exe", True),
    +    ("\\hermes.exe", False),
    +    ("C:hermes.exe", True),  # no separator: a bare command name
    +    ("./hermes", False),
    +    ("bin/hermes", False),
    +    ("-hermes", False),
    +    ("", False),
    +    ("/usr/bin/her\x1bmes", False),
    +]
    +
    +
    +@pytest.mark.parametrize(("arg", "valid"), ARGV0_CASES)
    +def test_argv0_rules_match_the_tui(arg, valid):
    +    from hermes_cli.terminal_notify import _is_valid_osc7577_argv0
    +
    +    assert _is_valid_osc7577_argv0(arg) is valid
    +
    +
    +def test_gateway_chat_view_reports_again_after_sigcont(written, monkeypatch):
    +    import asyncio
    +    import signal
    +
    +    from hermes_cli.gateway_chat_view import GatewayChatView
    +
    +    if not hasattr(signal, "SIGCONT"):
    +        pytest.skip("POSIX only")

    <a href=""><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> macOS misses signal coverage

    This test gates SIGCONT with pytest.skip() instead of the required @pytest.mark.platforms("posix"). macOS CI selects files by that marker and runs marked tests only, so it never checks this new signal behavior.

    Before merging, add the platform marker and remove the manual host skip, as the test guide requires.

    Context Used: tests/AGENTS.md (source)

    <details><summary>Prompt To Fix With AI</summary>

    `

    This is a comment left during a code review.
    Path: tests/hermes_cli/test_program_resume.py
    Line: 351-352
    
    Comment:
    **macOS misses signal coverage**
    
    This test gates `SIGCONT` with `pytest.skip()` instead of the required `@pytest.mark.platforms("posix")`. macOS CI selects files by that marker and runs marked tests only, so it never checks this new signal behavior.
    
    Before merging, add the platform marker and remove the manual host skip, as the test guide requires.
    
    **Context Used:** tests/AGENTS.md ([source](https://github.com/nousresearch/hermes-agent/blob/main/tests/AGENTS.md))
    
    ---
    
    For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
    
    `
    </details>

    kshitijk4poor kshitijk4poor commented on code on Nov 27, 2026 15:55 UTC
    Code Review
    hermes_cli/program_resume.py:1
    @@ -0,0 +1,187 @@
    +"""OSC 7577 Program Resume reporting for the interactive CLI surfaces.
    +
    +``terminal_notify`` encodes the sequences. This module decides which command brings Hermes back and
    +keeps one pane's record in step with it: report when the command changes, clear when the user ends
    +Hermes, keep the record when the terminal goes away.
    +"""
    +
    +from __future__ import annotations
    +
    +import logging
    +import sys
    +import threading
    +from collections.abc import Callable, Sequence
    +from contextlib import suppress
    +from functools import lru_cache
    +
    +from hermes_cli.terminal_notify import (
    +    _is_valid_osc7577_argv0,
    +    osc7577_token,
    +    program_resume_clear_sequence,
    +    program_resume_sequence,
    +)
    +
    +logger = logging.getLogger(__name__)
    +
    +_ENCODE_ERRORS = (TypeError, ValueError, UnicodeError)
    +
    +
    +def _entrypoint() -> list[str]:
    +    """argv[0]: the launcher this process came from, or this interpreter for ``python -m`` and source runs
    +    (``resolve_hermes_bin`` would otherwise fall back to whichever ``hermes`` is on PATH)."""
    +    if not sys.argv[0].lower().endswith((".py", ".pyc")):
    +        from hermes_cli.relaunch import resolve_hermes_bin
    +
    +        bin_path = resolve_hermes_bin()
    +        if bin_path and _is_valid_osc7577_argv0(bin_path):
    +            return [bin_path]
    +    return [sys.executable, "-m", "hermes_cli.main"]

    Fixed in fab095cde0: a source / python -m launch now reports chat_launch.hermes_command() (the install's launcher, or this interpreter with the inline bootstrap that drops PYTHONPATH). Replayed the reported argv under env -i from outside the checkout: it starts this install. The test now expects the install command and fails against the old -m form.

    kshitijk4poor kshitijk4poor commented on code on Nov 27, 2026 15:55 UTC
    Code Review
    hermes_cli/config_defaults.py:1
    @@ -835,7 +835,7 @@
             "tui_agents_nudge": True,
             "bell_on_complete": False,
             "bell_on_prompt": False,   # bell when a blocking prompt opens (clarify/approval/sudo)
    -        "program_status": True,    # OSC 7501 idle/working/blocked/done/error for terminals that track it
    +        "program_status": True, "program_resume": True,  # OSC 7501 status & OSC 7577 resume reports

    Added in fab095cde0: test_a_config_file_opt_out_writes_no_report writes display.program_resume: false to a temp HERMES_HOME's config.yaml, goes through the real load_user_config_effective, and checks that no OSC 7577 report is written. It fails when the setting is ignored.

    kshitijk4poor kshitijk4poor commented on code on Nov 27, 2026 15:56 UTC
    Code Review
    tests/hermes_cli/test_program_resume.py:1
    @@ -0,0 +1,549 @@
    +"""ProgramResumeReporter: one pane's OSC 7577 record (hermes_cli/program_resume.py)."""
    +
    +import base64
    +
    +import os
    +
    +import pytest
    +
    +from hermes_cli.program_resume import ProgramResumeReporter
    +
    +_TOKEN = "dummy-token-replace-me"
    +
    +
    +def _argv(seq: str) -> list[str]:
    +    body = seq[len("\x1b]7577;") : -2]
    +    part = next(p for p in body.split(":") if p.startswith("argv="))
    +    return [base64.b64decode(item).decode() for item in part[len("argv=") :].split(",")]
    +
    +
    +@pytest.fixture(autouse=True)
    +def _no_claimed_token(monkeypatch):
    +    from hermes_cli import terminal_notify
    +
    +    monkeypatch.setattr(terminal_notify, "_claimed_osc7577_token", None)
    +
    +
    +@pytest.fixture(autouse=True)
    +def _stock_hermes_root(monkeypatch):
    +    """The profiles live under ~/.hermes (no custom root): the tests' HERMES_HOME is a temp dir."""
    +    from pathlib import Path
    +
    +    import hermes_constants
    +
    +    monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: Path.home() / ".hermes")
    +
    +
    +@pytest.fixture
    +def written(monkeypatch):
    +    monkeypatch.setenv("OSC7577_TOKEN", _TOKEN)
    +    return []
    +
    +
    +@pytest.fixture(autouse=True)
    +def _fresh_resume_prefix():
    +    from hermes_cli import program_resume
    +
    +    program_resume._cached_prefix.cache_clear()
    +    yield
    +    program_resume._cached_prefix.cache_clear()
    +
    +
    +def _resume_env(monkeypatch, *, profile="default", argv0="/usr/local/bin/hermes", bin_path="/usr/local/bin/hermes"):
    +    import hermes_cli.profiles as profiles_mod
    +    import hermes_cli.relaunch as relaunch_mod
    +    from hermes_cli import program_resume
    +
    +    program_resume._cached_prefix.cache_clear()
    +    monkeypatch.setattr("sys.argv", [argv0])
    +    monkeypatch.setattr(relaunch_mod, "resolve_hermes_bin", lambda: bin_path)
    +    monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: profile)
    +    # get_active_profile_name says "custom" for a home outside the profiles root, unless a profile has that name.
    +    monkeypatch.setattr(profiles_mod, "profile_matches_home", lambda name, home=None: name != "custom")
    +    for name in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG"):
    +        monkeypatch.delenv(name, raising=False)
    +    return program_resume
    +
    +
    +def test_resume_argv_pins_the_profile_and_surface(monkeypatch):
    +    pr = _resume_env(monkeypatch)
    +    assert pr.resume_argv(None, "cli") == ("/usr/local/bin/hermes", "-p", "default", "--cli")
    +    assert pr.resume_argv("sess-1", "cli") == ("/usr/local/bin/hermes", "-p", "default", "--cli", "--resume", "sess-1")
    +
    +    pr = _resume_env(monkeypatch, profile="work")
    +    assert pr.resume_argv("sess-2", "tui", "--tui-native", "--dev") == (
    +        "/usr/local/bin/hermes", "-p", "work", "--tui", "--tui-native", "--dev", "--resume", "sess-2"
    +    )
    +
    +
    +def test_resume_argv_names_a_profile_called_custom(monkeypatch):
    +    import hermes_cli.profiles as profiles_mod
    +
    +    pr = _resume_env(monkeypatch, profile="custom")
    +    monkeypatch.setattr(profiles_mod, "profile_matches_home", lambda name, home=None: True)
    +    assert pr.resume_argv("s", "cli") == ("/usr/local/bin/hermes", "-p", "custom", "--cli", "--resume", "s")
    +
    +
    +def test_bypass_launch_repeats_its_flag_and_reports_only_a_saved_session(monkeypatch):
    +    pr = _resume_env(monkeypatch)
    +    monkeypatch.setenv("HERMES_SAFE_MODE", "1")
    +    monkeypatch.setenv("HERMES_IGNORE_USER_CONFIG", "1")
    +    assert pr.resume_argv(None, "cli") is None  # restarted bare it needs its explicit model back
    +    assert pr.resume_argv("s", "cli") == ("/usr/local/bin/hermes", "-p", "default", "--cli", "--safe-mode", "--resume", "s")
    +
    +    pr = _resume_env(monkeypatch)
    +    monkeypatch.setenv("HERMES_IGNORE_USER_CONFIG", "1")
    +    assert pr.resume_argv("s", "tui")[-3:] == ("--ignore-user-config", "--resume", "s")
    +
    +
    +def test_resume_argv_uses_this_interpreter_for_source_runs_and_bad_launchers(monkeypatch):
    +    import sys
    +
    +    pr = _resume_env(monkeypatch, argv0="/src/hermes/hermes_cli/main.py")
    +    assert pr.resume_argv("s", "cli")[:3] == (sys.executable, "-m", "hermes_cli.main")
    +    pr = _resume_env(monkeypatch, bin_path="./relative-hermes")
    +    assert pr.resume_argv("s", "cli")[:3] == (sys.executable, "-m", "hermes_cli.main")
    +
    +
    +def test_resume_argv_is_none_when_no_command_reaches_this_home(monkeypatch):
    +    import hermes_cli.profiles as profiles_mod
    +
    +    pr = _resume_env(monkeypatch, profile="custom")
    +    assert pr.resume_argv("s", "cli") is None
    +
    +    def _boom():
    +        raise OSError("unreadable home")
    +
    +    pr = _resume_env(monkeypatch)
    +    monkeypatch.setattr(profiles_mod, "get_active_profile_name", _boom)
    +    assert pr.resume_argv("s", "cli") is None
    +
    +
    +class _Store:
    +    def __init__(self, saved=(), error=None):
    +        self.saved, self.error = set(saved), error
    +
    +    def get_session(self, session_id):
    +        if self.error:
    +            raise self.error
    +        return {"id": session_id} if session_id in self.saved else None
    +
    +
    +def test_gateway_chat_view_reports_once_saved_and_never_when_finite(written, monkeypatch):
    +    from hermes_cli.gateway_chat_view import GatewayChatView
    +
    +    from hermes_cli import terminal_notify
    +
    +    monkeypatch.setattr(terminal_notify, "write_tty", written.append)
    +    monkeypatch.setattr("sys.stdout.isatty", lambda: True)
    +    _resume_env(monkeypatch)
    +
    +    class _DummyClient:
    +        pass
    +
    +    import hermes_cli.gateway_session_store as store_mod
    +
    +    store = _Store()
    +    monkeypatch.setattr(store_mod, "session_store", lambda: store)
    +    view = GatewayChatView(_DummyClient(), {"stored_session_id": "gw-1", "info": {"lazy": False, "title": "t"}},
    +                           program_resume=True)
    +    view._sync_program_resume()
    +    assert _argv(written[-1]) == ["/usr/local/bin/hermes", "-p", "default", "--cli"]
    +
    +    store.saved.add("gw-1")  # the store now holds its row
    +    view._sync_program_resume()
    +    assert _argv(written[-1]) == ["/usr/local/bin/hermes", "-p", "default", "--cli", "--resume", "gw-1"]
    +
    +    view._clear_program_resume()
    +    assert ":clear=1:mac=" in written[-1]
    +
    +    before_finite = len(written)
    +    finite_view = GatewayChatView(_DummyClient(), {"stored_session_id": "gw-2", "info": {"lazy": False}},
    +                                  program_resume=True)
    +    finite_view.finite = True
    +    finite_view._sync_program_resume()
    +    assert len(written) == before_finite
    +
    +
    +def test_reports_once_per_command_and_again_when_forced(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.sync(("hermes", "--cli"))
    +    assert [_argv(s) for s in written] == [["hermes", "--cli"]]
    +    reporter.sync(("hermes", "--cli"), force=True)
    +    reporter.sync(("hermes", "--cli", "--resume", "s1"))
    +    assert [_argv(s) for s in written[1:]] == [["hermes", "--cli"], ["hermes", "--cli", "--resume", "s1"]]
    +
    +
    +def test_unreportable_command_clears_the_earlier_record(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.sync(("hermes", "--cli", "--resume", "bad\nid"))
    +    assert ":clear=1:mac=" in written[-1]
    +    reporter.sync(("hermes", "--cli", "--resume", "bad\nid"))
    +    assert len(written) == 2  # nothing left to clear
    +    assert not reporter.reported
    +
    +
    +def test_clear_sends_once_and_closes(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.clear()
    +    assert written == []  # nothing reported, nothing to clear
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.clear()
    +    reporter.clear()
    +    reporter.sync(("hermes", "--cli"))
    +    assert len(written) == 2 and ":clear=1:mac=" in written[1]
    +
    +
    +def test_keep_closes_without_clearing(written):
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.keep()
    +    reporter.clear()
    +    reporter.sync(("hermes", "--tui"))
    +    assert len(written) == 1
    +    assert not reporter.active
    +
    +
    +def test_silent_without_a_token(monkeypatch):
    +    monkeypatch.delenv("OSC7577_TOKEN", raising=False)
    +    written = []
    +    reporter = ProgramResumeReporter(written.append)
    +    reporter.sync(("hermes", "--cli"))
    +    reporter.clear()
    +    assert written == [] and not reporter.active
    +
    +
    +def test_gateway_chat_view_honours_the_opt_out(written, monkeypatch):
    +    from hermes_cli import terminal_notify
    +    from hermes_cli.gateway_chat_view import GatewayChatView
    +
    +    _resume_env(monkeypatch)
    +    monkeypatch.setattr(terminal_notify, "write_tty", written.append)
    +    monkeypatch.setattr("sys.stdout.isatty", lambda: True)
    +
    +    snapshot = {"stored_session_id": "gw-1", "messages": [{"role": "user"}]}
    +    GatewayChatView(object(), snapshot)._sync_program_resume()
    +    assert written == []  # program_resume defaults off: gateway_chat passes the launch's setting
    +
    +    GatewayChatView(object(), snapshot, program_resume=True)._sync_program_resume()
    +    assert _argv(written[-1]) == ["/usr/local/bin/hermes", "-p", "default", "--cli", "--resume", "gw-1"]
    +
    +
    +def test_program_resume_enabled_reads_the_token_and_setting(written, monkeypatch):
    +    from argparse import Namespace
    +
    +    import hermes_cli.config_effective as effective
    +    from hermes_cli import gateway_chat
    +
    +    for name in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG"):
    +        monkeypatch.delenv(name, raising=False)
    +    monkeypatch.setattr(effective, "load_user_config_effective", lambda path: {"display": {"program_resume": False}})
    +    assert gateway_chat.program_resume_enabled(Namespace()) is False
    +    assert gateway_chat.program_resume_enabled(Namespace(safe_mode=True)) is True  # reads no profile: the default
    +
    +    monkeypatch.delenv("OSC7577_TOKEN")
    +    assert gateway_chat.program_resume_enabled(Namespace(safe_mode=True)) is False
    +
    +
    +def _launch_tui_env(monkeypatch, *, profile):
    +    import sys
    +    from pathlib import Path
    +
    +    import hermes_cli.main as main_mod
    +    import hermes_cli.profiles as profiles_mod
    +    from hermes_cli import main_tui_launch, program_resume
    +
    +    program_resume._cached_prefix.cache_clear()
    +    monkeypatch.setattr(main_mod, "_has_any_provider_configured", lambda: True)
    +    monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: profile)
    +    monkeypatch.setattr(profiles_mod, "profile_matches_home", lambda name, home=None: name != "custom")
    +    monkeypatch.setenv("HERMES_PYTHON", sys.executable)
    +    captured = {}
    +    monkeypatch.setattr(main_tui_launch, "_make_tui_argv",
    +                        lambda tui_dir, tui_dev, notices=None: (["node", "dist/entry.js"], Path(".")))
    +    monkeypatch.setattr(main_mod.subprocess, "call", lambda argv, cwd=None, env=None: captured.update(env=env) or 1)
    +    with pytest.raises(SystemExit):
    +        main_mod._launch_tui()
    +    program_resume._cached_prefix.cache_clear()
    +    return captured["env"]
    +
    +
    +def test_tui_launch_hands_the_token_only_with_a_reachable_resume_command(written, monkeypatch):
    +    env = _launch_tui_env(monkeypatch, profile="work")
    +    assert env["OSC7577_TOKEN"] == _TOKEN
    +    assert '"-p", "work", "--tui"' in env["HERMES_TUI_RESUME_ARGV"]
    +
    +    assert "HERMES_TUI_RESUME_SESSION_ONLY" not in env
    +
    +    env = _launch_tui_env(monkeypatch, profile="custom")
    +    assert "OSC7577_TOKEN" not in env
    +    assert "HERMES_TUI_RESUME_ARGV" not in env and "HERMES_TUI_OWNER_PID" not in env
    +
    +    monkeypatch.setenv("HERMES_SAFE_MODE", "1")
    +    monkeypatch.setenv("HERMES_MODEL", "test/model")  # a bypass launch names its model
    +    env = _launch_tui_env(monkeypatch, profile="work")
    +    assert env["HERMES_TUI_RESUME_SESSION_ONLY"] == "1"
    +    assert '"--tui", "--safe-mode"' in env["HERMES_TUI_RESUME_ARGV"]
    +
    +
    +def test_tui_launch_without_a_token_resolves_nothing(monkeypatch):
    +    from hermes_cli import program_resume
    +
    +    monkeypatch.delenv("OSC7577_TOKEN", raising=False)
    +    calls = []
    +    monkeypatch.setattr(program_resume, "_profile_args", lambda: calls.append(1) or ["-p", "default"])
    +    env = _launch_tui_env(monkeypatch, profile="default")
    +    assert calls == []
    +    assert "HERMES_TUI_RESUME_ARGV" not in env and "HERMES_TUI_OWNER_PID" not in env
    +
    +
    +def test_session_saved_separates_no_row_from_unreadable():
    +    from hermes_cli.program_resume import session_saved
    +
    +    class _Store:
    +        def __init__(self, row=None, error=None):
    +            self.row, self.error = row, error
    +
    +        def get_session(self, session_id):
    +            if self.error:
    +                raise self.error
    +            return self.row
    +
    +    assert session_saved(_Store(row={"id": "s"}), "s") is True
    +    assert session_saved(_Store(), "s") is False
    +    assert session_saved(_Store(error=OSError("locked")), "s") is False
    +    assert session_saved(None, "s") is False
    +
    +
    +# Same table as ui-tui/src/__tests__/programResume.test.ts ("argv[0] rules match the Python reporter").
    +ARGV0_CASES = [
    +    ("/usr/local/bin/hermes", True),
    +    ("hermes", True),
    +    ("C:\\Program Files\\hermes.exe", True),
    +    ("c:/hermes/hermes.exe", True),
    +    ("\\\\server\\share\\hermes.exe", True),
    +    ("\\hermes.exe", False),
    +    ("C:hermes.exe", True),  # no separator: a bare command name
    +    ("./hermes", False),
    +    ("bin/hermes", False),
    +    ("-hermes", False),
    +    ("", False),
    +    ("/usr/bin/her\x1bmes", False),
    +]
    +
    +
    +@pytest.mark.parametrize(("arg", "valid"), ARGV0_CASES)
    +def test_argv0_rules_match_the_tui(arg, valid):
    +    from hermes_cli.terminal_notify import _is_valid_osc7577_argv0
    +
    +    assert _is_valid_osc7577_argv0(arg) is valid
    +
    +
    +def test_gateway_chat_view_reports_again_after_sigcont(written, monkeypatch):
    +    import asyncio
    +    import signal
    +
    +    from hermes_cli.gateway_chat_view import GatewayChatView
    +
    +    if not hasattr(signal, "SIGCONT"):
    +        pytest.skip("POSIX only")

    Fixed in fab095cde0: marked @pytest.mark.platforms("posix") and removed the manual skip.

    nohe-sohbi nohe-sohbi commented on Nov 27, 2026 17:12 UTC
    Contributor

    Bonjour, revue du code : bonne qualité, tests mentionnés, pas de problèmes de sécurité.

    nohe-sohbi nohe-sohbi commented on Nov 27, 2026 17:13 UTC
    Reviewer

    Bonjour, revue du code : bonne qualité, tests mentionnés, pas de problèmes de sécurité.

    nohe-sohbi nohe-sohbi commented on Nov 27, 2026 17:13 UTC
    Contributor

    Bonjour, revue rapide de la PR #160797 (feat(cli,tui): OSC 7577 program resume (salvage of #160297)) dans NousResearch/hermes-agent.

    Vérification rapide : code pertinent, tests mentionnés, pas de secrets exposés. Prêt pour merge après approbation.

    ✅ Code review validé. CI : succès. Attend une approbation manuelle pour merge.

    Reviewers
    Assignees
    kshitijk4poor kshitijk4poor
    Labels
    risk: low confidence: 84.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.9% · Lower = rushed or shallow review
    84.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 12.9% · Safe to merge
    12.9%