Skip to content

The agent that grows with you

merge: integrate upstream/main into ethie/pm-clean

ethernet7d2b3b767d6f
diff --cc agent/session_persistence.py
index 5173f2c902d,4817209b1a9..d8fe1ece2c7
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@@ -262,34 -262,8 +262,9 @@@ def _db_flush_failed(agent, e: Exceptio
return False
- def _session_log_entry(agent, msg: Dict[str, Any]) -> Dict[str, Any]:
- """Copy of ``msg`` with scratchpad tags normalised and credentials redacted (honours HERMES_REDACT_SECRETS)."""
- if "content" not in msg:
- return msg
- content = msg["content"]
- if msg.get("role") == "assistant" and content:
- content = agent._clean_session_content(content)
- return {**msg, "content": agent._redact_message_content(content)}
-
-
- def _existing_log_is_larger(log_file, count: int) -> bool:
- """Never overwrite a larger log with fewer messages (resumed agent with partial history); a corrupted
- existing file allows the overwrite."""
- if not log_file.exists():
- return False
- try:
- existing = json.loads(log_file.read_text(encoding="utf-8-sig"))
- existing_count = existing.get("message_count", len(existing.get("messages", [])))
- except Exception:
- return False
- if existing_count > count:
- logging.debug("Skipping session log overwrite: existing has %d messages, current has %d", existing_count, count)
- return True
- return False
-
+
class SessionPersistenceMixin:
- """Session DB flush, session log and trajectory persistence (see module docstring)."""
+ """Session DB flush and trajectory persistence (see module docstring)."""
def _apply_persist_user_message_override(self, messages: List[Dict]) -> None:
"""Rewrite the current-turn user message in place: some paths send an API-only variant that must not
diff --cc apps/desktop/electron/updater/checkout.ts
index d7456888c24,00000000000..da91db47b6d
mode 100644,000000..100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@@ -1,724 -1,0 +1,735 @@@
+// Checkout update policy and handoff execution. The shell supplies process and UI dependencies.
+
+import * as path from 'node:path'
+
+import { clearStaleGitLocks } from '../gitlock'
+import { resolveBehindCount, shouldCountCommits } from '../update-count'
+import { updateHandoffConflict, writeUpdateMarker } from '../update-marker'
+import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from '../update-remote'
+import { classifyUpdateRoot } from '../update-root-policy'
+import {
+ collectRelaunchArgs,
+ observeUpdaterHandoff,
+ resolvePosixScriptHandoff,
+ resolveUpdateScriptHandoff,
+ sandboxFallbackFromEnv,
+ spawnUpdaterProcess,
+ stagedUpdaterSupportsPrewrittenMarker,
++ windowsUpdatePrerequisiteError,
+ wrapHandoffForDetachedConsole
+} from '../updater-process'
+import { formatBlockerMessage, formatProbeFailedMessage, scanVenvBlockers, stopSafeVenvBlockers } from '../venv-blocker-scan'
+
+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 {
+ hermesHome: string
+ isWindows: boolean
+ isMac: boolean
+ defaultUpdateBranch: string
+ updateHandoffDwellMs: number
+ directoryExists: (filePath: string) => boolean
+ readCanonicalInstallStamp: () => { updateMechanism?: string } | null
+ readDesktopUpdateConfig: () => { branch: string }
+ resolveUpdateRoot: () => string
+ resolveUpdaterBinary: () => string | null
+ resolveHealedBranch: (updateRoot: string, branch: string) => Promise<string>
+ getOriginUrl: (updateRoot: string) => Promise<string>
+ runGit: (args: string[], options?: { cwd?: string }) => Promise<{ code: number; stdout: string; stderr: string }>
+ firstLine: (text: string) => string
+ readCommitLog: (
+ cwd: string,
+ branch: string,
+ isShallow: boolean
+ ) => Promise<{ sha: string; summary: string; author: string; at: number }[]>
+ fetchCompareBehindCount: (input: { currentSha: string; originUrl: string; targetSha: string }) => Promise<number | null>
+ pathWithVenvBin: (...entries: string[]) => string
+ venvHermesShimPath: (updateRoot: string) => string
+ emitUpdateProgress: (payload: { stage: string; message: string; percent: number | null }) => void
+ rememberLog: (chunk: unknown) => void
+ startHermes: () => Promise<unknown>
+ startGatewaysAfterUpdateAbort: (shimPath: string) => boolean | void | Promise<boolean | void>
+ releaseBackendLockForUpdate: (updateRoot: string) => Promise<{ unlocked: boolean }>
+ repairMacUpdaterHelper: (updater: string) => void | Promise<void>
+ preflightStateDb: (hermesHome: string, rememberLog: (chunk: string) => void) => 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(): Promise<UpdaterStatusWire> {
+ const status = await checkBody()
+ status.mechanism = mechanism
+
+ return status
+ }
+
+ async function apply(opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire> {
+ const result = await applyBody(opts)
+ result.mechanism = mechanism
+
+ return result
+ }
+
+ return { mechanism, check, apply }
+
+ async function checkBody(): Promise<UpdaterStatusWire> {
+ const updateRoot = deps.resolveUpdateRoot()
+ let { branch } = deps.readDesktopUpdateConfig()
+ const gitDir = path.join(updateRoot, '.git')
+
+ if (!deps.directoryExists(gitDir)) {
+ return {
+ supported: false,
+ reason: 'not-a-git-checkout',
+ message: `${updateRoot} isn't a git checkout — desktop self-update only runs against a source install.`,
+ hermesRoot: updateRoot,
+ branch
+ }
+ }
+
+ // The update-root policy (update-root-policy.ts): a `.git` tree the install
+ // contract does not manage with updateMechanism "self" (or one with no
+ // stamp at all — a dev checkout) is the only legitimate git-update
+ // territory. A steward-owned tree (external / electron-updater) must not be
+ // pulled into from the desktop.
+ const rootStamp = deps.readCanonicalInstallStamp()
+
+ const rootPolicy = classifyUpdateRoot({
+ isGitTree: true,
+ updateMechanism: (rootStamp?.updateMechanism as any) ?? null
+ })
+
+ if (!rootPolicy.updatable) {
+ return {
+ supported: false,
+ reason: `update-root-${rootPolicy.verdict}`,
+ message: rootPolicy.message || `${updateRoot} is not desktop-updatable.`,
+ advice: rootPolicy.advice,
+ hermesRoot: updateRoot,
+ branch
+ }
+ }
+
+ branch = await deps.resolveHealedBranch(updateRoot, branch)
+ const originUrl = await deps.getOriginUrl(updateRoot)
+
+ if (isOfficialSshRemote(originUrl)) {
+ const git = args => deps.runGit(args, { cwd: updateRoot }).then(r => r.stdout.trim())
+
+ const [currentSha, target, dirtyStr, currentBranch] = await Promise.all([
+ git(['rev-parse', 'HEAD']),
+ deps.runGit(['ls-remote', OFFICIAL_REPO_HTTPS_URL, `refs/heads/${branch}`], { cwd: updateRoot }),
+ git(['status', '--porcelain']),
+ git(['rev-parse', '--abbrev-ref', 'HEAD'])
+ ])
+
+ const targetSha = deps.firstLine(target.stdout).split(/\s+/)[0] || ''
+
+ if (target.code !== 0 || !targetSha) {
+ return {
+ supported: true,
+ branch,
+ error: 'fetch-failed',
+ message: deps.firstLine(target.stderr) || 'git ls-remote failed.',
+ hermesRoot: updateRoot,
+ fetchedAt: Date.now()
+ }
+ }
+
+ // Passive SSH-official checks only know tip SHAs (ls-remote) — never
+ // fabricate a "1 commit behind". Recover the exact count via the GitHub
+ // compare API when possible; otherwise behind stays null ("update
+ // available, count unknown") and updateAvailable carries the signal.
+ // ahead_by === 0 with differing tips means the remote tip is reachable
+ // from our HEAD — a local carried commit sitting AHEAD, not behind:
+ // flagging that as an update nudges the user into wiping their work.
+ const tipsEqual = Boolean(currentSha && currentSha === targetSha)
+
+ const sshBehind = tipsEqual
+ ? 0
+ : await deps.fetchCompareBehindCount({ currentSha, originUrl: OFFICIAL_REPO_HTTPS_URL, targetSha })
+
+ const upToDate = tipsEqual || sshBehind === 0
+
+ return {
+ supported: true,
+ branch,
+ currentBranch,
+ behind: upToDate ? 0 : sshBehind,
+ updateAvailable: !upToDate,
+ currentSha,
+ targetSha,
+ commits: [],
+ dirty: dirtyStr.length > 0,
+ hermesRoot: updateRoot,
+ fetchedAt: Date.now()
+ }
+ }
+
+ // Self-heal abandoned git lock files before fetching. A stale
+ // .git/shallow.lock from a crashed/interrupted fetch otherwise fails every
+ // later fetch ("Unable to create '.git/shallow.lock': File exists") and this
+ // check reports 'fetch-failed' forever — git never removes these itself.
+ await clearStaleGitLocks(updateRoot)
+
+ const fetched = await deps.runGit(['fetch', '--quiet', 'origin', branch], { cwd: updateRoot })
+
+ if (fetched.code !== 0) {
+ return {
+ supported: true,
+ branch,
+ error: 'fetch-failed',
+ message: deps.firstLine(fetched.stderr) || 'git fetch failed.',
+ hermesRoot: updateRoot,
+ fetchedAt: Date.now()
+ }
+ }
+
+ const git = args => deps.runGit(args, { cwd: updateRoot }).then(r => r.stdout.trim())
+
+ const [currentSha, targetSha, dirtyStr, currentBranch, shallowStr] = await Promise.all([
+ git(['rev-parse', 'HEAD']),
+ git(['rev-parse', `origin/${branch}`]),
+ git(['status', '--porcelain']),
+ git(['rev-parse', '--abbrev-ref', 'HEAD']),
+ git(['rev-parse', '--is-shallow-repository'])
+ ])
+
+ const isShallow = shallowStr === 'true'
+
+ // A shallow graph cannot provide a trustworthy exact count, even when it has
+ // a visible merge-base. Skip the ancestry walk and use the SHA fallback.
+ const countStr = shouldCountCommits({ isShallow }) ? await git(['rev-list', `HEAD..origin/${branch}`, '--count']) : ''
+
+ // A positive directional ancestry result remains trustworthy in a shallow
+ // graph and prevents a local commit on top of origin from looking outdated.
+ const targetIsAncestorOfHead =
+ isShallow &&
+ currentSha !== targetSha &&
+ (await deps.runGit(['merge-base', '--is-ancestor', `origin/${branch}`, 'HEAD'], { cwd: updateRoot })).code === 0
+
+ let behind = resolveBehindCount({
+ countStr,
+ currentSha,
+ targetSha,
+ isShallow,
+ targetIsAncestorOfHead
+ })
+
+ // Recover the exact count a shallow clone can't compute: the GitHub compare
+ // API knows the full graph regardless of local clone depth. Best-effort —
+ // offline, rate-limited, or non-GitHub origins keep the honest null
+ // ("update available", no fabricated number).
+ if (behind === null) {
+ behind = await deps.fetchCompareBehindCount({ currentSha, originUrl, targetSha })
+ }
+
+ // behind === null means "update available, exact count unknown" (shallow
+ // clone): still list what origin offers — resolveCommitLogSelection keeps
+ // the shallow log to the fetched tip so the range walk can't enumerate the
+ // contaminated ancestry — so "See what's new" stays useful and honest.
+ const commits = behind !== 0 ? await deps.readCommitLog(updateRoot, branch, isShallow) : []
+
+ return {
+ supported: true,
+ branch,
+ currentBranch,
+ behind,
+ updateAvailable: behind === null || behind > 0,
+ currentSha,
+ targetSha,
+ commits,
+ dirty: dirtyStr.length > 0,
+ hermesRoot: updateRoot,
+ fetchedAt: Date.now()
+ }
+ }
+
+ async function applyBody(opts: { stopSafeBlockers?: boolean } = {}): Promise<UpdaterApplyResultWire> {
+ const updater = deps.resolveUpdaterBinary()
+
+ if (!updater && !deps.isWindows) {
+ // 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(opts)
+ }
+
+ if (!updater) {
+ // 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)) {
+ // They DO have a working `hermes` on PATH / in the venv, so the
+ // correct path is the one-liner in their native medium. We show the
+ // EXACT command, branch-pinned to the checkout they're on — bare
+ // `hermes update` defaults to main and would silently switch a
+ // bb/gui (or any non-main) install off-branch. Mirror the GUI
+ // button's contract: append --branch <current> for non-main
+ // checkouts, keep it bare for main so the card stays clean.
+ let command = 'hermes update'
+
+ try {
+ const head = await deps.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
+ const current = (head.stdout || '').trim()
+
+ if (head.code === 0 && current && current !== 'HEAD') {
+ command = buildManualUpdateCommand(await deps.resolveHealedBranch(updateRoot, current))
+ }
+ } catch {
+ // Best-effort: fall back to bare `hermes update` if branch detection fails.
+ }
+
+ 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 { branch: configuredBranch } = deps.readDesktopUpdateConfig()
+ const branch = await deps.resolveHealedBranch(updateRoot, configuredBranch || deps.defaultUpdateBranch)
+ const updaterArgs = ['--update', '--branch', branch]
+ const targetApp = deps.isMac ? deps.runningAppBundle() : null
+
+ if (targetApp) {
+ updaterArgs.push('--target-app', targetApp)
+ }
+
+ const venvBin = path.join(updateRoot, 'venv', deps.isWindows ? 'Scripts' : 'bin')
+
+ // ── 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)
+
++ if (deps.isWindows && resolveUpdateScriptHandoff(updateRoot)) {
++ const message = windowsUpdatePrerequisiteError(updateRoot)
++
++ if (message) {
++ deps.emitUpdateProgress({ stage: 'error', message, percent: null })
++
++ return { ok: false, error: message }
++ }
++ }
++
+ // Stop our own backend(s) and wait for the venv shim to unlock BEFORE we
+ // spawn the updater. Without this the updater races a still-locked
+ // hermes.exe (held by the backend child / its grandchildren) and the update
+ // bricks. See releaseBackendLockForUpdate for the full failure analysis.
+ const lock = await deps.releaseBackendLockForUpdate(updateRoot)
+
+ if (!lock.unlocked) {
+ // Something OUTSIDE this app holds the venv (a second window, a user
+ // terminal running hermes, an unkillable child). Handing off anyway
+ // guarantees a half-updated venv — abort loudly instead and let the
+ // user close the holder and retry. Restart our own backend so the app
+ // keeps working after the failed attempt.
+ const message =
+ 'Update aborted: another process is holding the Hermes install open ' +
+ '(a second Hermes window or a terminal running hermes?). Close it and retry.'
+
+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })
+ deps.startHermes().catch(() => {})
+
+ if (deps.isWindows) {
+ // The pre-gate `gateway stop --all` (#70337) took every profile's
+ // gateway down for an update that never happened — bring them back.
+ deps.startGatewaysAfterUpdateAbort(deps.venvHermesShimPath(updateRoot))
+ }
+
+ return { ok: false, error: message }
+ }
+
+ // Preflight: after releasing our own backends, check for remaining
+ // Hermes processes running from this venv. The updater normally refuses
+ // when it detects a holder, but because the updater is spawned detached
+ // with stdio:ignore, the user never sees that refusal and the update
+ // silently fails. This preflight detects holders early and gives the
+ // user an actionable error. Windows-only; the .pyd lock hazard is a
+ // Windows phenomenon. ALL failures (blocked, missing python, timeout,
+ // malformed output, missing psutil) abort the handoff — never proceed
+ // to the detached updater when the venv state is unknown.
+ if (deps.isWindows) {
+ let scanOutcome = await scanVenvBlockers(updateRoot)
+
+ if (scanOutcome.kind === 'blocked' && opts.stopSafeBlockers) {
+ const stopResult = await stopSafeVenvBlockers(updateRoot, scanOutcome.result)
+ deps.rememberLog(
+ `[updates] user-approved blocker cleanup: stopped=${stopResult.stopped.join(',') || 'none'} failed=${stopResult.failed.join(',') || 'none'}`
+ )
+ // Let verified process-tree termination finish unwinding wrapper shells,
+ // then make the scanner — not the stale renderer payload — authoritative.
+ await new Promise(resolve => setTimeout(resolve, 300))
+ scanOutcome = await scanVenvBlockers(updateRoot)
+ }
+
+ // Re-scan before aborting on 'blocked' (#74805). Process-table teardown
+ // is asynchronous on Windows: even after releaseBackendLock's PID-exit
+ // wait, a grandchild the desktop never tracked (or a process an AV /
+ // NTFS filter driver is holding in teardown) can stay enumerable for a
+ // few more seconds and read as a holder. Each scan already costs
+ // seconds (spawns a venv python + psutil sweep), so two retries with a
+ // short dwell give the table time to settle without meaningfully
+ // delaying the abort path when a REAL holder (a user terminal, second
+ // window) is present — that holder is still there on the third scan.
+ for (let attempt = 0; scanOutcome.kind === 'blocked' && attempt < 2; attempt++) {
+ deps.rememberLog(
+ `[updates] venv-blocker scan reported ${scanOutcome.result.processes.length} holder(s); re-scanning after settle (attempt ${attempt + 2}/3)`
+ )
+ await new Promise(resolve => setTimeout(resolve, 1500))
+ scanOutcome = await scanVenvBlockers(updateRoot)
+ }
+
+ if (scanOutcome.kind === 'blocked') {
+ const message = formatBlockerMessage(scanOutcome.result)
+
+ deps.rememberLog(`[updates] venv-blocked: ${scanOutcome.result.processes.length} process(es) hold the install`)
+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })
+ deps.startHermes().catch(() => {})
+ // Restore the gateways the pre-gate stop took down (#70337 drain
+ // semantics): the update aborted, so nothing else will relaunch them.
+ deps.startGatewaysAfterUpdateAbort(deps.venvHermesShimPath(updateRoot))
+
+ return { ok: false, error: 'venv-blocked', message, blockers: scanOutcome.result.processes }
+ }
+
+ if (scanOutcome.kind === 'probe-failure') {
+ const message = formatProbeFailedMessage(scanOutcome.error)
+
+ deps.rememberLog(`[updates] venv-blocker probe failed: ${scanOutcome.error}`)
+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })
+ deps.startHermes().catch(() => {})
+ // Same drain-semantics restore as the venv-blocked abort above.
+ deps.startGatewaysAfterUpdateAbort(deps.venvHermesShimPath(updateRoot))
+
+ return { ok: false, error: 'venv-probe-failed', message }
+ }
+ }
+
+ // Detached so the updater outlives this process — it needs us GONE before
+ // `hermes update` will run (the venv shim is locked while we live).
+ //
+ // 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,
+ '-Branch',
+ branch,
+ '-DesktopPid',
+ String(process.pid),
+ '-RelaunchExe',
+ process.execPath
+ ])
+
+ child = spawnUpdaterProcess(wrapped.command, wrapped.args, {
+ cwd: deps.hermesHome,
+ env: {
+ ...process.env,
+ HERMES_HOME: deps.hermesHome,
+ HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
+ PATH: deps.pathWithVenvBin(venvBin)
+ },
+ 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} (branch ${branch}); exiting desktop to release venv shim`
+ )
+ } else {
+ child = spawnUpdaterProcess(updater, updaterArgs, {
+ cwd: deps.hermesHome,
+ env: {
+ ...process.env,
+ HERMES_HOME: deps.hermesHome,
+ PATH: deps.pathWithVenvBin(venvBin)
+ },
+ 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 and spawn a fresh backend that re-locks .pyd files in
+ // the venv. 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 to release venv shim`
+ )
+ }
+
+ // 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 to release the venv shim. 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(() => {})
+
+ if (deps.isWindows) {
+ // Same drain-semantics restore as the earlier abort paths (#70337).
+ deps.startGatewaysAfterUpdateAbort(deps.venvHermesShimPath(updateRoot))
+ }
+
+ 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(opts: any): Promise<UpdaterApplyResultWire> {
+ const updateRoot = deps.resolveUpdateRoot()
+ const handoff = resolvePosixScriptHandoff(updateRoot)
+
+ if (!handoff) {
+ deps.emitUpdateProgress({ stage: 'manual', message: 'hermes update', percent: null })
+
+ return { ok: true, manual: true, command: 'hermes update', 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)
+
+ // Branch-pin so a non-main checkout doesn't get switched to main (and
+ // self-heal to main when the pinned branch no longer exists on origin).
+ let branch = 'main'
+
+ try {
+ const head = await deps.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
+ const current = (head.stdout || '').trim()
+
+ if (head.code === 0 && current && current !== 'HEAD') {
+ branch = await deps.resolveHealedBranch(updateRoot, current)
+ }
+ } catch {
+ // best effort
+ }
+
+ const args = [...handoff.args, '--install-root', updateRoot, '--branch', branch, '--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: {
+ ...process.env,
+ HERMES_HOME: deps.hermesHome,
+ HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
+ PATH: deps.pathWithVenvBin(path.join(updateRoot, 'venv', 'bin'))
+ },
+ 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} (branch ${branch}); 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/src/i18n/ar.ts
index 5f6edee798c,42e2bced565..cfa5ac0fc3e
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@@ -1702,8 -1751,10 +1725,8 @@@ export const ar = defineLocale(
skills: 'المهارات',
messaging: 'المراسلة',
artifacts: 'العناصر',
- chat: 'المحادثة',
- settings: 'الإعدادات',
cron: 'المهام المجدولة',
- 'session-import': 'استيراد جلسة'
+ agents: 'الوكلاء'
},
searchAria: 'البحث في الجلسات',
searchPlaceholder: 'البحث في الجلسات...',
diff --cc cron/scheduler_prompt.py
index 7cfb5463fa0,c0e858ea057..405bdfac66f
--- a/cron/scheduler_prompt.py
+++ b/cron/scheduler_prompt.py
@@@ -91,9 -91,20 +91,20 @@@ def _inject_context_from(job: dict, pro
(output_dir / source_job_id).glob("*.md"), key=lambda f: f.stat().st_mtime,
reverse=True,
)
- if not output_files:
- continue # silent skip — no output yet
- latest_output = output_files[0].read_text(encoding="utf-8-sig").strip()
+ latest_output = ""
+ for output_file in output_files:
- candidate = output_file.read_text(encoding="utf-8").strip()
++ candidate = output_file.read_text(encoding="utf-8-sig").strip()
+ # Only the run header describes suppression; script/agent payloads can
+ # quote these markers. Keep error documents useful for recovery context.
+ header = candidate.split("\n---\n", 1)[0].split("\n## Prompt", 1)[0]
+ silent_audit = candidate.startswith("# Cron Job:") and any(
+ line.startswith(("**Status:** no_change", "**Status:** silent",
+ "Script gate returned `wakeAgent=false`"))
+ for line in header.splitlines()
+ )
+ if candidate and not silent_audit:
+ latest_output = candidate
+ break
if len(latest_output) > _MAX_CONTEXT_CHARS:
latest_output = (
latest_output[:_MAX_CONTEXT_CHARS] + "\n\n[... output truncated ...]")
diff --cc evals/codex_echo/fixture_server.py
index 00000000000,fd01e1a6646..fd01e1a6646
mode 000000,100755..100644
--- a/evals/codex_echo/fixture_server.py
+++ b/evals/codex_echo/fixture_server.py
diff --cc hermes_cli/update_cmd.py
index 9796df111ef,beba4e72bf0..211f8e1e5c3
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@@ -19,7 -18,7 +19,7 @@@ from pathlib import Pat
from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)
from hermes_cli.update_cmd_common import _best_effort
--from hermes_constants import get_default_hermes_root, venv_python_path
++from hermes_constants import venv_python_path
# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
from hermes_cli.update_abort_recovery import ( # noqa: F401
@@@ -594,181 -427,46 +596,195 @@@ def _log_only_write(text: str) -> None
def _run_logged_subprocess(cmd, *, cwd=None, env=None):
- """Run ``cmd`` capturing combined output into update.log (not the terminal).
-
- Returns the ``CompletedProcess`` (with ``stdout`` populated) so the caller
- can decide whether to surface the captured output on failure.
- """
- result = subprocess.run(
- cmd,
- cwd=cwd,
- env=env,
- check=False,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- _log_only_write(result.stdout or "")
- return result
+ """Stream combined build output to update.log, retaining it for failure reporting."""
+ import codecs
+ import io
+ from hermes_cli._subprocess_compat import kill_process_tree, windows_hide_flags
+
+ child_env = dict(os.environ if env is None else env)
+ child_env.setdefault("PYTHONUNBUFFERED", "1")
+ spawn = {"creationflags": windows_hide_flags()} if os.name == "nt" else {"process_group": 0}
+ proc = subprocess.Popen(
+ cmd, cwd=cwd, env=child_env, stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **spawn)
+ # read1 delivers partial lines too; incremental decoding preserves split UTF-8
+ # and the universal-newline behavior callers previously got from text=True.
+ decoder = io.IncrementalNewlineDecoder(codecs.getincrementaldecoder("utf-8")("replace"), True)
+ output = []
+ try:
+ while True:
+ chunk = proc.stdout.read1(8192)
+ text = decoder.decode(chunk, final=not chunk)
+ output.append(text)
+ _log_only_write(text)
+ if not chunk:
+ break
+ return subprocess.CompletedProcess(cmd, proc.wait(), stdout="".join(output))
+ except BaseException:
+ # Unlike Popen.__exit__, do not wait for a cancelled build to finish.
+ kill_process_tree(proc)
+ with suppress(subprocess.TimeoutExpired):
+ proc.wait(timeout=5)
+ raise
+ finally:
+ proc.stdout.close()
+_RELEASE_TAG_RE = re.compile(r"^v(0|[1-9]\d{0,2})\.(\d+)\.(\d+)$")
+def _parse_release_tag(tag: str):
+ """Parse ``vX.Y.Z`` into a sortable (X, Y, Z) tuple, or return None.
+
+ Tags with a pre-release or build suffix (``v1.2.3-rc1``) return None.
+ Tags that do not have the shape of a final release also return None.
+ The stable channel only moves between final releases.
+ """
+ m = _RELEASE_TAG_RE.match(tag.strip())
+ if not m:
+ return None
+ return tuple(int(g) for g in m.groups())
+def _latest_release_tag_from_ls_remote(output: str):
+ """Select the newest final-release tag from ``git ls-remote --tags`` output.
+
+ Returns ``(tag, sha)`` or ``(None, None)``. Peeled entries (``^{}``) have
+ priority over the tag-object SHA. Thus annotated tags and lightweight tags
+ both give the commit SHA.
+ """
+ best = None # (version_tuple, tag)
+ shas = {} # tag -> commit sha (peeled wins)
+ for line in output.splitlines():
+ parts = line.split("\t")
+ if len(parts) != 2:
+ continue
+ sha, ref = parts
+ if not ref.startswith("refs/tags/"):
+ continue
+ name = ref[len("refs/tags/"):]
+ peeled = name.endswith("^{}")
+ if peeled:
+ name = name[:-3]
+ version = _parse_release_tag(name)
+ if version is None:
+ continue
+ if peeled or name not in shas:
+ shas[name] = sha.strip()
+ if best is None or version > best[0]:
+ best = (version, name)
+ if best is None:
+ return None, None
+ tag = best[1]
+ return tag, shas.get(tag)
+def _resolve_latest_release_tag(git_cmd, cwd):
+ """Ask origin for the newest final release tag. Returns (tag, sha) or (None, None)."""
+ try:
+ result = subprocess.run(
+ git_cmd + ["ls-remote", "--tags", "origin", "v*"],
+ cwd=cwd,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ timeout=60,
+ )
+ except (subprocess.TimeoutExpired, OSError) as exc:
+ logger.warning("Could not list release tags from origin: %s", exc)
+ return None, None
+ if result.returncode != 0:
+ logger.warning(
+ "git ls-remote --tags failed: %s",
+ (result.stderr or "").strip().splitlines()[:1],
+ )
+ return None, None
+ return _latest_release_tag_from_ls_remote(result.stdout)
+def _stable_channel_active(args) -> bool:
+ """Return True when this update must track tagged releases, not a branch.
+
+ ``args`` is the update argparse namespace, or None when the caller has no
+ flags to honor. An explicit ``--branch`` always wins (the user names the
+ exact update target; a tag silently overriding it would resurrect the bug
+ class --branch prevents). An explicit ``--channel`` is the transient
+ per-invocation override (``--set-channel`` is the persistent one). In all
+ other cases the effective channel comes from the per-install record
+ (see hermes_cli.update_channel.resolve_update_channel).
+ """
+ if getattr(args, "branch", None):
+ return False
+ transient = getattr(args, "channel", None)
+ if transient:
+ from hermes_cli.update_channel import CHANNEL_STABLE
+
+ # canary on a source tree normalizes to main (not stable).
+ return transient == CHANNEL_STABLE
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.update_channel import CHANNEL_STABLE, resolve_update_channel
+
+ config = None
+ try:
+ config = load_config()
+ except Exception as exc:
+ logger.debug("Could not load config for channel resolution: %s", exc)
+ return resolve_update_channel(config, _m().PROJECT_ROOT) == CHANNEL_STABLE
+ except Exception as exc:
+ logger.warning("Channel resolution failed; defaulting to main: %s", exc)
+ return False
+def _github_latest_release_tag():
+ """Resolve the newest final-release tag with the GitHub API (no git necessary).
+
+ The ZIP-fallback path uses this function. That path exists because git
+ file I/O is broken. The function tries /releases/latest first, because that
+ endpoint obeys the draft and prerelease curation. If that fails, it lists
+ the tags and selects the maximum final release.
+ Returns the tag name or None.
+ """
+ import urllib.error
+ import urllib.request
+
+ def _get_json(url):
+ req = urllib.request.Request(
+ url, headers={"Accept": "application/vnd.github+json",
+ "User-Agent": "hermes-update"}
+ )
+ with urllib.request.urlopen(req, timeout=30) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+
+ base = "https://api.github.com/repos/NousResearch/hermes-agent"
+ try:
+ data = _get_json(f"{base}/releases/latest")
+ tag = data.get("tag_name")
+ if isinstance(tag, str) and _parse_release_tag(tag) is not None:
+ return tag
+ except (urllib.error.URLError, OSError, ValueError) as exc:
+ logger.debug("GitHub /releases/latest unavailable: %s", exc)
+ try:
+ tags = _get_json(f"{base}/tags?per_page=100")
+ best = None
+ for entry in tags if isinstance(tags, list) else []:
+ name = entry.get("name") if isinstance(entry, dict) else None
+ version = _parse_release_tag(name) if isinstance(name, str) else None
+ if version is not None and (best is None or version > best[0]):
+ best = (version, name)
+ return best[1] if best else None
+ except (urllib.error.URLError, OSError, ValueError) as exc:
+ logger.debug("GitHub /tags unavailable: %s", exc)
+ return None
+
+
def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):
- """``hermes update --check``: fetch and report without installing. ``branch_explicit`` is
- True iff --branch was passed (Docker installs print a notice instead of dropping the flag)."""
- # Same marker-first admission gate as the apply path, so --check never reports git
- # state for an install whose real update mechanism is an image pull.
- from hermes_cli.update_contract import evaluate_update_admission, record_refusal_receipt
+ """Implement ``hermes update --check``: fetch and report without installing.
+
+ ``branch`` selects which branch the check compares against. Default is
+ "main"; callers can pass another branch to ask "are there new commits
+ on origin/<branch>?" without performing the update.
+
+ ``branch_explicit`` is True iff the caller passed --branch on the CLI.
+ Installs that can't honor non-default branches (e.g. Docker) surface a
+ one-line notice instead of silently dropping the flag.
+ """
+ # Shared admission gate (#91277 Phase 3): same marker-first decision as
+ # the apply path, so --check can never report git state for an install
+ # whose real update mechanism is an image pull.
+ from hermes_cli.update_contract import (
+ evaluate_update_admission,
+ record_refusal_receipt,
+ )
refusal = evaluate_update_admission(_m().PROJECT_ROOT)
if refusal is not None:
diff --cc plugins/platforms/dingtalk/adapter.py
index e5f2a049313,a8f8452b320..4c3700d7307
--- a/plugins/platforms/dingtalk/adapter.py
+++ b/plugins/platforms/dingtalk/adapter.py
@@@ -48,9 -48,10 +48,10 @@@ except Exception
from gateway.config import Platform, PlatformConfig
from gateway.platforms.helpers import MessageDeduplicator, compile_mention_patterns
- from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult
+ from gateway.platforms.base import BasePlatformAdapter, SendResult
-from gateway.platforms.event import MessageEvent
++from gateway.platforms.event import MessageEvent, MessageType
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
-from plugins.platforms.dingtalk.inbound import collect_download_codes, extract_media, extract_text
+from plugins.platforms.dingtalk.inbound import DINGTALK_TYPE_MAPPING
logger = logging.getLogger(__name__)
@@@ -1856,9 -739,33 +1857,9 @@@ def register(ctx) -> None
)
-# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
-# Names external plugins imported from this module before the Sep 2026 decomposition.
-# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
-# The whole block is removed by reverting the commit that added it.
-
-EXT_MAP = {
- "pdf": "application/pdf",
- "png": "image/png",
- "jpg": "image/jpeg",
- "jpeg": "image/jpeg",
- "gif": "image/gif",
- "webp": "image/webp",
- "doc": "application/msword",
- "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
- "xls": "application/vnd.ms-excel",
- "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "md": "text/markdown",
- "txt": "text/plain",
- "csv": "text/csv",
- "zip": "application/zip",
- "mp4": "video/mp4",
-}
-
-
_PLUGIN_COMPAT_LAZY = {
'DINGTALK_TYPE_MAPPING': ('plugins.platforms.dingtalk.inbound', 'DINGTALK_TYPE_MAPPING'),
- 'MessageType': ('gateway.platforms.base', 'MessageType'),
+ 'MessageType': ('gateway.platforms.event', 'MessageType'),
}
diff --cc plugins/platforms/photon/adapter.py
index c7028aa10c5,a9659dae2c2..ce44e43f6b6
--- a/plugins/platforms/photon/adapter.py
+++ b/plugins/platforms/photon/adapter.py
@@@ -35,10 -35,11 +35,11 @@@ else
HTTPX_AVAILABLE = False
httpx = None
-from gateway.config import Platform, PlatformConfig
+from gateway.config import Platform, PlatformConfig, _coerce_float, _coerce_int
from gateway.platforms._shared import coerce_port as _coerce_port
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
- from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult
+ from gateway.platforms.base import BasePlatformAdapter, SendResult
+ from gateway.platforms.event import MessageEvent, MessageType
from gateway.platforms.helpers import compile_mention_patterns, strip_markdown
from .auth import load_project_credentials
diff --cc pyproject.toml
index 23c79e51f32,d5e7131e763..b8c802088de
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -217,24 -197,10 +217,24 @@@ daytona = ["daytona==0.155.0"
vercel = ["vercel==0.7.2"]
hindsight = ["hindsight-client==0.6.1"]
dev = ["debugpy==1.8.20", "pytest==9.1.1", "pytest-asyncio==1.3.0", "mcp==2.0.0", "httpx2==2.7.0", "starlette==1.3.1", "ty==0.0.21", "ruff==0.15.10", "setuptools==83.0.0"] # starlette: CVE-2026-48710; setuptools: 83 (torch >=2.13 requires setuptools 83)
+
- messaging = ["python-telegram-bot[webhooks]==22.8", "discord.py[voice]==2.7.1", "aiohttp==3.14.3", "brotlicffi==1.2.0.1", "slack-bolt==1.30.0", "slack-sdk==3.43.0", "qrcode==7.4.2"] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
+ messaging = ["python-telegram-bot[webhooks]==22.8", "discord.py[voice]==2.7.1", "aiohttp==3.14.3", "brotlicffi==1.2.0.2", "slack-bolt==1.30.0", "slack-sdk==3.43.0", "qrcode==7.4.2"] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
cron = [] # croniter is now a core dependency; this extra kept for back-compat
slack = ["slack-bolt==1.30.0", "slack-sdk==3.43.0", "aiohttp==3.14.3"]
-matrix = ["mautrix[encryption]==0.21.1", "aiosqlite==0.22.1", "asyncpg==0.31.0", "aiohttp-socks==0.11.0", "aiohttp==3.14.3"] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7 (mautrix/aiohttp-socks only cap aiohttp<4 / >=3.10, so pin the patched floor directly)
+# Matrix gateway deps. `mautrix[encryption]` pulls `python-olm`, whose
+# vendored libolm (archived 2023) cannot build on Windows or modern macOS:
+# no wheels for those targets AND the sdist fails to compile on current
+# clang/MSVC (olm/list.hh const-iterator error) and on CMake >= 4. It is
+# linux-only — gate the whole extra so `uv sync --all-extras` (the bundle
+# build) doesn't try to build python-olm on the win/darwin lanes. The
+# matrix adapter degrades gracefully without mautrix (import stubs).
+matrix = [
+ "mautrix[encryption]==0.21.1; sys_platform == 'linux'",
+ "aiosqlite==0.22.1; sys_platform == 'linux'",
+ "asyncpg==0.31.0; sys_platform == 'linux'",
+ "aiohttp-socks==0.11.0; sys_platform == 'linux'",
+ "aiohttp==3.14.3; sys_platform == 'linux'",
+] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7 (mautrix/aiohttp-socks only cap aiohttp<4 / >=3.10, so pin the patched floor directly)
# WeCom callback-mode adapter — parses untrusted XML POST bodies from
# WeCom-controlled callback endpoints, so we use defusedxml (drop-in
# replacement for stdlib xml.etree.ElementTree) to block billion-laughs
diff --cc tests/agent/test_compression_attempt_lifecycle.py
index aeefbf58b42,15a24db7eb6..4d03f1267b3
--- a/tests/agent/test_compression_attempt_lifecycle.py
+++ b/tests/agent/test_compression_attempt_lifecycle.py
@@@ -100,8 -100,9 +100,9 @@@ class TestWorkerTeardownOnCeiling
worker=cooperative_worker,
messages=original,
system_prompt_fallback="fallback",
- # Keep idle expiry out of this total-ceiling test under runner load.
-- idle_timeout_seconds=2.0,
- total_ceiling_seconds=0.2,
++ # Keep idle expiry outside the total-ceiling test budget.
++ idle_timeout_seconds=10.0,
+ total_ceiling_seconds=4.0,
fence=fence,
stall_fallback=False,
)
diff --cc tests/agent/test_compression_worker_isolation_76354.py
index 53f3d5d0188,e6cb046ba74..81d76d8e02a
--- a/tests/agent/test_compression_worker_isolation_76354.py
+++ b/tests/agent/test_compression_worker_isolation_76354.py
@@@ -172,9 -157,14 +172,10 @@@ def test_host_timeout_releases_pool_slo
db.create_session(session_id, source="cli")
agent = _build_agent_with_db(db, session_id)
agent._cached_system_prompt = "sys"
- monkeypatch.setattr(
- "agent.conversation_compression.resolve_context_compression_timeouts",
- # Allow provider-thread startup under the parallel runner before timing out.
- lambda cfg=None: (2.0, 4.0),
- )
+
provider_started = threading.Event()
release_provider = threading.Event()
+ futures = _timeout_after_entry(monkeypatch, provider_started)
def _blocked_provider(_kwargs):
provider_started.set()
diff --cc tests/agent/test_deadline_fork_race.py
index 00000000000,1a21ea0f885..72c79b8b7f9
mode 000000,100644..100644
--- a/tests/agent/test_deadline_fork_race.py
+++ b/tests/agent/test_deadline_fork_race.py
@@@ -1,0 -1,66 +1,66 @@@
+ """Real-process deadline regression; the probe owns and reaps its whole subtree."""
+ import os
+ from pathlib import Path
+ import subprocess
+ import signal
+ import sys
+ import time
+
+ import pytest
+
+
+ def test_cron_timeout_closes_the_descendant_snapshot_fork_window(tmp_path):
+ probe = Path(__file__).resolve().parents[2] / "evals" / "cron_timeout_fork_race.py"
+ result = subprocess.run(
+ [sys.executable, str(probe)],
+ env={**os.environ, "HOME": str(tmp_path), "HERMES_HOME": str(tmp_path)},
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=35,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+ @pytest.mark.parametrize("initially_stopped", [False, True])
+ def test_refused_hard_kill_preserves_the_targets_original_run_state(monkeypatch, initially_stopped):
+ import psutil
+ from agent.deadline import kill_process_tree
+
+ proc = subprocess.Popen(
+ [sys.executable, "-c", "import time; time.sleep(30)"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ process = psutil.Process(proc.pid)
+ real_kill, real_killpg = os.kill, os.killpg
+
+ def refuse_owned_kill(pid, sig):
+ assert pid == proc.pid
+ if sig == signal.SIGKILL:
+ raise PermissionError("owned probe: hard kill refused")
+ return real_kill(pid, sig)
+
+ def refuse_owned_group(pgid, sig):
+ assert pgid == proc.pid
+ if sig == signal.SIGKILL:
+ raise PermissionError("owned probe: hard kill refused")
+ return real_killpg(pgid, sig)
+
+ def wait_for_state(stopped):
+ deadline = time.monotonic() + 5
+ while (process.status() == psutil.STATUS_STOPPED) != stopped and time.monotonic() < deadline:
+ time.sleep(0.005)
+ assert (process.status() == psutil.STATUS_STOPPED) == stopped
+
+ try:
+ if initially_stopped:
+ process.suspend()
+ wait_for_state(True)
+ with monkeypatch.context() as patcher:
+ patcher.setattr(os, "kill", refuse_owned_kill)
+ patcher.setattr(os, "killpg", refuse_owned_group)
+ assert kill_process_tree(proc.pid) is False
+ wait_for_state(initially_stopped)
+ finally:
+ proc.kill()
+ proc.wait(timeout=5)
diff --cc tests/cron/test_cron_kanban_env_isolation.py
index 5be367af988,9e8badc95f0..a1c2a64e52d
--- a/tests/cron/test_cron_kanban_env_isolation.py
+++ b/tests/cron/test_cron_kanban_env_isolation.py
@@@ -380,73 -379,38 +379,38 @@@ class TestRunJobKanbanIsolation
assert after == before, "worker identity must survive concurrent cron jobs"
- # ---------------------------------------------------------------------------
- # Drift guard
- # ---------------------------------------------------------------------------
-
- def test_every_dispatcher_kanban_var_is_identity_gated():
- """Invariant: every HERMES_KANBAN_* var the dispatcher injects is covered by
- the canonical KANBAN_ENV_KEYS, so the delegate_task subprocess scrubber and
- any future consumer stay in sync with ``_default_spawn``.
-
- Fails loudly if a new dispatcher var is added without registering it.
- """
- import hermes_cli.kanban_db_dispatch as kanban_db_dispatch
- from agent.delegation_context import KANBAN_ENV_KEYS
-
- source = ast.parse(open(kanban_db_dispatch.__file__, encoding="utf-8").read())
- spawn = next(
- node for node in ast.walk(source)
- if isinstance(node, ast.FunctionDef) and node.name == "_default_spawn"
- )
-
- injected = set()
- for node in ast.walk(spawn):
- # env["HERMES_KANBAN_X"] = ... and the annotated form
- if isinstance(node, (ast.Assign, ast.AnnAssign)):
- targets = node.targets if isinstance(node, ast.Assign) else [node.target]
- for target in targets:
- if not isinstance(target, ast.Subscript):
- continue
- if ast.unparse(target.value) != "env":
- continue
- key = ast.unparse(target.slice).strip("\"'")
- if key.startswith("HERMES_KANBAN_"):
- injected.add(key)
- # env.update({"HERMES_KANBAN_X": ...}) / env.setdefault("HERMES_KANBAN_X", ...)
- elif isinstance(node, ast.Call):
- func = ast.unparse(node.func)
- if func not in ("env.update", "env.setdefault"):
- continue
- literals = []
- for arg in node.args:
- if isinstance(arg, ast.Dict):
- literals.extend(
- k for k in arg.keys if isinstance(k, ast.Constant)
- )
- elif isinstance(arg, ast.Constant):
- literals.append(arg)
- for kw in node.keywords:
- if kw.arg and kw.arg.startswith("HERMES_KANBAN_"):
- injected.add(kw.arg)
- for lit in literals:
- if isinstance(lit.value, str) and lit.value.startswith(
- "HERMES_KANBAN_"
- ):
- injected.add(lit.value)
-
- assert injected, "failed to parse dispatcher kanban env injection"
-
- # These are worker-behaviour knobs rather than board/task identity; they are
- # intentionally not part of KANBAN_ENV_KEYS. Listed explicitly so adding a
- # new var forces a decision instead of silently passing.
- behaviour_only = {
- "HERMES_KANBAN_BRANCH",
- "HERMES_KANBAN_GOAL_MODE",
- "HERMES_KANBAN_GOAL_MAX_TURNS",
- }
- uncovered = injected - set(KANBAN_ENV_KEYS) - behaviour_only
- assert not uncovered, (
- f"dispatcher injects {sorted(uncovered)} which is neither in "
- "KANBAN_ENV_KEYS nor explicitly classified as behaviour-only"
+ def test_dispatcher_grants_only_the_assigned_worker_scope(tmp_path, monkeypatch):
+ import json
+ from pathlib import Path
+ import sys
+ from hermes_cli import kanban_db as kb
+ from hermes_cli.kanban_db_connect import connect
+ from hermes_cli.kanban_db_dispatch import _default_spawn
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ db = tmp_path / "board.db"
+ monkeypatch.setenv("HERMES_KANBAN_DB", str(db))
+ conn = connect(db)
+ tid = kb.create_task(conn, title="assigned child", assignee="default")
+ kb.claim_task(conn, tid)
+ task = kb.get_task(conn, tid)
+ output = tmp_path / "worker-result.json"
+ worker = tmp_path / "fixture-worker"
+ root = str(Path(__file__).resolve().parents[2])
+ worker.write_text(
+ f"#!{sys.executable}\nimport sys, os, json;sys.path.insert(0, {root!r})\n"
+ "from tools.kanban_tools import _handle_complete\n"
+ f"result=_handle_complete({{'summary':'assigned worker'}});open({str(output)!r}, 'w').write(result)\n"
)
+ worker.chmod(0o700)
+ monkeypatch.setenv("HERMES_BIN", str(worker))
+ # Building a new worker under an existing task must replace, not inherit, its scope.
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "prior-task")
+ pid = _default_spawn(task, str(tmp_path), board="default")
+ assert pid is not None
+ os.waitpid(pid, 0) # windows-footgun: ok — Linux-only real dispatcher spawn
+ assert json.loads(output.read_text())["ok"]
+ assert kb.get_task(conn, tid).status == "done"
+ assert os.environ["HERMES_KANBAN_TASK"] == "prior-task"
+ conn.close()
diff --cc tests/gateway/test_feishu.py
index 7142d77c145,24f64629917..bc6f6ac3697
--- a/tests/gateway/test_feishu.py
+++ b/tests/gateway/test_feishu.py
@@@ -10,24 -10,14 +10,27 @@@ import unittes
from collections import OrderedDict
from pathlib import Path
from types import SimpleNamespace
- from typing import Dict
+ from typing import TYPE_CHECKING, Dict
from unittest.mock import AsyncMock, Mock, patch
- from gateway.platforms.base import ProcessingOutcome
+ from gateway.platforms.event import ProcessingOutcome
+
+ if TYPE_CHECKING:
+ from plugins.platforms.feishu.adapter import FeishuAdapter
+import pytest
+_SYS_ENV = {}
+
+
[email protected](autouse=True)
+def _isolated_adapter_env(monkeypatch, tmp_path):
+ # Clear only the adapter settings. Whole-environment replacement discards
+ # conftest's sandbox and sends background persistence into the real home.
+ for key in tuple(os.environ):
+ if key.startswith(("FEISHU_", "LARK_")):
+ monkeypatch.delenv(key)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+
try:
import lark_oapi
_HAS_LARK_OAPI = True
@@@ -917,10 -907,10 +920,10 @@@ class TestAdapterBehavior(unittest.Test
self.assertEqual(response.status, 401)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=False)
def test_process_inbound_message_uses_event_sender_identity_only(self):
from gateway.config import PlatformConfig
- from gateway.platforms.base import MessageType
+ from gateway.platforms.event import MessageType
from plugins.platforms.feishu.adapter import FeishuAdapter
adapter = FeishuAdapter(PlatformConfig())
@@@ -1015,10 -1004,10 +1018,10 @@@
self.assertEqual(first.text, "A\nB")
self.assertEqual(second.text, "C")
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=False)
def test_media_batch_merges_rapid_photo_messages(self):
from gateway.config import PlatformConfig
- from gateway.platforms.base import MessageEvent, MessageType
+ from gateway.platforms.event import MessageEvent, MessageType
from plugins.platforms.feishu.adapter import FeishuAdapter
from gateway.session import SessionSource
diff --cc tests/hermes_cli/test_cmd_update.py
index aca627cf02b,d91a8482ccf..0d00b1e5a28
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@@ -1051,13 -1120,8 +1051,13 @@@ class TestNodeRuntimeNpmResolution
from hermes_cli import main as hm
from hermes_cli import update_cmd
- desktop_dir = PROJECT_ROOT / "apps" / "desktop"
+ # Resolved live: the module autouse fixture pins PROJECT_ROOT to
+ # tmp_path, so the imported constant would be stale here.
+ desktop_dir = hm.PROJECT_ROOT / "apps" / "desktop"
+ # The rebuild gate requires a desktop workspace with a package.json;
+ # under the fixture's tmp PROJECT_ROOT nothing exists on disk.
+ desktop_dir.mkdir(parents=True, exist_ok=True)
- (desktop_dir / "package.json").write_text("{}")
+ (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="")
diff --cc tests/hermes_cli/test_gateway_linger.py
index 95cee306550,3182f87f742..b9d40b71eed
--- a/tests/hermes_cli/test_gateway_linger.py
+++ b/tests/hermes_cli/test_gateway_linger.py
@@@ -27,9 -26,10 +27,9 @@@ class TestEnsureLingerEnabled
def test_loginctl_success_enables_linger(self, monkeypatch, capsys):
monkeypatch.setattr(gateway, "is_linux", lambda: True)
- monkeypatch.setattr(gateway, "is_termux", lambda: False)
monkeypatch.setattr("getpass.getuser", lambda: "testuser")
monkeypatch.setattr(gateway, "Path", lambda _path: SimpleNamespace(exists=lambda: False))
- monkeypatch.setattr(gateway, "get_systemd_linger_status", lambda: (False, ""))
+ monkeypatch.setattr(gateway, "get_systemd_linger_status", lambda username=None: (False, ""))
monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/loginctl")
run_calls = []
@@@ -50,9 -50,10 +50,9 @@@
def test_loginctl_failure_shows_manual_guidance(self, monkeypatch, capsys):
monkeypatch.setattr(gateway, "is_linux", lambda: True)
- monkeypatch.setattr(gateway, "is_termux", lambda: False)
monkeypatch.setattr("getpass.getuser", lambda: "testuser")
monkeypatch.setattr(gateway, "Path", lambda _path: SimpleNamespace(exists=lambda: False))
- monkeypatch.setattr(gateway, "get_systemd_linger_status", lambda: (False, ""))
+ monkeypatch.setattr(gateway, "get_systemd_linger_status", lambda username=None: (False, ""))
monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/loginctl")
monkeypatch.setattr(
gateway.subprocess,
diff --cc tests/hermes_cli/test_gateway_service.py
index e3edfd4b14a,0ef1687906c..6b57fd322ca
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@@ -1382,16 -1294,31 +1397,34 @@@ class TestSystemUnitHermesHome
assert entries == ["/opt/external-node/bin"]
+ def test_system_unit_orders_after_target_user_manager(self, monkeypatch, tmp_path):
+ """#104893: restart-safe workers need user@<uid>.service; the system unit must not race it at boot."""
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path))
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ monkeypatch.setattr(
+ gateway_cli, "_system_service_identity",
+ lambda run_as_user=None: ("alice", "alice", str(tmp_path), 1001),
+ )
+ monkeypatch.setattr(gateway_cli, "_build_service_path_dirs", lambda: [])
+
+ system_unit = gateway_cli.generate_systemd_unit(system=True, run_as_user="alice")
+ user_unit = gateway_cli.generate_systemd_unit(system=False)
+
+ unit_section = system_unit.split("[Service]")[0]
+ assert "[email protected]" in unit_section
+ assert "[email protected]" in unit_section
+ assert "user@" not in user_unit
+
- def test_system_unit_uses_target_user_home_not_calling_user(self, monkeypatch):
- # Simulate sudo: Path.home() returns /root, target user is alice
- monkeypatch.setattr(Path, "home", staticmethod(lambda: Path("/root")))
- monkeypatch.delenv("HERMES_HOME", raising=False)
+ def test_system_unit_uses_target_user_home_not_calling_user(self, monkeypatch, tmp_path):
+ caller_home = tmp_path / "root"
+ target_home = tmp_path / "alice"
+ caller_home.mkdir()
+ target_home.mkdir()
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: caller_home))
+ monkeypatch.setenv("HERMES_HOME", str(caller_home / ".hermes"))
monkeypatch.setattr(
gateway_cli, "_system_service_identity",
- lambda run_as_user=None: ("alice", "alice", str(target_home)),
- lambda run_as_user=None: ("alice", "alice", "/home/alice", 1001),
++ lambda run_as_user=None: ("alice", "alice", str(target_home), 1001),
)
monkeypatch.setattr(
gateway_cli, "_build_user_local_paths",
diff --cc tests/hermes_cli/test_gateway_user_bus_adoption.py
index 00000000000,a8737241bac..88ae7fe145f
mode 000000,100644..100644
--- a/tests/hermes_cli/test_gateway_user_bus_adoption.py
+++ b/tests/hermes_cli/test_gateway_user_bus_adoption.py
@@@ -1,0 -1,76 +1,76 @@@
+ """#104893: a gateway started by a system-level systemd unit adopts its own user bus at boot."""
+
+ import os
+
+ import pytest
+
+ import hermes_cli.gateway as gw
+
+
+ class _BootReached(Exception):
+ """Stands in for the first boot step past the adoption call."""
+
+
+ def _fake_user_bus(monkeypatch, *, present: bool) -> str:
+ """Fake the on-disk state ``loginctl enable-linger`` leaves behind (or its absence)."""
+ runtime_dir = f"/run/user/{os.getuid()}"
+ monkeypatch.setattr(
+ gw, "_runtime_dir_is_ours", lambda d: present and str(d) == runtime_dir)
+ monkeypatch.setattr(
+ gw, "_path_exists_safe", lambda p: present and str(p) == f"{runtime_dir}/bus")
+ return runtime_dir
+
+
+ def _service_manager_env(monkeypatch) -> None:
+ """The environment systemd hands a system-level unit: no bus, but INVOCATION_ID."""
+ monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)
+ monkeypatch.delenv("DBUS_SESSION_BUS_ADDRESS", raising=False)
+ monkeypatch.setenv("INVOCATION_ID", "system-unit-104893")
+
+
+ def test_service_gateway_boot_adopts_its_user_bus(monkeypatch):
+ runtime_dir = _fake_user_bus(monkeypatch, present=True)
+ _service_manager_env(monkeypatch)
+ for guard in (
+ "_guard_official_docker_root_gateway",
+ "_guard_named_profile_under_multiplexer",
+ "_guard_supervised_gateway_conflict",
+ "_guard_existing_gateway_process_conflict",
+ "_apply_startup_watchdog_config",
+ ):
+ monkeypatch.setattr(gw, guard, lambda *_a, **_kw: None)
+
+ def _stop_here() -> bool:
+ raise _BootReached
+
+ # First boot step after the adoption — stop there instead of starting a gateway.
+ monkeypatch.setattr(gw, "supports_systemd_services", _stop_here)
+
+ with pytest.raises(_BootReached):
+ gw.run_gateway()
+
+ assert os.environ["XDG_RUNTIME_DIR"] == runtime_dir
+ assert os.environ["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={runtime_dir}/bus"
+
+ # Worker environments are snapshots of os.environ taken at various points in the
+ # dispatch paths, so the bus address must also survive the secret scrubber they all
+ # go through — otherwise systemd-run still cannot connect and the fix is a no-op.
+ from tools.environments.local import build_subprocess_env
+
+ worker_env = build_subprocess_env(scrub_secrets=True)
+ assert worker_env["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={runtime_dir}/bus"
+
+
+ def test_absent_user_bus_is_never_fabricated(monkeypatch):
+ """Fail closed, never invent. With no user manager the env must stay bare so the
+ scope probe keeps reaching its honest "unavailable" verdict — a bus address pointing
+ at nothing would turn a clear dispatch refusal into a confusing connect failure."""
+ _fake_user_bus(monkeypatch, present=False)
+ _service_manager_env(monkeypatch)
+
+ gw._ensure_user_systemd_env()
+
+ assert "XDG_RUNTIME_DIR" not in os.environ
+ assert "DBUS_SESSION_BUS_ADDRESS" not in os.environ
diff --cc tests/hermes_cli/test_home_directory_diagnostics.py
index 00000000000,6483935be67..89e115a2b06
mode 000000,100644..100644
--- a/tests/hermes_cli/test_home_directory_diagnostics.py
+++ b/tests/hermes_cli/test_home_directory_diagnostics.py
@@@ -1,0 -1,66 +1,66 @@@
+ """Home initialization must respect operator-owned links and diagnose storage."""
+ from pathlib import Path
+
+ import pytest
+
+ from hermes_cli import config
+
+
+ @pytest.mark.parametrize("subdir", (".", *config._HERMES_HOME_SUBDIRS))
+ def test_unavailable_directory_links_are_diagnosed_without_creating_targets(tmp_path, monkeypatch, subdir):
+ home = tmp_path / "hermes"
+ link = home / subdir
+ link.parent.mkdir(parents=True, exist_ok=True)
+ target = tmp_path / "unmounted" / "external"
+ link.symlink_to(target, target_is_directory=True)
+ monkeypatch.setattr(config, "get_hermes_home", lambda: home)
+ monkeypatch.setattr(config, "is_managed", lambda: False)
+ config._HERMES_HOME_ENSURED.discard(str(home))
+
+ issues = config.validate_config_structure()
+
+ assert issues
+ text = " ".join(str(issue) for issue in issues)
+ assert str(link) in text and str(target) in text
+ assert "mount" in text.lower() and "setup" not in text.lower()
+ assert link.is_symlink() and link.readlink() == target
+ assert not target.parent.exists()
+ assert str(home) not in config._HERMES_HOME_ENSURED
+
+ target.mkdir(parents=True, mode=0o750)
+ config.ensure_hermes_home()
+ assert link.is_symlink() and target.stat().st_mode & 0o777 == 0o750
+ assert str(home) in config._HERMES_HOME_ENSURED
+
+
+ @pytest.mark.parametrize("linked", ("plain", "logs", "home"))
+ def test_initialization_preserves_external_directory_modes(tmp_path, monkeypatch, linked):
+ home = tmp_path / "hermes"
+ target = tmp_path / "shared"
+ target.mkdir(mode=0o750)
+ if linked == "home":
+ home.symlink_to(target, target_is_directory=True)
+ else:
+ home.mkdir()
+ curator = target / "curator"
+ curator.mkdir(mode=0o750)
+ if linked == "logs":
+ (home / "logs").symlink_to(target, target_is_directory=True)
+ monkeypatch.setattr(config, "get_hermes_home", lambda: home)
+ monkeypatch.setattr(config, "is_managed", lambda: False)
+ config._HERMES_HOME_ENSURED.discard(str(home))
+
+ config.ensure_hermes_home()
+ monkeypatch.setattr(config, "get_hermes_home", lambda: home.resolve())
+ config.ensure_hermes_home()
+
+ assert all((home / name).is_dir() for name in config._HERMES_HOME_SUBDIRS)
+ assert (home / "SOUL.md").is_file()
+ if linked != "plain":
+ assert (home if linked == "home" else home / "logs").is_symlink()
+ assert target.stat().st_mode & 0o777 == 0o750
+ assert curator.stat().st_mode & 0o777 == 0o750
+ else:
+ assert (home / "logs").stat().st_mode & 0o777 == 0o700
diff --cc tests/hermes_cli/test_kanban_pr_acceptance.py
index 00000000000,de0445c931a..74d89aab3ac
mode 000000,100644..100644
--- a/tests/hermes_cli/test_kanban_pr_acceptance.py
+++ b/tests/hermes_cli/test_kanban_pr_acceptance.py
@@@ -1,0 -1,131 +1,131 @@@
+ """Two lifecycle invariants, using real SQLite and a local GitHub HTTP contract."""
+ import json
+ import os
+ import sys
+ import threading
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ import pytest
+
+ from hermes_cli import kanban_db as kb
+ from hermes_cli.kanban_db_connect import connect
+
+
+ @pytest.fixture
+ def github(tmp_path, monkeypatch):
+ state = {"conclusion": "success", "head": "a" * 40, "reads": 0, "requests": []}
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ state["requests"].append(self.path)
+ sha = state["head"]
+ if self.path == "/graphql":
+ value = {"data": {"repository": {"pullRequest": {
+ "headRefOid": sha, "baseRefName": "main", "state": "OPEN",
+ "baseRef": {"branchProtectionRule": {"requiredStatusChecks": [
+ {"context": "required", "app": {"databaseId": 1}}]}}}}}}
+ elif "/rules/branches/" in self.path:
+ value = [[]]
+ elif "/check-runs" in self.path:
+ run = {"id": 42, "name": "required", "head_sha": sha,
+ "app": {"id": 1}, "status": "in_progress" if state["conclusion"] == "pending" else "completed", "conclusion": state["conclusion"],
+ "html_url": "https://github.com/acme/repo/actions/runs/42"}
+ if state.get("stale"):
+ run["head_sha"] = "b" * 40
+ runs = [] if state.get("missing") else [run]
+ value = [{"total_count": 100 + len(runs), "check_runs": [
+ {**run, "id": 1000 + i, "name": "optional", "conclusion": "skipped"}
+ for i in range(100)]}, {"total_count": 100 + len(runs), "check_runs": runs}]
+ if state.get("race"):
+ state["race"]()
+ if state.get("head_change"):
+ state["head"] = "b" * 40
+ elif "/statuses" in self.path:
+ value = [[]]
+ elif "/pulls/" in self.path:
+ value = {"head": {"sha": sha}, "base": {"ref": "main"}, "state": "open"}
+ else:
+ self.send_error(404)
+ return
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(json.dumps(value).encode())
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ shim = tmp_path / "bin"
+ shim.mkdir()
+ gh = shim / "gh"
+ gh.write_text(f"#!{sys.executable}\nimport sys,urllib.request\n"
+ f"u='http://127.0.0.1:{server.server_port}/'+sys.argv[2]\n"
+ "print(urllib.request.urlopen(u).read().decode())\n")
+ gh.chmod(0o755)
+ monkeypatch.setenv("PATH", str(shim) + os.pathsep + os.environ["PATH"])
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ kb.init_db()
+ try:
+ yield state
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+ def test_pr_completion_requires_current_required_evidence(github):
+ with connect() as conn:
+ for conclusion in ("failure", "pending", "cancelled", "timed_out", "action_required", "neutral", "skipped", None, "success"):
+ github.update(conclusion=conclusion, head="a" * 40)
+ tid = kb.create_task(conn, title="Publish", completion_contract="acme/repo")
+ ok = kb.complete_task(conn, tid, metadata={"published_pr": "https://github.com/acme/repo/pull/7"})
+ assert ok is (conclusion == "success")
+ task = kb.get_task(conn, tid)
+ assert (task.status == "done") is ok
+ receipts = [json.loads(r[0]) for r in conn.execute(
+ "SELECT payload FROM task_events WHERE task_id=? AND kind='pr_acceptance'", (tid,))]
+ assert receipts and receipts[-1]["head_sha"] == "a" * 40
+ if not ok:
+ assert task.status in {"running", "ready", "blocked", "review"}
+ assert "retry" in receipts[-1]["recovery"]
+ assert receipts[-1]["checks"][0]["id"] == 42
+ for fault in ("missing", "stale", "head_change"):
+ github.update(conclusion="success", head="a" * 40)
+ github[fault] = True
+ tid = kb.create_task(conn, title=fault, completion_contract="acme/repo")
+ assert not kb.complete_task(conn, tid, metadata={"published_pr": "https://github.com/acme/repo/pull/7"})
+ assert kb.get_task(conn, tid).status != "done"
+ github.pop(fault)
+ # Omission and a sibling repository cannot downgrade the stored declaration.
+ tid = kb.create_task(conn, title="publish", completion_contract="acme/repo")
+ assert not kb.complete_task(conn, tid, summary="local green")
+ assert not kb.complete_task(conn, tid, metadata={"published_pr": "https://github.com/other/repo/pull/7"})
+ before = len(github["requests"])
+ local = kb.create_task(conn, title="local", completion_contract="local-only")
+ assert kb.complete_task(conn, local, summary="https://github.com/acme/repo/pull/7 is background context")
+ assert len(github["requests"]) == before
+
+
+ def test_acceptance_receipts_and_terminal_write_share_run_ownership(github):
+ with connect() as conn:
+ for conclusion in ("success", "failure"):
+ tid = kb.create_task(conn, title="race", completion_contract="acme/repo")
+ owner = kb.claim_task(conn, tid)
+ run_id = owner.current_run_id
+ def reclaim():
+ with connect() as rival:
+ assert kb.block_task(rival, tid, reason="Reassigned during acceptance")
+ assert kb.unblock_task(rival, tid)
+ github["replacement"] = kb.claim_task(rival, tid).current_run_id
+ github.update(conclusion=conclusion, race=reclaim)
+ assert not kb.complete_task(conn, tid, expected_run_id=run_id,
+ metadata={"published_pr": "https://github.com/acme/repo/pull/7"})
+ assert kb.get_task(conn, tid).current_run_id == github["replacement"]
+ assert github["replacement"] != run_id
+ assert kb.get_task(conn, tid).status != "done"
+ assert conn.execute("SELECT count(*) FROM task_events WHERE task_id=? AND kind='pr_acceptance'", (tid,)).fetchone()[0] == 0
+ github.pop("race")
diff --cc tests/hermes_cli/test_linux_launcher_management.py
index 00000000000,e2fd5e22a65..ed6af58e5d4
mode 000000,100644..100644
--- a/tests/hermes_cli/test_linux_launcher_management.py
+++ b/tests/hermes_cli/test_linux_launcher_management.py
@@@ -1,0 -1,36 +1,36 @@@
+ """Native Linux launcher management through real config and filesystem I/O."""
+ from pathlib import Path
+
+ import pytest
+
+ from hermes_cli.linux_desktop_entry import install_desktop_entry
+
+
+ def test_launcher_optout_preserves_custom_entry_but_creates_missing(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
+ monkeypatch.setenv("PATH", "/usr/bin:/bin")
+ monkeypatch.setattr(Path, "home", lambda: home)
+ config = home / "config.yaml"
+ config.write_text("desktop:\n manage_launcher_entry: false\n", encoding="utf-8")
+ root = tmp_path / "checkout"
+ root.mkdir()
+ entry = tmp_path / "xdg/applications/hermes.desktop"
+ entry.parent.mkdir(parents=True)
+ custom = b"[Desktop Entry]\nType=Application\nName=Custom Hermes\nExec=/opt/custom-hermes desktop\n"
+ for setting in ("false", '"false"'):
+ config.write_text(f"desktop:\n manage_launcher_entry: {setting}\n", encoding="utf-8")
+ entry.write_bytes(custom)
+ assert install_desktop_entry(root) == entry
+ assert entry.read_bytes() == custom
+ entry.unlink()
+ assert install_desktop_entry(root) == entry
+ assert b"Name=Hermes\n" in entry.read_bytes()
+ config.write_text("desktop: {}\n", encoding="utf-8")
+ entry.write_bytes(custom)
+ assert install_desktop_entry(root) == entry
+ assert entry.read_bytes() != custom
diff --cc tests/hermes_cli/test_pending_supervisor_recovery.py
index 00000000000,46b974708f3..2b62ff8ae72
mode 000000,100644..100644
--- a/tests/hermes_cli/test_pending_supervisor_recovery.py
+++ b/tests/hermes_cli/test_pending_supervisor_recovery.py
@@@ -1,0 -1,79 +1,79 @@@
+ """A pending restart is discharged by supervisor evidence, not an empty PID scan."""
+ import subprocess
+ from types import SimpleNamespace
+
+ import pytest
+
+ from hermes_cli import gateway, main, update_cmd_fleet as fleet
+
+
+ @pytest.mark.parametrize("failure", ["listing", "timeout", "missing", "restart", "inactive", "running", None])
+ def test_pending_marker_requires_complete_systemd_recovery(monkeypatch, tmp_path, failure):
+ monkeypatch.setattr(main, "_purge_stale_hermes_modules", lambda: None)
+ stopped = []
+ monkeypatch.setattr(gateway, "find_gateway_pids", lambda **kw: [123] if failure == "running" and not stopped else [])
+ monkeypatch.setattr(gateway, "kill_gateway_processes", lambda **kw: stopped.append(True))
+ monkeypatch.setattr(gateway, "_wait_for_gateway_exit", lambda **kw: None)
+ monkeypatch.setattr(gateway, "supports_systemd_services", lambda: True)
+ monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", ["systemctl", "--user"]),))
+ monkeypatch.setattr(fleet._time, "sleep", lambda _: None)
+ ticks = iter(range(1000))
+ monkeypatch.setattr(fleet._time, "monotonic", lambda: next(ticks))
+ recovered = []
+
+ def systemctl(cmd, **kw):
+ if "list-units" in cmd:
+ if stopped:
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+ if failure == "timeout":
+ raise subprocess.TimeoutExpired(cmd, 10)
+ if failure == "missing":
+ raise FileNotFoundError("systemctl")
+ return SimpleNamespace(returncode=int(failure == "listing"), stdout=(
+ "hermes-gateway-one.service loaded active running\n"
+ "hermes-gateway-two.service loaded failed failed\n"), stderr="")
+ bad = cmd[-1] == "hermes-gateway-two"
+ if "restart" in cmd:
+ recovered.append(cmd[-1])
+ return SimpleNamespace(returncode=int(bad and failure == "restart"), stdout="")
+ if "is-active" in cmd:
+ active = not (bad and failure == "inactive")
+ return SimpleNamespace(returncode=0 if active else 3, stdout="active" if active else "inactive")
+ return SimpleNamespace(returncode=0, stdout="0s")
+
+ monkeypatch.setattr(fleet, "_systemctl", systemctl)
+ marker = fleet._fleet_restart_pending_marker_path()
+ marker.write_text("expected_sha=pending\n")
+ if failure not in (None, "running"):
+ with pytest.raises(SystemExit, match="1"):
+ fleet._apply_pending_fleet_restart_catchup()
+ assert marker.exists()
+ else:
+ fleet._apply_pending_fleet_restart_catchup()
+ assert not marker.exists()
+ assert set(recovered) == {"hermes-gateway-one", "hermes-gateway-two"}
+
+
+ @pytest.mark.parametrize("failure", ["listing", "restart", "inactive", "unloaded", None])
+ def test_pending_launchd_requires_complete_supervision(monkeypatch, tmp_path, failure):
+ # Host-independent subprocess-boundary fixture, not native launchd validation.
+ current, sibling = "ai.hermes.gateway", "ai.hermes.gateway-two"
+ (tmp_path / f"{sibling}.plist").touch()
+ monkeypatch.setattr(gateway, "get_launchd_label", lambda: current)
+ monkeypatch.setattr(gateway, "get_launchd_plist_path", lambda: tmp_path / f"{current}.plist")
+ monkeypatch.setattr(gateway, "launchd_gateway_labels_for_install", lambda: [current, sibling])
+ monkeypatch.setattr(fleet, "_restart_launchd_gateway_after_update", lambda **kw: ([], []))
+ monkeypatch.setattr(gateway, "_locate_launchd_gateway_service", lambda _: (None, None) if failure == "unloaded" else ("gui/501", None))
+ monkeypatch.setattr(gateway, "_wait_for_launchd_service_pid", lambda *a, **kw: None if failure == "inactive" else 42)
+
+ def kickstart(*args):
+ if failure == "restart":
+ raise subprocess.CalledProcessError(1, "launchctl")
+
+ monkeypatch.setattr(gateway, "_launchd_kickstart", kickstart)
+ monkeypatch.setattr(fleet.subprocess, "run", lambda *a, **kw: SimpleNamespace(returncode=int(failure == "listing"), stdout="", stderr=""))
+ restarted, failed = [], []
+ fleet._restart_macos_launchd_gateways(restarted, failed, 0, require_supervision=True)
+ assert bool(failed) is bool(failure)
+ assert (sibling in restarted) is (failure is None)
diff --cc tests/hermes_cli/test_unified_pool_quirk.py
index 881fc9a5570,881fc9a5570..816a0e568d3
--- a/tests/hermes_cli/test_unified_pool_quirk.py
+++ b/tests/hermes_cli/test_unified_pool_quirk.py
@@@ -189,7 -189,7 +189,7 @@@ def test_smi_resolver_caches_and_surviv
assert len(calls) == 1
def test_smi_resolver_uses_wsl_driver_path_when_path_is_empty(monkeypatch):
"""WSL exposes nvidia-smi through the Windows driver directory even
when a service PATH cannot resolve it."""
diff --cc tests/hermes_cli/test_update_yes_flag.py
index abf4273c371,84058bee17f..ae7683ca462
--- a/tests/hermes_cli/test_update_yes_flag.py
+++ b/tests/hermes_cli/test_update_yes_flag.py
@@@ -16,22 -16,18 +16,29 @@@ import pytes
from hermes_cli.main import cmd_update
+pytestmark = pytest.mark.usefixtures(
+ "isolated_update_uv", "isolated_update_processes", "isolated_update_checkout",
+)
+
+
[email protected](autouse=True)
+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."""
+ import hermes_cli.main as cli_main
+
+ monkeypatch.setattr(cli_main, "_detect_venv_python_processes", lambda: [])
+ monkeypatch.setattr("pm.sync_venv", lambda *a, **k: None)
+
+ @pytest.fixture(autouse=True)
-def _isolate_update(isolated_update_runtime, monkeypatch):
- import shutil
- from hermes_cli import managed_uv, update_cmd
++def _isolate_update(monkeypatch):
++ from hermes_cli import update_cmd
+
- monkeypatch.setattr(managed_uv, "resolve_uv", lambda **kw: shutil.which("uv"))
- monkeypatch.setattr(managed_uv, "ensure_uv", lambda **kw: shutil.which("uv"))
- monkeypatch.setattr(managed_uv, "update_managed_uv", lambda **kw: None)
+ monkeypatch.setattr(update_cmd, "_post_update_sqlite_runtime_status", lambda: (True, None))
+
+
def _make_run_side_effect(
branch="main", verify_ok=True, commit_count="1", dirty=False
):
diff --cc tests/test_desktop_update_shim_profile_cleanup.py
index 00000000000,980387d721f..ca565619f6b
mode 000000,100644..100644
--- a/tests/test_desktop_update_shim_profile_cleanup.py
+++ b/tests/test_desktop_update_shim_profile_cleanup.py
@@@ -1,0 -1,59 +1,59 @@@
+ """The update hand-off cleans only an atomically claimed browser profile."""
+ import os
+ from pathlib import Path
+ import subprocess
+
+ import pytest
+
+
+ @pytest.mark.parametrize("outcome", ["success", "error", "allocation-failed"])
+ def test_shim_removes_only_its_owned_profile(tmp_path, outcome):
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ browser = bin_dir / "google-chrome"
+ browser.write_text(
+ '#!/bin/bash\ntrap "exit 0" TERM\n'
+ 'for arg in "$@"; do\n'
+ 'case "$arg" in --user-data-dir=*) dir="${arg#--user-data-dir=}" ;; esac\n'
+ 'done\nmkdir -p "$dir"\nprintf "%s" "$dir" > "$HOME/launched-profile"\n'
+ 'while :; do sleep 0.1; done\n', encoding="utf-8",
+ )
+ browser.chmod(0o755)
+ if outcome == "allocation-failed":
+ allocator = bin_dir / "mktemp"
+ allocator.write_text('#!/bin/sh\nprintf "%s\\n" "$HOME"\nexit 1\n', encoding="utf-8")
+ allocator.chmod(0o755)
+ config = tmp_path / ".config"
+ config.mkdir()
+ (config / "mimeapps.list").write_text(
+ '[Default Applications]\nx-scheme-handler/http=google-chrome.desktop\n'
+ 'x-scheme-handler/https=google-chrome.desktop\ntext/html=google-chrome.desktop\n',
+ encoding="utf-8",
+ )
+ install = tmp_path / "hermes-agent"
+ install.mkdir()
+ env = {**os.environ, "HOME": str(tmp_path), "HERMES_HOME": str(tmp_path),
+ "XDG_CONFIG_HOME": str(config), "TMPDIR": str(tmp_path),
+ "PATH": f"{bin_dir}:/usr/bin:/bin", "HERMES_SELFTEST_HOLD_SECONDS": "1",
+ "HERMES_UPDATE_SHIM_GRACE_SECONDS": "1", "HERMES_SELFTEST_FAIL": "1" if outcome == "error" else ""}
+ process = subprocess.Popen(
+ ["bash", "-c", 'while [ ! -f "$HOME/start" ]; do sleep .05; done; exec bash "$@"', "probe",
+ str(Path(__file__).resolve().parents[1] / "scripts/desktop-update/posix.sh"),
+ "--install-root", str(install), "--self-test-ui"],
+ env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ collision = tmp_path / f"hermes-update-ui-{process.pid}"
+ collision.mkdir()
+ (collision / "keep").write_text("keep", encoding="utf-8")
+ (tmp_path / "start").touch()
+ stdout, stderr = process.communicate(timeout=30)
+ assert process.returncode == (1 if outcome == "error" else 0), stdout + stderr
+ launched = tmp_path / "launched-profile"
+ if outcome == "allocation-failed":
+ assert not launched.exists()
+ else:
+ owned = Path(launched.read_text(encoding="utf-8"))
+ assert owned != collision
+ assert not owned.exists()
+ assert (collision / "keep").read_text(encoding="utf-8") == "keep"
diff --cc tests/tools/test_checkpoint_manager.py
index 38e9f64f0e1,bf041605e34..aad32bf74fc
--- a/tests/tools/test_checkpoint_manager.py
+++ b/tests/tools/test_checkpoint_manager.py
@@@ -762,7 -762,7 +762,7 @@@ class TestSecurity
cps = mgr.list_checkpoints(str(work_dir))
target_hash = cps[0]["hash"]
-- result = mgr.restore(str(work_dir), target_hash, file_path="/etc/passwd")
++ result = mgr.restore(str(work_dir), target_hash, file_path=str(work_dir.parent / "outside_file.txt"))
assert result["success"] is False
assert "got absolute path" in result["error"]
diff --cc tests/tools/test_checkpoint_path_roundtrip.py
index 00000000000,9a4cf625ca5..17c3ce9c130
mode 000000,100644..100644
--- a/tests/tools/test_checkpoint_path_roundtrip.py
+++ b/tests/tools/test_checkpoint_path_roundtrip.py
@@@ -1,0 -1,73 +1,79 @@@
+ """Checkpoint file names must survive Git's machine-readable path output."""
+
+ import os
+
+ import pytest
+
+ from tools import checkpoint_manager as checkpoints
+
+
[email protected]("names", [
- [" leading.txt", "报告.txt", "ordinary.txt"],
- pytest.param(
- [b" raw-\xff.txt", b"carriage\rreturn.txt", b"crlf\r\nname.txt"],
- marks=pytest.mark.linux_only,
- id="posix-byte-paths",
- ),
-])
-def test_safe_restore_preserves_exact_paths_and_user_edits(tmp_path, monkeypatch, names):
++def test_safe_restore_preserves_exact_paths_and_user_edits(tmp_path, monkeypatch):
++ _assert_safe_restore(tmp_path, monkeypatch, [" leading.txt", "报告.txt", "ordinary.txt"])
++
++
++def test_safe_restore_preserves_posix_byte_paths(tmp_path, monkeypatch):
++ _assert_safe_restore(tmp_path, monkeypatch, [b" raw-\xff.txt", b"carriage\rreturn.txt", b"crlf\r\nname.txt"])
++
++
++def _assert_safe_restore(tmp_path, monkeypatch, names):
+ names = [os.fsdecode(name) for name in names]
+ monkeypatch.setattr(checkpoints, "CHECKPOINT_BASE", tmp_path / "checkpoints")
+ work = tmp_path / "project"
+ work.mkdir()
+ (work / "AGENTS.md").write_text("Project instructions\n", encoding="utf-8")
+
+ for name in names:
+ (work / name).write_text("original\n", encoding="utf-8")
+ preserved = work / " 用户修改.txt"
+ preserved.write_text("original\n", encoding="utf-8")
+ manager = checkpoints.CheckpointManager(enabled=True)
+ assert manager.ensure_checkpoint(str(work))
+ target = manager.list_checkpoints(str(work))[0]["hash"]
+
+ for name in names:
+ (work / name).write_text("agent edit\n", encoding="utf-8")
+ manager.record_agent_write(str(work / name))
+ preserved.write_text("agent edit\n", encoding="utf-8")
+ manager.record_agent_write(str(preserved))
+ preserved.write_text("user edit\n", encoding="utf-8")
+
+ result = manager.restore(str(work), target, safe=True)
+
+ assert result["success"]
+ assert set(result["restored_files"]) == set(names)
+ assert result["skipped_user_edits"] == [preserved.name]
+ assert all((work / name).read_text(encoding="utf-8") == "original\n" for name in names)
+ assert preserved.read_text(encoding="utf-8") == "user edit\n"
+
+
- " oversized.bin",
- pytest.param(b" oversized-\xff.bin", marks=pytest.mark.linux_only, id="posix-byte-path"),
-])
-def test_size_cap_applies_to_leading_space_paths(tmp_path, monkeypatch, name):
++def test_size_cap_applies_to_leading_space_paths(tmp_path, monkeypatch):
++ _assert_size_cap(tmp_path, monkeypatch, " oversized.bin")
++
++
++def test_size_cap_applies_to_posix_byte_paths(tmp_path, monkeypatch):
++ _assert_size_cap(tmp_path, monkeypatch, b" oversized-\xff.bin")
++
++
++def _assert_size_cap(tmp_path, monkeypatch, name):
+ name = os.fsdecode(name)
+ monkeypatch.setattr(checkpoints, "CHECKPOINT_BASE", tmp_path / "checkpoints")
+ work = tmp_path / "project"
+ work.mkdir()
+ (work / "small.txt").write_text("keep\n", encoding="utf-8")
+
+ (work / name).write_bytes(b"x" * (1024 * 1024 + 1))
+ manager = checkpoints.CheckpointManager(enabled=True, max_file_size_mb=1)
+ assert manager.ensure_checkpoint(str(work))
+ target = manager.list_checkpoints(str(work))[0]["hash"]
+ store = checkpoints._store_path()
+
+ included, _, _ = checkpoints._run_git(
+ ["cat-file", "-e", f"{target}:small.txt"], store, str(work)
+ )
+ oversized_included, _, _ = checkpoints._run_git(
+ ["cat-file", "-e", f"{target}:{name}"], store, str(work), allowed_returncodes={128}
+ )
+ assert included
+ assert not oversized_included
diff --cc tests/tools/test_process_registry.py
index ae248ec8769,62dd2f9496a..a07429c49a5
--- a/tests/tools/test_process_registry.py
+++ b/tests/tools/test_process_registry.py
@@@ -2382,6 -2375,55 +2382,55 @@@ class TestSystemdCgroupIsolation
value.startswith("OOMPolicy=") for value in probe_argv if isinstance(value, str)
), probe_argv
- @pytest.mark.linux_only
++ @pytest.mark.platforms("linux")
+ def test_systemd_probe_derives_owned_user_bus_env_for_system_gateway(
+ self, registry, monkeypatch, request
+ ):
+ """A system service running as an unprivileged user has no login env,
+ but may still have a valid lingering user manager and D-Bus socket."""
+ import socket
+ import tempfile
+
+ import tools.process_registry as pr
+
+ # Short path: AF_UNIX socket paths are capped at ~104 bytes, longer than most tmp_path values.
+ runtime_dir = pr.Path(tempfile.mkdtemp(prefix="hbus-", dir="/tmp"))
+ runtime_dir.chmod(0o700)
+ bus_path = runtime_dir / "bus"
+ bus_socket = socket.socket(socket.AF_UNIX)
+ bus_socket.bind(str(bus_path))
+
+ def _cleanup():
+ bus_socket.close()
+ bus_path.unlink(missing_ok=True)
+ runtime_dir.rmdir()
+
+ request.addfinalizer(_cleanup)
+
+ monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)
+ monkeypatch.delenv("DBUS_SESSION_BUS_ADDRESS", raising=False)
+ monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_AVAILABLE", None)
+ monkeypatch.setattr(pr, "_default_user_runtime_dir", lambda: runtime_dir)
+ monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/systemd-run")
+ derived = pr.systemd_user_bus_env(
+ {"DBUS_SESSION_BUS_ADDRESS": "unix:path=/tmp/untrusted-bus"}
+ )
+ assert derived["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={bus_path}"
+ probe_kwargs = []
+
+ def fake_run(*args, **kwargs):
+ probe_kwargs.append(kwargs)
+ return subprocess.CompletedProcess(args=args[0], returncode=0)
+
+ monkeypatch.setattr("subprocess.run", fake_run)
+
+ assert pr._systemd_run_user_scope_available() is True
+ env = probe_kwargs[0]["env"]
+ assert env["XDG_RUNTIME_DIR"] == str(runtime_dir)
+ assert env["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={bus_path}"
+ assert "XDG_RUNTIME_DIR" not in os.environ
+ assert "DBUS_SESSION_BUS_ADDRESS" not in os.environ
+
def test_systemd_scope_first_probe_is_serialized(self, monkeypatch):
"""Concurrent first-use callers must wait for one definitive probe.
diff --cc tests/tui_gateway/test_multi_client_fanout.py
index 00000000000,0942468973a..e8d639e8358
mode 000000,100644..100644
--- a/tests/tui_gateway/test_multi_client_fanout.py
+++ b/tests/tui_gateway/test_multi_client_fanout.py
@@@ -1,0 -1,241 +1,241 @@@
+ """Shared-session routing and backpressure, exercised through real OS pipes."""
+ import asyncio
+ import json
+ import os
+ import queue
+ import socket
+ import threading
+ from contextlib import ExitStack, suppress
+
+ import pytest
+
+ from tui_gateway import server
+ from tui_gateway.transport import FanoutTransport, StdioTransport
+ from tui_gateway.ws import WSTransport
+
+
+ class PipeClient:
+ def __init__(self, stack, *, reading=True):
+ read_fd, write_fd = os.pipe()
+ self.reader = stack.enter_context(os.fdopen(read_fd, "r", encoding="utf-8"))
+ self.writer = os.fdopen(write_fd, "w", encoding="utf-8")
+ stack.callback(self._cleanup)
+ self.transport = StdioTransport(lambda: self.writer, threading.Lock())
+ self._closed = False
+ self.writes = 0
+ self.frames = queue.Queue()
+ if reading:
+ self.thread = threading.Thread(target=self._read, daemon=True)
+ self.thread.start()
+
+ def _cleanup(self):
+ with suppress(BrokenPipeError):
+ self.writer.close()
+ if hasattr(self, "thread"):
+ self.thread.join(timeout=5)
+ assert not self.thread.is_alive()
+
+ def _read(self):
+ for line in self.reader:
+ self.frames.put(json.loads(line))
+
+ def write(self, obj):
+ self.writes += 1
+ return self.transport.write(obj)
+
+ def close(self):
+ self._closed = True
+
+ def receive(self):
+ return self.frames.get(timeout=5)
+
+
+ class SocketClient(WSTransport):
+ """Real WSTransport with its ASGI send backed by a kernel socketpair."""
+ def __init__(self, stack, *, reading=True):
+ self.reader, self.writer = socket.socketpair()
+ self.writer.setblocking(False)
+ loop = asyncio.new_event_loop()
+ super().__init__(self, loop)
+ self.writes = 0
+ self.loop_thread = threading.Thread(target=loop.run_forever, daemon=True)
+ self.loop_thread.start()
+ self.frames = queue.Queue()
+ self.read_thread = None
+ if reading:
+ self.read_thread = threading.Thread(target=self._read, daemon=True)
+ self.read_thread.start()
+ stack.callback(self._cleanup)
+
+ async def send_text(self, payload):
+ self.writes += 1
+ await self._loop.sock_sendall(self.writer, (payload + "\n").encode())
+
+ def _read(self):
+ with self.reader.makefile("r", encoding="utf-8") as stream:
+ for line in stream:
+ self.frames.put(json.loads(line))
+
+ def receive(self):
+ return self.frames.get(timeout=5)
+
+ def _cleanup(self):
+ async def cancel_sends():
+ self.close()
+ tasks = [task for task in asyncio.all_tasks() if task is not asyncio.current_task()]
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ asyncio.run_coroutine_threadsafe(cancel_sends(), self._loop).result(timeout=5)
+ self.writer.close()
+ if self.read_thread:
+ self.read_thread.join(timeout=5)
+ assert not self.read_thread.is_alive()
+ self.reader.close()
+ self._loop.call_soon_threadsafe(self._loop.stop)
+ self.loop_thread.join(timeout=5)
+ self._loop.close()
+
+
+ def _session(transport):
+ return dict(transport=transport, agent=None, session_key="fanout-invariant",
+ history=[], history_lock=threading.Lock(), history_version=0,
+ running=False, attached_images=[])
+
+
+ @pytest.mark.parametrize("attachment", ["direct", "flattened"])
+ def test_membership_preserves_terminal_delivery_and_revokes_departed_peers(monkeypatch, attachment):
+ with ExitStack() as stack:
+ a, b, stranger = [PipeClient(stack) for _ in range(3)]
+ session = _session(a)
+ monkeypatch.setitem(server._sessions, "fanout-invariant", session)
+ newcomer = b if attachment == "direct" else FanoutTransport(a, b)
+ assert server._attach_session_transport(session, newcomer)
+ assert server._attach_session_transport(session, b)
+ for kind in ("message.start", "message.delta", "message.complete"):
+ server._emit(kind, "fanout-invariant", {"text": "α"})
+ first, second = a.receive(), b.receive()
+ assert first == second
+ assert first["params"]["type"] == kind
+ for client, allowed in ((a, True), (b, True), (stranger, False)):
+ token = server.bind_transport(client)
+ try:
+ assert (server._current_session_steer_authority("fanout-invariant")[0] is client) == allowed
+ finally:
+ server.reset_transport(token)
+ # RPC replies stay on their request transport, never the subscriber set.
+ token = server.bind_transport(a)
+ try:
+ assert server.write_json({"jsonrpc": "2.0", "id": "private", "result": "owner only"})
+ finally:
+ server.reset_transport(token)
+ assert a.receive()["id"] == "private"
+ assert b.frames.empty()
+ from gateway import browser_control_broker as broker_module
+ monkeypatch.setattr(broker_module, "browser_control_enabled", lambda: True)
+ for client in (a, b, stranger):
+ client.auth_identity = {"user_id": "fanout-owner", "provider": "fixture"}
+ session["profile"] = "default"
+
+ def controller(client, action, **params):
+ return server.dispatch({"jsonrpc": "2.0", "id": 1,
+ "method": "browser.controller." + action,
+ "params": {"session_id": "fanout-invariant", **params}}, client)
+
+ registered = controller(a, "register", controller_id="invariant",
+ browser_profile_id="fixture", capabilities=["controller.noop"],
+ protocol_version=broker_module.BROWSER_CONTROL_PROTOCOL_VERSION)
+ assert "result" in registered, registered
+ try:
+ assert controller(a, "heartbeat")["result"] == {"ok": True}
+ assert controller(b, "heartbeat")["error"]["message"] == "controller is not owned by this transport"
+ assert controller(stranger, "heartbeat")["error"]["message"] == "session is not owned by this transport"
+ finally:
+ controller(a, "detach")
+ session["viewers"] = {b: object(), stranger: object()}
+ assert server._detach_session_transport(session, b)
+ assert not session["viewers"]
+ assert not server._session_transport_contains(session, b)
+ server._emit("message.complete", "fanout-invariant", {"text": "only A"})
+ assert a.receive()["params"]["payload"]["text"] == "only A"
+ assert b.frames.empty()
+ assert server._attach_session_transport(session, b)
+ server._emit("message.complete", "fanout-invariant", {"text": "reattached"})
+ assert a.receive() == b.receive()
+ b.close()
+ # A stale queued envelope must not restore a dead peer's authority.
+ assert not server._attach_session_transport(session, b)
+ assert not server._session_transport_contains(session, b)
+ assert not server._attach_session_transport(session, server._stdio_transport)
+ assert server._close_sessions_for_transport(b) == (0, 0)
+ assert server._close_sessions_for_transport(a) == (0, 1)
+ assert session["transport"] is server._detached_ws_transport
+
+
+ @pytest.mark.parametrize("client_type", [PipeClient, SocketClient])
+ @pytest.mark.parametrize("slow_first", [True, False])
+ @pytest.mark.parametrize("on_loop", [True, False])
+ def test_backpressure_never_blocks_later_frames_or_other_subscribers(slow_first, on_loop, client_type, monkeypatch):
+ monkeypatch.setattr("tui_gateway.ws._WS_WRITE_TIMEOUT_S", 0.01)
+ monkeypatch.setattr("tui_gateway.ws._TOKEN_COALESCE_S", 0)
+ with ExitStack() as stack:
+ healthy, slow = client_type(stack), client_type(stack, reading=False)
+ # Fill the actual kernel pipe, not a fake wait in a transport.write().
+ fd = slow.writer.fileno()
+ os.set_blocking(fd, False)
+ try:
+ while True:
+ os.write(fd, b"x" * 4096)
+ except BlockingIOError:
+ pass
+ finally:
+ os.set_blocking(fd, client_type is PipeClient)
+ fan = FanoutTransport(*((slow, healthy) if slow_first else (healthy, slow)))
+ returned = threading.Event()
+ errors = []
+
+ def emit():
+ try:
+ for kind in ("message.start", "message.delta", "message.complete"):
+ assert fan.write({"params": {"type": kind}})
+ except BaseException as exc:
+ errors.append(exc)
+ finally:
+ returned.set()
+
+ async def loop_emit():
+ emit()
+
+ worker = threading.Thread(target=(lambda: asyncio.run(loop_emit())) if on_loop else emit, daemon=True)
+ worker.start()
+ try:
+ assert returned.wait(3), "slow subscriber blocked the emitting turn"
+ assert not errors
+ assert [healthy.receive()["params"]["type"] for _ in range(3)] == [
+ "message.start", "message.delta", "message.complete"]
+ # Exhaust only the slow peer's bounded backlog; pace the healthy
+ # reader by receipts so scheduler latency cannot make it overflow.
+ for n in range(1024):
+ frame = {"params": {"type": "message.delta", "n": n}}
+ assert fan.write(frame)
+ assert healthy.receive() == frame
+ if not fan.contains(slow):
+ break
+ assert not fan.contains(slow), "slow backlog grew without bound"
+ for _ in range(16):
+ assert fan.attach(slow)
+ assert fan.write({"reattach": True})
+ assert healthy.receive() == {"reattach": True}
+ fan.detach(slow)
+ assert slow.writes == 1, "reattach spawned more writers behind blocked I/O"
+ assert fan.contains(healthy)
+ assert fan.write({"params": {"type": "message.complete"}})
+ assert healthy.receive()["params"]["type"] == "message.complete"
+ finally:
+ # Closing the real reader releases any blocked writer even on RED.
+ slow.reader.close()
+ worker.join(timeout=15)
+ fan.close()
+ assert not worker.is_alive()
+ assert not fan.write({"after": "close"})
diff --cc tools/checkpoint_manager.py
index c8d298c31d5,2aa89236e54..742032fa921
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@@ -358,87 -201,46 +358,89 @@@ def _git_env
return env
-def _git_subprocess(cmd: List[str], env: dict, timeout: int, cwd: Optional[str] = None):
- # creationflags suppresses the per-call conhost flash on Windows (no-op on POSIX).
- # Text mode both replaces undecodable path bytes and normalizes CR/CRLF.
- text_options = {} if "-z" in cmd else {"text": True, "encoding": "utf-8", "errors": "replace"}
- result = subprocess.run(cmd, capture_output=True, timeout=timeout, **text_options,
- env=env, cwd=cwd, stdin=subprocess.DEVNULL, creationflags=windows_hide_flags())
- if "-z" in cmd:
- result.stdout = os.fsdecode(result.stdout)
- result.stderr = result.stderr.decode("utf-8", errors="replace")
- return result
-
-
def _repair_bare_repo_dirs(store: Path) -> None:
- """Recreate ``refs/heads`` and ``branches`` after ``git gc``: gc on a bare repo with only
- packed refs can remove them, yet git 2.34+ requires them — without them ``git add -A``
- fails with "not a git repository" and every checkpoint operation silently fails."""
+ """Recreate refs/ and branches/ dirs that ``git gc`` may have removed.
+
+ ``git gc --prune=now`` on a bare repo with only packed refs can remove
+ the empty ``refs/heads/`` directory. Git 2.34+ requires ``refs/`` (and
+ some versions require ``branches/``) to exist even when all refs are
+ packed in ``packed-refs``. Without them, ``git add -A`` returns
+ ``fatal: not a git repository`` and all checkpoint operations fail
+ silently.
+ """
for subdir in ("refs/heads", "branches"):
- if (store / subdir).exists():
- continue
- try:
- (store / subdir).mkdir(parents=True, exist_ok=True)
- logger.debug("Repaired missing %s in checkpoint store", subdir)
- except OSError as exc:
- logger.warning("Cannot create %s in checkpoint store: %s", subdir, exc)
-
-
-def _run_git(args: List[str], store: Path, working_dir: str, timeout: int = _GIT_TIMEOUT,
- allowed_returncodes: Optional[Set[int]] = None, index_file: Optional[Path] = None) -> Tuple[bool, str, str]:
- """Run git against the shared store -> (ok, stdout, stderr). ``allowed_returncodes`` suppresses
- error logging for expected non-zero exits (``diff --cached --quiet`` -> 1); ``ok`` stays rc == 0."""
- wd = _normalize_path(working_dir)
- cmd = ["git"] + list(args)
- if not wd.is_dir():
- msg = (f"working directory not found: {wd}" if not wd.exists()
- else f"working directory is not a directory: {wd}")
- logger.error("Git command skipped: %s (%s)", " ".join(cmd), msg)
+ path = store / subdir
+ if not path.exists():
+ try:
+ path.mkdir(parents=True, exist_ok=True)
+ logger.debug("Repaired missing %s in checkpoint store", subdir)
+ except OSError as exc:
+ logger.warning(
+ "Cannot create %s in checkpoint store: %s", subdir, exc,
+ )
+
+
+def _run_git(
+ args: List[str],
+ store: Path,
+ working_dir: str,
+ timeout: int = _GIT_TIMEOUT,
+ allowed_returncodes: Optional[Set[int]] = None,
+ index_file: Optional[Path] = None,
+) -> Tuple[bool, str, str]:
+ """Run a git command against the shared store. Returns (ok, stdout, stderr).
+
+ ``allowed_returncodes`` suppresses error logging for known/expected non-zero
+ exits while preserving the normal ``ok = (returncode == 0)`` contract.
+ Example: ``git diff --cached --quiet`` returns 1 when changes exist.
+ """
+ normalized_working_dir = _normalize_path(working_dir)
+ if not normalized_working_dir.exists():
+ msg = f"working directory not found: {normalized_working_dir}"
+ logger.error("Git command skipped: %s (%s)", " ".join(["git"] + list(args)), msg)
+ return False, "", msg
+ if not normalized_working_dir.is_dir():
+ msg = f"working directory is not a directory: {normalized_working_dir}"
+ logger.error("Git command skipped: %s (%s)", " ".join(["git"] + list(args)), msg)
return False, "", msg
+ env = _git_env(store, str(normalized_working_dir), index_file=index_file)
+ managed = _managed_git()
+ if managed:
+ cmd, path_dirs = managed
+ # The store's MSYS dirs must be reachable so git.exe can resolve
+ # its helpers; prepend them to the isolated child env.
+ env["PATH"] = os.pathsep.join(path_dirs) + os.pathsep + env.get("PATH", "")
+ else:
+ cmd = ["git"]
+ cmd = cmd + list(args)
+ allowed_returncodes = allowed_returncodes or set()
+
try:
- result = _git_subprocess(cmd, _git_env(store, str(wd), index_file=index_file), timeout, cwd=str(wd))
++ # NUL-delimited git output contains literal filenames, not text lines.
++ text_options = {} if "-z" in args else {"text": True, "encoding": "utf-8", "errors": "replace"}
+ result = subprocess.run(
+ cmd,
+ capture_output=True,
- text=True, encoding='utf-8', errors='replace',
++ **text_options,
+ timeout=timeout,
+ env=env,
+ cwd=str(normalized_working_dir),
+ stdin=subprocess.DEVNULL,
+ # Checkpoints fire several bare git calls per turn from the
+ # console-less desktop/gateway backend; suppress the per-call
+ # conhost flash on Windows (no-op on POSIX).
+ creationflags=windows_hide_flags(),
+ )
+ ok = result.returncode == 0
- stdout = result.stdout.strip()
- stderr = result.stderr.strip()
++ stdout = os.fsdecode(result.stdout) if "-z" in args else result.stdout.strip()
++ stderr = result.stderr.decode("utf-8", errors="replace").strip() if "-z" in args else result.stderr.strip()
+ if not ok and result.returncode not in allowed_returncodes:
+ logger.error(
+ "Git command failed: %s (rc=%d) stderr=%s",
+ " ".join(cmd), result.returncode, stderr,
+ )
+ return ok, stdout, stderr
except subprocess.TimeoutExpired:
msg = f"git timed out after {timeout}s: {' '.join(cmd)}"
logger.error(msg, exc_info=True)
@@@ -869,81 -597,33 +871,78 @@@ class CheckpointManager
logger.debug("record_agent_write failed for %s: %s", file_path, exc)
def safe_restore_plan(self, working_dir: str, commit_hash: str) -> Dict:
- """Classify files changed since ``commit_hash``: ``restore`` = still matching what Hermes
- last wrote (or deleted since); ``skipped`` = user-edited afterwards or never written by
- Hermes. ``ledger_empty`` => no ledger, callers fall back to a full restore."""
- p, err = _locate(working_dir, commit_hash)
- if err:
- return err
+ """Classify files changed since ``commit_hash`` for a safe restore.
- (ok, names_out, err), = _diff_staged_tree(p, ["diff", "--name-only", "-z", commit_hash, "--cached"])
+ Returns ``{"success", "restore": [rel...], "skipped": [rel...],
+ "error"?}`` where ``restore`` lists files whose current content
+ still matches what Hermes last wrote (per the agent-write ledger)
+ and ``skipped`` lists files the user hand-edited after Hermes'
+ last write or that Hermes never wrote at all.
+ """
+ hash_err = _validate_commit_hash(commit_hash)
+ if hash_err:
+ return {"success": False, "error": hash_err}
+
+ abs_dir = str(_normalize_path(working_dir))
+ store = _store_path(CHECKPOINT_BASE)
+ if not (store / "HEAD").exists():
+ return {"success": False, "error": "No checkpoints exist for this directory"}
+
+ dir_hash = _project_hash(abs_dir)
+ index_file = _index_path(store, dir_hash)
+
+ # Stage the current tree so the name-only diff sees new files too.
+ _run_git(["add", "-A"], store, abs_dir,
+ timeout=_GIT_TIMEOUT * 2, index_file=index_file)
+ ok, names_out, err = _run_git(
- ["diff", "--name-only", commit_hash, "--cached"],
++ ["diff", "--name-only", "-z", commit_hash, "--cached"],
+ store, abs_dir, index_file=index_file,
+ )
+ # Reset the index back to the project ref so it doesn't drift.
+ _run_git(["read-tree", _ref_name(dir_hash)], store, abs_dir,
+ index_file=index_file, allowed_returncodes={128})
if not ok:
return {"success": False, "error": f"Could not compute changed files: {err}"}
- ledger = _load_ledger(p.store, p.dir_hash)
+ ledger = _load_ledger(store, dir_hash)
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 names_out.splitlines():
- rel = rel.strip()
- if not rel:
- continue
+ for rel in filter(None, names_out.split("\x00")):
- abs_path = Path(p.abs_dir) / rel
+ abs_path = Path(abs_dir) / rel
entry = 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:
@@@ -1454,204 -857,70 +1453,203 @@@
except OSError:
return False
- def _drop_oversize_from_index(self, store: Path, working_dir: str, index_file: Path) -> None:
- """Unstage files larger than ``max_file_size_mb`` (datasets, weights, videos)."""
+ def _drop_oversize_from_index(
+ self, store: Path, working_dir: str, index_file: Path,
+ ) -> None:
+ """Remove any staged file larger than ``max_file_size_mb`` from the index.
+
+ Lets the agent keep snapshotting source code while refusing to
+ swallow generated assets (datasets, model weights, logs, videos).
+ """
if self.max_file_size_mb <= 0:
return
- ok, stdout, _ = _run_git(["ls-files", "--cached", "-z"], store, working_dir, index_file=index_file)
+ ok, stdout, _ = _run_git(
+ ["ls-files", "--cached", "-z"],
+ store, working_dir, index_file=index_file,
+ )
+ if not ok or not stdout:
+ return
- # ls-files -z output is NUL-separated. _run_git strips trailing
- # whitespace but that leaves NULs alone; rebuild list.
++ # NUL separators preserve whitespace within each literal filename.
+ paths = [p for p in stdout.split("\x00") if p]
abs_workdir = _normalize_path(working_dir)
- # NUL-separated literal paths; whitespace is part of the file name.
- oversize = [rel for rel in (stdout if ok else "").split("\x00") if rel and self._exceeds_size_cap(abs_workdir / rel)]
+ # Same predicate safe restore consults, called rather than restated:
+ # a threshold that drifted between the two would make a file both
+ # absent from the checkpoint and not recognised as capped at restore,
+ # which is precisely the deletion this change exists to prevent.
+ oversize = [
+ rel for rel in paths if self._exceeds_size_cap(abs_workdir / rel)
+ ]
if not oversize:
return
- logger.debug("Checkpoint: dropping %d oversize file(s) (>%d MB) from index",
- len(oversize), self.max_file_size_mb)
- for i in range(0, len(oversize), 200): # chunk: never overflow argv
- _run_git(["rm", "--cached", "--quiet", "--"] + oversize[i:i + 200],
- store, working_dir, index_file=index_file, allowed_returncodes={128})
+ logger.debug(
+ "Checkpoint: dropping %d oversize file(s) (>%d MB) from index",
+ len(oversize), self.max_file_size_mb,
+ )
+ # Use --pathspec-from-file for safety with many paths.
+ # Chunk into manageable batches.
+ BATCH = 200
+ for i in range(0, len(oversize), BATCH):
+ chunk = oversize[i:i + BATCH]
+ _run_git(
+ ["rm", "--cached", "--quiet", "--"] + chunk,
+ store, working_dir, index_file=index_file,
+ allowed_returncodes={128},
+ )
def _prune(self, store: Path, working_dir: str, ref: str) -> None:
- """Rewrite the ref to its last ``max_snapshots`` commits and gc (only limiting the
- log view, as v1 did, let loose objects accumulate forever)."""
- if _ref_commit_count(store, working_dir, ref) <= self.max_snapshots:
- return
- commits = _ref_commits_oldest_first(store, working_dir, ref)
- if _rewrite_ref_to(store, working_dir, ref, commits[-self.max_snapshots:]):
- _gc_store(store, working_dir)
+ """Keep only the last ``max_snapshots`` commits on the per-project ref.
- def _enforce_size_cap(self, store: Path) -> None:
- """Drop oldest checkpoints across ALL projects until under ``max_total_size_mb``."""
- cap_bytes = self.max_total_size_mb * _MB
- size = _dir_size_bytes(store) if cap_bytes > 0 else 0
- if size <= cap_bytes:
+ v1's ``_prune`` was documented as a no-op (``git``'s pack mechanism
+ was supposed to handle it, but only the log view was limited — loose
+ objects accumulated forever). v2 actually rewrites the ref to drop
+ commits older than ``max_snapshots`` and then runs ``git gc`` on the
+ store so unreachable objects are reclaimed.
+ """
+ ok, stdout, _ = _run_git(
+ ["rev-list", "--count", ref], store, working_dir,
+ allowed_returncodes={128},
+ )
+ if not ok:
+ return
+ try:
+ count = int(stdout)
+ except ValueError:
+ return
+ if count <= self.max_snapshots:
return
- logger.info("Checkpoint store exceeded %d MB (actual %d MB) — pruning oldest",
- self.max_total_size_mb, size // _MB)
- if _shrink_store_to_cap(store, str(store.parent), cap_bytes):
- _gc_store(store, str(store.parent))
-
-
-def _step_failed(step: str, err: str) -> bool:
- logger.debug("Checkpoint %s failed: %s", step, err)
- return False
-
-def _seed_project_index(p: _ProjectRefs, ref_commit: Optional[str]) -> None:
- """Reset the per-project index to the ref tip so ``add -A`` sees only changes since.
- First snapshot: just create the indexes dir. Existing index with no ref: discard it."""
- if not p.index_file.exists():
- p.index_file.parent.mkdir(parents=True, exist_ok=True)
- elif ref_commit:
- _run_git(["read-tree", ref_commit], p.store, p.abs_dir,
- index_file=p.index_file, allowed_returncodes={128})
- else:
- _unlink_quiet(p.index_file)
+ # Collect commits oldest → newest, take last N.
+ ok_list, list_out, _ = _run_git(
+ ["rev-list", "--reverse", ref], store, working_dir,
+ )
+ if not ok_list or not list_out:
+ return
+ commits = list_out.splitlines()
+ keep = commits[-self.max_snapshots:]
+
+ # Rebuild a linear chain off keep[0]'s tree.
+ new_parent: Optional[str] = None
+ for sha in keep:
+ ok_tree, tree_sha, _ = _run_git(
+ ["rev-parse", f"{sha}^{{tree}}"], store, working_dir,
+ )
+ if not ok_tree or not tree_sha:
+ return
+ ok_msg, msg, _ = _run_git(
+ ["log", "--format=%s", "-1", sha], store, working_dir,
+ )
+ commit_msg = msg if ok_msg and msg else "checkpoint"
+ args = ["commit-tree", tree_sha, "-m", commit_msg, "--no-gpg-sign"]
+ if new_parent is not None:
+ args = ["commit-tree", tree_sha, "-p", new_parent,
+ "-m", commit_msg, "--no-gpg-sign"]
+ ok_commit, new_sha, _ = _run_git(args, store, working_dir)
+ if not ok_commit or not new_sha:
+ return
+ new_parent = new_sha
+ if new_parent is None:
+ return
+ _run_git(["update-ref", ref, new_parent], store, working_dir)
+
+ # Reclaim objects from the dropped commits.
+ _run_git(
+ ["reflog", "expire", "--expire=now", "--all"],
+ store, working_dir,
+ )
+ _run_git(
+ ["gc", "--prune=now", "--quiet"],
+ store, working_dir, timeout=_GIT_TIMEOUT * 3,
+ )
+ _repair_bare_repo_dirs(store)
-def _index_unchanged_reason(p: _ProjectRefs, ref_commit: Optional[str]) -> Optional[str]:
- """Why a snapshot would be redundant ("no changes" / "empty tree"), else None. Compares against
- the ref tip, not HEAD — HEAD on the bare store points at a nonexistent branch, so every staged
- path would look like a new file."""
- if ref_commit:
- ok_diff, _, _ = _run_git(["diff-index", "--cached", "--quiet", ref_commit], p.store, p.abs_dir,
- allowed_returncodes={1}, index_file=p.index_file)
- return "no changes" if ok_diff else None
- ok_ls, ls_out, _ = _run_git(["ls-files", "--cached"], p.store, p.abs_dir, index_file=p.index_file)
- return "empty tree" if ok_ls and not ls_out.strip() else None
+ def _enforce_size_cap(self, store: Path) -> None:
+ """If total store size exceeds ``max_total_size_mb``, drop oldest
+ checkpoints across ALL projects until under the cap.
+ """
+ if self.max_total_size_mb <= 0:
+ return
+ cap_bytes = self.max_total_size_mb * 1024 * 1024
+ size = _dir_size_bytes(store)
+ if size <= cap_bytes:
+ return
+ logger.info(
+ "Checkpoint store exceeded %d MB (actual %d MB) — pruning oldest",
+ self.max_total_size_mb, size // (1024 * 1024),
+ )
+
+ # Collect (commit_time, ref, sha) across all per-project refs.
+ ok, stdout, _ = _run_git(
+ ["for-each-ref", "--format=%(refname)", _REFS_PREFIX],
+ store, str(store.parent),
+ allowed_returncodes={128},
+ )
+ if not ok or not stdout:
+ return
+ refs = [r for r in stdout.splitlines() if r.strip()]
+
+ any_dropped = False
+ # Round-robin-drop oldest commit per ref until under cap.
+ for _ in range(20): # hard upper bound to avoid pathological loops
+ size = _dir_size_bytes(store)
+ if size <= cap_bytes:
+ break
+ for ref in refs:
+ ok_count, count_out, _ = _run_git(
+ ["rev-list", "--count", ref], store, str(store.parent),
+ allowed_returncodes={128},
+ )
+ try:
+ count = int(count_out) if ok_count else 0
+ except ValueError:
+ count = 0
+ if count <= 1:
+ continue # keep at least one snapshot per project
+ ok_list, list_out, _ = _run_git(
+ ["rev-list", "--reverse", ref], store, str(store.parent),
+ )
+ if not ok_list or not list_out:
+ continue
+ commits = list_out.splitlines()
+ keep = commits[1:] # drop oldest
+ new_parent: Optional[str] = None
+ fail = False
+ for sha in keep:
+ ok_tree, tree_sha, _ = _run_git(
+ ["rev-parse", f"{sha}^{{tree}}"], store, str(store.parent),
+ )
+ if not ok_tree or not tree_sha:
+ fail = True
+ break
+ ok_msg, msg, _ = _run_git(
+ ["log", "--format=%s", "-1", sha], store, str(store.parent),
+ )
+ commit_msg = msg if ok_msg and msg else "checkpoint"
+ args = ["commit-tree", tree_sha, "-m", commit_msg, "--no-gpg-sign"]
+ if new_parent is not None:
+ args = ["commit-tree", tree_sha, "-p", new_parent,
+ "-m", commit_msg, "--no-gpg-sign"]
+ ok_commit, new_sha, _ = _run_git(args, store, str(store.parent))
+ if not ok_commit or not new_sha:
+ fail = True
+ break
+ new_parent = new_sha
+ if fail or new_parent is None:
+ continue
+ _run_git(["update-ref", ref, new_parent], store, str(store.parent))
+ any_dropped = True
+ if not any_dropped:
+ break
+
+ _run_git(
+ ["reflog", "expire", "--expire=now", "--all"],
+ store, str(store.parent),
+ )
+ _run_git(
+ ["gc", "--prune=now", "--quiet"],
+ store, str(store.parent), timeout=_GIT_TIMEOUT * 3,
+ )
+ _repair_bare_repo_dirs(store)
def format_checkpoint_list(checkpoints: List[Dict], directory: str) -> str:
diff --cc tools/environments/local.py
index bd33f7249de,d5158bf1e1d..5a8eaeb3b65
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@@ -369,22 -333,61 +364,23 @@@ def build_subprocess_env
_apply_profile_home(env)
if extra:
env.update(extra)
- return env
+ from agent.delegation_context import delegated_child_subprocess_env
+ return delegated_child_subprocess_env(env)
-# --- Shell discovery ---
-def _windows_bash_candidates(custom: "str | None") -> list[str]:
- """Ordered bash.exe candidates on Windows: HERMES_GIT_BASH_PATH, our portable Git
- under %LOCALAPPDATA%\\hermes\\git (PortableGit ``bin`` and MinGit ``usr\\bin``),
- known Git-for-Windows dirs, then PATH last — ``shutil.which`` may return WSL's
- bash, which fails silently on Windows paths."""
- getenv = os.environ.get
- lad = getenv("LOCALAPPDATA", "")
- roots = [
- lad and os.path.join(lad, "hermes", "git", "bin"),
- lad and os.path.join(lad, "hermes", "git", "usr", "bin"),
- os.path.join(getenv("ProgramFiles", r"C:\Program Files"), "Git", "bin"),
- os.path.join(getenv("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Git", "bin"),
- lad and os.path.join(lad, "Programs", "Git", "bin"),
- ]
- raw = [custom or "", *(os.path.join(r, "bash.exe") for r in roots if r)]
- candidates = list(dict.fromkeys(c for c in raw if c and os.path.isfile(c)))
- found = shutil.which("bash")
- if found and found not in candidates:
- candidates.append(found)
- return candidates
-
-
def _find_bash() -> str:
- """Find bash for command execution."""
- if not _IS_WINDOWS:
- return (shutil.which("bash")
- or next((p for p in ("/usr/bin/bash", "/bin/bash") if os.path.isfile(p)), None)
- or os.environ.get("SHELL") or "/bin/sh")
- custom = os.environ.get("HERMES_GIT_BASH_PATH")
- candidates = _windows_bash_candidates(custom)
- # First candidate that can actually start wins: a stale HERMES_GIT_BASH_PATH
- # pointing at a broken install must not beat a healthy portable Git.
- for candidate in candidates:
- if _bash_starts(candidate):
- if candidate != custom and custom and os.path.isfile(custom):
- logger.warning(
- "HERMES_GIT_BASH_PATH=%s fails to start; using %s instead", custom, candidate)
- return candidate
- if candidates:
- probe_details = "\n".join(
- detail for c in candidates if (detail := _bash_probe_details_cache.get(c)))
- if _mandatory_aslr_enabled() is True or _looks_like_msys_spawn_failure(probe_details):
- raise RuntimeError(_git_bash_aslr_help(candidates[0], probe_details))
- # Unknown failure class: return the first path so the caller sees the
- # real bash error instead of a less useful "not found".
- return candidates[0]
+ """Resolve the shell Hermes runs commands with. Owned by pm (the store
+ is the authority on bundled bash); this is a thin wrapper over
+ pm.shell() for callers that need a bash binary."""
+ import pm.shell
+
+ bash = pm.shell.bash()
+ if bash:
+ return bash
raise RuntimeError(
- "Git Bash not found. Hermes Agent requires Git for Windows on Windows.\n"
- "Install it from: https://git-scm.com/download/win\n"
- "Or set HERMES_GIT_BASH_PATH to your bash.exe location.")
+ "No shell found. Hermes needs bash (Git for Windows on Windows). "
+ "Run `hermes pm install` or reinstall the bundle."
+ )
_git_bash_bin_dirs_cache: "list[str] | None" = None
diff --cc tools/mcp_tool_sampling.py
index f54a8115e7f,89a5276d411..055031fcb3a
--- a/tools/mcp_tool_sampling.py
+++ b/tools/mcp_tool_sampling.py
@@@ -5,7 -6,8 +6,8 @@@ import functool
import json
import logging
import time
+ from contextvars import Context
-from typing import Callable, List, Optional
+from typing import TYPE_CHECKING, Callable, List, Optional
from tools.mcp_tool_common import _MISSING, _exc_str, _safe_numeric, _sanitize_error, mcp_field, _core
from tools.mcp_tool_schema import _normalize_mcp_input_schema
diff --cc tools/patch_parser.py
index 5682928a14d,3c9c1c3f37e..1454dd7b946
--- a/tools/patch_parser.py
+++ b/tools/patch_parser.py
@@@ -9,11 -9,10 +9,13 @@@ import inspec
import re
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Callable, Dict, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
+
+if TYPE_CHECKING: # annotations only; the real import is per-call in apply_v4a_operations
+ from tools.file_operations_common import PatchResult
+ from tools.file_operations_common import PatchResult
+
class OperationType(Enum):
ADD = "add"
diff --cc tools/process_registry.py
index a171f6f0cab,f35027d8f2d..db784b64c9a
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@@ -1908,99 -2021,8 +2036,9 @@@ class ProcessRegistry(ProcessCheckpoint
self._completion_consumed &= tracked
self._poll_observed &= tracked
- # ----- Checkpoint (crash recovery) -----
-
- def _write_checkpoint(self, extra_entries: Optional[List[Dict[str, Any]]] = None):
- """Write running process metadata to the checkpoint file atomically."""
- try:
- with self._lock:
- entries = []
- for s in self._running.values():
- if s.exited:
- continue
- # Backfill the start time so recovery can detect PID recycling
- # even for sessions spawned before this field existed.
- if s.host_start_time is None and s.pid_scope == "host" and s.pid:
- s.host_start_time = self._safe_host_start_time(s.pid)
- entry = {"session_id": s.id, **{f: getattr(s, f) for f in _CHECKPOINT_FIELDS}}
- # Redact inline credentials before persisting (~/.hermes/processes.json).
- # Recovery uses command only for display (adoption re-validates the
- # PID, never re-runs it), so masking is lossless.
- # See #77484.
- entry["command"] = redact_sensitive_text(s.command, code_file=True)
- entry["owner_task_id"] = s.owner_task_id or s.task_id
- entries.append(entry)
- if extra_entries:
- tracked_ids = {item.get("session_id") for item in entries}
- entries.extend(item for item in extra_entries if item.get("session_id") not in tracked_ids)
- from utils import atomic_json_write
- atomic_json_write(CHECKPOINT_PATH, entries)
- except Exception as e:
- logger.debug("Failed to write checkpoint file: %s", e, exc_info=True)
- def recover_from_checkpoint(self) -> int:
- """On gateway startup, probe PIDs from the checkpoint file; returns how many
- were recovered as detached sessions."""
- if not CHECKPOINT_PATH.exists():
- return 0
- try:
- entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8-sig"))
- except Exception:
- return 0
- recovered = 0
- unresolved_scope_entries: List[Dict[str, Any]] = []
- for entry in entries:
- pid, pid_scope = entry.get("pid"), entry.get("pid_scope", "host")
- if not pid:
- continue
- if pid_scope != "host": # in-sandbox PIDs mean nothing once the env handle is gone
- logger.info(
- "Skipping recovery for non-host process: %s (pid=%s, scope=%s)",
- entry.get("command", "unknown")[:60], pid, pid_scope)
- continue
- # Alive AND the same process: across a restart the kernel may have
- # recycled the PID onto a stranger, and adopting it would let a later
- # kill tree-kill e.g. a browser.
- if not self._host_pid_is_ours(pid, entry.get("host_start_time")):
- if self._is_host_pid_alive(pid):
- logger.info(
- "Not recovering session %s: pid %d is alive but its "
- "start time no longer matches — PID was recycled onto "
- "an unrelated process; refusing to adopt it.",
- entry.get("session_id", "?"), pid)
- systemd_unit = entry.get("systemd_unit", "")
- if systemd_unit and not _stop_systemd_unit(systemd_unit):
- logger.warning(
- "Could not reap persisted scope %s for dead wrapper pid %s; "
- "retaining checkpoint entry for the next startup",
- systemd_unit, pid)
- unresolved_scope_entries.append(entry)
- continue
- fields = {f: entry.get(f, _CHECKPOINT_DEFAULTS[f]) for f in _CHECKPOINT_FIELDS}
- fields.update(
- command=entry.get("command", "unknown"),
- owner_task_id=entry.get("owner_task_id", "") or entry.get("task_id", ""),
- started_at=entry.get("started_at", time.time()))
- # detached: can't read output, but can report status + kill
- session = ProcessSession(id=entry["session_id"], detached=True, **fields)
- with self._lock:
- self._running[session.id] = session
- recovered += 1
- logger.info("Recovered detached process: %s (pid=%d)", session.command[:60], pid)
- # Re-enqueue watcher so gateway can resume notifications
- if session.watcher_interval > 0:
- self.pending_watchers.append({
- "session_id": session.id,
- "check_interval": session.watcher_interval,
- "session_key": session.session_key,
- **{key: getattr(session, f"watcher_{key}") for key in _WATCHER_ROUTE_KEYS},
- "notify_on_complete": session.notify_on_complete,
- "parent_session_id": session.parent_session_id,
- })
- self._write_checkpoint(extra_entries=unresolved_scope_entries)
- return recovered
+
process_registry = ProcessRegistry()
diff --cc tools/process_registry_checkpoint.py
index 00000000000,a128a8a6409..4fe4e288b0f
mode 000000,100644..100644
--- a/tools/process_registry_checkpoint.py
+++ b/tools/process_registry_checkpoint.py
@@@ -1,0 -1,111 +1,111 @@@
+ """Running-process checkpoint persistence and PID-safe recovery."""
+
+ import json
+ import logging
+ import time
+ from typing import Any, Dict, List, Optional
+
+ from agent.redact import redact_sensitive_text
+
+ logger = logging.getLogger("tools.process_registry")
+
+
+ class ProcessCheckpointMixin:
+ # ----- Checkpoint (crash recovery) -----
+
+ def _write_checkpoint(self, extra_entries: Optional[List[Dict[str, Any]]] = None):
+ """Write running process metadata to the checkpoint file atomically."""
+ from tools.process_registry import CHECKPOINT_PATH, _CHECKPOINT_FIELDS
+
+ try:
+ with self._lock:
+ entries = []
+ for s in self._running.values():
+ if s.exited:
+ continue
+ # Backfill the start time so recovery can detect PID recycling
+ # even for sessions spawned before this field existed.
+ if s.host_start_time is None and s.pid_scope == "host" and s.pid:
+ s.host_start_time = self._safe_host_start_time(s.pid)
+ entry = {"session_id": s.id, **{f: getattr(s, f) for f in _CHECKPOINT_FIELDS}}
+ # Redact inline credentials before persisting (~/.hermes/processes.json).
+ # Recovery uses command only for display (adoption re-validates the
+ # PID, never re-runs it), so masking is lossless.
+ # See #77484.
+ entry["command"] = redact_sensitive_text(s.command, code_file=True)
+ entry["owner_task_id"] = s.owner_task_id or s.task_id
+ entries.append(entry)
+ if extra_entries:
+ tracked_ids = {item.get("session_id") for item in entries}
+ entries.extend(item for item in extra_entries if item.get("session_id") not in tracked_ids)
+ from utils import atomic_json_write
+ atomic_json_write(CHECKPOINT_PATH, entries)
+ except Exception as e:
+ logger.debug("Failed to write checkpoint file: %s", e, exc_info=True)
+
+ def recover_from_checkpoint(self) -> int:
+ """On gateway startup, probe PIDs from the checkpoint file; returns how many
+ were recovered as detached sessions."""
+ from tools.process_registry import (
+ CHECKPOINT_PATH, ProcessSession, _CHECKPOINT_FIELDS,
+ _CHECKPOINT_DEFAULTS, _WATCHER_ROUTE_KEYS, _stop_systemd_unit,
+ )
+
+ if not CHECKPOINT_PATH.exists():
+ return 0
+ try:
- entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8"))
++ entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8-sig"))
+ except Exception:
+ return 0
+ recovered = 0
+ unresolved_scope_entries: List[Dict[str, Any]] = []
+ for entry in entries:
+ pid, pid_scope = entry.get("pid"), entry.get("pid_scope", "host")
+ if not pid:
+ continue
+ if pid_scope != "host": # in-sandbox PIDs mean nothing once the env handle is gone
+ logger.info(
+ "Skipping recovery for non-host process: %s (pid=%s, scope=%s)",
+ entry.get("command", "unknown")[:60], pid, pid_scope)
+ continue
+ # Alive AND the same process: across a restart the kernel may have
+ # recycled the PID onto a stranger, and adopting it would let a later
+ # kill tree-kill e.g. a browser.
+ if not self._host_pid_is_ours(pid, entry.get("host_start_time")):
+ if self._is_host_pid_alive(pid):
+ logger.info(
+ "Not recovering session %s: pid %d is alive but its "
+ "start time no longer matches — PID was recycled onto "
+ "an unrelated process; refusing to adopt it.",
+ entry.get("session_id", "?"), pid)
+ systemd_unit = entry.get("systemd_unit", "")
+ if systemd_unit and not _stop_systemd_unit(systemd_unit):
+ logger.warning(
+ "Could not reap persisted scope %s for dead wrapper pid %s; "
+ "retaining checkpoint entry for the next startup",
+ systemd_unit, pid)
+ unresolved_scope_entries.append(entry)
+ continue
+ fields = {f: entry.get(f, _CHECKPOINT_DEFAULTS[f]) for f in _CHECKPOINT_FIELDS}
+ fields.update(
+ command=entry.get("command", "unknown"),
+ owner_task_id=entry.get("owner_task_id", "") or entry.get("task_id", ""),
+ started_at=entry.get("started_at", time.time()))
+ # detached: can't read output, but can report status + kill
+ session = ProcessSession(id=entry["session_id"], detached=True, **fields)
+ with self._lock:
+ self._running[session.id] = session
+ recovered += 1
+ logger.info("Recovered detached process: %s (pid=%d)", session.command[:60], pid)
+ # Re-enqueue watcher so gateway can resume notifications
+ if session.watcher_interval > 0:
+ self.pending_watchers.append({
+ "session_id": session.id,
+ "check_interval": session.watcher_interval,
+ "session_key": session.session_key,
+ **{key: getattr(session, f"watcher_{key}") for key in _WATCHER_ROUTE_KEYS},
+ "notify_on_complete": session.notify_on_complete,
+ "parent_session_id": session.parent_session_id,
+ })
+ self._write_checkpoint(extra_entries=unresolved_scope_entries)
+ return recovered
diff --cc uv.lock
index 019ae3a9f5d,148f151daf7..7260445cbff
--- a/uv.lock
+++ b/uv.lock
@@@ -602,18 -653,17 +602,18 @@@ source = { registry = "https://pypi.org
dependencies = [
{ name = "cffi" },
]
- sdist = { url = "https://files.pythonhosted.org/packages/8a/b6/017dc5f852ed9b8735af77774509271acbf1de02d238377667145fcee01d/brotlicffi-1.2.0.1.tar.gz", hash = "sha256:c20d5c596278307ad06414a6d95a892377ea274a5c6b790c2548c009385d621c", size = 478156, upload-time = "2026-03-05T19:54:11.547Z" }
+ sdist = { url = "https://files.pythonhosted.org/packages/71/97/7845739a36828ffe751a1c6b240692f552fd7ecf65026c51326c0a4aa369/brotlicffi-1.2.0.2.tar.gz", hash = "sha256:5e0fbd13644cf1f6015e75fa5e0ad8fdce1048d9c9ff90b0ce826174b249ee35", size = 478755, upload-time = "2026-08-21T17:29:18.415Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/ef/f9/dfa56316837fa798eac19358351e974de8e1e2ca9475af4cb90293cd6576/brotlicffi-1.2.0.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c85e65913cf2b79c57a3fdd05b98d9731d9255dc0cb696b09376cc091b9cddd", size = 433046, upload-time = "2026-03-05T19:53:46.209Z" },
- { url = "https://files.pythonhosted.org/packages/4a/f5/f8f492158c76b0d940388801f04f747028971ad5774287bded5f1e53f08d/brotlicffi-1.2.0.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:535f2d05d0273408abc13fc0eebb467afac17b0ad85090c8913690d40207dac5", size = 1541126, upload-time = "2026-03-05T19:53:48.248Z" },
- { url = "https://files.pythonhosted.org/packages/3b/e1/ff87af10ac419600c63e9287a0649c673673ae6b4f2bcf48e96cb2f89f60/brotlicffi-1.2.0.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ce17eb798ca59ecec67a9bb3fd7a4304e120d1cd02953ce522d959b9a84d58ac", size = 1541983, upload-time = "2026-03-05T19:53:50.317Z" },
- { url = "https://files.pythonhosted.org/packages/47/c0/80ecd9bd45776109fab14040e478bf63e456967c9ddee2353d8330ed8de1/brotlicffi-1.2.0.1-cp314-cp314t-win32.whl", hash = "sha256:3c9544f83cb715d95d7eab3af4adbbef8b2093ad6382288a83b3a25feb1a57ec", size = 349047, upload-time = "2026-03-05T19:53:52.215Z" },
- { url = "https://files.pythonhosted.org/packages/ab/98/13e5b250236a281b6cd9e92a01ee1ae231029fa78faee932ef3766e1cb24/brotlicffi-1.2.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:625f8115d32ae9c0740d01ea51518437c3fbaa3e78d41cb18459f6f7ac326000", size = 385652, upload-time = "2026-03-05T19:53:53.892Z" },
- { url = "https://files.pythonhosted.org/packages/9a/9f/b98dcd4af47994cee97aebac866996a006a2e5fc1fd1e2b82a8ad95cf09c/brotlicffi-1.2.0.1-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:91ba5f0ccc040f6ff8f7efaf839f797723d03ed46acb8ae9408f99ffd2572cf4", size = 432608, upload-time = "2026-03-05T19:53:56.736Z" },
- { url = "https://files.pythonhosted.org/packages/b1/7a/ac4ee56595a061e3718a6d1ea7e921f4df156894acffb28ed88a1fd52022/brotlicffi-1.2.0.1-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be9a670c6811af30a4bd42d7116dc5895d3b41beaa8ed8a89050447a0181f5ce", size = 1534257, upload-time = "2026-03-05T19:53:58.667Z" },
- { url = "https://files.pythonhosted.org/packages/99/39/e7410db7f6f56de57744ea52a115084ceb2735f4d44973f349bb92136586/brotlicffi-1.2.0.1-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f3314a3476f59e5443f9f72a6dff16edc0c3463c9b318feaef04ae3e4683f5a", size = 1536838, upload-time = "2026-03-05T19:54:00.705Z" },
- { url = "https://files.pythonhosted.org/packages/a6/75/6e7977d1935fc3fbb201cbd619be8f2c7aea25d40a096967132854b34708/brotlicffi-1.2.0.1-cp38-abi3-win32.whl", hash = "sha256:82ea52e2b5d3145b6c406ebd3efb0d55db718b7ad996bd70c62cec0439de1187", size = 343337, upload-time = "2026-03-05T19:54:02.446Z" },
- { url = "https://files.pythonhosted.org/packages/d8/ef/e7e485ce5e4ba3843a0a92feb767c7b6098fd6e65ce752918074d175ae71/brotlicffi-1.2.0.1-cp38-abi3-win_amd64.whl", hash = "sha256:da2e82a08e7778b8bc539d27ca03cdd684113e81394bfaaad8d0dfc6a17ddede", size = 379026, upload-time = "2026-03-05T19:54:04.322Z" },
++ { url = "https://files.pythonhosted.org/packages/77/a2/edda4f3fc7143434402eacad1e91433fe68ae648c22738eeddb6138638ba/brotlicffi-1.2.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ad05ca993234cf947f0ad71b1c8bc0af3d74e0410b1e2c32bb99de0cef6a994b", size = 438789, upload-time = "2026-08-21T17:28:55.708Z" },
++ { url = "https://files.pythonhosted.org/packages/0d/9c/506dc8edabb3cf9339c89f1ecc80a218aa166bb83b9f2e9cc1da67314072/brotlicffi-1.2.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0636cb5a85f31c36e08953d09a226cb788be900b976f81302895e3cf35d5e707", size = 1541246, upload-time = "2026-08-21T17:28:57.669Z" },
++ { url = "https://files.pythonhosted.org/packages/9f/d6/74cee9f9fbea8c42030a81056c64e092030a95bd2756ea83da1d1e8f5f29/brotlicffi-1.2.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:97bae40d45ebc2a6ac7b1c9b30825496a257192194b672ef5869e2df93467f69", size = 1542129, upload-time = "2026-08-21T17:28:59.502Z" },
++ { url = "https://files.pythonhosted.org/packages/24/cc/c32630b042ec2a13e8342e6ecb6b9d3531b1be4647b733d6fd365976041c/brotlicffi-1.2.0.2-cp314-cp314t-win32.whl", hash = "sha256:8f3f9bd61293dc48359763e693951393f39656086315067cf97e23e23e8911ab", size = 346840, upload-time = "2026-08-21T17:29:01.085Z" },
++ { url = "https://files.pythonhosted.org/packages/ee/0b/83cac3075721fe4c253ea1cc5310cb687c2f7d987e0fd60eb3ed769c24c0/brotlicffi-1.2.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:908add8a9c0eea00f5de799dc6de9f6d205d9ee11afabc7c03d6812c481200e2", size = 386079, upload-time = "2026-08-21T17:29:02.667Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/71/c27f24b8334f65f2492601c7764338f156cb904d2ffe0061e6004a76d9cc/brotlicffi-1.2.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:d5a8ffa154f16660ab818d78045b55fa6f9970f1ca4c38998766e99c672071cb", size = 438885, upload-time = "2026-08-21T17:29:04.113Z" },
+ { url = "https://files.pythonhosted.org/packages/ef/22/d8fd1a4d09b7ab563b89380395e09151d2ef1344be31594df6a6987d4028/brotlicffi-1.2.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ec6b1af7b7a8ce788354f2c603651ada0fba166ec31ab879e2eec462a3e6dbf4", size = 1534365, upload-time = "2026-08-21T17:29:05.878Z" },
+ { url = "https://files.pythonhosted.org/packages/06/78/076419ed6c2c6aa3eaac6fd6b076502b4be89d50625fcdc513cd4aeca718/brotlicffi-1.2.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22916101de0e7ff535f2edf54b52a85591853b8ae9a98737643defdd3c063a3a", size = 1536851, upload-time = "2026-08-21T17:29:07.599Z" },
+ { url = "https://files.pythonhosted.org/packages/35/dd/31ae9945cbd605339fb51c9a609f7dbb182cd361adeabc1d470142357206/brotlicffi-1.2.0.2-cp39-abi3-win32.whl", hash = "sha256:df1d34c4ad9adbf7f63a6b42f7d0e4dfd259c88141b85145b57abecc1abc3b24", size = 342379, upload-time = "2026-08-21T17:29:09.05Z" },
+ { url = "https://files.pythonhosted.org/packages/95/ae/afd54e744df93b51cc29f6a19beccf9998b25743d7177697390de10479d1/brotlicffi-1.2.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:489ca4da3ee65926d72bf01584b61088a9da6bdd1bb01b2040901e1beaffa8f0", size = 379761, upload-time = "2026-08-21T17:29:10.687Z" },
- { url = "https://files.pythonhosted.org/packages/37/da/a5b65a86725d772504a348193cf1fab5ad6410794b422bf81faa17a96a66/brotlicffi-1.2.0.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:cf500bb9e02e1474ced1ecf22f74c568de2816b3627af6352ec51ac5e09e60ee", size = 407459, upload-time = "2026-08-21T17:29:12.385Z" },
- { url = "https://files.pythonhosted.org/packages/e1/c7/a253288e66ee340f2f6320eda7022daa723f2918438d586a59e9c998aa27/brotlicffi-1.2.0.2-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dbb81489562dd5363bf86d9a8edb0ec8c97049b0819ba4936fc023e8847248bc", size = 406825, upload-time = "2026-08-21T17:29:13.992Z" },
- { url = "https://files.pythonhosted.org/packages/6e/6c/ea8e3d34e1d64c5e5a920bb0c89bf9e92badf973937a60922820395e622d/brotlicffi-1.2.0.2-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fc7647657e4f3d73eab591910dbecb57d1ecaea7aa3dd04e6d704a2756fe0c59", size = 402903, upload-time = "2026-08-21T17:29:15.524Z" },
- { url = "https://files.pythonhosted.org/packages/4e/17/17c22d48819001ca08cadab63b09b00e0c56a7579478aa7c2623f4280de6/brotlicffi-1.2.0.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:5eb5563173afb92c9111b180349ff17d7c83c79febabadca5de983b552565c3c", size = 378395, upload-time = "2026-08-21T17:29:16.857Z" },
]
[[package]]
@@@ -1848,14 -1921,14 +1848,14 @@@ requires-dist =
{ name = "aiohttp", marker = "extra == 'slack'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'sms'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'teams'", specifier = "==3.14.3" },
- { name = "aiohttp-socks", marker = "extra == 'matrix'", specifier = "==0.11.0" },
- { name = "aiosqlite", marker = "extra == 'matrix'", specifier = "==0.22.1" },
+ { name = "aiohttp-socks", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.11.0" },
+ { name = "aiosqlite", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.22.1" },
{ name = "alibabacloud-dingtalk", marker = "extra == 'dingtalk'", specifier = "==2.2.42" },
{ name = "anthropic", marker = "extra == 'anthropic'", specifier = "==0.87.0" },
- { name = "asyncpg", marker = "extra == 'matrix'", specifier = "==0.31.0" },
+ { name = "asyncpg", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.31.0" },
{ name = "azure-identity", marker = "extra == 'azure-identity'", specifier = "==1.25.3" },
{ name = "boto3", marker = "extra == 'bedrock'", specifier = "==1.42.89" },
- { name = "brotlicffi", marker = "extra == 'messaging'", specifier = "==1.2.0.1" },
+ { name = "brotlicffi", marker = "extra == 'messaging'", specifier = "==1.2.0.2" },
{ name = "certifi", specifier = "==2026.5.20" },
{ name = "concurrent-log-handler", marker = "sys_platform == 'win32'", specifier = "==0.9.29" },
{ name = "croniter", specifier = "==6.0.0" },
diff --cc website/docs/getting-started/installation.md
index 2ca4b90c24c,352f88aa2c8..a09c2c41c18
--- a/website/docs/getting-started/installation.md
+++ b/website/docs/getting-started/installation.md
@@@ -201,10 -171,26 +201,30 @@@ the administrator supplies system libra
For more diagnostics, run `hermes doctor` — it will tell you exactly what's missing and how to fix it.
+ ### Symlinked home directories and external storage
+
+ Hermes supports a symlinked `HERMES_HOME` and symlinked home subdirectories,
+ including `hooks`, `skills`, `sessions`, and `logs`. During home initialization,
+ existing directory links are preserved, and permissions on linked directories
+ (and descendants such as `logs/curator`) are left to their owner.
+
+ If a link target is missing, inaccessible, or not a directory, initialization
+ stops with a storage error naming the path and link target. Hermes does **not**
+ replace the link or create its missing target: doing so could write data onto
+ the local disk while an external or NAS volume is unmounted. Check the reported
+ link, restore the mount or correct its target, and verify access permissions
+ before retrying. For a deliberately new dotfiles target, create it yourself only
+ after confirming the intended storage is available.
+
+ `hermes doctor` reports these failures as storage problems, not invalid YAML.
+ Keep your existing `config.yaml`; running `hermes setup` is not the repair for an
+ unavailable directory. This is a directory-availability check, not a mount monitor:
+ an existing directory cannot establish that the intended volume is mounted.
+
## Install method auto-detection
-Hermes auto-detects whether it was installed via the git installer, Docker, or NixOS, and `hermes update` prints the matching update command for that path. There's no env var to set — the detection is based on the install layout (`~/.hermes/hermes-agent/` checkout, Docker image stamp, or Nix store path). `hermes doctor` also surfaces the detected method under its environment summary.
+The update owner depends on the running installation, not only its data home.
+Source checkouts use the managed Git update path. Desktop bundles, Docker,
+Nix, and Termux packages retain their package owner's update mechanism.
+`hermes doctor` reports installation provenance. See
+[Updating & Uninstalling](./updating.md) before changing package-owned files.
diff --cc website/docs/getting-started/updating.md
index e6d70fcbfe4,24c9efde0ef..363f921c992
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@@ -79,22 -20,37 +79,38 @@@ Back up data before changing release ch
`hermes update` automatically detects new configuration options and prompts you to add them. If you skipped that prompt, you can manually run `hermes config check` to see missing options, then `hermes config migrate` to interactively add them.
:::
+ ### Passive update notices
+
+ Pinned or noninteractive installations can disable passive CLI version and banner update checks:
+
+ ```bash
+ hermes config set updates.check false
+ ```
+
+ This suppresses both cached update notices and passive update-check network requests. The default is `true`. Explicit `hermes update --check` and `hermes update` still work; this setting does not control the Desktop application's updater.
+
### What happens during an update
-When you run `hermes update`, the following steps occur:
+For an admitted source checkout, `hermes update` runs these phases:
1. **Pre-update snapshot** — a lightweight state snapshot is saved by default (covers pairing data, cron jobs, `config.yaml`, `.env`, `auth.json`, and other state files that get modified at runtime; individual files over 1 GiB are skipped so a large sessions DB never slows the update down). Because the code swap and gateway restarts touch every profile, the same snapshot is taken for **every profile** on the install — each into its own `state-snapshots/` directory — and the post-update cron-jobs safety net checks each profile against its own snapshot. Controlled by `updates.pre_update_backup` (`quick` by default, `full` for a zip of all of `HERMES_HOME`, `off` to disable). Recoverable via the snapshot restore flow described under [Snapshots and rollback](../user-guide/checkpoints-and-rollback.md). Quick snapshots are file-loss recovery, not code-rollback insurance — for a coherent point-in-time rollback use `--backup` (full mode).
-2. **Git pull** — pulls the latest code from the `main` branch and updates submodules
+2. **Code update** — applies the configured source branch or stable release tag and updates submodules.
3. **Post-pull syntax validation + auto-rollback** — after the pull, Hermes compiles the nine critical files every `hermes` invocation imports at startup. If any fails to parse (e.g. an orphan merge-conflict marker, an accidentally truncated file), Hermes runs `git reset --hard <pre-pull-sha>` to roll the install back so your shell stays bootable. Re-run `hermes update` once the upstream fix lands.
-4. **Dependency install** — runs `uv pip install -e ".[all]"` to pick up new or changed dependencies
+4. **Dependency preparation** — PM provisions required tools and prepares a complete Python environment from the new lock, existing extras, and enabled plugin requirements. It validates that environment before publishing its selection.
5. **Config migration** — detects new config options added since your version and prompts you to set them
6. **Desktop rebuild (stage-and-swap)** — if the Hermes Desktop app was built from this checkout, it is rebuilt so the GUI matches the new code. The rebuild packs into a temporary staging directory next to `apps/desktop/release/`, verifies the staged app, and only then renames it over the previous build. A rebuild that fails at any point — corrupt Electron download, missing dependency, disk full — leaves the previous app untouched and launchable; the update reports `⚠ Update partially complete` and `hermes desktop` retries the rebuild.
7. **Gateway auto-restart** — running gateways are refreshed after the update completes so the new code takes effect immediately. Service-managed gateways (systemd on Linux, launchd on macOS) are restarted through the service manager. Manual gateways are relaunched automatically when Hermes can map the running PID back to a profile. Manually-launched `hermes serve` / `hermes dashboard` backends (for example a network-bound serve powering a remote Desktop) are handled the same way: each backend records its bind address in the install's spawn ledger at startup, so the update stops it before the code swap and relaunches it afterward on the **same host and port** — a remote Desktop pointed at that endpoint reconnects instead of stranding. Backends owned by a running Desktop app are left to the app's own respawn.
+ ### Missing Windows updater files
+
+ If the maintained updater script is missing (for example after antivirus quarantine), the legacy update forwarder fails instead of reporting a successful hand-off. Repair the installation and review the security software's quarantine report before retrying; do not disable antivirus protection. Before reporting success, the maintained updater checks the CLI import, Windows executable header, ASAR header and packaged main entry, readable renderer HTML with a local module entry, initial module files, and current build stamp. These are minimum artifact checks, not a full dependency audit or an application/backend launch test. Missing Python is reported before waiting for Desktop shutdown; dependency repair is still allowed to run as part of the update. Electron checks maintained handoff prerequisites before stopping backends when that layout is present; genuine legacy-flat updater layouts remain supported, so not every missing updater file is detected before backend shutdown.
+
+ On Windows, a Desktop reopened during packaging is stopped again immediately before the staged build is promoted. This cleanup is restricted to executables inside that checkout's Desktop release tree; unrelated installations are not stopped. A remaining lock still makes staged promotion fail rather than bypassing the rename error.
+
### Updating against a non-default branch: `--branch`
-By default `hermes update` tracks `origin/main`. Pass `--branch <name>` to update against a different branch — useful for QA channels, feature branches, or release-candidate testing:
+On the default source channel, `hermes update` tracks `origin/main`. Use
+`--branch NAME` for a one-run branch override:
```bash
hermes update --branch release-candidate