Skip to content

The agent that grows with you

fix(pm): close runtime publication and updater audit gaps

ethernet3c08d16ba749
diff --git a/apps/desktop/electron/desktop-installation.test.ts b/apps/desktop/electron/desktop-installation.test.ts
index dbb15ac557f..47d20265e92 100644
--- a/apps/desktop/electron/desktop-installation.test.ts
+++ b/apps/desktop/electron/desktop-installation.test.ts
@@ -38,7 +38,10 @@ test('loadOrCreateInstallationId persists and reuses one installation ID', () =>
loadOrCreateInstallationId(filePath, () => ID_B),
ID_A
)
- if (process.platform !== 'win32') assert.equal(fs.statSync(filePath).mode & 0o777, 0o600)
+
+ if (process.platform !== 'win32') {
+ assert.equal(fs.statSync(filePath).mode & 0o777, 0o600)
+ }
}))
test('loadOrCreateInstallationId tightens an existing identity file', () =>
diff --git a/apps/desktop/electron/git-worktree-ops.ts b/apps/desktop/electron/git-worktree-ops.ts
index f8bc1bf2ff9..992322936bc 100644
--- a/apps/desktop/electron/git-worktree-ops.ts
+++ b/apps/desktop/electron/git-worktree-ops.ts
@@ -387,8 +387,13 @@ async function listBranches(repoPath, gitBin) {
runGit(gitBin, ['for-each-ref', '--format=%(refname:short)', '--sort=-committerdate', 'refs/heads'], resolved),
runGit(gitBin, ['for-each-ref', '--format=%(refname:short)', '--sort=-committerdate', 'refs/remotes'], resolved)
])
+
const [local, remote] = probes
- if (local.status === 'rejected' || remote.status === 'rejected') return []
+
+ if (local.status === 'rejected' || remote.status === 'rejected') {
+ return []
+ }
+
const [localOut, remoteOut] = [local.value, remote.value]
const trees = await listWorktrees(resolved, gitBin)
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 1ef349835ed..ac442207569 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -205,7 +205,6 @@ import {
import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
import { probeGatewayWebSocket } from './gateway-ws-probe'
import { registerGitIpc } from './git-ipc'
-import { clearStaleGitLocks } from './gitlock'
import { readAndConsumeHandoffResult } from './handoff-result'
import {
ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
@@ -309,6 +308,7 @@ import {
runPrimaryBackendStartup
} from './primary-backend-startup'
import { rehomePrimaryConnection } from './primary-connection-rehome'
+import { PRODUCT_IDENTITY } from './product-identity'
import {
assertLocalProfileCanStart,
decideProfileDeleteAction,
@@ -390,35 +390,28 @@ import {
import {
compareApiUrl,
parseCompareBehindCount,
- resolveBehindCount,
- resolveCommitLogSelection,
- shouldCountCommits
+ resolveCommitLogSelection
} from './update-count'
import { waitForUpdateClearance } from './update-gate'
import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'
import { isOfficialSshRemote, OFFICIAL_REPO_HTTPS_URL } from './update-remote'
-import { classifyUpdateRoot } from './update-root-policy'
-import { resolveUpdaterMechanism } from './updater'
import {
- collectRelaunchArgs,
+ resolveUpdaterMechanism,
+ type UpdaterStrategy
+} from './updater'
+import {
observeUpdaterHandoff,
- resolvePosixScriptHandoff,
resolveStagedUpdaterBinary,
- resolveUpdateScriptHandoff,
- sandboxFallbackFromEnv,
spawnUpdaterProcess,
- stagedUpdaterSupportsPrewrittenMarker,
- wrapHandoffForDetachedConsole
+ stagedUpdaterSupportsPrewrittenMarker
} from './updater-process'
import { AppInstallerStrategy } from './updater/app-installer'
-import { ExternalStrategy } from './updater/external'
-import { consumePendingRelaunch, writePendingRelaunch } from './updater/relaunch'
import {
- formatBlockerMessage,
- formatProbeFailedMessage,
- scanVenvBlockers,
- stopSafeVenvBlockers
-} from './venv-blocker-scan'
+ createCheckoutStrategy
+} from './updater/checkout'
+import { ExternalStrategy } from './updater/external'
+import { consumePendingRelaunch, registerUpdateRelaunch } from './updater/relaunch'
+import { startRelaunchWaiter } from './updater/relaunch-waiter'
import { isHermesOwnedVenvDaemon } from './venv-holder-select'
import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'
import { createWakeIndicatorWindowController } from './wake-indicator-window'
@@ -3049,176 +3042,10 @@ async function checkUpdates() {
}))
}
- const updateRoot = resolveUpdateRoot()
- let { branch } = readDesktopUpdateConfig()
- const gitDir = path.join(updateRoot, '.git')
-
- if (!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 = 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 resolveHealedBranch(updateRoot, branch)
- const originUrl = await getOriginUrl(updateRoot)
-
- if (isOfficialSshRemote(originUrl)) {
- const git = args => runGit(args, { cwd: updateRoot }).then(r => r.stdout.trim())
-
- const [currentSha, target, dirtyStr, currentBranch] = await Promise.all([
- git(['rev-parse', 'HEAD']),
- runGit(['ls-remote', OFFICIAL_REPO_HTTPS_URL, `refs/heads/${branch}`], { cwd: updateRoot }),
- git(['status', '--porcelain']),
- git(['rev-parse', '--abbrev-ref', 'HEAD'])
- ])
-
- const targetSha = firstLine(target.stdout).split(/\s+/)[0] || ''
-
- if (target.code !== 0 || !targetSha) {
- return {
- supported: true,
- branch,
- error: 'fetch-failed',
- message: 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 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 runGit(['fetch', '--quiet', 'origin', branch], { cwd: updateRoot })
-
- if (fetched.code !== 0) {
- return {
- supported: true,
- branch,
- error: 'fetch-failed',
- message: firstLine(fetched.stderr) || 'git fetch failed.',
- hermesRoot: updateRoot,
- fetchedAt: Date.now()
- }
- }
-
- const git = args => 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 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 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 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()
- }
+ // Checkout install: dispatch through the strategy layer — one mechanism,
+ // one stamp, no direct body path. The flow lives in updater/checkout.ts;
+ // this is the only production door to the checkout arms.
+ return resolveCheckoutUpdateStrategy().check()
}
// Best-effort exact behind-count for graphs the local clone can't measure.
@@ -3329,13 +3156,78 @@ function resolveBundledUpdateStrategy(bundledPayload) {
emitUpdateProgress,
appVersion: app.getVersion(),
quit: () => app.quit(),
- registerPendingRelaunch: fromVersion => writePendingRelaunch(HERMES_HOME, fromVersion)
+ registerPendingRelaunch: fromVersion =>
+ registerUpdateRelaunch(HERMES_HOME, fromVersion, {
+ // The relaunch mechanism: a detached waiter, external to the dying
+ // process. It snapshots the OLD package, signals the handshake,
+ // waits for this process to exit and for the OS to swap the
+ // installed package version, then activates the NEW package.
+ // Electron's app.relaunch would re-execute the OLD package's
+ // binary and can hold the swap open, so it is not used. The
+ // script is staged to a temp dir and resolved absolutely so
+ // nothing inherited from the package holds the swap open.
+ relaunch: () =>
+ startRelaunchWaiter({
+ processId: process.pid,
+ processStartTimeMs: Math.round(Date.now() - process.uptime() * 1000),
+ identityName: PRODUCT_IDENTITY.msixAppIdWithOrg,
+ scriptPath: path.join(
+ bundledPayload.repoDir,
+ 'apps',
+ 'desktop',
+ 'scripts',
+ 'update-relaunch-waiter.ps1'
+ )
+ })
+ })
})
}
return new ExternalStrategy()
}
+/**
+ * The checkout updater strategy (windows-handoff / posix-handoff). The flow
+ * lives in updater/checkout.ts; this is the composition root that hands it
+ * the app shell's impure edges. The public checkUpdates/applyUpdates
+ * entrypoints dispatch only through this strategy — there is no other
+ * production path to the checkout arms.
+ */
+function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
+ return createCheckoutStrategy({
+ hermesHome: HERMES_HOME,
+ isWindows: IS_WINDOWS,
+ isMac: IS_MAC,
+ defaultUpdateBranch: DEFAULT_UPDATE_BRANCH,
+ updateHandoffDwellMs: UPDATE_HANDOFF_DWELL_MS,
+ directoryExists,
+ readCanonicalInstallStamp,
+ readDesktopUpdateConfig,
+ resolveUpdateRoot,
+ resolveUpdaterBinary,
+ resolveHealedBranch,
+ getOriginUrl,
+ runGit,
+ firstLine,
+ readCommitLog,
+ fetchCompareBehindCount,
+ pathWithVenvBin,
+ venvHermesShimPath,
+ emitUpdateProgress,
+ rememberLog,
+ startHermes,
+ startGatewaysAfterUpdateAbort,
+ releaseBackendLockForUpdate,
+ repairMacUpdaterHelper,
+ preflightStateDb,
+ runningAppBundle,
+ markQuittingForHandoff: () => {
+ isQuittingForHandoff = true
+ },
+ quit: () => app.quit()
+ })
+}
+
/** True when this process is a Microsoft Store deployment. */
function isWindowsStore(): boolean {
// process.windowsStore is true for ANY MSIX package — App Installer
@@ -4034,340 +3926,13 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {
return strategy.apply(opts)
}
+ // Checkout install: dispatch through the strategy layer. The in-flight
+ // guard stays with the public entrypoint so no body path can start a
+ // second update. The flow lives in updater/checkout.ts.
updateInFlight = true
try {
- const updater = resolveUpdaterBinary()
-
- if (!updater && !IS_WINDOWS) {
- // 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 applyUpdatesPosixHandoff(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 = 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 runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
- const current = (head.stdout || '').trim()
-
- if (head.code === 0 && current && current !== 'HEAD') {
- const branch = await resolveHealedBranch(updateRoot, current)
-
- if (branch !== 'main') {
- command = `hermes update --branch ${branch}`
- }
- }
- } catch {
- // Best-effort: fall back to bare `hermes update` if branch detection fails.
- }
-
- rememberLog(`[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`)
- emitUpdateProgress({ stage: 'manual', message: command, percent: null })
-
- return { ok: true, manual: true, command, hermesRoot: updateRoot }
- }
-
- rememberLog('[updates] no staged updater; using repo hand-off script for CLI install')
- }
-
- const handoffConflict = updateHandoffConflict(HERMES_HOME)
-
- 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.
- rememberLog(`[updates] refusing hand-off: ${handoffConflict.message}`)
- emitUpdateProgress({ stage: 'error', message: handoffConflict.message, percent: null })
-
- return { ok: false, error: 'update-already-running', message: handoffConflict.message }
- }
-
- 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
- })
- repairMacUpdaterHelper(updater)
-
- const updateRoot = resolveUpdateRoot()
- const { branch: configuredBranch } = readDesktopUpdateConfig()
- const branch = await resolveHealedBranch(updateRoot, configuredBranch || DEFAULT_UPDATE_BRANCH)
- const updaterArgs = ['--update', '--branch', branch]
- const targetApp = IS_MAC ? runningAppBundle() : null
-
- if (targetApp) {
- updaterArgs.push('--target-app', targetApp)
- }
-
- const venvBin = path.join(updateRoot, 'venv', IS_WINDOWS ? '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.
- preflightStateDb(HERMES_HOME, rememberLog)
-
- // 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 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.'
-
- emitUpdateProgress({ stage: 'error', message, percent: null })
- startHermes().catch(() => {})
-
- if (IS_WINDOWS) {
- // The pre-gate `gateway stop --all` (#70337) took every profile's
- // gateway down for an update that never happened — bring them back.
- startGatewaysAfterUpdateAbort(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 (IS_WINDOWS) {
- let scanOutcome = await scanVenvBlockers(updateRoot)
-
- if (scanOutcome.kind === 'blocked' && opts.stopSafeBlockers) {
- const stopResult = await stopSafeVenvBlockers(updateRoot, scanOutcome.result)
- 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++) {
- 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)
-
- rememberLog(`[updates] venv-blocked: ${scanOutcome.result.processes.length} process(es) hold the install`)
- emitUpdateProgress({ stage: 'error', message, percent: null })
- startHermes().catch(() => {})
- // Restore the gateways the pre-gate stop took down (#70337 drain
- // semantics): the update aborted, so nothing else will relaunch them.
- startGatewaysAfterUpdateAbort(venvHermesShimPath(updateRoot))
-
- return { ok: false, error: 'venv-blocked', message, blockers: scanOutcome.result.processes }
- }
-
- if (scanOutcome.kind === 'probe-failure') {
- const message = formatProbeFailedMessage(scanOutcome.error)
-
- rememberLog(`[updates] venv-blocker probe failed: ${scanOutcome.error}`)
- emitUpdateProgress({ stage: 'error', message, percent: null })
- startHermes().catch(() => {})
- // Same drain-semantics restore as the venv-blocked abort above.
- startGatewaysAfterUpdateAbort(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: HERMES_HOME,
- env: {
- ...process.env,
- HERMES_HOME,
- HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
- PATH: 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(HERMES_HOME, child.pid, { startedAt: updateStartedAt })
- }
-
- rememberLog(
- `[updates] launched repo hand-off script: ${scriptHandoff.scriptPath} (branch ${branch}); exiting desktop to release venv shim`
- )
- } else {
- child = spawnUpdaterProcess(updater, updaterArgs, {
- cwd: HERMES_HOME,
- env: {
- ...process.env,
- HERMES_HOME,
- PATH: 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(HERMES_HOME, child.pid)
- } else if (Number.isInteger(child.pid)) {
- rememberLog(
- `[updates] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`
- )
- }
-
- 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, UPDATE_HANDOFF_DWELL_MS)
-
- if (!handoffOutcome.ok) {
- const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`
-
- rememberLog(`[updates] hand-off not viable, aborting quit: ${handoffOutcome.message}`)
- emitUpdateProgress({ stage: 'error', message, percent: null })
- startHermes().catch(() => {})
-
- if (IS_WINDOWS) {
- // Same drain-semantics restore as the earlier abort paths (#70337).
- startGatewaysAfterUpdateAbort(venvHermesShimPath(updateRoot))
- }
-
- return { ok: false, error: 'updater-spawn-failed', message }
- }
-
- isQuittingForHandoff = true
- setTimeout(
- () => {
- app.quit()
- },
- Math.max(0, UPDATE_HANDOFF_DWELL_MS - (Date.now() - dwellStartedAt))
- )
-
- return { ok: true, handedOff: true, updater }
+ return await resolveCheckoutUpdateStrategy().apply(opts)
} finally {
updateInFlight = false
}
@@ -4602,129 +4167,6 @@ function preflightStateDb(hermesHome, rememberLog) {
// .hermes-update-result.json for the relaunched Desktop to surface. It shows
// its own tiny shim window (or nothing, headless) — this process only needs
// to leave. Checkouts that predate the script get the manual card once.
-async function applyUpdatesPosixHandoff(opts: any) {
- const updateRoot = resolveUpdateRoot()
- const handoff = resolvePosixScriptHandoff(updateRoot)
-
- if (!handoff) {
- emitUpdateProgress({ stage: 'manual', message: 'hermes update', percent: null })
-
- return { ok: true, manual: true, command: 'hermes update', hermesRoot: updateRoot }
- }
-
- const handoffConflict = updateHandoffConflict(HERMES_HOME)
-
- if (handoffConflict) {
- // Same hazard as the Windows path (#75778): a live foreign updater
- // already owns the marker — refuse rather than double-mutate the tree.
- rememberLog(`[updates] refusing posix hand-off: ${handoffConflict.message}`)
- 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) ──
- preflightStateDb(HERMES_HOME, 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 runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
- const current = (head.stdout || '').trim()
-
- if (head.code === 0 && current && current !== 'HEAD') {
- branch = await 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 = IS_MAC ? runningAppBundle() : process.execPath
-
- if (targetApp) {
- args.push('--relaunch-target', targetApp)
- }
-
- const relaunchArgs = collectRelaunchArgs(process.argv.slice(1))
-
- if (!IS_MAC) {
- 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: HERMES_HOME,
- env: {
- ...process.env,
- HERMES_HOME,
- HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
- PATH: 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(HERMES_HOME, child.pid, { startedAt: updateStartedAt })
- }
-
- rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (branch ${branch}); quitting to hand off`)
- 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, UPDATE_HANDOFF_DWELL_MS)
-
- if (!handoffOutcome.ok) {
- const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`
-
- rememberLog(`[updates] posix hand-off not viable, aborting quit: ${handoffOutcome.message}`)
- emitUpdateProgress({ stage: 'error', message, percent: null })
-
- return { ok: false, error: 'updater-spawn-failed', message }
- }
-
- isQuittingForHandoff = true
- setTimeout(
- () => {
- app.quit()
- },
- Math.max(0, UPDATE_HANDOFF_DWELL_MS - (Date.now() - dwellStartedAt))
- )
-
- return { ok: true, handedOff: true, updater: handoff.scriptPath }
-}
-
function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'))
@@ -7031,6 +6473,7 @@ async function showPluginCompatNoticeOnce() {
if (!mainWindow || mainWindow.isDestroyed()) {
return
}
+
let notice
try {
@@ -7044,6 +6487,7 @@ async function showPluginCompatNoticeOnce() {
if (!notice) {
return
}
+
pluginCompatNoticeShown = true
rememberLog(`[plugins] compat notice shown (${notice.key})`)
diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.ts
index fcd1b4c223f..263c8b42c15 100644
--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts
+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts
@@ -1,6 +1,6 @@
// updater/app-installer-strategy.test.ts — the apply-flow contract: the
-// one-shot relaunch marker is written BEFORE the OS hand-off, teardown runs
-// before the trigger, and quit is unconditional (no relaunch question).
+// relaunch registration (marker + detached waiter) completes BEFORE the OS
+// hand-off, teardown runs before the trigger, and quit is unconditional.
import { describe, expect, it } from 'vitest'
@@ -22,7 +22,7 @@ function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}) {
emitUpdateProgress: () => {},
appVersion: '0.18.2',
quit: () => { calls.push('quit') },
- registerPendingRelaunch: () => { calls.push('relaunch-marker');
+ registerPendingRelaunch: async () => { calls.push('relaunch-marker');
return true },
...over
@@ -42,10 +42,17 @@ describe('AppInstallerStrategy.apply', () => {
})
it('fails open: a marker-write failure never blocks the update', async () => {
- const { deps, calls } = makeDeps({ registerPendingRelaunch: () => false })
+ const progress: string[] = []
+
+ const { deps, calls } = makeDeps({
+ registerPendingRelaunch: async () => false,
+ emitUpdateProgress: event => { progress.push(event.message) }
+ })
+
const result = await new AppInstallerStrategy(deps).apply({})
expect(result.ok).toBe(true)
expect(calls).toContain('quit')
+ expect(progress.some(message => message.includes('Reopen Hermes'))).toBe(true)
})
it('no feed URL → manual card, no teardown, no quit', async () => {
diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.ts
index f2917b8dfdc..17509d14f27 100644
--- a/apps/desktop/electron/updater/app-installer.ts
+++ b/apps/desktop/electron/updater/app-installer.ts
@@ -41,12 +41,13 @@ export interface AppInstallerStrategyDeps {
/** Quit the app (after handing the swap to the OS). */
quit: () => void
/**
- * Register a one-shot post-update relaunch (run-key entry or equivalent)
- * before quitting, so Hermes reopens on the new version with no user
- * action. The new version's first run detects + deletes the marker.
- * Returns false when registration failed (relaunch stays manual).
+ * Register a one-shot post-update relaunch before quitting, so Hermes
+ * reopens on the new version with no user action. Resolves true only once
+ * the relaunch mechanism has acknowledged (the waiter handshake) — the
+ * caller must await this BEFORE quitting. Resolves false when the
+ * mechanism could not be started (relaunch stays manual).
*/
- registerPendingRelaunch: (targetVersion: string) => boolean
+ registerPendingRelaunch: (targetVersion: string) => Promise<boolean>
}
export interface CheckOutcome {
@@ -101,9 +102,19 @@ export class AppInstallerStrategy {
percent: 100
})
- // Unconditional relaunch: register the one-shot marker BEFORE the swap so
- // Hermes comes back on the new version with no user action.
- this.deps.registerPendingRelaunch(this.deps.appVersion)
+ // Unconditional relaunch: register the mechanism BEFORE the swap so
+ // Hermes comes back on the new version with no user action. The
+ // handshake is awaited so the app never quits into an unregistered
+ // waiter (false = the waiter lost the race or failed to spawn; the
+ // update proceeds and relaunch stays manual).
+ const registered = await this.deps.registerPendingRelaunch(this.deps.appVersion)
+
+ if (!registered) {
+ this.deps.emitUpdateProgress({
+ stage: 'restart', percent: 100,
+ message: 'Automatic relaunch could not be registered. Reopen Hermes after App Installer finishes.'
+ })
+ }
await triggerAppInstallerUpdate(
feedBaseUrl,
diff --git a/apps/desktop/electron/updater/checkout-ownership.test.ts b/apps/desktop/electron/updater/checkout-ownership.test.ts
new file mode 100644
index 00000000000..359fd054e02
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-ownership.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'
+
+function dependencies(): CheckoutStrategyDeps {
+ return {
+ hermesHome: 'home',
+ isWindows: process.platform === 'win32',
+ isMac: process.platform === 'darwin',
+ defaultUpdateBranch: 'main',
+ updateHandoffDwellMs: 0,
+ directoryExists: () => true,
+ readCanonicalInstallStamp: () => ({ updateMechanism: 'external' }),
+ readDesktopUpdateConfig: () => ({ branch: 'main' }),
+ resolveUpdateRoot: () => 'repo',
+ resolveUpdaterBinary: () => null,
+ resolveHealedBranch: async (_, branch) => branch,
+ getOriginUrl: async () => '',
+ runGit: vi.fn(async () => { throw new Error('unexpected git invocation') }),
+ firstLine: text => text.split('\n')[0],
+ readCommitLog: async () => [],
+ fetchCompareBehindCount: async () => null,
+ pathWithVenvBin: () => '',
+ venvHermesShimPath: () => '',
+ emitUpdateProgress: vi.fn(),
+ rememberLog: vi.fn(),
+ startHermes: vi.fn(async () => {}),
+ startGatewaysAfterUpdateAbort: vi.fn(),
+ releaseBackendLockForUpdate: vi.fn(async () => ({ unlocked: true })),
+ repairMacUpdaterHelper: vi.fn(),
+ preflightStateDb: vi.fn(),
+ runningAppBundle: () => null,
+ markQuittingForHandoff: vi.fn(),
+ quit: vi.fn()
+ }
+}
+
+describe('checkout update admission', () => {
+ it('refuses steward-owned code without fetching or stopping the backend', async () => {
+ const deps = dependencies()
+ const strategy = createCheckoutStrategy(deps)
+ const result = await strategy.check()
+
+ expect(result.supported).toBe(false)
+ expect(result.mechanism).toBe(strategy.mechanism)
+ expect(deps.runGit).not.toHaveBeenCalled()
+ expect(deps.releaseBackendLockForUpdate).not.toHaveBeenCalled()
+ expect(deps.quit).not.toHaveBeenCalled()
+ })
+
+ it('rejects a missing source checkout without attempting git', async () => {
+ const deps = dependencies()
+ deps.directoryExists = () => false
+ const result = await createCheckoutStrategy(deps).check()
+
+ expect(result.reason).toBe('not-a-git-checkout')
+ expect(deps.runGit).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index 6ccd066e80b..d7456888c24 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -1,53 +1,724 @@
-// updater/checkout.ts — the git-checkout strategies (win + posix + manual).
-//
-// These wrap the existing bodies in main.ts rather than re-implementing
-// them: the checkout update flow is deeply entangled with the god-file's
-// closure helpers (resolveHealedBranch, venv-lock release, blocker scans,
-// hand-off marker claims). The strategy adapter delegates; the ladder's
-// TAIL (manual `hermes update` command card) lives here because it is pure
-// enough to test.
+// Checkout update policy and handoff execution. The shell supplies process and UI dependencies.
-import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'
+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,
+ 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 {
- /** The existing checkUpdates git-checkout body (unchanged). */
- checkBody: () => Promise<UpdaterStatusWire>
- /** The existing applyUpdates git-checkout body (unchanged). */
- applyBody: (opts: { stopSafeBlockers?: boolean }) => Promise<UpdaterApplyResultWire>
+ 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
}
-export class CheckoutStrategy {
- readonly mechanism: 'windows-handoff' | 'posix-handoff'
+/**
+ * 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'
+}
- constructor(private readonly deps: CheckoutStrategyDeps) {
- this.mechanism = deps.isWindows ? 'windows-handoff' : 'posix-handoff'
- }
+/**
+ * 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 check(): Promise<UpdaterStatusWire> {
- const status = await this.deps.checkBody()
- status.mechanism = this.mechanism
+ async function check(): Promise<UpdaterStatusWire> {
+ const status = await checkBody()
+ status.mechanism = mechanism
return status
}
- async apply(opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire> {
- const result = await this.deps.applyBody(opts)
- result.mechanism = this.mechanism
+ async function apply(opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire> {
+ const result = await applyBody(opts)
+ result.mechanism = mechanism
return result
}
-}
-/**
- * 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). Extracted from applyUpdates so the wording contract is
- * unit-testable.
- */
-export function buildManualUpdateCommand(currentBranch: string | null | undefined): string {
- return currentBranch && currentBranch !== 'HEAD' && currentBranch !== 'main'
- ? `hermes update --branch ${currentBranch}`
- : 'hermes update'
+ 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)
+
+ // 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 --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.ts
index 6d98e7ed8ea..90fe021fc7e 100644
--- a/apps/desktop/electron/updater/index.ts
+++ b/apps/desktop/electron/updater/index.ts
@@ -55,6 +55,7 @@ export interface UpdaterStatusWire {
currentBranch?: string
reason?: string
message?: string
+ advice?: string
error?: string
behind?: number | null
currentSha?: string
diff --git a/apps/desktop/electron/updater/relaunch-waiter.test.ts b/apps/desktop/electron/updater/relaunch-waiter.test.ts
new file mode 100644
index 00000000000..ac222af285f
--- /dev/null
+++ b/apps/desktop/electron/updater/relaunch-waiter.test.ts
@@ -0,0 +1,190 @@
+// updater/relaunch-waiter.test.ts — staging, argv, and the ready/error
+// handshake contract. No PowerShell is spawned: the spawn point is injected
+// and the handshake file is written by the test (as the real script would),
+// so the parent-side race contract is exercised without touching a package.
+
+import { EventEmitter } from 'node:events'
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { afterEach, describe, expect, it } from 'vitest'
+
+import {
+ buildRelaunchWaiterArgs,
+ POWERSHELL_PATH,
+ RELAUNCH_WAITER_READY_FILENAME,
+ RELAUNCH_WAITER_SCRIPT,
+ type SpawnWaiter,
+ startRelaunchWaiter
+} from './relaunch-waiter'
+
+const OPTIONS = {
+ processId: 4242,
+ processStartTimeMs: 1_000_000,
+ identityName: 'NousResearch.HermesBundled',
+ scriptPath: '/payload/apps/desktop/scripts/update-relaunch-waiter.ps1'
+}
+
+const tempDirs: string[] = []
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
+
+function fakeSpawn(handshake: 'ready' | 'error' | 'exit-nonzero' | 'none'): { spawn: SpawnWaiter; seen: any } {
+ const seen: any = {}
+
+ const spawn: SpawnWaiter = (_command, args, opts) => {
+ seen.command = _command
+ seen.args = args
+ seen.opts = opts
+ tempDirs.push(opts.cwd)
+
+ const child: any = new EventEmitter()
+
+ child.unref = () => {}
+
+ child.kill = () => { seen.killed = true; child.emit('exit', null) }
+
+ const readyFile = args[args.indexOf('-ReadyFile') + 1]
+
+ queueMicrotask(() => {
+ if (handshake === 'ready') {
+ fs.mkdirSync(path.dirname(readyFile), { recursive: true })
+ fs.writeFileSync(readyFile, '0.18.1|Family|App')
+ } else if (handshake === 'error') {
+ child.emit('error', new Error('spawn ENOENT'))
+ } else if (handshake === 'exit-nonzero') {
+ child.emit('exit', 3)
+ }
+ })
+
+ return child
+ }
+
+ return { spawn, seen }
+}
+
+async function stageScript(): Promise<string> {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-waiter-test-'))
+ tempDirs.push(dir)
+ const file = path.join(dir, RELAUNCH_WAITER_SCRIPT)
+ fs.writeFileSync(file, '# stub\n')
+
+ return file
+}
+
+describe('buildRelaunchWaiterArgs', () => {
+ it('carries pid, start time, identity, ready file, and timeout as named parameters', () => {
+ const args = buildRelaunchWaiterArgs(OPTIONS, 'C:\\temp\\ready.txt')
+
+ expect(args).toEqual([
+ '-NoProfile',
+ '-NonInteractive',
+ '-ExecutionPolicy',
+ 'Bypass',
+ '-File',
+ OPTIONS.scriptPath,
+ '-ProcessId',
+ '4242',
+ '-ProcessStartTimeMs',
+ '1000000',
+ '-IdentityName',
+ 'NousResearch.HermesBundled',
+ '-ReadyFile',
+ 'C:\\temp\\ready.txt',
+ '-TimeoutSeconds',
+ '900'
+ ])
+ })
+})
+
+describe('startRelaunchWaiter', () => {
+ it('stages the script into a fresh temp dir and spawns the absolute PowerShell from there', async () => {
+ const scriptPath = await stageScript()
+ const { spawn, seen } = fakeSpawn('ready')
+
+ const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 })
+
+ expect(result).toBe(true)
+ expect(seen.command).toBe(POWERSHELL_PATH)
+ expect(seen.opts.detached).toBe(true)
+ expect(seen.opts.stdio).toBe('ignore')
+ expect(seen.opts.windowsHide).toBe(true)
+ // The child runs from the staged dir, not the payload — nothing
+ // inherited from the package may hold the swap open.
+ expect(seen.opts.cwd).not.toBe(path.dirname(scriptPath))
+ expect(seen.args).toContain('-File')
+ const stagedScript = seen.args[seen.args.indexOf('-File') + 1]
+ expect(stagedScript).not.toBe(scriptPath)
+ expect(fs.existsSync(stagedScript)).toBe(true)
+ })
+
+ it('resolves true on the ready-file handshake (the waiter snapshotted the OLD package)', async () => {
+ const scriptPath = await stageScript()
+ const { spawn } = fakeSpawn('ready')
+
+ const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 })
+
+ expect(result).toBe(true)
+ })
+
+ it('resolves false when the child errors before the handshake', async () => {
+ const scriptPath = await stageScript()
+ const { spawn } = fakeSpawn('error')
+
+ const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 })
+
+ expect(result).toBe(false)
+ })
+
+ it('resolves false on a non-zero early exit (waiter never signalled ready)', async () => {
+ const scriptPath = await stageScript()
+ const { spawn } = fakeSpawn('exit-nonzero')
+
+ const result = await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 })
+
+ expect(result).toBe(false)
+ })
+
+ it('resolves false when the handshake never arrives within the deadline', async () => {
+ const scriptPath = await stageScript()
+ const { spawn, seen } = fakeSpawn('none')
+
+ const result = await startRelaunchWaiter(
+ { ...OPTIONS, scriptPath },
+ { spawn, handshakeTimeoutMs: 80, pollMs: 20 }
+ )
+
+ expect(result).toBe(false)
+ expect(seen.killed).toBe(true)
+ expect(fs.existsSync(seen.opts.cwd)).toBe(false)
+ }, 5_000)
+
+ it('resolves false when staging fails (missing script), never throwing', async () => {
+ const spawn = (() => {
+ throw new Error('should not be reached')
+ }) as unknown as SpawnWaiter
+
+ const result = await startRelaunchWaiter(
+ { ...OPTIONS, scriptPath: path.join(os.tmpdir(), 'definitely-missing.ps1') },
+ { spawn }
+ )
+
+ expect(result).toBe(false)
+ })
+
+ it('the staged handshake file uses the reserved ready filename', async () => {
+ const scriptPath = await stageScript()
+ const { spawn, seen } = fakeSpawn('ready')
+
+ await startRelaunchWaiter({ ...OPTIONS, scriptPath }, { spawn, pollMs: 10 })
+
+ const readyFile = seen.args[seen.args.indexOf('-ReadyFile') + 1]
+
+ expect(path.basename(readyFile)).toBe(RELAUNCH_WAITER_READY_FILENAME)
+ })
+})
diff --git a/apps/desktop/electron/updater/relaunch-waiter.ts b/apps/desktop/electron/updater/relaunch-waiter.ts
new file mode 100644
index 00000000000..21b140e6989
--- /dev/null
+++ b/apps/desktop/electron/updater/relaunch-waiter.ts
@@ -0,0 +1,153 @@
+// Stage the waiter outside the package and await its old-version snapshot.
+// A failed handshake cancels our child instead of leaving a delayed relaunch.
+
+import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+export const RELAUNCH_WAITER_SCRIPT = 'update-relaunch-waiter.ps1'
+export const RELAUNCH_WAITER_READY_FILENAME = 'ready.txt'
+export const DEFAULT_RELAUNCH_WAITER_TIMEOUT_SECONDS = 900
+export const DEFAULT_RELAUNCH_WAITER_HANDSHAKE_MS = 10_000
+
+/** Absolute path — never resolved via inherited PATH (it can point into the package). */
+export const POWERSHELL_PATH = path.win32.join(process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
+
+export interface RelaunchWaiterOptions {
+ /** The quitting app's pid — the waiter waits for this process to exit. */
+ processId: number
+ /** Wall-clock ms the parent process started (PID-reuse guard). */
+ processStartTimeMs: number
+ /** The MSIX identity name of this install (e.g. NousResearch.HermesBundled). */
+ identityName: string
+ /** Absolute path to the waiter script inside the payload repo snapshot. */
+ scriptPath: string
+ timeoutSeconds?: number
+}
+
+export interface WaiterStaging {
+ stageDir: string
+ scriptPath: string
+ readyFile: string
+}
+
+export type SpawnWaiter = (
+ command: string,
+ args: string[],
+ opts: { detached: boolean; stdio: 'ignore'; windowsHide: boolean; cwd: string }
+) => ChildProcess
+
+export interface RelaunchWaiterDeps {
+ spawn?: SpawnWaiter
+ /** Handshake deadline in ms (tests shrink this). */
+ handshakeTimeoutMs?: number
+ /** Poll interval for the ready file (tests shrink this). */
+ pollMs?: number
+}
+
+/** Pure: the exact argv the waiter is spawned with. */
+export function buildRelaunchWaiterArgs(options: RelaunchWaiterOptions, readyFile: string): string[] {
+ return [
+ '-NoProfile',
+ '-NonInteractive',
+ '-ExecutionPolicy',
+ 'Bypass',
+ '-File',
+ options.scriptPath,
+ '-ProcessId',
+ String(options.processId),
+ '-ProcessStartTimeMs',
+ String(options.processStartTimeMs),
+ '-IdentityName',
+ options.identityName,
+ '-ReadyFile',
+ readyFile,
+ '-TimeoutSeconds',
+ String(options.timeoutSeconds ?? DEFAULT_RELAUNCH_WAITER_TIMEOUT_SECONDS)
+ ]
+}
+
+/** Stage script + handshake file into a fresh temp dir outside the package. */
+export async function stageRelaunchWaiter(options: RelaunchWaiterOptions): Promise<WaiterStaging> {
+ const stageDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'hermes-relaunch-'))
+ const scriptPath = path.join(stageDir, RELAUNCH_WAITER_SCRIPT)
+ const readyFile = path.join(stageDir, RELAUNCH_WAITER_READY_FILENAME)
+
+ try {
+ await fs.promises.copyFile(options.scriptPath, scriptPath)
+ } catch (error) {
+ await fs.promises.rm(stageDir, { recursive: true, force: true })
+ throw error
+ }
+
+ return { stageDir, scriptPath, readyFile }
+}
+
+/** Return true only after the waiter confirms its package snapshot. */
+export async function startRelaunchWaiter(
+ options: RelaunchWaiterOptions,
+ deps: RelaunchWaiterDeps = {}
+): Promise<boolean> {
+ const spawn = deps.spawn ?? (nodeSpawn as unknown as SpawnWaiter)
+ const handshakeTimeoutMs = deps.handshakeTimeoutMs ?? DEFAULT_RELAUNCH_WAITER_HANDSHAKE_MS
+ const pollMs = deps.pollMs ?? 250
+
+ let staging: WaiterStaging
+
+ try {
+ staging = await stageRelaunchWaiter(options)
+ } catch {
+ return false
+ }
+
+ const cleanup = () => fs.promises.rm(staging.stageDir, { recursive: true, force: true })
+ let child: ChildProcess
+
+ try {
+ child = spawn(POWERSHELL_PATH,
+ buildRelaunchWaiterArgs({ ...options, scriptPath: staging.scriptPath }, staging.readyFile),
+ { detached: true, stdio: 'ignore', windowsHide: true, cwd: staging.stageDir })
+ } catch {
+ await cleanup()
+
+ return false
+ }
+
+ return new Promise<boolean>(resolve => {
+ let settled = false
+ let timer: ReturnType<typeof setTimeout>
+ const deadline = Date.now() + handshakeTimeoutMs
+
+ const finish = (ready: boolean) => {
+ if (settled) { return }
+ settled = true
+ clearTimeout(timer)
+
+ if (ready) {
+ child.unref()
+ resolve(true)
+ } else {
+ child.kill()
+ void cleanup().catch(() => {}).finally(() => resolve(false))
+ }
+ }
+
+ child.once('error', () => finish(false))
+ child.once('exit', () => finish(false))
+
+ const check = () => {
+ if (settled) { return }
+
+ if (fs.existsSync(staging.readyFile)) {
+ finish(true)
+ } else if (Date.now() >= deadline) {
+ finish(false)
+ } else {
+ timer = setTimeout(check, pollMs)
+ }
+ }
+
+ check()
+ })
+}
diff --git a/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts b/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts
new file mode 100644
index 00000000000..546ab4bea15
--- /dev/null
+++ b/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts
@@ -0,0 +1,65 @@
+import { spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { describe, expect, it } from 'vitest'
+
+import { POWERSHELL_PATH, RELAUNCH_WAITER_SCRIPT } from './relaunch-waiter'
+
+const scriptPath = path.resolve(__dirname, '..', '..', 'scripts', RELAUNCH_WAITER_SCRIPT)
+const quote = (value: string) => `'${value.replaceAll("'", "''")}'`
+
+describe.skipIf(process.platform !== 'win32')('real PowerShell waiter control flow', () => {
+ it.each([false, true])('activates only after parent exit and package change (%s)', unavailable => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-control-'))
+ const ready = path.join(root, 'ready.txt')
+ const activation = path.join(root, 'activation.txt')
+ const wrapper = path.join(root, 'run.ps1')
+
+ fs.writeFileSync(wrapper, `
+$global:checks = 0
+$global:birth = Get-Date
+$global:clock = $global:birth
+function Get-Date { return $global:clock }
+function Start-Sleep { param($Milliseconds); $global:clock = $global:clock.AddSeconds(1) }
+function Get-Process {
+ param($Id, $ErrorAction)
+ $global:checks++
+ if ($global:checks -le 6) { return [pscustomobject]@{ StartTime = $global:birth } }
+ return $null
+}
+function Get-AppxPackage {
+ param($Name)
+ ${unavailable ? 'return $null' : "return [pscustomobject]@{ Version = $(if ($global:checks -gt 6) { '2.0.0.0' } else { '1.0.0.0' }); PackageFamilyName = 'audit-only' }"}
+}
+function Get-AppxPackageManifest {
+ return [pscustomobject]@{ Package = [pscustomobject]@{ Applications = [pscustomobject]@{ Application = [pscustomobject]@{ Id = 'Hermes' } } } }
+}
+function Start-Process {
+ param($FilePath)
+ if ($global:checks -le 6) { throw 'parent is still alive' }
+ Set-Content -LiteralPath ${quote(activation)} -Value $FilePath
+}
+$birthMs = ([DateTimeOffset]$global:birth).ToUnixTimeMilliseconds()
+& ${quote(scriptPath)} -ProcessId $PID -ProcessStartTimeMs $birthMs -IdentityName audit-only -ReadyFile ${quote(ready)} -TimeoutSeconds 10 -PollMillis 1
+exit $LASTEXITCODE
+`, 'utf8')
+
+ try {
+ const result = spawnSync(POWERSHELL_PATH, ['-NoProfile', '-NonInteractive', '-File', wrapper], {
+ cwd: root, encoding: 'utf8', windowsHide: true, timeout: 30_000
+ })
+
+ expect(result.status, result.stdout + result.stderr).toBe(unavailable ? 2 : 0)
+ expect(fs.existsSync(ready)).toBe(false)
+ expect(fs.existsSync(activation)).toBe(!unavailable)
+
+ if (!unavailable) {
+ expect(fs.readFileSync(activation, 'utf8').trim()).toBe('shell:AppsFolder\\audit-only!Hermes')
+ }
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ }, 40_000)
+})
diff --git a/apps/desktop/electron/updater/relaunch.ts b/apps/desktop/electron/updater/relaunch.ts
index 2170254bfe9..cba87f8d5da 100644
--- a/apps/desktop/electron/updater/relaunch.ts
+++ b/apps/desktop/electron/updater/relaunch.ts
@@ -9,10 +9,11 @@
// The marker is a JSON file under HERMES_HOME (not a run-key / scheduled
// task): a registry entry can't be made one-shot safely from a dying process,
// and a file survives the package swap (HERMES_HOME lives outside the
-// package). For the actual relaunch we rely on Windows restarting the app
-// when an MSIX package update completes while the app registered itself
-// for restart (RegisterApplicationRestart) — the marker's job is only to
-// tell the NEW version it was an update relaunch, so it can toast + clean up.
+// package). The actual relaunch is the detached waiter
+// (relaunch-waiter.ts + scripts/update-relaunch-waiter.ps1): it waits for
+// this process to exit, waits for the installed package version to change,
+// and activates the NEW package. The marker's job is only to tell the NEW
+// version it was an update relaunch, so it can toast + clean up.
//
// If the OS does NOT relaunch (update applied later, on next launch), the
// marker is still correct: the first launch after the swap detects it and
@@ -62,6 +63,41 @@ export function writePendingRelaunch(
}
}
+/**
+ * Register the post-update relaunch: write the pending-relaunch marker AND
+ * start the relaunch mechanism. The mechanism itself is injected — the
+ * App Installer arm passes the detached relaunch waiter (relaunch-waiter.ts),
+ * which re-opens the NEW package after the OS swap; nothing here re-executes
+ * the current binary. The relaunched instance reads the marker, toasts, and
+ * cleans it up. Failure never blocks the update — relaunch just stays
+ * manual (the marker alone still produces the "updated" toast on the next
+ * manual launch).
+ */
+export interface UpdateRelaunchDeps {
+ /** Start the relaunch mechanism (the detached relaunch waiter). */
+ relaunch: () => boolean | void | Promise<boolean | void>
+}
+
+export async function registerUpdateRelaunch(
+ hermesHome: string,
+ fromVersion: string,
+ deps: UpdateRelaunchDeps,
+ writeFile: (file: string, contents: string) => void = (f, c) => fs.writeFileSync(f, c)
+): Promise<boolean> {
+ // Marker first: a relaunch that wins the race against the write still
+ // leaves the next manual launch marker-less (honest), but a marker without
+ // a started mechanism is the exact "marker is not a mechanism" gap.
+ writePendingRelaunch(hermesHome, fromVersion, writeFile)
+
+ try {
+ // `undefined` (a fire-and-forget mechanism) counts as started; only an
+ // explicit false or a throw means registration failed.
+ return (await deps.relaunch()) !== false
+ } catch {
+ return false
+ }
+}
+
export interface ConsumedRelaunch {
/** True when this launch IS the post-update relaunch (new version). */
wasUpdateRelaunch: boolean
diff --git a/apps/desktop/electron/updater/updater.test.ts b/apps/desktop/electron/updater/updater.test.ts
index e1218851889..20a7491132f 100644
--- a/apps/desktop/electron/updater/updater.test.ts
+++ b/apps/desktop/electron/updater/updater.test.ts
@@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest'
import { appInstallerCheckToStatus, parseCheckOutput } from './app-installer'
import { buildManualUpdateCommand } from './checkout'
-import { consumePendingRelaunch, PENDING_RELAUNCH_FILENAME, writePendingRelaunch } from './relaunch'
+import { consumePendingRelaunch, PENDING_RELAUNCH_FILENAME, registerUpdateRelaunch, writePendingRelaunch } from './relaunch'
import { resolveUpdaterMechanism } from './index'
@@ -151,3 +151,49 @@ describe('pending relaunch marker', () => {
expect(Object.keys(files)).toHaveLength(0)
})
})
+
+describe('registerUpdateRelaunch — the mechanism, not just the marker', () => {
+ it('writes the marker AND starts the relaunch mechanism', async () => {
+ const files: Record<string, string> = {}
+ let started = 0
+
+ const ok = await registerUpdateRelaunch(
+ '/home',
+ '0.18.2',
+ { relaunch: () => { started += 1 } },
+ (f, c) => { files[f] = c as string }
+ )
+
+ expect(ok).toBe(true)
+ expect(started).toBe(1)
+ expect(Object.keys(files)).toHaveLength(1)
+ })
+
+ it('awaits the mechanism outcome: a waiter that reports false leaves the marker as the only trace', async () => {
+ const files: Record<string, string> = {}
+
+ const ok = await registerUpdateRelaunch(
+ '/home',
+ '0.18.2',
+ { relaunch: async () => false },
+ (f, c) => { files[f] = c as string }
+ )
+
+ expect(ok).toBe(false)
+ expect(Object.keys(files)).toHaveLength(1)
+ })
+
+ it('a mechanism throw never blocks the update (marker-only manual relaunch)', async () => {
+ const files: Record<string, string> = {}
+
+ const ok = await registerUpdateRelaunch(
+ '/home',
+ '0.18.2',
+ { relaunch: () => { throw new Error('spawn failed') } },
+ (f, c) => { files[f] = c as string }
+ )
+
+ expect(ok).toBe(false)
+ expect(Object.keys(files)).toHaveLength(1)
+ })
+})
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 006b941c269..7546a1e41fb 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -57,6 +57,7 @@
"test:desktop:msix": "node scripts/test-desktop.mjs msix",
"test:desktop:existing": "node scripts/test-desktop.mjs existing",
"test:desktop:fresh": "node scripts/test-desktop.mjs fresh",
+ "test:desktop:lifecycle": "node scripts/test-desktop.mjs lifecycle",
"typecheck": "tsc -p . --noEmit && tsc -p tsconfig.electron.json --noEmit && tsc -p tsconfig.e2e.json --noEmit && tsc --ignoreConfig --allowJs --checkJs --noEmit --skipLibCheck --module nodenext --moduleResolution nodenext --target es2022 electron-builder.config.cjs",
"lint": "eslint src/ electron/",
"lint:fix": "eslint src/ electron/ --fix",
diff --git a/apps/desktop/scripts/before-build.mjs b/apps/desktop/scripts/before-build.mjs
index acb4d5b14c8..c984105a441 100644
--- a/apps/desktop/scripts/before-build.mjs
+++ b/apps/desktop/scripts/before-build.mjs
@@ -70,12 +70,11 @@ function writeMsixExtensions() {
const desktop = path.join(import.meta.dirname, '..')
const output = path.join('build', 'msix-extensions.xml')
const file = path.join(desktop, output)
- // One uap5:Extension per payload CLI launcher exe (see
- // scripts/desktop-cli/cli-entrypoints.mjs): the minted exes are three
- // REAL executables now — the old rust shim's one-exe-argv[0]-dispatch is
- // gone — and an AppExecutionAlias's Executable must name the exact exe
- // that serves the alias, so each alias gets its own Extension block.
- const aliases = light ? '' : appExecutionAliasExtensions()
+ const manifest = path.join(desktop, 'build', 'agent-payload', 'manifest.json')
+ const payload = fs.existsSync(manifest) ? JSON.parse(fs.readFileSync(manifest, 'utf8')) : null
+ const launchers = light || !payload || payload.external
+ ? [] : CLI_LAUNCHER_SPECS.map(spec => spec.name)
+ const aliases = appExecutionAliasExtensions(launchers)
// The uap3:AppExtension fragment that registers the app as a Windows
// Copilot hardware key provider. The press activates hermes://copilot-key/start.
//
@@ -115,6 +114,7 @@ ${aliases}`
* @param {{ name: string }[]} [launchers] exe stems under bin/
*/
export function appExecutionAliasExtensions(launchers = CLI_LAUNCHER_SPECS.map((s) => s.name)) {
+ if (launchers.length === 0) return ''
const bs = String.fromCharCode(92)
const executable = (name) => ['app', 'resources', 'agent-payload', 'bin', `${name}.exe`].join(bs)
// ONE windows.appExecutionAlias extension per package — makeappx rejects a
diff --git a/apps/desktop/scripts/msix-alias-population.test.mjs b/apps/desktop/scripts/msix-alias-population.test.mjs
new file mode 100644
index 00000000000..11598322045
--- /dev/null
+++ b/apps/desktop/scripts/msix-alias-population.test.mjs
@@ -0,0 +1,8 @@
+import { describe, expect, it } from 'vitest'
+import { appExecutionAliasExtensions } from './before-build.mjs'
+
+describe('MSIX alias population', () => {
+ it('omits execution aliases when no payload launchers are present', () => {
+ expect(appExecutionAliasExtensions([])).toBe('')
+ })
+})
diff --git a/apps/desktop/scripts/test-desktop.mjs b/apps/desktop/scripts/test-desktop.mjs
index 2087eadb884..319dac70df4 100644
--- a/apps/desktop/scripts/test-desktop.mjs
+++ b/apps/desktop/scripts/test-desktop.mjs
@@ -27,13 +27,20 @@ const APP = (() => {
}
}
if (PLATFORM === 'win32') {
- const unpacked = path.join(RELEASE_ROOT, 'win-unpacked')
+ // electron-builder names the unpacked output per-arch: win-arm64-unpacked
+ // on arm64, plain win-unpacked on x64. Accept either so the harness works
+ // on both hosts instead of hardcoding the x64 layout.
+ const unpacked = ['win-unpacked', `win-${ARCH}-unpacked`]
+ .map(name => path.join(RELEASE_ROOT, name))
+ .find(exists)
return {
appPath: unpacked,
- binary: path.join(unpacked, 'Hermes.exe'),
- resourcesPath: path.join(unpacked, 'resources'),
- asarPath: path.join(unpacked, 'resources', 'app.asar'),
- unpackedDistIndex: path.join(unpacked, 'resources', 'app.asar.unpacked', 'dist', 'index.html')
+ binary: unpacked ? path.join(unpacked, 'Hermes.exe') : path.join(RELEASE_ROOT, 'win-unpacked', 'Hermes.exe'),
+ resourcesPath: unpacked ? path.join(unpacked, 'resources') : path.join(RELEASE_ROOT, 'win-unpacked', 'resources'),
+ asarPath: unpacked ? path.join(unpacked, 'resources', 'app.asar') : path.join(RELEASE_ROOT, 'win-unpacked', 'resources', 'app.asar'),
+ unpackedDistIndex: unpacked
+ ? path.join(unpacked, 'resources', 'app.asar.unpacked', 'dist', 'index.html')
+ : path.join(RELEASE_ROOT, 'win-unpacked', 'resources', 'app.asar.unpacked', 'dist', 'index.html')
}
}
// linux unpacked layout matches windows but with different binary name
@@ -265,7 +272,167 @@ function launchFresh() {
console.log(` cwd: ${cwd}`)
}
+// ── lifecycle: automated packaged-app start → serve-ready → relaunch → teardown ──
+// Drives the REAL packaged binary through Playwright's Electron channel
+// (launch / firstWindow / app.close() — the app's own exact quit path, backend
+// teardown included), so the harness never kills a process itself. Isolation
+// and identity come from the flags main.ts already honors: sandboxed Electron
+// userData (own single-instance lock) + sandboxed HERMES_HOME + an explicit
+// backend root (main.ts backend-resolution rung 1). Readiness is the serve
+// protocol — a python backend child LISTENING on 127.0.0.1 answering
+// GET /api/health — never gateway.pid (that file is the messaging gateway's
+// record, a different surface) and never a mock.
+const LIFECYCLE_BACKEND_ROOT = process.env.HERMES_DESKTOP_LIFECYCLE_BACKEND_ROOT
+const LIFECYCLE_TIMEOUT_MS = Number(process.env.HERMES_DESKTOP_LIFECYCLE_TIMEOUT_MS) || 150_000
+const LIFECYCLE_KEEP = process.env.HERMES_DESKTOP_LIFECYCLE_KEEP === '1'
+
+function lifecycleEnv(sandbox) {
+ const userDataDir = path.join(sandbox, 'electron-user-data')
+ const hermesHome = path.join(sandbox, 'hermes-home')
+ const cwd = path.join(sandbox, 'workspace')
+ for (const dir of [userDataDir, hermesHome, cwd]) fs.mkdirSync(dir, { recursive: true })
+
+ const env = {}
+ for (const [key, value] of Object.entries(process.env)) {
+ if (isCredentialEnvVar(key)) continue
+ env[key] = value
+ }
+ env.HERMES_DESKTOP_CWD = cwd
+ env.HERMES_DESKTOP_USER_DATA_DIR = userDataDir
+ env.HERMES_HOME = hermesHome
+ env.HERMES_DESKTOP_SKIP_QUIT_CONFIRM = '1'
+ // Window-title label only — NOT package identity; package identity is build-
+ // time. Identity isolation here is the sandboxed userData (single-instance
+ // lock is scoped to it), so a live Hermes instance can never be contacted.
+ env.HERMES_DESKTOP_APP_NAME = 'HermesLifecycleProbe'
+ // REQUIRED: with a thin (external-payload) build there is no sealed runtime,
+ // and an unresolved backend would fall through to first-run bootstrap —
+ // install.ps1, which writes User PATH, Start-Menu shortcuts and ACLs on a
+ // real host. This harness must never let that happen.
+ if (LIFECYCLE_BACKEND_ROOT) {
+ env.HERMES_DESKTOP_HERMES_ROOT = path.resolve(LIFECYCLE_BACKEND_ROOT)
+ }
+ delete env.HERMES_DESKTOP_HERMES
+ delete env.HERMES_DESKTOP_TEST_MODE
+ return { env, userDataDir, hermesHome, cwd }
+}
+
+// Readiness, the app's own way: the Electron main logs
+// `HERMES_BACKEND_READY port=<N>` (backend-ready.ts's announcement contract)
+// into <HERMES_HOME>/logs/desktop.log once uvicorn has bound the serve socket.
+// Parse that, then confirm externally that the announced port answers
+// GET /api/health with 200 — the same anonymous health route the app probes.
+// No process enumeration, no kills.
+async function serveBackendReady(hermesHome, label, offset) {
+ const logPath = path.join(hermesHome, 'logs', 'desktop.log')
+ const deadline = Date.now() + LIFECYCLE_TIMEOUT_MS
+ const tried = new Map()
+ let announced = new Set()
+ while (Date.now() < deadline) {
+ let text = ''
+ try {
+ text = fs.readFileSync(logPath, 'utf8').slice(offset)
+ } catch { /* log not created yet */ }
+ for (const m of text.matchAll(/HERMES_(?:BACKEND|DASHBOARD)_READY port=(\d+)/g)) {
+ announced.add(Number(m[1]))
+ }
+ for (const port of announced) {
+ tried.set(port, 'pending')
+ try {
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(5_000) })
+ if (res.status === 200) return { port }
+ tried.set(port, `/api/health ${res.status}`)
+ } catch (err) {
+ tried.set(port, err && err.name === 'TimeoutError' ? 'timeout' : 'conn-refused')
+ }
+ }
+ await new Promise(resolve => setTimeout(resolve, 500))
+ }
+ throw new Error(`[${label}] no announced serve backend answered /api/health within ${LIFECYCLE_TIMEOUT_MS}ms (announced ports: ${[...announced].join(', ') || 'none'}; probes: ${[...tried].map(([p, r]) => `${p}:${r}`).join(', ') || 'none'}; log: ${logPath})`)
+}
+
+// Everything the first session created in the isolated home must survive the
+// quit + relaunch cycle. Transient scratch (*.tmp/.lock/.part) is excluded:
+// a healthy later session may clean up stale temp files — that is not loss.
+function snapshotHome(root) {
+ const out = []
+ const walk = (dir, depth) => {
+ if (depth > 2) return
+ let entries
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true })
+ } catch {
+ return
+ }
+ for (const entry of entries) {
+ if (/\.(tmp|lock|part)$/.test(entry.name)) continue
+ const rel = path.relative(root, path.join(dir, entry.name))
+ out.push(entry.isDirectory() ? `dir ${rel}` : `file ${rel}`)
+ if (entry.isDirectory()) walk(path.join(dir, entry.name), depth + 1)
+ }
+ }
+ walk(root, 0)
+ return out
+}
+
+async function runLifecycle() {
+ const { _electron } = await import('@playwright/test')
+ const sandbox = fs.mkdtempSync(`${FRESH_SANDBOX_ROOT}-lifecycle-`)
+ const { env, userDataDir, hermesHome } = lifecycleEnv(sandbox)
+ const sessions = []
+ let preservedBefore = null
+
+ try {
+ for (const label of ['session-1', 'session-2']) {
+ const log = path.join(hermesHome, 'logs', 'desktop.log')
+ const offset = fs.existsSync(log) ? fs.readFileSync(log, 'utf8').length : 0
+ const app = await _electron.launch({
+ executablePath: APP.binary,
+ env,
+ cwd: sandbox,
+ timeout: LIFECYCLE_TIMEOUT_MS
+ })
+ const proc = app.process()
+ console.log(`[${label}] launched ${APP.binary} (pid ${proc.pid})`)
+ try {
+ const window = await app.firstWindow({ timeout: LIFECYCLE_TIMEOUT_MS })
+ console.log(`[${label}] first window: ${window.url()}`)
+ const ready = await serveBackendReady(hermesHome, label, offset)
+ console.log(`[${label}] READY: serve backend announced port ${ready.port}, /api/health → 200`)
+ sessions.push({ label, appPid: proc.pid, ...ready, windowUrl: window.url() })
+ if (label === 'session-1') preservedBefore = snapshotHome(hermesHome)
+ } finally {
+ // app.close() is the app's own quit path (before-quit teardown, backend
+ // shutdown included) — not a kill.
+ await app.close()
+ await new Promise((resolve, reject) => {
+ if (proc.exitCode !== null || proc.signalCode !== null) return resolve()
+ const timer = setTimeout(() => reject(new Error(`[${label}] app process ${proc.pid} did not exit after close()`)), 30_000)
+ proc.once('exit', () => { clearTimeout(timer); resolve() })
+ })
+ console.log(`[${label}] exited cleanly (code ${proc.exitCode})`)
+ }
+ }
+ const preservedAfter = snapshotHome(hermesHome)
+ const lost = preservedBefore.filter(entry => !preservedAfter.includes(entry))
+ console.log('\nLifecycle summary:')
+ console.log(` sessions: ${sessions.length}`)
+ console.log(` home entries before relaunch: ${preservedBefore.length}, after: ${preservedAfter.length}`)
+ if (lost.length > 0) {
+ throw new Error(`preserved-state check FAILED — entries missing after relaunch:\n ${lost.join('\n ')}`)
+ }
+ console.log(' preservation: all pre-relaunch home entries survived the quit + relaunch cycle')
+ console.log(JSON.stringify({ sandbox, userDataDir, hermesHome, backendRoot: env.HERMES_DESKTOP_HERMES_ROOT || null, sessions, preserved: { before: preservedBefore.length, after: preservedAfter.length, lost: 0 } }, null, 2))
+ } finally {
+ if (!LIFECYCLE_KEEP) {
+ fs.rmSync(sandbox, { recursive: true, force: true })
+ console.log(` sandbox removed: ${sandbox}`)
+ } else {
+ console.log(` sandbox kept (HERMES_DESKTOP_LIFECYCLE_KEEP=1): ${sandbox}`)
+ }
+ }
+}
// The packaged app must contain the PM payload, node-pty, and renderer assets.
function validateBundle() {
if (!exists(APP.binary)) {
@@ -392,6 +559,15 @@ function help() {
Fast rerun (skip rebuild if the packaged app already exists):
HERMES_DESKTOP_SKIP_BUILD=1 npm run test:desktop:fresh
+
+Automated packaged lifecycle (no host side effects; isolated userData + HERMES_HOME):
+ npm run test:desktop:lifecycle
+ # start packaged app → real serve backend ready (/api/health 200) → graceful
+ # quit → relaunch → preserved-home check → full teardown of our own processes.
+ # Requires a backend root the packaged app may use (backend-resolution rung 1):
+ # HERMES_DESKTOP_LIFECYCLE_BACKEND_ROOT=<hermes checkout with .venv|venv>
+ # Knobs: HERMES_DESKTOP_LIFECYCLE_TIMEOUT_MS and
+ # HERMES_DESKTOP_LIFECYCLE_KEEP=1 to keep the sandbox for inspection.
`)
}
@@ -422,6 +598,13 @@ if (MODE === 'existing') {
ensurePackagedApp()
}
printArtifacts(validateBundle())
+} else if (MODE === 'lifecycle') {
+ ensurePackagedApp()
+ printArtifacts(validateBundle())
+ runLifecycle().catch(err => {
+ console.error(err && err.message ? err.message : err)
+ process.exit(1)
+ })
} else {
help()
}
diff --git a/apps/desktop/scripts/update-relaunch-waiter.ps1 b/apps/desktop/scripts/update-relaunch-waiter.ps1
new file mode 100644
index 00000000000..f1b92db75ef
--- /dev/null
+++ b/apps/desktop/scripts/update-relaunch-waiter.ps1
@@ -0,0 +1,47 @@
+# Wait outside the package until the original app exits and Windows publishes its update.
+param(
+ [Parameter(Mandatory = $true)][int]$ProcessId,
+ [Parameter(Mandatory = $true)][long]$ProcessStartTimeMs,
+ [Parameter(Mandatory = $true)][string]$IdentityName,
+ [Parameter(Mandatory = $true)][string]$ReadyFile,
+ [int]$TimeoutSeconds = 900,
+ [int]$PollMillis = 500
+)
+
+try {
+ $ErrorActionPreference = 'Stop'
+ $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
+ $package = Get-AppxPackage -Name $IdentityName | Select-Object -First 1
+ if (-not $package) { exit 2 }
+ $appId = (Get-AppxPackageManifest $package).Package.Applications.Application.Id | Select-Object -First 1
+ if (-not $appId) { exit 2 }
+ $fromVersion = $package.Version
+ $familyName = $package.PackageFamilyName
+ Set-Content -LiteralPath $ReadyFile -Value "$fromVersion|$familyName|$appId"
+
+ while ($true) {
+ $parent = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
+ if (-not $parent) { break }
+ # Compare absolute birth times. Process age changes on every poll.
+ $birthMs = ([DateTimeOffset]$parent.StartTime).ToUnixTimeMilliseconds()
+ if ([Math]::Abs($birthMs - $ProcessStartTimeMs) -gt 3000) { break }
+ if ((Get-Date) -gt $deadline) { exit 3 }
+ Start-Sleep -Milliseconds $PollMillis
+ }
+
+ while ((Get-Date) -le $deadline) {
+ $current = Get-AppxPackage -Name $IdentityName | Select-Object -First 1
+ if ($current -and $current.Version -ne $fromVersion -and $current.PackageFamilyName -eq $familyName) {
+ Start-Process "shell:AppsFolder\$familyName!$appId"
+ exit 0
+ }
+ Start-Sleep -Milliseconds $PollMillis
+ }
+ exit 4
+} finally {
+ Set-Location $env:TEMP
+ Remove-Item -LiteralPath $ReadyFile -Force -ErrorAction SilentlyContinue
+ if ([IO.Path]::GetFileName($PSScriptRoot).StartsWith('hermes-relaunch-')) {
+ Remove-Item -LiteralPath $PSScriptRoot -Recurse -Force -ErrorAction SilentlyContinue
+ }
+}
diff --git a/apps/desktop/src/app/messaging/index.test.tsx b/apps/desktop/src/app/messaging/index.test.tsx
index 75bb9701e6f..b87cf2e7340 100644
--- a/apps/desktop/src/app/messaging/index.test.tsx
+++ b/apps/desktop/src/app/messaging/index.test.tsx
@@ -3,8 +3,18 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import { MemoryRouter } from 'react-router'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { $changeEventsAvailable, $pairingChangeTick, $platformsChangeTick } from '@/store/live-sync'
+import { $settingsScopeOverride } from '@/store/settings-scope'
import type { MessagingPlatformInfo } from '@/types/hermes'
+import { MessagingView } from './index'
+
+// Imports are static on purpose: `await import(...)` inside test bodies ran
+// against the test timer, and a cold evaluate of the MessagingView graph blew
+// the 15s timeout — the timed-out first test then left the DOM empty for
+// every later test. vi.mock calls below are hoisted above these imports, so
+// the mocks still apply.
+
const getMessagingPlatforms = vi.fn()
const updateMessagingPlatform = vi.fn()
const getPairing = vi.fn()
@@ -75,7 +85,6 @@ afterEach(() => {
})
async function renderMessaging() {
- const { MessagingView } = await import('./index')
let result: ReturnType<typeof render>
await act(async () => {
result = render(
@@ -90,8 +99,6 @@ async function renderMessaging() {
describe('MessagingView profile scope', () => {
it('follows the active profile instead of targeting primary when there is no override', async () => {
- const { $settingsScopeOverride } = await import('@/store/settings-scope')
-
$settingsScopeOverride.set(null)
getMessagingPlatforms.mockResolvedValue({ platforms: [platform()] })
@@ -204,8 +211,6 @@ describe('MessagingView pairing', () => {
// connect/disconnect health via gateway_state.json, which a new pairing
// request never moves. Riding it would leave someone invisible in the
// pending list until an unrelated reconnect happened to fire.
- const { $changeEventsAvailable, $pairingChangeTick, $platformsChangeTick } = await import('@/store/live-sync')
-
getMessagingPlatforms.mockResolvedValue({ platforms: [platform()] })
getPairing.mockResolvedValue({ approved: [], pending: [] })
diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsx
index 02d04b7ec2e..5d095848c55 100644
--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx
@@ -1,6 +1,8 @@
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { GatewaySettings } from './gateway-settings'
+
const getConnectionConfig = vi.fn()
const saveConnectionConfig = vi.fn()
@@ -37,8 +39,6 @@ afterEach(() => {
describe('GatewaySettings', () => {
it('loads the machine-level connection config (no profile scoping)', async () => {
- const { GatewaySettings } = await import('./gateway-settings')
-
render(<GatewaySettings />)
expect(await screen.findByText('Local gateway')).toBeTruthy()
expect(
diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsx
index 7f91260b929..0dda3a8a904 100644
--- a/apps/desktop/src/app/updates-overlay.tsx
+++ b/apps/desktop/src/app/updates-overlay.tsx
@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'
import { useEffect, useState } from 'react'
import { BrandMark } from '@/components/brand-mark'
+import { SyncStatusCard } from '@/components/sync-status-card'
import { Button } from '@/components/ui/button'
import { writeClipboardText } from '@/components/ui/copy-button'
import {
@@ -254,6 +255,7 @@ function IdleView({
version={version}
/>
<UpdateStatusCard target={target} />
+ <SyncStatusCard />
{details}
</div>
)
@@ -312,6 +314,8 @@ function IdleView({
</div>
{remaining > 0 && <p className="text-center text-xs text-muted-foreground">{u.moreChanges(remaining)}</p>}
+
+ <SyncStatusCard />
</div>
)
}
diff --git a/apps/desktop/src/components/sync-status-card.test.tsx b/apps/desktop/src/components/sync-status-card.test.tsx
new file mode 100644
index 00000000000..06ee1c7ef5c
--- /dev/null
+++ b/apps/desktop/src/components/sync-status-card.test.tsx
@@ -0,0 +1,88 @@
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { DesktopSyncReceipt } from '@/global'
+
+import { SyncStatusCard } from './sync-status-card'
+
+function setBridge(receipt: DesktopSyncReceipt | null | Promise<DesktopSyncReceipt | null>, failing = false) {
+ ;(window as any).hermesDesktop = {
+ getSyncStatus: failing
+ ? vi.fn(() => Promise.reject(new Error('bridge gone')))
+ : vi.fn(() => Promise.resolve(receipt))
+ }
+}
+
+afterEach(() => {
+ cleanup()
+ delete (window as any).hermesDesktop
+})
+
+async function renderCard() {
+ await act(async () => {
+ render(<SyncStatusCard />)
+ })
+}
+
+describe("SyncStatusCard — the renderer's getSyncStatus warning surface", () => {
+ it('renders the needs-fixing warning headline and per-plugin reasons', async () => {
+ setBridge({
+ kind: 'sync',
+ outcome: 'checked',
+ plugin_checks: [
+ { name: 'bad-url', needs_fixing: 'update_url points at a fork', update_available: false },
+ { name: 'fine', update_available: false }
+ ]
+ })
+ await renderCard()
+
+ expect(screen.getByTestId('sync-status-card')).toBeTruthy()
+ expect(screen.getByText(/need update-url review/)).toBeTruthy()
+ expect(screen.getByText(/bad-url: update_url points at a fork/)).toBeTruthy()
+ expect(screen.queryByText(/fine/)).toBeNull()
+ })
+
+ it('renders bisect disables and available updates', async () => {
+ setBridge({
+ kind: 'sync',
+ outcome: 'bisected',
+ plugin_bisect: [{ plugin: 'conflictor', action: 'disabled', reason: 'conflicts with core pin' }],
+ plugin_checks: [{ name: 'grower', update_available: true, current: '1.0.0', latest: '1.1.0' }]
+ })
+ await renderCard()
+
+ expect(screen.getByText(/disabled by dependency conflicts/)).toBeTruthy()
+ expect(screen.getByText(/conflictor: conflicts with core pin/)).toBeTruthy()
+ expect(screen.getByText(/grower: 1.0.0 → 1.1.0/)).toBeTruthy()
+ })
+
+ it('renders a failed venv rebuild as the top signal', async () => {
+ setBridge({
+ kind: 'sync',
+ outcome: 'failed',
+ venv_rebuild: { ok: false, reason: 'uv sync exited 1' }
+ })
+ await renderCard()
+
+ expect(screen.getByText(/rebuild failed/)).toBeTruthy()
+ })
+
+ it('renders nothing without a receipt and nothing on a healthy receipt', async () => {
+ setBridge(null)
+ const { container } = render(<SyncStatusCard />)
+ await act(async () => {})
+ expect(container.textContent).toBe('')
+
+ cleanup()
+ setBridge({ kind: 'sync', outcome: 'ok' })
+ await renderCard()
+ expect(screen.queryByTestId('sync-status-card')).toBeNull()
+ })
+
+ it('a broken bridge degrades to nothing instead of breaking the updates overlay', async () => {
+ setBridge(null, true)
+ const { container } = render(<SyncStatusCard />)
+ await act(async () => {})
+ expect(container.textContent).toBe('')
+ })
+})
diff --git a/apps/desktop/src/components/sync-status-card.tsx b/apps/desktop/src/components/sync-status-card.tsx
new file mode 100644
index 00000000000..a5ecc8161d3
--- /dev/null
+++ b/apps/desktop/src/components/sync-status-card.tsx
@@ -0,0 +1,111 @@
+/**
+ * SyncStatusCard — the desktop warning surface for the latest pm/plugin sync
+ * receipt (SPEC-05). The renderer calls `getSyncStatus` here and paints the
+ * derived summary: failed venv rebuilds, dependency-bisect disables,
+ * needs-fixing update_url mismatches, and available plugin updates. The
+ * surface degrades to nothing when there is no receipt (older backends, no
+ * sync yet) rather than rendering an empty box.
+ *
+ * The copy lives in `deriveSyncStatusSummary` (the extracted, unit-tested
+ * owner) — this component is presentation only, so the wording cannot drift
+ * between the derivation and the paint.
+ */
+
+import { useEffect, useState } from 'react'
+
+import { AlertCircle, AlertTriangle, Check } from '@/lib/icons'
+
+import { deriveSyncStatusSummary, type SyncStatusSummary } from './sync-status'
+
+const LEVEL_STYLES: Record<SyncStatusSummary['level'], string> = {
+ ok: 'text-muted-foreground',
+ info: 'text-muted-foreground',
+ warn: 'text-amber-600 dark:text-amber-400',
+ error: 'text-destructive'
+}
+
+export function SyncStatusCard() {
+ const [summary, setSummary] = useState<SyncStatusSummary | null>(null)
+
+ useEffect(() => {
+ let alive = true
+
+ void window.hermesDesktop
+ ?.getSyncStatus?.()
+ .then(receipt => {
+ if (alive) {
+ setSummary(deriveSyncStatusSummary(receipt))
+ }
+ })
+ .catch(() => {
+ // A missing/broken receipt surface must never break the updates
+ // overlay — degrade to nothing (the receipt is advisory).
+ if (alive) {
+ setSummary(null)
+ }
+ })
+
+ return () => {
+ alive = false
+ }
+ }, [])
+
+ if (!summary?.headline) {
+ return null
+ }
+
+ const tone = LEVEL_STYLES[summary.level]
+
+ return (
+ <div
+ className="grid gap-2 rounded-lg border border-border bg-muted/40 p-3 text-left"
+ data-testid="sync-status-card"
+ >
+ <p className={`flex items-center gap-2 text-sm font-medium ${tone}`}>
+ {summary.level === 'error' || summary.level === 'warn' ? (
+ <AlertCircle aria-hidden className="size-4 shrink-0" />
+ ) : (
+ <Check aria-hidden className="size-4 shrink-0" />
+ )}
+ {summary.headline}
+ </p>
+
+ {summary.needsFixing.length > 0 && (
+ <ul className="grid gap-1 text-xs text-foreground">
+ {summary.needsFixing.map(item => (
+ <li className="flex items-start gap-2" key={`needs-fixing-${item.plugin}`}>
+ <AlertTriangle aria-hidden className="mt-0.5 size-3 shrink-0 text-amber-600 dark:text-amber-400" />
+ <span className="leading-snug">
+ {item.plugin}: {item.reason}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {summary.disabledPlugins.length > 0 && (
+ <ul className="grid gap-1 text-xs text-foreground">
+ {summary.disabledPlugins.map(item => (
+ <li className="flex items-start gap-2" key={`disabled-${item.plugin}`}>
+ <AlertTriangle aria-hidden className="mt-0.5 size-3 shrink-0 text-amber-600 dark:text-amber-400" />
+ <span className="leading-snug">
+ {item.plugin}: {item.reason}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {summary.updatesAvailable.length > 0 && (
+ <ul className="grid gap-1 text-xs text-foreground">
+ {summary.updatesAvailable.map(item => (
+ <li className="leading-snug" key={`update-${item.name}`}>
+ {item.name}
+ {item.current && item.latest ? `: ${item.current} → ${item.latest}` : ''}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )
+}
diff --git a/apps/desktop/src/components/sync-status.test.ts b/apps/desktop/src/components/sync-status.test.ts
index a78d97d765f..1c3cd72df00 100644
--- a/apps/desktop/src/components/sync-status.test.ts
+++ b/apps/desktop/src/components/sync-status.test.ts
@@ -5,6 +5,19 @@ import type { DesktopSyncReceipt } from '@/global'
import { deriveSyncStatusSummary } from './sync-status'
describe('deriveSyncStatusSummary', () => {
+ test('a no-op sync is healthy, while an embedded failed sync is visible', () => {
+ expect(deriveSyncStatusSummary({ outcome: 'ok', venv_rebuild: { ok: false, reason: 'already in sync' } }).headline).toBeNull()
+
+ const receipt = {
+ outcome: 'failed', pm_sync_outcome: 'failed',
+ pm_steps: [{ name: 'dependency-sync', ok: false, detail: 'network unavailable' }]
+ }
+
+ const summary = deriveSyncStatusSummary(receipt)
+ expect(summary.level).toBe('error')
+ expect(summary.headline).toContain('network unavailable')
+ })
+
test('null receipt degrades to nothing-to-show', () => {
const summary = deriveSyncStatusSummary(null)
expect(summary.headline).toBeNull()
diff --git a/apps/desktop/src/components/sync-status.ts b/apps/desktop/src/components/sync-status.ts
index e0e7cd8a864..a8109ec543e 100644
--- a/apps/desktop/src/components/sync-status.ts
+++ b/apps/desktop/src/components/sync-status.ts
@@ -33,7 +33,7 @@ export function deriveSyncStatusSummary(
if (!receipt) {return empty}
- const disabledPlugins = (receipt.plugin_bisect ?? [])
+ const disabledPlugins = (receipt.pm_plugin_bisect ?? receipt.plugin_bisect ?? [])
.filter(d => d.action === 'disabled')
.map(d => ({ plugin: d.plugin, reason: d.reason }))
@@ -47,14 +47,19 @@ export function deriveSyncStatusSummary(
.filter(c => c.update_available === true)
.map(c => ({ name: c.name, current: c.current ?? null, latest: c.latest ?? null }))
- const rebuildFailed =
- receipt.venv_rebuild != null && receipt.venv_rebuild.ok === false
+ const outcome = receipt.pm_sync_outcome ?? receipt.outcome
+ const rebuild = receipt.pm_venv_rebuild ?? receipt.venv_rebuild
+ const steps = receipt.pm_steps ?? receipt.steps ?? []
+ const failureDetail = steps.find(step => step.ok === false)?.detail ?? rebuild?.reason
+
+ const rebuildFailed = outcome === 'failed' || outcome === 'refused' ||
+ (outcome !== 'ok' && outcome !== 'success' && rebuild?.ok === false)
let headline: string | null = null
let level: SyncStatusSummary['level'] = 'ok'
if (rebuildFailed) {
- headline = 'Dependency rebuild failed — some plugins may be missing packages'
+ headline = failureDetail ? `Dependency rebuild failed — ${failureDetail}` : 'Dependency rebuild failed — inspect the update receipt'
level = 'error'
} else if (needsFixing.length > 0) {
headline = `${needsFixing.length} plugin${
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index b6587803183..5b90f0f2ae6 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -605,6 +605,10 @@ export interface DesktopSyncReceipt {
finished_at?: string
steps?: Array<{ name: string; ok: boolean; detail?: string; at?: string }>
venv_rebuild?: { ok: boolean; reason?: string } | null
+ pm_sync_outcome?: string
+ pm_steps?: DesktopSyncReceipt['steps']
+ pm_venv_rebuild?: DesktopSyncReceipt['venv_rebuild']
+ pm_plugin_bisect?: DesktopSyncReceipt['plugin_bisect']
plugin_bisect?: Array<{ plugin: string; action: string; reason: string }>
plugin_checks?: Array<{
name: string
diff --git a/apps/desktop/src/store/session-unread-tile.test.ts b/apps/desktop/src/store/session-unread-tile.test.ts
index c93480dced1..b0df4a700f4 100644
--- a/apps/desktop/src/store/session-unread-tile.test.ts
+++ b/apps/desktop/src/store/session-unread-tile.test.ts
@@ -1,26 +1,25 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import * as model from '@/components/pane-shell/tree/model'
+import { declareDefaultTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'
+import { registry } from '@/contrib/registry'
+import { createClientSessionState } from '@/lib/chat-runtime'
+
+import { $selectedStoredSessionId, $unreadFinishedSessionIds } from './session'
+import { publishSessionState } from './session-states'
// The completed-unread dot is keyed on the FOCUSED session, not the selected
// one. A tile is never $selectedStoredSessionId, so keying either half on the
// selection left a tiled session's dot green with no way to clear it.
+//
+// Static imports on purpose: re-evaluating this module graph per test
+// (vi.resetModules) takes ~10s cold and blew the 10s hook timeout. Each test
+// only needs fresh store state, which beforeEach resets directly.
describe('completed-unread dot follows the focused session', () => {
- beforeEach(() => {
- vi.resetModules()
- })
-
- afterEach(() => {
- vi.resetModules()
- })
-
- async function setup() {
- const tree = await import('@/components/pane-shell/tree/store')
- const model = await import('@/components/pane-shell/tree/model')
- const { registry } = await import('@/contrib/registry')
- const { createClientSessionState } = await import('@/lib/chat-runtime')
- const session = await import('./session')
- const states = await import('./session-states')
+ let finishTurn: (storedSessionId: string) => void
+ beforeEach(() => {
for (const id of ['workspace', 'session-tile:tiled']) {
registry.register({
area: 'panes',
@@ -32,53 +31,45 @@ describe('completed-unread dot follows the focused session', () => {
}
// The workspace holds the primary chat, a second zone holds the tile.
- tree.declareDefaultTree(
+ declareDefaultTree(
model.split('row', [
model.group(['workspace'], { active: 'workspace', id: 'grp-main' }),
model.group(['session-tile:tiled'], { active: 'session-tile:tiled', id: 'grp-tile' })
])
)
- session.$unreadFinishedSessionIds.set([])
- session.$selectedStoredSessionId.set('primary')
+ $unreadFinishedSessionIds.set([])
+ $selectedStoredSessionId.set('primary')
- const finishTurn = (storedSessionId: string) => {
+ finishTurn = (storedSessionId: string) => {
const working = { ...createClientSessionState(null), busy: true, storedSessionId }
- states.publishSessionState(`rt-${storedSessionId}`, working)
- states.publishSessionState(`rt-${storedSessionId}`, { ...working, busy: false })
+ publishSessionState(`rt-${storedSessionId}`, working)
+ publishSessionState(`rt-${storedSessionId}`, { ...working, busy: false })
}
+ })
- return { finishTurn, session, tree }
- }
-
- it('clears the dot when an already-open tile is fronted', async () => {
- const { finishTurn, session, tree } = await setup()
-
- tree.noteActiveTreeGroup('grp-main')
+ it('clears the dot when an already-open tile is fronted', () => {
+ noteActiveTreeGroup('grp-main')
finishTurn('tiled')
- expect(session.$unreadFinishedSessionIds.get()).toEqual(['tiled'])
+ expect($unreadFinishedSessionIds.get()).toEqual(['tiled'])
// Fronting the tile is what a tab click does. Before the fix nothing on
// this path cleared the marker, so the dot stayed green.
- tree.noteActiveTreeGroup('grp-tile')
- expect(session.$unreadFinishedSessionIds.get()).toEqual([])
+ noteActiveTreeGroup('grp-tile')
+ expect($unreadFinishedSessionIds.get()).toEqual([])
})
- it('never marks a tile that finishes while it is the focused one', async () => {
- const { finishTurn, session, tree } = await setup()
-
- tree.noteActiveTreeGroup('grp-tile')
+ it('never marks a tile that finishes while it is the focused one', () => {
+ noteActiveTreeGroup('grp-tile')
finishTurn('tiled')
- expect(session.$unreadFinishedSessionIds.get()).toEqual([])
+ expect($unreadFinishedSessionIds.get()).toEqual([])
})
- it('marks the primary session when a tile has focus', async () => {
- const { finishTurn, session, tree } = await setup()
-
- tree.noteActiveTreeGroup('grp-tile')
+ it('marks the primary session when a tile has focus', () => {
+ noteActiveTreeGroup('grp-tile')
finishTurn('primary')
- expect(session.$unreadFinishedSessionIds.get()).toEqual(['primary'])
+ expect($unreadFinishedSessionIds.get()).toEqual(['primary'])
})
})
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 7719c871d81..3160fb533cd 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3470,7 +3470,7 @@ def _maybe_run_worktree_maintenance() -> None:
repos = _worktree_maintenance_repos()
if not repos:
return
- from cli import _prune_stale_worktrees
+ from hermes_cli.worktree_ops import _prune_stale_worktrees
for repo in repos:
try:
diff --git a/docs/pm-audit-status.md b/docs/pm-audit-status.md
index 72df4a9c791..c229e415f06 100644
--- a/docs/pm-audit-status.md
+++ b/docs/pm-audit-status.md
@@ -28,49 +28,74 @@ The updater, backup, setup, voice-text helpers, and several plugins now use
one implementation per reconciled concern. Runtime paths have a shared owner
in `hermes_cli/runtime_paths.py`.
-## Verification limits
+## Closure implementation
-The first broad native-Windows run completed its file list with 43,358 passed,
-257 failed, and 1,390 skipped tests. Eight files had no completed result.
-Repairs overlapped that run, so it does not certify the final tree.
+| Contract | Owner and proof |
+| --- | --- |
+| Interrupted publication | `hermes_cli/runtime_state.py` journals the old config and the proposed config hash. Startup recovers before dependency activation. Recovery refuses to overwrite unrelated edits. Real subprocess tests terminate before and after facts publication. |
+| Live-generation collection | Startup holds a generation lease under the publication lock. `pm gc` removes only unselected, lease-managed generations without live readers. Tests keep a real reader alive while collection runs. |
+| Receipt correlation | PM completions carry the invoking update ID. The updater embeds that completion, including failed steps and refusal reasons. Nested commands and copied contexts cannot finalize an enclosing receipt. |
+| Warning surfaces | Doctor uses the update checker's local provenance rules. The desktop reads sync status and distinguishes a healthy no-op from an embedded failure. |
+| Updater ownership | `electron/updater/checkout.ts` owns checkout checks and handoffs. `main.ts` supplies its dependencies. |
+| Windows relaunch | A detached PowerShell waiter snapshots package identity before quit, waits for the original process to exit, then waits for the installed version to change. A failed registration produces a manual-reopen warning. |
+| Test integrity | TCC behavior uses actual host markers. Installer source-grep assertions were removed. Runtime and installer behavior tests remain. |
+
+## Verified execution
-A later run selected all changed Python test files plus the broad run's failed
-files. Its 206 files reported 4,630 passed, one failed, and 330 skipped tests.
-There were no files without completed results. The remaining failure was a
-Hindsight setup fixture that crossed into dependency installation. The fixture
-now isolates that boundary. The final six-file rerun reported 234 passed and
-two skipped tests, including Hindsight setup, PM state, admission, environment
-sanitization, and terminal timeout output. A separate four-file store review
-rerun reported 83 passed and one skipped test.
+- The latest complete native-Windows Python run reported 44,557 passed, one
+ failed, and 1,404 skipped tests across 3,746 files. Python source hashes stayed
+ unchanged throughout the run. It also reported one pass-on-retry HTTP test.
+ The install-ID race and HTTP test were then fixed. Their two files passed
+ 35 tests without retries. This is not a complete final-tree suite pass.
+- Root `npm run check` completed with exit code zero, including MSIX packaging.
+ Desktop UI: 7,231 passed. Electron: 2,311 passed and 23 skipped. TUI:
+ 1,719 passed and eight skipped. Dashboard: 291 passed. Root JS: 77 passed.
+ Type checks and lint had no errors. Existing lint warnings remain. This
+ packaging check used the primary build directory's existing payload, not
+ the separately verified fresh audit payload.
+- The actual core project resolved and built through the workspace helper.
+ Imports resolved from the generated workspace and the source lock was unchanged.
+- A fresh native ARM64 PM bundle completed its pinned-tool checks and all-extras
+ environment build. Its manifest records source tree
+ `60c9fb444c93e8a79ae22a01677c3291385343a6`.
+- The rebuilt thin desktop started its real backend twice in an isolated home,
+ answered HTTP 200, and exited cleanly. Home entries survived relaunch.
+- A real isolated API-server messaging gateway retained its PID and birth time
+ after ordinary desktop quit. The desktop backend stopped; the gateway did not.
+- A thin MSIX built with the real packaging toolchain. Windows Sandbox installed
+ version `0.17.0.0`, updated to `0.17.0.1`, and verified absence after uninstall.
+ Test-certificate creation and trust were confined to the disposable guest.
-Desktop renderer tests reported 7,225 passed. Electron tests reported 2,295
-passed and 23 skipped. Both desktop TypeScript checks also passed after the
-locked development packages were restored. These are unit/type checks, not an
-installer or signed-release lifecycle test.
+- A separate fresh bundled MSIX was produced from payload tree `60c9fb44...`.
+ The unpacked artifact's own CLI ran, imports resolved inside its payload,
+ and `hermes serve` answered HTTP 200. The Sandbox deployment attempt failed
+ on an incorrect unpacked path. It does not prove bundled installation.
+- Plugin checks now run from the first housekeeping tick, with the configured
+ interval gate controlling network checks. A real isolated gateway wrote two
+ successful plugin-check receipts one tick apart. Auto-apply was disabled.
-A real Hindsight side-environment daemon started in a disposable home, answered
-its health endpoint with HTTP 200, and stopped successfully. This verifies
-startup, health, and shutdown, not an LLM retain/recall operation.
+These receipts cover different layers. Thin-package deployment and unpacked
+runtime startup do not prove bundled installation or App Installer-triggered
+relaunch. No tests sent an LLM request as evidence of this acceptance pass.
## Remaining acceptance work
-- Run the full Python suite on one fixed final tree and the relevant native
- platform CI lanes. Targeted reruns do not substitute for this gate.
-- Complete packaged install, update, relaunch, and uninstall checks. Verify
- that the messaging gateway survives ordinary desktop quit.
-- Complete the remaining updater-strategy and warning-surface contracts from
- the audit. Manual update checks alone do not prove those surfaces.
-- Define and verify safe collection of obsolete dependency generations while
- older processes still use them. The current conservative retention avoids
- deleting a live generation but does not bound storage use.
-- Strengthen publication recovery for process death between plugin-config and
- runtime-facts writes. Exception rollback is tested; those two files are not
- one crash-atomic transaction.
-- Complete receipt correlation and failure-reporting checks across nested PM
- and updater operations.
-- Reconcile the remaining documentation and complete the final aggregate diff
- review. The bounded pre-commit review does not cover every moved updater line.
+- Obtain a green complete Python run on the final tree. The completed run and
+ later bounded reruns must be reported separately.
+- Repeat bundled MSIX deployment with the corrected Sandbox harness and the
+ final source snapshot. The existing fresh bundle predates the final cron,
+ install-ID, and plugin-cadence fixes. Its unpacked runtime proof remains
+ scoped to the recorded payload tree.
+- Exercise an actual App Installer-triggered package update and automatic
+ relaunch. The tested Windows Sandbox image has no Desktop App Installer.
+- Run the relevant native macOS/Linux acceptance lanes. Windows host selection
+ verifies markers, not foreign-platform behavior.
+- Resolve the remaining review limit: a context-only config home outside the
+ process install root cannot be recovered by the current journal validator.
+- Identify the test that creates relative `MagicMock` SQLite artifacts. The
+ generated files are preserved outside the commit, but the producer is unresolved.
+- Record the final commit and native CI verification.
-The external audit directory contains the original reports, per-batch logs,
-review adjudication, and the exact test-file selection. No remote release,
-service installation, or push is implied by this commit.
+The external audit directory contains original findings, exact test selections,
+per-run logs, source snapshots, and review adjudication. No remote release,
+production service installation, or push is implied by this work.
diff --git a/gateway/run.py b/gateway/run.py
index 3f947f3a961..22ac1f8166e 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4533,7 +4533,7 @@ def _start_gateway_housekeeping(
(60, "Sync pull tick", _housekeeping_skill_sync),
(60, "Org sync pull tick", _housekeeping_org_skill_sync),
(60, "Auto-archive tick", _housekeeping_auto_archive),
- (60, "Plugin update check", _housekeeping_plugin_update_check),
+ (1, "Plugin update check", _housekeeping_plugin_update_check),
(1, "Deferred FTS retry tick", _housekeeping_deferred_fts_retry),
(1, "gateway housekeeping memory trim", _housekeeping_memory_trim)]
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.py
index f149cdabf30..4f7785f0c8b 100644
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@ -53,6 +53,7 @@ from hermes_cli.doctor_state import (
_check_profiles,
_check_skills_hub,
_check_state_db,
+ _check_update_provenance,
)
_PROVIDER_ENV_HINTS = (
@@ -113,7 +114,7 @@ DOCTOR_CHECKS = (
('xAI Model Retirement (May 15, 2026)', _check_xai_retirement),
('Plugin import paths (removed Sep 14, 2026)', _check_plugin_compat), ('Auth Providers', _check_auth_providers),
('Directory Structure', _check_directory_structure), (None, _check_state_db),
- (None, _check_gateway_supervision), (None, _check_command_installation),
+ (None, _check_update_provenance), (None, _check_gateway_supervision), (None, _check_command_installation),
('External Tools', _check_git_and_rg), (None, _check_terminal_backend), (None, _check_node_and_browser),
(None, _check_npm_audit), ('API Connectivity', _check_api_connectivity),
('Tool Availability', _check_tool_availability), ('Skills Hub', _check_skills_hub),
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index ada357abdc0..15f3443183b 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -333,6 +333,42 @@ def _check_state_db(should_fix: bool, f: Finding) -> None:
_state_db_wal(f, should_fix, state_db_path)
+def _plugin_provenance_rows(plugins_dir) -> list:
+ """Report local provenance using the update checker's admission rules."""
+ from hermes_cli.plugins_provenance import ProvenanceClass, plugins_provenance
+ from hermes_cli.plugins_updates import check_local_provenance
+
+ if plugins_dir is None or not Path(plugins_dir).is_dir():
+ return [("info", "No plugins directory yet (nothing to check provenance for)", "")]
+ try:
+ provenances = plugins_provenance(Path(plugins_dir))
+ except (OSError, ValueError, RuntimeError) as exc:
+ return [("warn", "Plugin provenance could not be read", str(exc))]
+ rows = []
+ for provenance in provenances:
+ result = check_local_provenance(provenance)
+ detail = result.needs_fixing or result.reason
+ if result.needs_fixing or provenance.klass is ProvenanceClass.DRIFT:
+ rows.append(("warn", f"Plugin '{provenance.name}': {detail}", ""))
+ elif provenance.klass is ProvenanceClass.MANUAL:
+ rows.append(("info", f"Plugin '{provenance.name}' installed manually", detail))
+ elif provenance.klass is ProvenanceClass.SELF_CLONED:
+ rows.append(("info", f"Plugin '{provenance.name}': self-cloned", detail))
+ else:
+ rows.append(("ok", f"Plugin '{provenance.name}': provenance in good standing", detail))
+ return rows or [("info", "No provenanced plugins found", "")]
+
+
+@doctor_check("")
+def _check_update_provenance(should_fix: bool, f: Finding) -> None:
+ """Inspect local plugin update provenance without network or writes."""
+ from hermes_constants import get_hermes_home
+
+ printers = {"warn": check_warn, "ok": check_ok, "info": lambda text, detail: check_info(f"{text} {detail}".rstrip())}
+ for kind, text, detail in _plugin_provenance_rows(get_hermes_home() / "plugins"):
+ printers[kind](text, detail)
+
+
def _gh_authenticated() -> bool:
"""Check if gh CLI is authenticated via token file or device flow.
diff --git a/hermes_cli/install_identity.py b/hermes_cli/install_identity.py
index 553520df006..6aad8107172 100644
--- a/hermes_cli/install_identity.py
+++ b/hermes_cli/install_identity.py
@@ -81,34 +81,35 @@ def read_or_create_install_id(root: Path | None = None) -> Optional[str]:
"""
root = get_default_hermes_root() if root is None else root
path = root / _INSTALL_ID_FILENAME
- existing, mint = _read_existing(path)
- if not mint:
- return existing
- try:
- root.mkdir(parents=True, exist_ok=True)
- # Windows byte-range locks can report a same-process conflict instead of waiting for another
- # thread: serialize threads here, then keep the file lock as the cross-process publication fence.
- with _INSTALL_ID_PUBLICATION_LOCK, _install_id_file_lock(root):
- existing, mint = _read_existing(path)
- if not mint:
- return existing
- fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
- handle.write(uuid.uuid4().hex + "\n")
- handle.flush()
- os.fsync(handle.fileno())
- os.replace(tmp_name, path)
- _fsync_directory(root)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
-
- committed = path.read_text(encoding="utf-8-sig").strip().lower()
- return committed if _INSTALL_ID_RE.fullmatch(committed) else None
- except OSError:
- return None
+ # A reader can collide with the first atomic replace on Windows. Serialize
+ # threads before reading, and recheck an unavailable file under the OS lock.
+ with _INSTALL_ID_PUBLICATION_LOCK:
+ existing, _ = _read_existing(path)
+ if existing is not None:
+ return existing # Existing identities remain readable on read-only roots.
+ try:
+ root.mkdir(parents=True, exist_ok=True)
+ with _install_id_file_lock(root):
+ existing, mint = _read_existing(path)
+ if not mint:
+ return existing
+ fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(uuid.uuid4().hex + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_name, path)
+ _fsync_directory(root)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
+
+ committed = path.read_text(encoding="utf-8-sig").strip().lower()
+ return committed if _INSTALL_ID_RE.fullmatch(committed) else None
+ except OSError:
+ return None
def get_install_id(*, cache: dict[str, Optional[str]] | None = None) -> Optional[str]:
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 338c0e19664..63003f4479a 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2245,6 +2245,10 @@ def _update_preflight_handled(args) -> bool:
return False
+from hermes_cli.update_receipt import update_receipt_scope
+
+
+@update_receipt_scope()
def cmd_update(args):
"""Update Hermes Agent: hangup protection + update lock around ``_cmd_update_impl``."""
if _update_preflight_handled(args):
diff --git a/hermes_cli/plugins_admission.py b/hermes_cli/plugins_admission.py
index 93216bc5ac5..c1151499d33 100644
--- a/hermes_cli/plugins_admission.py
+++ b/hermes_cli/plugins_admission.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import os
from pathlib import Path
from typing import Iterable, Optional
@@ -43,43 +42,13 @@ def _config_path() -> Path:
return get_hermes_home() / "config.yaml"
-def _atomic_write_bytes(path: Path, data: bytes) -> None:
- import tempfile
-
- fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".admission-")
- try:
- with os.fdopen(fd, "wb") as stream:
- stream.write(data)
- stream.flush()
- os.fsync(stream.fileno())
- os.replace(temporary, path)
- finally:
- Path(temporary).unlink(missing_ok=True)
-
-
def _config_commit(candidate_enabled: set, candidate_disabled: set):
- """The before_publish hook: commit the config EXACTLY ONCE while pm
- holds the install lock. Returns an undo callable — invoked by
- sync_venv only when the subsequent facts write fails — that restores
- the previous config bytes atomically (or removes a config this
- commit created)."""
- path = _config_path()
- existed = path.is_file()
- previous = path.read_bytes() if existed else None
-
- commit_plugin_sets(candidate_enabled, candidate_disabled)
-
- def undo() -> None:
- if previous is None:
- path.unlink(missing_ok=True)
- else:
- _atomic_write_bytes(path, previous)
-
- return undo
-
+ """Journal both config versions before publishing either config or facts."""
+ import shutil
+ import tempfile
-def commit_plugin_sets(enabled: set, disabled: set) -> None:
- """Write BOTH plugin keys in ONE atomic config save."""
+ from pm.paths import repo_root
+ from hermes_cli.runtime_state import begin_publication, _atomic_bytes
from hermes_cli.config import read_raw_config
from utils import atomic_roundtrip_yaml_save
@@ -88,9 +57,21 @@ def commit_plugin_sets(enabled: set, disabled: set) -> None:
plugins_cfg = config.setdefault("plugins", {})
if not isinstance(plugins_cfg, dict):
raise ValueError(f"plugins must be a mapping in {path}")
- plugins_cfg["enabled"] = sorted(enabled)
- plugins_cfg["disabled"] = sorted(disabled)
- atomic_roundtrip_yaml_save(path, config)
+ plugins_cfg["enabled"] = sorted(candidate_enabled)
+ plugins_cfg["disabled"] = sorted(candidate_disabled)
+ with tempfile.TemporaryDirectory(prefix="hermes-admission-") as temporary:
+ staged = Path(temporary) / "config.yaml"
+ if path.is_file():
+ shutil.copyfile(path, staged)
+ atomic_roundtrip_yaml_save(staged, config)
+ proposed = staged.read_bytes()
+ publication = begin_publication(repo_root(), path, proposed)
+ try:
+ _atomic_bytes(path, proposed)
+ except BaseException:
+ publication()
+ raise
+ return publication
def admit_plugin_set_change(
@@ -111,13 +92,13 @@ def admit_plugin_set_change(
"""
from pm.ensure import sync_venv
- members = candidate_member_dirs(
- candidate_enabled, candidate_disabled, active_plugins_dir=active_plugins_dir, extra_dirs=extra_dirs
- )
+ extra_dirs = tuple(extra_dirs)
try:
sync_venv(
explicit=True,
- plugin_dirs=members,
+ plugin_dirs=lambda: candidate_member_dirs(
+ candidate_enabled, candidate_disabled, active_plugins_dir=active_plugins_dir, extra_dirs=extra_dirs
+ ),
before_publish=lambda: _config_commit(candidate_enabled, candidate_disabled),
)
except Exception as exc:
diff --git a/hermes_cli/plugins_cadence.py b/hermes_cli/plugins_cadence.py
index 6d7acb1fa24..88cfec0df48 100644
--- a/hermes_cli/plugins_cadence.py
+++ b/hermes_cli/plugins_cadence.py
@@ -139,10 +139,12 @@ def _run_check_locked(
config_get: Callable = None,
) -> list:
check_ok = True
+ warning = ""
try:
results = run_checks_fn(plugins_dir)
except Exception:
- log.warning("plugin update check failed", exc_info=True)
+ warning = "plugin update check failed"
+ log.warning(warning, exc_info=True)
results = []
check_ok = False
@@ -150,8 +152,11 @@ def _run_check_locked(
from pm import receipt
token = receipt.begin("plugin-check")
receipt.record_plugin_checks(results)
+ if warning:
+ receipt.record_warning(warning)
updates = [r for r in results if getattr(r, "update_available", None) is True]
- receipt.finalize("failed" if not check_ok else "updates-available" if updates else "ok", token=token)
+ receipt.finalize("failed" if not check_ok else "updates-available" if updates else "ok",
+ exit_code=0 if check_ok else 1, token=token)
except Exception:
log.debug("plugin-check receipt write failed", exc_info=True)
diff --git a/hermes_cli/plugins_updates.py b/hermes_cli/plugins_updates.py
index b7234c4f6a7..90f6e11a77f 100644
--- a/hermes_cli/plugins_updates.py
+++ b/hermes_cli/plugins_updates.py
@@ -76,13 +76,8 @@ def _read_manifest_field(plugin_dir: Path, key: str) -> Optional[str]:
return value.strip() if isinstance(value, str) and value.strip() else None
-def check_provenanced(
- prov: Provenance,
- *,
- fetch: Callable[[str], str], # url -> text (raises on failure)
- ls_remote: Callable[[str], str], # source -> HEAD sha (raises)
-) -> CheckResult:
- """Check ONE sidecar-provenanced plugin per the resolution order."""
+def check_local_provenance(prov: Provenance) -> CheckResult:
+ """Check installed provenance without fetching remote metadata."""
result = CheckResult(name=prov.name, klass=prov.klass.value)
if prov.klass is ProvenanceClass.MANUAL:
@@ -123,6 +118,22 @@ def check_provenanced(
)
return result
+ return result
+
+
+def check_provenanced(
+ prov: Provenance,
+ *,
+ fetch: Callable[[str], str],
+ ls_remote: Callable[[str], str],
+) -> CheckResult:
+ """Check local provenance before contacting its approved update source."""
+ result = check_local_provenance(prov)
+ if result.reason or result.needs_fixing:
+ return result
+ row = prov.row or {}
+ saved = row.get("update_url") or None
+
# ── 1. matching saved tag → fetch the feed ─────────────────────
if saved is not None:
try:
diff --git a/hermes_cli/runtime_paths.py b/hermes_cli/runtime_paths.py
index 8542bc02f2a..bbef8ac8860 100644
--- a/hermes_cli/runtime_paths.py
+++ b/hermes_cli/runtime_paths.py
@@ -105,9 +105,17 @@ def activate_dependencies(project_root: Path) -> None:
"""
import sys
- if not runtime_facts_path(project_root).is_file():
+ state = install_state_dir(project_root)
+ if not state.is_dir():
return
- selected = site_packages(selected_venv(project_root))
+ from hermes_cli.runtime_state import runtime_lock, recover_publication, lease_generation
+ with runtime_lock(project_root):
+ recover_publication(project_root)
+ if not runtime_facts_path(project_root).is_file():
+ return
+ environment = selected_venv(project_root)
+ lease_generation(environment)
+ selected = site_packages(environment)
if not selected.is_dir():
raise RuntimeError(f"dependency environment has no site-packages: {selected}")
import site
diff --git a/hermes_cli/runtime_state.py b/hermes_cli/runtime_state.py
new file mode 100644
index 00000000000..342b12e94e6
--- /dev/null
+++ b/hermes_cli/runtime_state.py
@@ -0,0 +1,183 @@
+"""Stdlib-only recovery and lifetime protection for dependency generations."""
+from __future__ import annotations
+
+import atexit
+import errno
+import base64
+from contextlib import contextmanager
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import tempfile
+import time
+import uuid
+
+from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path
+from hermes_constants import get_default_hermes_root
+
+
+def _lock(fd: int, *, wait: bool) -> bool:
+ if os.name == "nt":
+ import msvcrt
+ while True:
+ try:
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ return True
+ except OSError as exc:
+ if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
+ raise
+ if not wait:
+ return False
+ time.sleep(0.05)
+ else:
+ import fcntl
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
+ return True
+ except BlockingIOError:
+ return False
+
+
+@contextmanager
+def runtime_lock(project: Path):
+ state = install_state_dir(project)
+ state.mkdir(parents=True, exist_ok=True)
+ fd = os.open(state / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ _lock(fd, wait=True)
+ yield
+ finally:
+ os.close(fd)
+
+
+def _bytes(path: Path) -> bytes | None:
+ try:
+ return path.read_bytes()
+ except FileNotFoundError:
+ return None
+
+
+def _digest(path: Path) -> str | None:
+ data = _bytes(path)
+ return hashlib.sha256(data).hexdigest() if data is not None else None
+
+
+def _atomic_bytes(path: Path, data: bytes):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".publish-")
+ try:
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ if os.name != "nt":
+ directory = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def recover_publication(project: Path) -> None:
+ """Recover while holding runtime_lock, before activation or another write."""
+ journal = install_state_dir(project) / "publication.json"
+ data = _bytes(journal)
+ if data is None:
+ return
+ try:
+ row = json.loads(data)
+ config = Path(row["config"])
+ if config.name != "config.yaml" or not config.resolve().is_relative_to(get_default_hermes_root().resolve()):
+ raise ValueError("config path is outside Hermes state")
+ previous = base64.b64decode(row["previous"], validate=True) if row["previous"] is not None else None
+ if _digest(runtime_facts_path(project)) == row["facts_before"]:
+ current = _digest(config)
+ prior = hashlib.sha256(previous).hexdigest() if previous is not None else None
+ if current not in (prior, row.get("config_after")):
+ raise ValueError("config changed after publication began; preserve it for manual recovery")
+ # No selection was published. Roll back before any plugin is loaded.
+ if previous is None:
+ config.unlink(missing_ok=True)
+ else:
+ _atomic_bytes(config, previous)
+ journal.unlink()
+ except (ValueError, KeyError, TypeError, OSError) as exc:
+ raise RuntimeError(f"cannot recover dependency publication: {journal}: {exc}") from exc
+
+
+class Publication:
+ def __init__(self, project: Path, config: Path, proposed: bytes | None = None):
+ self.project = project
+ self.journal = install_state_dir(project) / "publication.json"
+ previous = _bytes(config)
+ row = {"config": str(config.resolve()), "previous": base64.b64encode(previous).decode() if previous is not None else None,
+ "facts_before": _digest(runtime_facts_path(project)),
+ "config_after": hashlib.sha256(proposed).hexdigest() if proposed is not None else None}
+ _atomic_bytes(self.journal, json.dumps(row).encode())
+
+ def __call__(self) -> None:
+ recover_publication(self.project)
+
+ def finish(self) -> None:
+ self.journal.unlink(missing_ok=True)
+
+
+def begin_publication(project: Path, config: Path, proposed: bytes | None = None) -> Publication:
+ recover_publication(project)
+ return Publication(project, config, proposed)
+
+
+def lease_generation(environment: Path) -> None:
+ """Hold a kernel lock until process exit; call under runtime_lock at boot."""
+ generation = environment.parent
+ if not (generation / ".lease-managed").is_file():
+ return # Generations produced before leases stay conservatively retained.
+ leases = generation / ".leases"
+ leases.mkdir(exist_ok=True)
+ fd = os.open(leases / uuid.uuid4().hex, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
+ try:
+ _lock(fd, wait=True)
+ except BaseException:
+ os.close(fd)
+ raise
+ atexit.register(os.close, fd)
+
+
+def collect_generations(project: Path, *, min_age_seconds: float = 86400) -> list[Path]:
+ """Remove unselected lease-managed generations after their readers exit."""
+ from hermes_cli.runtime_paths import selected_venv
+ removed = []
+ root = install_state_dir(project)
+ if not root.exists():
+ return removed
+ with runtime_lock(project):
+ recover_publication(project)
+ selected = selected_venv(project).parent.resolve()
+ generations = root / "environments"
+ if not generations.is_dir():
+ return removed
+ for generation in generations.iterdir():
+ if generation.is_symlink() or not generation.is_dir() or generation.resolve() == selected:
+ continue
+ marker = generation / ".lease-managed"
+ if not marker.is_file() or time.time() - marker.stat().st_mtime < min_age_seconds:
+ continue
+ active = False
+ for lease in (generation / ".leases").glob("*"):
+ fd = os.open(lease, os.O_RDWR)
+ try:
+ if not _lock(fd, wait=False):
+ active = True
+ break
+ finally:
+ os.close(fd)
+ if not active:
+ shutil.rmtree(generation)
+ removed.append(generation)
+ return removed
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index e42e3c71cbe..1e00f2ba736 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -1262,8 +1262,9 @@ def _verify_fleet_after_update(restart, *, _pre_update_plan, _windows_gateway_re
restart.incomplete = True
with suppress(Exception):
import hermes_cli.update_receipt as _ur
- if _ur._current is not None:
- _ur._current.data["runtime_outcomes"] = _runtime_outcomes
+ _active = _ur._current.get()
+ if _active is not None:
+ _active.data["runtime_outcomes"] = _runtime_outcomes
with _best_effort('Update receipt finalize failed: %s'):
from hermes_cli.update_receipt import finalize_update_receipt
diff --git a/hermes_cli/update_inventory.py b/hermes_cli/update_inventory.py
index d20eaaa6c84..589a298540d 100644
--- a/hermes_cli/update_inventory.py
+++ b/hermes_cli/update_inventory.py
@@ -385,8 +385,9 @@ def record_plan_in_receipt(plan: UpdatePlan) -> None:
try:
import hermes_cli.update_receipt as ur
- if ur._current is not None:
- ur._current.data["plan"] = plan.to_dict()
+ current = ur._current.get()
+ if current is not None:
+ current.data["plan"] = plan.to_dict()
except Exception as exc:
logger.debug("Could not record plan in receipt: %s", exc)
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index c4a93a6fd23..8e108f073f8 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -28,12 +28,15 @@ receipt records that the install is not in-place updatable.
from __future__ import annotations
+import contextvars
+import copy
import json
import logging
import os
import sys
import time
-from contextlib import suppress
+import uuid
+from contextlib import contextmanager, suppress
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
@@ -42,9 +45,36 @@ logger = logging.getLogger(__name__)
_RECEIPT_KEEP = 20 # keep the last N receipts per profile home
-# ``hermes update`` is a single-threaded CLI command; a module singleton lets the 7k-line updater
-# record steps from any depth without threading a handle through every helper.
-_current: Optional["UpdateReceipt"] = None
+# Receipt state is per-CONTEXT, not a module global: a nested
+# ``hermes update`` receipt (or one in another thread) must never clobber
+# the outer one, and the boundary finalize must see exactly its own
+# process's receipt. Same pattern as pm.receipt's ContextVars — no
+# manager object.
+_current: contextvars.ContextVar[Optional["UpdateReceipt"]] = contextvars.ContextVar(
+ "update_receipt_current", default=None
+)
+
+
+@contextmanager
+def update_receipt_scope():
+ """Keep the command's finalization guard away from an enclosing update."""
+ token = _current.set(None)
+ try:
+ yield
+ finally:
+ _current.reset(token)
+
+
+def current_correlation_id() -> Optional[str]:
+ """The update correlation id in force in this context, or None.
+
+ Derived from the OPEN update receipt itself — one source of truth, no
+ duplicate id variable: a nested update's begin replaces the current
+ receipt (so syncs begun under it capture the nested id), and its
+ finalize RESTORES the outer receipt via the ContextVar token (so the
+ outer id comes back for the rest of the outer update)."""
+ current = _current.get()
+ return current.correlation_id if current is not None else None
def _utc_now_iso() -> str:
@@ -83,6 +113,10 @@ class UpdateReceipt:
"pre_update": _code_identity(), "post_update": {},
"steps": [], "skips": [], "gateway_restart": {}, "fleet": [],
}
+ # The id binds this update to the pm sync receipts begun under it
+ # (pm.receipt captures it via the _correlation ContextVar).
+ self.correlation_id = uuid.uuid4().hex
+ self.data["update_id"] = self.correlation_id
def step(self, name: str, ok: bool, detail: str = "") -> None:
self.data["steps"].append({"name": name, "ok": bool(ok), "detail": detail, "at": _utc_now_iso()})
@@ -144,20 +178,38 @@ def _receipt_dir() -> Path:
def begin_update_receipt() -> None:
- """Start recording a new update receipt. Never raises."""
- global _current
+ """Start recording a new update receipt.
+
+ Nested updates are safe: the previous receipt (if any) is preserved
+ behind the ContextVar token and comes back when this one finalizes —
+ a nested begin/finalize never drops the outer update's receipt or
+ correlation. Never raises."""
try:
- _current = UpdateReceipt()
+ receipt = UpdateReceipt()
except Exception as exc: # pragma: no cover - defensive
logger.debug("Could not start update receipt: %s", exc)
- _current = None
+ return
+ receipt.current_token = _current.set(receipt)
def _record(method: str, what: str, *args: Any, **kwargs: Any) -> None:
- """Invoke ``method`` on the active receipt; no-op when none, never raises."""
+ """Invoke ``method`` on the active receipt; no-op when none, never raises.
+
+ Copy-on-write, same rule as pm.receipt: a copied context (copy_context,
+ asyncio.to_thread) inherits the SAME receipt object — mutate a clone
+ and re-set it in THIS context only, so a child's records never leak
+ into (or corrupt) the parent's receipt.
+ """
try:
- if _current is not None:
- getattr(_current, method)(*args, **kwargs)
+ import copy
+
+ current = _current.get()
+ if current is None:
+ return
+ clone = copy.copy(current)
+ clone.data = copy.deepcopy(current.data)
+ getattr(clone, method)(*args, **kwargs)
+ _current.set(clone)
except Exception as exc: # pragma: no cover - defensive
logger.debug("Could not record %s: %s", what, exc)
@@ -180,14 +232,26 @@ def record_gateway_restart(**kwargs: Any) -> None:
def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason: str = "") -> Optional[Path]:
"""Finalize + persist the receipt (``success``/``partial``/``failed``/``refused``); path or None.
- Exactly-once by construction: the module singleton is popped first, so a second call (e.g. the
+ Exactly-once by construction: the context's receipt is popped first, so a second call (e.g. the
command-boundary safety net after an inner path already finalized) is a no-op returning None.
+ The receipt is popped via its OWN begin token, so a nested update's finalize RESTORES the outer
+ update's open receipt and correlation instead of discarding them.
"""
- global _current
- receipt = _current
- _current = None
- if receipt is None:
+ current = _current.get()
+ if current is None:
return None
+ receipt = copy.copy(current)
+ receipt.data = copy.deepcopy(current.data)
+ token = getattr(receipt, "current_token", None)
+ try:
+ if token is not None:
+ _current.reset(token)
+ else: # pragma: no cover - receipts begun before token binding
+ _current.set(None)
+ except ValueError:
+ # Token from another context (finalize ran in a copied context) —
+ # pop THIS context only, so exactly-once still holds.
+ _current.set(None)
try:
receipt.finalize(outcome)
if stop_reason:
@@ -196,28 +260,44 @@ def finalize_update_receipt(outcome: str, fleet: list | None = None, stop_reason
receipt.data["fleet"] = fleet
# EMBED the pm sync sections (the settled receipts contract): the
# update's rebuild/bisect ran through pm's own sync receipt, which
- # finalizes before this one. Fold the newest sync receipt's
- # venv_rebuild + plugin_bisect into the update receipt so ONE file
- # carries the whole story (desktop reads a single latest.json).
+ # finalizes before this one. Fold in only the completion filed
+ # under THIS update's correlation id (pm.receipt.last_for_update,
+ # per-context, never latest.json) — a sync from before this update
+ # began, a standalone sync, or one in a concurrent thread cannot
+ # be misattributed, and a nested update's sync cannot displace
+ # this update's own. ONE file still carries the whole story
+ # (desktop reads a single latest.json).
try:
from pm import receipt as pm_receipt
- sync = pm_receipt.latest()
+ sync = pm_receipt.last_for_update(receipt.correlation_id, consume=True)
if isinstance(sync, dict):
- for key in ("venv_rebuild", "plugin_bisect", "feature_list"):
+ for key in ("venv_rebuild", "plugin_bisect", "feature_list", "steps", "exit_code"):
if sync.get(key) is not None:
receipt.data[f"pm_{key}"] = sync[key]
if sync.get("outcome") is not None:
receipt.data["pm_sync_outcome"] = sync.get("outcome")
+ if sync.get("warnings"):
+ receipt.data["pm_warnings"] = sync["warnings"]
+ if sync.get("refusal") is not None:
+ receipt.data["pm_refusal"] = sync["refusal"]
except Exception as exc: # pragma: no cover — embedding is additive
logger.debug("pm sync-section embed skipped: %s", exc)
directory = _receipt_dir()
directory.mkdir(parents=True, exist_ok=True)
- path = directory / f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}.json"
- body = json.dumps(receipt.data, indent=2, default=str)
- path.write_text(body, encoding="utf-8")
- with suppress(OSError): # stable pointer for the dashboard/desktop
- (directory / "latest.json").write_text(body, encoding="utf-8")
+ # Unique name: stamp+pid collides for nested/concurrent receipts in
+ # the same process+second — the correlation id makes the name unique
+ # per update run. Atomic write for BOTH the stamped receipt and the
+ # latest.json pointer (no torn readers).
+ import utils
+
+ path = directory / (
+ f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}_"
+ f"{receipt.correlation_id}.json"
+ )
+ utils.atomic_json_write(path, receipt.data, default=str)
+ with suppress(Exception): # stable pointer for the dashboard/desktop
+ utils.atomic_json_write(directory / "latest.json", receipt.data, default=str)
_prune_old_receipts(directory)
return path
except Exception as exc: # pragma: no cover - defensive
@@ -234,14 +314,18 @@ def finalize_pending_update_receipt(exit_code: Optional[int] = None, stop_reason
(preflight convention), else → ``failed``.
No-op when no receipt is open (the inner paths already finalized — exactly-once via the popped
- singleton) or when recording was never started. See #91283.
+ per-context receipt) or when recording was never started. See #91283.
"""
- if _current is None:
+ current = _current.get()
+ if current is None:
return None
outcome = "success" if exit_code in (0, None) else "refused" if exit_code == 2 else "failed"
if exit_code is not None:
with suppress(Exception):
- _current.data["exit_code"] = int(exit_code)
+ clone = copy.copy(current)
+ clone.data = copy.deepcopy(current.data)
+ clone.data["exit_code"] = int(exit_code)
+ _current.set(clone)
return finalize_update_receipt(outcome, stop_reason=stop_reason)
diff --git a/pm/cli.py b/pm/cli.py
index cea1e929ba2..ec86fce1436 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -351,10 +351,16 @@ def _gc_store(store, facts) -> tuple[int, int]:
def cmd_gc(args) -> int:
- facts = _facts()
- store = _store()
+ from pm.paths import writable_store_root
+ from pm.lock import Facts
+ from pm.store import Store
+ store = Store(writable_store_root())
+ facts = _facts() if store.root == _store().root else Facts(store.root / "facts.json")
removed, kept = _gc_store(store, facts)
- print(f"gc: removed {removed}, kept {kept}")
+ from hermes_cli.runtime_state import collect_generations
+ from pm.paths import repo_root
+ generations = collect_generations(repo_root())
+ print(f"gc: removed {removed}, kept {kept}; removed {len(generations)} dependency generations")
return 0
diff --git a/pm/downloader.py b/pm/downloader.py
index f8bde3f6f63..784313cc876 100644
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@ -157,7 +157,7 @@ def gc_protected_names(
# contract for "sweep everything"). mtime can tick a hair
# NEWER than `now` on some filesystems, which <= would
# wrongly treat as inside a zero window.
- if now - entry.stat().st_mtime < grace_seconds:
+ if grace_seconds > 0 and now - entry.stat().st_mtime < grace_seconds:
protected.add(entry.name)
except OSError:
protected.add(entry.name) # unreadable → assume live
diff --git a/pm/ensure.py b/pm/ensure.py
index d8d1152af7f..b12b6e2fa6c 100644
--- a/pm/ensure.py
+++ b/pm/ensure.py
@@ -108,11 +108,15 @@ def sealed() -> bool:
def _refuse_lazy(name: str, what: str) -> InstallError:
- return InstallError(
+ from pm import receipt
+
+ error = InstallError(
name,
f"not installed and lazy installs are disabled: {what}",
"enable security.allow_lazy_installs or run `hermes pm install`",
)
+ receipt.record_refusal("lazy-install", str(error))
+ return error
def _remove_entry(store: Store, entry_name: str) -> None:
@@ -372,26 +376,22 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu
)
package = get_package("venv")
- inputs = {} if plugin_dirs is None else {"plugin_dirs": plugin_dirs}
- facts = Facts(paths.runtime_facts_path())
- baseline = _facts().get("venv") or {}
- fact = facts.get("venv") or baseline
- enabled = sorted(set(fact.get("extras", [])) | set(extras or []))
- stamp = package.expected_stamp(enabled, **inputs)
- if before_publish is None and _runtime_state_matches(fact, stamp):
- receipt.record_venv_rebuild(False, "already in sync")
- outcome = "ok"
- return
- if not explicit and not lazy_installs_allowed() and not _runtime_state_matches(fact, stamp):
- raise _refuse_lazy("venv", str(extras) if extras else "venv out of sync")
- with Store(facts.path.parent).install_lock():
- facts.reload()
- fact = facts.get("venv") or baseline
+ from hermes_cli.runtime_state import runtime_lock, recover_publication
+ with runtime_lock(paths.repo_root()):
+ recover_publication(paths.repo_root())
+ members = plugin_dirs() if callable(plugin_dirs) else plugin_dirs
+ inputs = {} if members is None else {"plugin_dirs": members}
+ facts = Facts(paths.runtime_facts_path())
+ fact = facts.get("venv") or _facts().get("venv") or {}
enabled = sorted(set(fact.get("extras", [])) | set(extras or []))
stamp = package.expected_stamp(enabled, **inputs)
+ if not explicit and not lazy_installs_allowed() and not _runtime_state_matches(fact, stamp):
+ raise _refuse_lazy("venv", str(extras) if extras else "venv out of sync")
if _runtime_state_matches(fact, stamp):
if before_publish is not None:
- before_publish()
+ publication = before_publish()
+ if hasattr(publication, "finish"):
+ publication.finish()
receipt.record_venv_rebuild(False, "already in sync")
outcome = "ok"
return
@@ -402,6 +402,8 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu
if before_publish is not None:
undo = before_publish()
facts.record_state("venv", stamp, enabled, **result)
+ if hasattr(undo, "finish"):
+ undo.finish()
receipt.record_venv_rebuild(True)
except BaseException:
if undo is not None:
@@ -411,6 +413,9 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plu
LOG.exception("pm sync: publish undo failed; config may drift")
raise
outcome = "ok"
+ except BaseException as exc:
+ receipt.record_step("dependency-sync", False, f"{type(exc).__name__}: {exc}")
+ raise
finally:
receipt.finalize(outcome, 0 if outcome == "ok" else 1, token=token)
diff --git a/pm/lock.py b/pm/lock.py
index a5b28efc069..508919c04f0 100644
--- a/pm/lock.py
+++ b/pm/lock.py
@@ -56,11 +56,8 @@ def _read(path: Path) -> dict:
def _write(path: Path, data: dict) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_suffix(".tmp")
- tmp.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- os.replace(tmp, path)
-
+ from hermes_cli.runtime_state import _atomic_bytes
+ _atomic_bytes(path, (json.dumps(data, indent=2, sort_keys=True) + "\n").encode("utf-8"))
class Lockfile:
"""Read side of lock.json. Written only by `pm lock --bump` (cli)."""
diff --git a/pm/packages.py b/pm/packages.py
index 0c101fa12e7..1524c6e364f 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -386,6 +386,7 @@ class Venv(StatePackage):
members = enabled_member_dirs() if plugin_dirs is None else plugin_dirs
try:
generation.mkdir(parents=True)
+ (generation / ".lease-managed").touch()
create = subprocess.run(
[uv_bin, "venv", "--relocatable", "--python", sys.executable, str(candidate)],
env=env, capture_output=True, text=True, timeout=120,
@@ -408,6 +409,7 @@ class Venv(StatePackage):
except BaseException:
shutil.rmtree(generation, ignore_errors=True)
raise
+ (generation / ".lease-managed").touch()
return {"environment": candidate, "resolved_lock": resolved_lock}
diff --git a/pm/receipt.py b/pm/receipt.py
index 5f5ab3fed52..5b32020be7b 100644
--- a/pm/receipt.py
+++ b/pm/receipt.py
@@ -23,6 +23,15 @@ Two hazards of ContextVar state are handled explicitly:
to ``finalize(..., token=...)`` restores the OUTER receipt instead of
discarding it. The ambient no-token begin→finalize stays as-is (the
existing linear consumers — pm sync, the plugin-check cadence).
+
+Correlation: ``begin`` stamps the receipt with the ambient update
+correlation id (derived from the open update receipt's own identity in
+the same context). ``finalize`` files the finished receipt under that
+id in a per-context map, and the updater embeds only the entry carrying
+ITS OWN id (``last_for_update``), never latest.json — a sync that
+finished before the update began, a standalone sync, or one from a
+concurrent thread cannot be misattributed to it, and a nested update's
+sync never displaces the outer update's entry.
"""
from __future__ import annotations
@@ -45,6 +54,29 @@ _current: contextvars.ContextVar[Optional[dict[str, Any]]] = contextvars.Context
"pm_receipt_current", default=None
)
+# Completed sync receipts, keyed by the update correlation id they were
+# begun under (copy-on-written per finalize — copied contexts never share
+# a mutated dict). The updater embeds ONLY the entry carrying ITS id, so
+# a nested update's sync can never displace the outer update's, and a
+# standalone sync (update_id None) is never embedded. Bounded: one entry
+# per distinct update id seen in this context (nesting depth).
+_completed_by_update: contextvars.ContextVar[Optional[dict[str, dict[str, Any]]]] = (
+ contextvars.ContextVar("pm_receipt_completed_by_update", default=None)
+)
+
+
+def _ambient_update_id() -> Optional[str]:
+ """The update correlation id in force in this context, or None.
+
+ Lazy import: hermes_cli.update_receipt imports pm.receipt at embed
+ time, so this direction must stay function-scoped. Never raises."""
+ try:
+ from hermes_cli.update_receipt import current_correlation_id
+
+ return current_correlation_id()
+ except Exception:
+ return None
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@@ -62,11 +94,16 @@ def begin(kind: str) -> contextvars.Token:
"""Start recording a sync. ``kind``: 'sync' | 'update' | 'plugin-check'.
Returns the ContextVar token — pass it to ``finalize(token=...)`` when
this begin nests inside an outer begin in the same context, so the
- outer receipt survives the inner finalize."""
+ outer receipt survives the inner finalize.
+
+ The receipt is stamped with the ambient update correlation id (the
+ ``hermes update`` this sync belongs to), or None for a standalone
+ sync — the id is what makes the updater's embed selective."""
return _current.set(
{
"schema": 1,
"kind": kind,
+ "update_id": _ambient_update_id(),
"started_at": _utc_now_iso(),
"steps": [],
"venv_rebuild": None,
@@ -74,6 +111,8 @@ def begin(kind: str) -> contextvars.Token:
"feature_list": None,
"platform": None,
"outcome": None,
+ "warnings": [],
+ "refusal": None,
}
)
@@ -120,6 +159,28 @@ def record_plugin_checks(results: list) -> None:
)
+def record_warning(message: str) -> None:
+ """Record a warning surfaced to the user during this sync — a warning
+ that reached the operator's eyes must reach the receipt too."""
+ _record(
+ lambda r: r.update(
+ warnings=[*r.get("warnings", []),
+ {"message": str(message), "at": _utc_now_iso()}]
+ )
+ )
+
+
+def record_refusal(code: str, detail: str = "") -> None:
+ """Record WHY this sync refused to act (e.g. the lazy-install policy).
+ ``outcome`` stays whatever ``finalize`` is given (refusals finalize as
+ ``failed``/``refused``) — this names the refusal class."""
+ _record(
+ lambda r: r.__setitem__(
+ "refusal", {"code": str(code), "detail": str(detail), "at": _utc_now_iso()}
+ )
+ )
+
+
def snapshot() -> Optional[dict[str, Any]]:
"""The in-flight receipt data — for the updater to EMBED its sync
sections into its own receipt (one schema, one directory). A deep
@@ -148,6 +209,13 @@ def finalize(
current["outcome"] = outcome
current["exit_code"] = exit_code
current["finished_at"] = _utc_now_iso()
+ # Correlation: file this completion under its update id (copy-on-write
+ # — a deep-copied entry in a freshly copied map, never a shared dict).
+ update_id = current.get("update_id")
+ if update_id:
+ completed = dict(_completed_by_update.get() or {})
+ completed[update_id] = copy.deepcopy(current)
+ _completed_by_update.set(completed)
try:
path = _write_rotated(current)
except OSError:
@@ -155,6 +223,23 @@ def finalize(
return path
+def last_for_update(update_id: Optional[str], *, consume: bool = False) -> Optional[dict[str, Any]]:
+ """The last sync receipt completed in THIS context under ``update_id``
+ — the correlation surface for an invoking update's embed. A sync from
+ before this update, a standalone sync, or one from a concurrent
+ context cannot be returned; a nested update's sync is filed under the
+ nested id and never displaces the outer update's entry. Deep copy;
+ None when no matching completion exists."""
+ if not update_id:
+ return None
+ entries = dict(_completed_by_update.get() or {})
+ completed = entries.get(update_id)
+ if consume:
+ entries.pop(update_id, None)
+ _completed_by_update.set(entries)
+ return copy.deepcopy(completed) if completed is not None else None
+
+
def latest() -> Optional[dict[str, Any]]:
"""The newest receipt (any kind) — the reader surface for
``hermes pm status`` + the desktop. Pure read: never creates the
diff --git a/pm/store.py b/pm/store.py
index 8c08bd1a8d3..6ddb79ed6b3 100644
--- a/pm/store.py
+++ b/pm/store.py
@@ -303,47 +303,12 @@ class Store:
@contextmanager
def install_lock(self):
- """Single-flight advisory lock for all installs on this machine.
- Blocks until acquired: installs legitimately hold it for minutes
- (browser downloads), so the Windows rung polls LK_NBLCK instead of
- msvcrt's 10-second LK_LOCK ladder."""
+ """Serialize writers using the same advisory lock as runtime publication."""
+ from hermes_cli.runtime_state import _lock
self.root.mkdir(parents=True, exist_ok=True)
- lock_path = self.root / ".install.lock"
- handle = open(lock_path, "a+b")
+ fd = os.open(self.root / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)
try:
- if sys.platform.startswith("win"):
- import msvcrt
-
- handle.seek(0)
- waited = 0
- while True:
- try:
- msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
- break
- except OSError:
- if waited == 5:
- print("waiting for another hermes install to finish...")
- time.sleep(1)
- waited += 1
- else:
- import fcntl
-
- try:
- fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
- except OSError:
- print("waiting for another hermes install to finish...")
- fcntl.flock(handle, fcntl.LOCK_EX)
+ _lock(fd, wait=True)
yield
finally:
- try:
- if sys.platform.startswith("win"):
- import msvcrt
-
- handle.seek(0)
- msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
- else:
- import fcntl
-
- fcntl.flock(handle, fcntl.LOCK_UN)
- finally:
- handle.close()
+ os.close(fd)
diff --git a/tests/agent/test_compression_attempt_lifecycle.py b/tests/agent/test_compression_attempt_lifecycle.py
index 84879151fbb..aeefbf58b42 100644
--- a/tests/agent/test_compression_attempt_lifecycle.py
+++ b/tests/agent/test_compression_attempt_lifecycle.py
@@ -81,7 +81,7 @@ class TestWorkerTeardownOnCeiling:
# Continuous progress (the #97488 'last progress 0.0s ago'
# shape) so only the TOTAL ceiling expires; poll the poison
# fence like the production worker does between provider phases.
- deadline = time.monotonic() + 5.0
+ deadline = time.monotonic() + 15.0
while time.monotonic() < deadline:
if fence.is_cancelled:
break
@@ -100,8 +100,8 @@ class TestWorkerTeardownOnCeiling:
worker=cooperative_worker,
messages=original,
system_prompt_fallback="fallback",
- idle_timeout_seconds=0.1,
- total_ceiling_seconds=0.2,
+ idle_timeout_seconds=2.0,
+ total_ceiling_seconds=4.0,
fence=fence,
stall_fallback=False,
)
diff --git a/tests/agent/test_compression_stall_fallback_78981.py b/tests/agent/test_compression_stall_fallback_78981.py
index 398cbd4b2af..fdfe49450d4 100644
--- a/tests/agent/test_compression_stall_fallback_78981.py
+++ b/tests/agent/test_compression_stall_fallback_78981.py
@@ -90,7 +90,7 @@ class _StalledSummaryWorker:
fence.finish_commit()
-def _run(worker, *, chain, timeouts, messages, idle=0.05, ceiling=0.2):
+def _run(worker, *, chain, timeouts, messages, idle=2.0, ceiling=5.0):
with _patch_chain(chain):
return run_compress_context_with_progress_timeout(
worker=worker,
@@ -151,8 +151,8 @@ def test_retry_runs_on_a_host_published_fence():
worker=worker,
messages=original,
system_prompt_fallback="degraded-prompt",
- idle_timeout_seconds=0.05,
- total_ceiling_seconds=0.2,
+ idle_timeout_seconds=2.0,
+ total_ceiling_seconds=5.0,
new_fence=_new_fence,
)
finally:
@@ -181,8 +181,8 @@ def test_hard_interrupt_suppresses_the_fallback_attempt():
worker=worker,
messages=original,
system_prompt_fallback="degraded-prompt",
- idle_timeout_seconds=0.05,
- total_ceiling_seconds=0.2,
+ idle_timeout_seconds=2.0,
+ total_ceiling_seconds=5.0,
on_timeout=lambda *args: timeouts.append(args),
telemetry_agent=agent,
)
@@ -217,7 +217,7 @@ def test_fallback_that_also_stalls_degrades_after_one_attempt():
[{"role": "user", "content": "unused"}], stall_attempts=2
)
timeouts = []
- entry = dict(CHAIN_ENTRY, timeout=0.05)
+ entry = dict(CHAIN_ENTRY, timeout=2.0)
try:
msgs, prompt = _run(worker, chain=[entry], timeouts=timeouts, messages=original)
diff --git a/tests/compat/old_updater_surface.json b/tests/compat/old_updater_surface.json
index c097fec115b..b156aec1541 100644
--- a/tests/compat/old_updater_surface.json
+++ b/tests/compat/old_updater_surface.json
@@ -106,6 +106,9 @@
"hermes_cli.runtime_paths::selected_venv",
"hermes_cli.runtime_paths::site_packages",
"hermes_cli.runtime_paths::store_root",
+ "hermes_cli.runtime_state::_atomic_bytes",
+ "hermes_cli.runtime_state::_lock",
+ "hermes_cli.runtime_state::collect_generations",
"hermes_cli.sizefmt::format_bytes",
"hermes_cli.sqlite_runtime::probe_sqlite_runtime",
"hermes_cli.sqlite_safe_read::LiveConnectionError",
@@ -220,7 +223,9 @@
"pm.paths::repo_root",
"pm.paths::runtime_facts_path",
"pm.paths::store_root",
+ "pm.paths::writable_store_root",
"pm.registry::get_package",
+ "pm.store::Store",
"pm.store::extract",
"pm.store::tree_digest",
"pm.workspace::enabled_member_dirs",
@@ -251,6 +256,8 @@
"hermes_cli.macos_tcc_anchor::ensure_tcc_anchor",
"hermes_cli.memory_setup::_install_dependencies",
"hermes_cli.process_identity::REAPABLE_PURPOSES",
+ "hermes_cli.runtime_state::recover_publication",
+ "hermes_cli.runtime_state::runtime_lock",
"hermes_cli.update_channel::resolve_update_channel",
"hermes_cli.update_cmd_windows::_detect_venv_python_processes",
"hermes_cli.update_receipt::read_latest_receipt",
diff --git a/tests/cron/test_cron_workdir.py b/tests/cron/test_cron_workdir.py
index 39ee01ece2e..0c722ba87fd 100644
--- a/tests/cron/test_cron_workdir.py
+++ b/tests/cron/test_cron_workdir.py
@@ -159,6 +159,7 @@ class TestTickWorkdirPartition:
]
monkeypatch.setattr(sched, "get_due_jobs", lambda: jobs)
monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)
+ monkeypatch.setattr(sched, "_maybe_run_worktree_maintenance", lambda: None)
barrier = threading.Barrier(2, timeout=5)
calls: list[tuple[str, str]] = []
@@ -215,7 +216,7 @@ class TestRunJobTerminalCwd:
observed["terminal_cwd_during_run"] = os.environ.get(
"TERMINAL_CWD", "_UNSET_"
)
- return {"final_response": "done", "messages": []}
+ return {"final_response": "done", "messages": [{"role": "assistant", "content": "done"}]}
def get_activity_summary(self):
return {"seconds_since_activity": 0.0}
diff --git a/tests/cron/test_recurring_eagain_redispatch.py b/tests/cron/test_recurring_eagain_redispatch.py
index 4bf56a0eccc..da89a0ae8a0 100644
--- a/tests/cron/test_recurring_eagain_redispatch.py
+++ b/tests/cron/test_recurring_eagain_redispatch.py
@@ -47,6 +47,8 @@ def wedge_env(tmp_path, monkeypatch):
(hermes_home / "cron" / "output").mkdir()
(hermes_home / "scripts").mkdir()
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr("cron.scheduler._worktree_maintenance_repos", lambda: [])
import cron.jobs as jobs_mod
monkeypatch.setattr(jobs_mod, "HERMES_DIR", hermes_home)
@@ -80,6 +82,7 @@ class TestEAGAINRecurringRedispatches:
"""
import cron.scheduler as sched_mod
state = {"n": 0}
+ real_popen = sched_mod.subprocess.Popen
class _OkProc:
def __init__(self, argv, **kwargs):
@@ -95,6 +98,8 @@ class TestEAGAINRecurringRedispatches:
return 0
def fake_popen(argv, **kwargs):
+ if str(env["home"] / "scripts" / "probe.py") not in argv:
+ return real_popen(argv, **kwargs)
state["n"] += 1
if state["n"] == 1:
raise OSError(11, "Resource temporarily unavailable")
diff --git a/tests/cron/test_worktree_maintenance_isolation.py b/tests/cron/test_worktree_maintenance_isolation.py
new file mode 100644
index 00000000000..a2b545358c0
--- /dev/null
+++ b/tests/cron/test_worktree_maintenance_isolation.py
@@ -0,0 +1,49 @@
+"""Background worktree maintenance must not initialize the interactive CLI."""
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+
+def test_cold_worktree_maintenance_preserves_terminal_cwd(tmp_path):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ subprocess.run(["git", "init", "--initial-branch=main", str(repo)], check=True,
+ capture_output=True, timeout=15)
+ (repo / ".worktrees").mkdir()
+ workspace = tmp_path / "workspace"
+ workspace.mkdir()
+ env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[2]),
+ TERMINAL_CWD=str(workspace))
+ script = """
+import os
+import sys
+import threading
+from cron import scheduler
+from hermes_cli import worktree_ops
+
+assert 'cli' not in sys.modules, 'requires a cold CLI import'
+before = os.environ['TERMINAL_CWD']
+finished = threading.Event()
+errors = []
+prune = worktree_ops._prune_stale_worktrees
+
+def observed_prune(repo):
+ try:
+ prune(repo)
+ except Exception as exc:
+ errors.append(exc)
+ finally:
+ finished.set()
+
+worktree_ops._prune_stale_worktrees = observed_prune
+scheduler._worktree_maintenance_repos = lambda: [sys.argv[1]]
+scheduler._maybe_run_worktree_maintenance()
+assert finished.wait(30), 'maintenance did not finish'
+assert not errors, errors
+assert os.environ['TERMINAL_CWD'] == before
+"""
+ result = subprocess.run([sys.executable, "-c", script, str(repo)], env=env,
+ cwd=tmp_path, capture_output=True, text=True, timeout=45)
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tests/gateway/test_plugin_check_housekeeping.py b/tests/gateway/test_plugin_check_housekeeping.py
new file mode 100644
index 00000000000..c7c6fb6aed8
--- /dev/null
+++ b/tests/gateway/test_plugin_check_housekeeping.py
@@ -0,0 +1,32 @@
+"""Plugin checks are due-gated from startup, not delayed for an hour."""
+
+import threading
+
+from gateway import run
+from hermes_cli import plugins_cadence
+
+
+def test_plugin_cadence_runs_at_startup_and_each_housekeeping_tick(monkeypatch):
+ stop = threading.Event()
+ calls = []
+
+ def check(**kwargs):
+ calls.append(kwargs)
+ if len(calls) == 2:
+ stop.set()
+
+ # Stop an unfixed loop after its second sleep, without waiting for tick 60.
+ sleeps = []
+
+ def wait(timeout=None):
+ sleeps.append(timeout)
+ if len(sleeps) == 2:
+ stop.set()
+ return stop.is_set()
+
+ monkeypatch.setattr(stop, "wait", wait)
+ monkeypatch.setattr(plugins_cadence, "maybe_run_gateway_check", check)
+ monkeypatch.setattr(run, "_housekeeping_deferred_fts_retry", lambda: None)
+ monkeypatch.setattr(run, "_housekeeping_memory_trim", lambda: None)
+ run._start_gateway_housekeeping(stop)
+ assert len(calls) == 2
diff --git a/tests/gateway/test_send_multiple_images.py b/tests/gateway/test_send_multiple_images.py
index 2773b9f770e..9a21bfbe347 100644
--- a/tests/gateway/test_send_multiple_images.py
+++ b/tests/gateway/test_send_multiple_images.py
@@ -72,12 +72,13 @@ class _StubAdapter(BasePlatformAdapter):
class TestBaseDefaultLoop:
- def test_loops_per_image_by_default(self):
+ def test_loops_per_image_by_default(self, tmp_path):
+ local = tmp_path / "foo.png"
a = _StubAdapter()
images = [
("https://x.com/a.png", "alt 1"),
("https://x.com/b.png", "alt 2"),
- ("file:///tmp/foo.png", "local"),
+ (local.as_uri(), "local"),
("https://x.com/c.gif", ""),
]
_run(a.send_multiple_images("chat1", images))
@@ -85,7 +86,7 @@ class TestBaseDefaultLoop:
assert len(a.sent_images) == 2
assert len(a.sent_animations) == 1
assert len(a.sent_files) == 1
- assert a.sent_files[0][1] == "/tmp/foo.png"
+ assert a.sent_files[0][1] == str(local)
from plugins.platforms.telegram.adapter import TelegramAdapter # noqa: E402
diff --git a/tests/hermes_cli/conftest.py b/tests/hermes_cli/conftest.py
index 45eb1ebe431..50b31fd4705 100644
--- a/tests/hermes_cli/conftest.py
+++ b/tests/hermes_cli/conftest.py
@@ -1,7 +1,11 @@
-"""Fixtures shared across hermes_cli kanban tests."""
+"""Shared CLI fixtures; updater mutation boundaries are explicitly opt-in."""
from __future__ import annotations
+from types import SimpleNamespace
+from unittest.mock import patch
+import subprocess
+
import pytest
@@ -72,3 +76,78 @@ def patch_pm_uv_to_shutil_which():
with patch("pm.uv", side_effect=_fake_pm_uv):
yield
+
+
+def isolated_update_uv(patch_pm_uv_to_shutil_which):
+ """Make pm.uv follow shutil.which mocking in tests."""
+ yield
+
+
+def isolated_update_processes():
+ """Keep cmd_update's gateway auto-restart phase off this machine's gateways.
+
+ The restart phase used to swallow every exception at debug level, so these
+ end-to-end tests never noticed it touching real gateway discovery. Since
+ the phase is surfaced (#78574: an aborted restart now fails the update),
+ an unmocked ``find_gateway_pids`` on a box with a live gateway reaches the
+ conftest live-system guard and turns into a spurious ``sys.exit(1)``.
+ Discovery returning nothing makes the phase a clean no-op for every test
+ in this module (none of them assert on gateway restarts).
+ """
+ with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \
+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \
+ patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \
+ patch("hermes_cli.main._detect_venv_python_processes", return_value=[]), \
+ patch("hermes_cli.main._fleet_probe_expected_runtimes", return_value=False), \
+ patch("os.kill"), \
+ patch("pm.sync_venv"), \
+ patch(
+ "hermes_cli.update_inventory.collect_runtime_inventory",
+ return_value=SimpleNamespace(runtimes=[], to_dict=lambda: {}),
+ ), \
+ patch("hermes_cli.main._purge_stale_hermes_modules"), \
+ patch("hermes_cli.main._pause_windows_gateways_for_update", return_value=None), \
+ patch("hermes_cli.main._resume_windows_gateways_after_update"), \
+ patch(
+ "hermes_cli.main._install_hangup_protection",
+ return_value={
+ "prev_stdout": None, "prev_stderr": None,
+ "log_file": None, "installed": False,
+ },
+ ), \
+ patch("hermes_cli.main._finalize_update_output"), \
+ patch("hermes_cli.update_cmd._reload_config_modules"):
+ yield
+
+
+def isolated_update_checkout(monkeypatch, tmp_path):
+ """Keep the updater on an isolated checkout and intercept the web build's Popen path."""
+ import hermes_cli.main as cli_main
+ from hermes_cli import main_web_build
+
+ (tmp_path / ".git").mkdir(exist_ok=True)
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", tmp_path, raising=False)
+ noop_build = lambda *args, **kwargs: True # noqa: E731
+ monkeypatch.setattr(cli_main, "_build_web_ui", noop_build, raising=False)
+ monkeypatch.setattr(main_web_build, "_build_web_ui", noop_build, raising=False)
+ monkeypatch.setattr(
+ main_web_build, "_web_ui_build_needed", lambda *a, **k: False, raising=False
+ )
+ fake_npm = lambda *a, **k: subprocess.CompletedProcess( # noqa: E731
+ [], 0, stdout="", stderr=""
+ )
+ monkeypatch.setattr(
+ main_web_build, "_run_npm_install_deterministic", fake_npm, raising=False
+ )
+
+ # Tests that exercise ZIP fallback must override this tripwire explicitly.
+ def _no_zip_fallback(*args, **kwargs):
+ pytest.fail(
+ "test reached _update_via_zip — the git checkout path was not "
+ "isolated correctly (missing tmp .git or unexpected fallback)"
+ )
+
+ monkeypatch.setattr("hermes_cli.update_cmd._update_via_zip", _no_zip_fallback)
diff --git a/tests/hermes_cli/test_cadence_failure_receipt.py b/tests/hermes_cli/test_cadence_failure_receipt.py
new file mode 100644
index 00000000000..b11371fb2df
--- /dev/null
+++ b/tests/hermes_cli/test_cadence_failure_receipt.py
@@ -0,0 +1,19 @@
+"""Cadence failures retain the same warning shown to the operator."""
+from unittest.mock import Mock
+
+from hermes_cli.plugins_cadence import run_scheduled_check
+from pm import receipt
+
+
+def test_failed_check_records_warning_and_nonzero_exit(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ log = Mock()
+
+ def fail(_):
+ raise OSError("offline")
+
+ run_scheduled_check(run_checks_fn=fail, plugins_dir=tmp_path / "plugins", log=log)
+ saved = receipt.latest()
+ assert saved["outcome"] == "failed"
+ assert saved["exit_code"] != 0
+ assert saved["warnings"][0]["message"] == log.warning.call_args_list[0].args[0]
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index 2d00adaa02f..aca627cf02b 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -62,49 +62,9 @@ def mock_args():
# to control whether uv is "available" — this autouse fixture makes
# pm.uv delegate to the patched ``shutil.which`` so the existing test
# setup keeps working without per-test changes.
[email protected](autouse=True)
-def _patch_managed_uv(request, patch_pm_uv_to_shutil_which):
- """Make pm.uv follow shutil.which mocking in tests."""
- yield
-
-
[email protected](autouse=True)
-def _patch_gateway_discovery():
- """Keep cmd_update's gateway auto-restart phase off this machine's gateways.
-
- The restart phase used to swallow every exception at debug level, so these
- end-to-end tests never noticed it touching real gateway discovery. Since
- the phase is surfaced (#78574: an aborted restart now fails the update),
- an unmocked ``find_gateway_pids`` on a box with a live gateway reaches the
- conftest live-system guard and turns into a spurious ``sys.exit(1)``.
- Discovery returning nothing makes the phase a clean no-op for every test
- in this module (none of them assert on gateway restarts).
- """
- with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \
- patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \
- patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \
- patch("hermes_cli.main._detect_venv_python_processes", return_value=[]), \
- patch("hermes_cli.main._fleet_probe_expected_runtimes", return_value=False), \
- patch("os.kill"), \
- patch("pm.sync_venv"), \
- patch(
- "hermes_cli.update_inventory.collect_runtime_inventory",
- return_value=SimpleNamespace(runtimes=[], to_dict=lambda: {}),
- ), \
- patch("hermes_cli.main._purge_stale_hermes_modules"), \
- patch("hermes_cli.main._pause_windows_gateways_for_update", return_value=None), \
- patch("hermes_cli.main._resume_windows_gateways_after_update"), \
- patch(
- "hermes_cli.main._install_hangup_protection",
- return_value={
- "prev_stdout": None, "prev_stderr": None,
- "log_file": None, "installed": False,
- },
- ), \
- patch("hermes_cli.main._finalize_update_output"), \
- patch("hermes_cli.update_cmd._reload_config_modules"):
- yield
-
+pytestmark = pytest.mark.usefixtures(
+ "isolated_update_uv", "isolated_update_processes", "isolated_update_checkout",
+)
class TestCmdUpdateNpmLockfileCache:
@staticmethod
@@ -281,7 +241,9 @@ class TestCmdUpdateBranchFallback:
)
sync_mock.assert_called_once_with(
expected_git_cmd,
- PROJECT_ROOT,
+ # Resolved live: the module autouse fixture pins PROJECT_ROOT to
+ # tmp_path, so the imported constant would be stale here.
+ hm.PROJECT_ROOT,
assume_yes=False,
input_fn=None,
)
@@ -999,7 +961,7 @@ class TestCmdUpdateZipBranchRefusal:
"""
def test_zip_fallback_refuses_non_main_branch(self, capsys):
- from hermes_cli.update_cmd import _update_via_zip
+ from hermes_cli.update_cmd_zip import _update_via_zip
args = SimpleNamespace(branch="bb/gui")
with pytest.raises(SystemExit) as exc_info:
@@ -1089,7 +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("{}")
packaged_exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"
build_ok = subprocess.CompletedProcess([], 0, stdout="", stderr="")
@@ -1112,7 +1080,7 @@ class TestNodeRuntimeNpmResolution:
assert packaged.call_count == 2
desktop_build.assert_called_once_with(
[hm.sys.executable, "-m", "hermes_cli.main", "desktop", "--build-only"],
- cwd=PROJECT_ROOT,
+ cwd=hm.PROJECT_ROOT,
env=ANY,
)
@@ -1130,6 +1098,7 @@ class TestNodeRuntimeNpmResolution:
from hermes_cli import main as hm
from hermes_cli import update_cmd
+ from hermes_cli import update_cmd_zip
project_root = tmp_path / "hermes-agent"
(project_root / ".git").mkdir(parents=True)
@@ -1190,6 +1159,12 @@ class TestNodeRuntimeNpmResolution:
with (
patch("hermes_cli.config.load_config", return_value={}),
+ # This test legitimately exercises the real ZIP fallback; undo the
+ # module autouse fixture's fail-fast tripwire for exactly this run.
+ patch(
+ "hermes_cli.update_cmd._update_via_zip",
+ update_cmd_zip._update_via_zip,
+ ),
patch("subprocess.run", side_effect=fail_git_fetch),
patch("urllib.request.urlretrieve", side_effect=write_source_zip),
patch("pm.uv", return_value=("uv", dict(os.environ))),
diff --git a/tests/hermes_cli/test_diff_command.py b/tests/hermes_cli/test_diff_command.py
index 0652f0f77ba..24e5a7cc9d3 100644
--- a/tests/hermes_cli/test_diff_command.py
+++ b/tests/hermes_cli/test_diff_command.py
@@ -72,7 +72,8 @@ def repo(tmp_path, monkeypatch):
d = tmp_path / "repo"
d.mkdir()
_git(d, "init", "-q")
- (d / "main.py").write_text("print('hello')\n")
+ _git(d, "config", "core.autocrlf", "false")
+ (d / "main.py").write_bytes(b"print('hello')\n")
_git(d, "add", "-A")
_git(d, "commit", "-q", "-m", "init")
monkeypatch.setenv("TERMINAL_CWD", str(d))
diff --git a/tests/hermes_cli/test_doctor_update_provenance.py b/tests/hermes_cli/test_doctor_update_provenance.py
new file mode 100644
index 00000000000..d61c6a15980
--- /dev/null
+++ b/tests/hermes_cli/test_doctor_update_provenance.py
@@ -0,0 +1,124 @@
+"""Doctor's plugin update-provenance check (SPEC-05 warning surface).
+
+Bounded and READ-ONLY: the pure 2x2 plugin provenance reconciliation
+(hermes_cli.plugins_provenance — the actual authority) plus the
+manifest/sidecar update-url cross-check, surfaced as doctor rows. NO
+network (no fetch, no ls-remote — the cadence owns online checks), no
+mkdir — the plugins dir is computed, never created.
+"""
+
+from __future__ import annotations
+
+import json
+import pytest
+from pathlib import Path
+from unittest.mock import patch
+
+import hermes_cli.doctor_state as ds
+
+
+# --- plugin provenance rows ---------------------------------------------
+def _make_plugin(plugins: Path, name, *, sidecar=None, git=False, manifest_update_url=None):
+ pdir = plugins / name
+ pdir.mkdir(parents=True, exist_ok=True)
+ if sidecar is not None:
+ side = plugins / ".install-metadata.json"
+ rows = {}
+ if side.is_file():
+ rows = json.loads(side.read_text(encoding="utf-8-sig"))
+ rows[name] = sidecar
+ side.write_text(json.dumps(rows), encoding="utf-8")
+ if git:
+ (pdir / ".git").mkdir()
+ (pdir / ".git" / "config").write_text(
+ '[remote "origin"]\n\turl = https://example.com/x.git\n', encoding="utf-8"
+ )
+ if manifest_update_url is not None:
+ (pdir / "plugin.yaml").write_text(
+ f"name: {name}\nupdate_url: {manifest_update_url}\n", encoding="utf-8"
+ )
+ return pdir
+
+
+def test_no_plugins_dir_is_info(tmp_path):
+ rows = ds._plugin_provenance_rows(tmp_path / "missing")
+ assert rows == [("info", "No plugins directory yet (nothing to check provenance for)", "")]
+
+
+def test_drift_plugin_warns_with_reinstall_remedy(tmp_path):
+ _make_plugin(tmp_path, "drifty", sidecar={"source": "git", "update_url": "https://example.com/x"})
+ rows = ds._plugin_provenance_rows(tmp_path)
+ warns = [r for r in rows if r[0] == "warn"]
+ assert len(warns) == 1
+ assert "'drifty'" in warns[0][1] and "drift" in warns[0][1]
+ assert "reinstall" in str(warns[0])
+
+
+def test_manual_and_self_cloned_are_info(tmp_path):
+ _make_plugin(tmp_path, "dropped")
+ _make_plugin(tmp_path, "cloned", git=True)
+ rows = ds._plugin_provenance_rows(tmp_path)
+ assert any("manually" in text and kind == "info" for kind, text, _ in rows)
+ assert any("'cloned'" in text and "adopt" in detail for kind, text, detail in rows if kind == "info")
+ assert not any(kind == "warn" for kind, _, _ in rows)
+
+
+def test_git_plugin_in_good_standing_is_ok(tmp_path):
+ _make_plugin(
+ tmp_path, "fine",
+ sidecar={"source": "git", "update_url": "https://example.com/x"},
+ git=True, manifest_update_url="https://example.com/x",
+ )
+ rows = ds._plugin_provenance_rows(tmp_path)
+ assert not any(kind == "warn" for kind, _, _ in rows)
+ assert any(kind == "ok" and "good standing" in text for kind, text, _ in rows)
+
+
+def test_manifest_url_without_saved_url_warns(tmp_path):
+ _make_plugin(tmp_path, "sneaky", sidecar={"source": "git"}, git=True,
+ manifest_update_url="https://evil.example/x")
+ rows = ds._plugin_provenance_rows(tmp_path)
+ warns = [r for r in rows if r[0] == "warn"]
+ assert len(warns) == 1
+ assert "'sneaky'" in warns[0][1] and "no url was saved" in warns[0][1]
+
+
[email protected]("claimed", [None, "https://evil.example/x"])
+def test_manifest_url_mismatch_warns(tmp_path, claimed):
+ _make_plugin(tmp_path, "swapped", sidecar={"source": "git", "update_url": "https://example.com/x"},
+ git=True, manifest_update_url=claimed)
+ rows = ds._plugin_provenance_rows(tmp_path)
+ warns = [r for r in rows if r[0] == "warn"]
+ assert len(warns) == 1
+ assert "update_url mismatch" in str(warns[0])
+
+
+# --- doctor-side wiring -------------------------------------------------
+
+
+def test_check_is_read_only(tmp_path, monkeypatch, capsys):
+ """The check must not create or modify anything under HERMES_HOME —
+ no plugins/ mkdir; a missing dir is informational, not a warning."""
+ import hermes_constants as config_mod
+
+ monkeypatch.setattr(config_mod, "get_hermes_home", lambda: tmp_path, raising=False)
+ ds._check_update_provenance(False)
+ out = capsys.readouterr().out
+ assert "No plugins directory yet" in out
+ assert not (tmp_path / "plugins").exists()
+ assert "⚠" not in out
+
+
+def test_check_swallows_provenance_read_failure(tmp_path, monkeypatch, capsys):
+ import hermes_constants as config_mod
+
+ monkeypatch.setattr(config_mod, "get_hermes_home", lambda: tmp_path, raising=False)
+ (tmp_path / "plugins").mkdir()
+ with patch(
+ "hermes_cli.plugins_provenance.plugins_provenance",
+ side_effect=RuntimeError("disk gone"),
+ ):
+ ds._check_update_provenance(False)
+ out = capsys.readouterr().out
+ assert "could not be read" in out
+ assert "disk gone" in out # unreadable provenance must not look healthy
diff --git a/tests/hermes_cli/test_install_identity.py b/tests/hermes_cli/test_install_identity.py
index 218b5156cea..930acd338b3 100644
--- a/tests/hermes_cli/test_install_identity.py
+++ b/tests/hermes_cli/test_install_identity.py
@@ -3,6 +3,8 @@ import multiprocessing
from pathlib import Path
import time
+import pytest
+
from gateway.hosted_rooms import local_authority_gateway_id
import hermes_cli.install_identity as install_identity
from hermes_cli.install_identity import read_or_create_install_id
@@ -41,6 +43,31 @@ def test_concurrent_first_use_returns_one_persisted_identity(tmp_path):
assert (tmp_path / "install_id").read_text(encoding="utf-8").strip() == values[0]
[email protected]("transient_read_failure", [False, True])
+def test_existing_identity_survives_read_only_root_or_racing_publication(
+ tmp_path, monkeypatch, transient_read_failure,
+):
+ value = "a" * 32
+ (tmp_path / "install_id").write_text(value, encoding="utf-8")
+ original_read = Path.read_text
+ failed = False
+
+ def read(path, *args, **kwargs):
+ nonlocal failed
+ if transient_read_failure and not failed and path.name == "install_id":
+ failed = True
+ raise PermissionError("publication in progress")
+ return original_read(path, *args, **kwargs)
+
+ def refuse_lock(_root):
+ raise AssertionError("read-only identity lookup must not acquire a writable lock")
+
+ monkeypatch.setattr(Path, "read_text", read)
+ if not transient_read_failure:
+ monkeypatch.setattr(install_identity, "_install_id_file_lock", refuse_lock)
+ assert read_or_create_install_id(tmp_path) == value
+
+
def test_independent_first_callers_return_the_single_committed_identity(tmp_path, monkeypatch):
context = multiprocessing.get_context("spawn")
results = context.Queue()
diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.py
index 6053305ffd9..b05991a8fc3 100644
--- a/tests/hermes_cli/test_local_runtime.py
+++ b/tests/hermes_cli/test_local_runtime.py
@@ -74,6 +74,8 @@ class _StubHandler(BaseHTTPRequestHandler):
self._send(404, {})
def do_POST(self): # noqa: N802
+ length = int(self.headers.get("Content-Length", 0))
+ body = json.loads(self.rfile.read(length)) if length else {}
if self.path == "/v1/chat/completions":
self._send(200, {"choices": [{"message": {
"role": "assistant", "content": self.chat_answer}}]})
@@ -81,8 +83,6 @@ class _StubHandler(BaseHTTPRequestHandler):
self._send(200, {"success": True})
elif self.path == "/models/unload":
type(self).unloaded = getattr(type(self), "unloaded", [])
- length = int(self.headers.get("Content-Length", 0))
- body = json.loads(self.rfile.read(length)) if length else {}
type(self).unloaded.append(body.get("model"))
self._send(200, {"success": True})
else:
@@ -105,8 +105,12 @@ def stub_server():
server = HTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
- yield server.server_address[1], Handler
- server.shutdown()
+ try:
+ yield server.server_address[1], Handler
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
# ── detection (Rollout 1) ────────────────────────────────────
diff --git a/tests/hermes_cli/test_macos_tcc_anchor.py b/tests/hermes_cli/test_macos_tcc_anchor.py
index bbcbe84609d..267676397a7 100644
--- a/tests/hermes_cli/test_macos_tcc_anchor.py
+++ b/tests/hermes_cli/test_macos_tcc_anchor.py
@@ -5,9 +5,11 @@ bricked real Macs two ways: dynamically-linked builds died in dyld because
``@executable_path/../lib/libpython`` resolved into ``venv/lib/`` (#95425),
and alias symlinks to the copied interpreter lost the venv prefix (#95541).
-Linux tests use fake checkout/uv-store layouts with ``platform.system``
-monkeypatched. The real-interpreter E2E is ``platforms("macos")`` so it runs on
-the existing macOS CI job, not against one-byte fixtures.
+macOS behaviour is tested on real macOS (``platforms("macos")``) using fake
+checkout/uv-store layouts; the non-macOS no-op branch is tested on real
+non-macOS hosts (``platforms("not macos")`` / ``platforms("linux")``). The
+real-interpreter E2E is ``platforms("macos")`` so it runs on the existing
+macOS CI job, not against one-byte fixtures.
"""
from __future__ import annotations
@@ -28,14 +30,6 @@ from hermes_constants import venv_python_path
from hermes_cli import doctor_platform
-def _darwin(monkeypatch):
- monkeypatch.setattr(tcc.platform, "system", lambda: "Darwin")
-
-
-def _linux(monkeypatch):
- monkeypatch.setattr(tcc.platform, "system", lambda: "Linux")
-
-
def _build_store(tmp_path, version: str = "3.11.15", *, with_libpython: bool = False) -> Path:
store = (
tmp_path
@@ -128,18 +122,25 @@ class TestUvStoreDetection:
assert not tcc._is_uv_macos_store(path)
-class TestEnsureTccAnchor:
- def test_noop_on_non_macos(self, tmp_path, monkeypatch):
- _linux(monkeypatch)
- root = _build_checkout(tmp_path, store_bin=_build_store(tmp_path))
- venv_py = venv_python_path(root / ".venv")
[email protected]("not macos")
+class TestEnsureTccAnchorNonMacos:
+ def test_noop_on_non_macos(self, tmp_path):
+ # The host check gates before any filesystem access, so a plain
+ # regular-file interpreter fixture is enough: ensure must return None
+ # and leave the file byte-identical. Assert the fixture's actual path
+ # (venv_python_path is host-shaped: Scripts/python.exe on Windows).
+ venv_py = tmp_path / "checkout" / ".venv" / "bin" / "python"
+ venv_py.parent.mkdir(parents=True)
+ venv_py.write_bytes(b"#!fake interpreter")
+ venv_py.chmod(0o755)
- assert tcc.ensure_tcc_anchor(root) is None
- assert venv_py.is_symlink()
+ assert tcc.ensure_tcc_anchor(tmp_path / "checkout") is None
+ assert venv_py.read_bytes() == b"#!fake interpreter"
+
+class TestEnsureTccAnchor:
def test_install_signs_the_anchor_copy(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
signed = []
import hermes_cli.runtime_repair as runtime_repair
@@ -155,8 +156,7 @@ class TestEnsureTccAnchor:
assert len(signed) == 1
assert signed[0].parent == anchored.parent
- def test_anchors_repair_generation_interpreter(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_anchors_repair_generation_interpreter(self, tmp_path):
store = (
tmp_path
/ "checkout"
@@ -180,8 +180,7 @@ class TestEnsureTccAnchor:
assert not venv_py.is_symlink()
assert venv_py.read_bytes() == store_py.read_bytes()
- def test_anchors_uv_managed_interpreter(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_anchors_uv_managed_interpreter(self, tmp_path):
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin)
venv_py = venv_python_path(root / ".venv")
@@ -201,8 +200,7 @@ class TestEnsureTccAnchor:
assert alias.is_file() and not alias.is_symlink()
assert alias.read_bytes() == venv_py.read_bytes()
- def test_idempotent(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_idempotent(self, tmp_path):
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin, anchored=True)
venv_py = venv_python_path(root / ".venv")
@@ -215,8 +213,7 @@ class TestEnsureTccAnchor:
assert venv_py.is_file() and not venv_py.is_symlink()
assert marker.read_text(encoding="utf-8") == before
- def test_repairs_alias_symlinks_left_by_predecessor(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_repairs_alias_symlinks_left_by_predecessor(self, tmp_path):
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin, anchored=True)
venv_bin = root / ".venv" / "bin"
@@ -230,8 +227,7 @@ class TestEnsureTccAnchor:
assert alias.is_file() and not alias.is_symlink()
assert alias.read_bytes() == venv_py.read_bytes()
- def test_reanchors_after_patch_bump(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_reanchors_after_patch_bump(self, tmp_path):
old_bin = _build_store(tmp_path, version="3.11.15")
root = _build_checkout(tmp_path, store_bin=old_bin, anchored=True)
venv_py = venv_python_path(root / ".venv")
@@ -253,20 +249,17 @@ class TestEnsureTccAnchor:
assert alias.is_file() and not alias.is_symlink()
assert alias.read_bytes() == new_py.read_bytes()
- def test_skips_homebrew_interpreter(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_skips_homebrew_interpreter(self, tmp_path):
root = _build_checkout(tmp_path, homebrew=True)
venv_py = venv_python_path(root / ".venv")
assert tcc.ensure_tcc_anchor(root) is None
assert venv_py.is_symlink()
- def test_no_venv_returns_none(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_no_venv_returns_none(self, tmp_path):
assert tcc.ensure_tcc_anchor(tmp_path / "missing") is None
- def test_preserves_stdlib_source_home(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_preserves_stdlib_source_home(self, tmp_path):
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin)
cfg = root / ".venv" / "pyvenv.cfg"
@@ -275,8 +268,7 @@ class TestEnsureTccAnchor:
assert f"home = {store_bin}" in cfg.read_text(encoding="utf-8")
- def test_provisions_libpython_as_hardlink_when_present(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_provisions_libpython_as_hardlink_when_present(self, tmp_path):
store_bin = _build_store(tmp_path, with_libpython=True)
root = _build_checkout(tmp_path, store_bin=store_bin)
src_dylib = store_bin.parent / "lib" / "libpython3.11.dylib"
@@ -289,7 +281,6 @@ class TestEnsureTccAnchor:
assert dst.stat().st_ino == src_dylib.stat().st_ino
def test_boot_gate_refusal_leaves_venv_untouched(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin)
venv_py = venv_python_path(root / ".venv")
@@ -304,7 +295,6 @@ class TestEnsureTccAnchor:
# written: a symlink alias to the anchored copy is the #95541 crash
# shape, and a marker would make doctor report "active" over it.
# The next ensure retries the whole install.
- _darwin(monkeypatch)
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin)
venv_py = venv_python_path(root / ".venv")
@@ -322,7 +312,6 @@ class TestEnsureTccAnchor:
# Recovery: with alias copies working again the retry completes.
monkeypatch.undo()
- monkeypatch.setattr(tcc.platform, "system", lambda: "Darwin")
assert tcc.ensure_tcc_anchor(root) is not None
assert tcc.tcc_anchor_state(root)[0] == "active"
@@ -369,7 +358,6 @@ class TestEnsureTccAnchor:
assert f"/{_RUNTIME_DIR_NAME}/python/" in tcc._STORE_ROOT_MARKERS
class TestBootGate:
"""Direct branch coverage for _passes_boot_gate.
@@ -457,14 +445,23 @@ class TestBootGate:
@pytest.mark.platforms("linux")
+class TestTccAnchorStateNonMacos:
+ def test_state_skip_on_linux(self, tmp_path):
+ store_bin = _build_store(tmp_path)
+ root = _build_checkout(tmp_path, store_bin=store_bin)
+ status, detail = tcc.tcc_anchor_state(root)
+ assert status == "skip"
+ assert detail == "not macOS"
+
+
class TestTccAnchorState:
- def test_state_active_through_unpatched_home_symlink(self, tmp_path, monkeypatch):
+ def test_state_active_through_unpatched_home_symlink(self, tmp_path):
# The managed-runtime layout symlinks cpython-3.11-macos-* →
# cpython-3.11.15-macos-*, so pyvenv.cfg home and the marker record
# different spellings of the same binary. State must resolve both
# sides before comparing, or a fresh install reports stale
# (review: kokhlo on #95605, hit on a live venv).
- _darwin(monkeypatch)
patched = _build_store(tmp_path, version="3.11.15")
versionless = patched.parent.parent / "cpython-3.11-macos-aarch64-none"
os.symlink(patched.parent, versionless)
@@ -481,8 +478,7 @@ class TestTccAnchorState:
status, _ = tcc.tcc_anchor_state(root)
assert status == "active"
- def test_state_missing_then_active(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_state_missing_then_active(self, tmp_path):
store_bin = _build_store(tmp_path)
root = _build_checkout(tmp_path, store_bin=store_bin)
@@ -495,23 +491,13 @@ class TestTccAnchorState:
status, detail = tcc.tcc_anchor_state(root)
assert status == "active"
- def test_state_skip_on_linux(self, tmp_path, monkeypatch):
- _linux(monkeypatch)
- store_bin = _build_store(tmp_path)
- root = _build_checkout(tmp_path, store_bin=store_bin)
- status, detail = tcc.tcc_anchor_state(root)
- assert status == "skip"
- assert detail == "not macOS"
-
- def test_state_skip_for_homebrew(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_state_skip_for_homebrew(self, tmp_path):
root = _build_checkout(tmp_path, homebrew=True)
status, detail = tcc.tcc_anchor_state(root)
assert status == "skip"
assert "not uv-managed" in detail
- def test_state_stale_after_patch_bump(self, tmp_path, monkeypatch):
- _darwin(monkeypatch)
+ def test_state_stale_after_patch_bump(self, tmp_path):
old_bin = _build_store(tmp_path, version="3.11.15")
root = _build_checkout(tmp_path, store_bin=old_bin, anchored=True)
new_bin = _build_store(tmp_path, version="3.11.16")
@@ -527,7 +513,6 @@ class TestTccAnchorState:
assert status == "active"
class TestDoctorCheck:
def test_missing_warns_without_fix(self, monkeypatch, capsys):
monkeypatch.setattr(
diff --git a/tests/hermes_cli/test_model_alias_credentials_83612.py b/tests/hermes_cli/test_model_alias_credentials_83612.py
index e39eaec71ee..0cf00103414 100644
--- a/tests/hermes_cli/test_model_alias_credentials_83612.py
+++ b/tests/hermes_cli/test_model_alias_credentials_83612.py
@@ -721,130 +721,3 @@ class TestOneshotPassesAliasCredential:
assert captured["explicit_base_url"] == ALIAS_HOST
assert captured["explicit_api_key"] == "sk-theta-ALIAS"
-
-
-class TestNoProductionCodeMutatesTheAliasCacheInPlace:
- """The profile-isolation property depends on an unwritten rule.
-
- ``_ensure_direct_aliases`` keeps a copy of what it loaded and treats any
- divergence as a caller's data, not its own stale cache — that is what lets
- tests seed ``DIRECT_ALIASES`` in place without the loader wiping them
- (#16767). The cost is that a *production* in-place mutation would pin the
- cache: contents would never again match the copy, so the config-identity
- check that reloads on a profile switch would stop being consulted, and one
- profile's aliases and credentials would be served to the next.
-
- No production code mutates it today — only the loader itself, and every
- other reference is a read. This pins that, because the failure mode is
- silent: nothing raises, nothing logs, and the leak only shows up as one
- profile answering with another profile's key.
- """
-
- #: The only place allowed to write the cache.
- OWNER = ("hermes_cli/model_switch.py", "_ensure_direct_aliases")
-
- MUTATORS = frozenset(
- {"update", "clear", "pop", "popitem", "setdefault", "__setitem__"}
- )
-
- @staticmethod
- def _production_sources():
- import pathlib
-
- repo = pathlib.Path(__file__).resolve().parents[2]
- skip = {".git", "node_modules", "tests", "build", "dist", ".venv"}
- for path in repo.rglob("*.py"):
- if any(part in skip for part in path.parts):
- continue
- yield path, path.relative_to(repo).as_posix()
-
- @classmethod
- def _violations(cls, source: str, rel: str):
- """Yield (function, description) for each in-place write."""
- import ast
-
- tree = ast.parse(source)
- enclosing = {}
- for node in ast.walk(tree):
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- for child in ast.walk(node):
- enclosing[id(child)] = node.name
-
- def _names(node):
- """DIRECT_ALIASES, whether bare or attribute-qualified."""
- if isinstance(node, ast.Name):
- return node.id
- if isinstance(node, ast.Attribute):
- return node.attr
- return None
-
- for node in ast.walk(tree):
- where = enclosing.get(id(node), "<module>")
- if (rel, where) == cls.OWNER:
- continue
- if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
- if (
- _names(node.func.value) == "DIRECT_ALIASES"
- and node.func.attr in cls.MUTATORS
- ):
- yield where, f"DIRECT_ALIASES.{node.func.attr}()"
- if isinstance(node, (ast.Assign, ast.AugAssign)):
- targets = node.targets if isinstance(node, ast.Assign) else [node.target]
- for target in targets:
- if (
- isinstance(target, ast.Subscript)
- and _names(target.value) == "DIRECT_ALIASES"
- ):
- yield where, "DIRECT_ALIASES[...] = ..."
-
- def test_only_the_loader_writes_the_cache(self):
- found = []
- for path, rel in self._production_sources():
- try:
- source = path.read_text(encoding="utf-8")
- except (OSError, UnicodeDecodeError):
- continue
- if "DIRECT_ALIASES" not in source:
- continue
- try:
- found.extend(
- f"{rel}:{where}: {what}"
- for where, what in self._violations(source, rel)
- )
- except SyntaxError:
- continue
-
- assert not found, (
- "In-place writes to DIRECT_ALIASES outside "
- f"{self.OWNER[0]}::{self.OWNER[1]} pin the alias cache and break "
- "per-profile isolation:\n " + "\n ".join(found)
- )
-
- def test_the_scan_actually_detects_a_violation(self):
- """Negative control — an always-passing scanner would prove nothing."""
- offending = (
- "from hermes_cli.model_switch import DIRECT_ALIASES\n"
- "def warm():\n"
- " DIRECT_ALIASES.update({'x': 1})\n"
- " DIRECT_ALIASES['y'] = 2\n"
- )
-
- hits = list(self._violations(offending, "some/other_module.py"))
-
- assert {what for _, what in hits} == {
- "DIRECT_ALIASES.update()",
- "DIRECT_ALIASES[...] = ...",
- }
- assert all(where == "warm" for where, _ in hits)
-
- def test_the_owner_itself_is_exempt(self):
- """...and an exemption that swallowed everything would prove nothing."""
- import pathlib
-
- repo = pathlib.Path(__file__).resolve().parents[2]
- source = (repo / self.OWNER[0]).read_text(encoding="utf-8")
-
- assert list(self._violations(source, self.OWNER[0])) == []
- # The loader really does write in place, so the exemption is load-bearing.
- assert "DIRECT_ALIASES.clear()" in source
- assert "DIRECT_ALIASES.update(loaded)" in source
diff --git a/tests/hermes_cli/test_plugins_admission_setter.py b/tests/hermes_cli/test_plugins_admission_setter.py
index 2b035227d90..168e3bb4468 100644
--- a/tests/hermes_cli/test_plugins_admission_setter.py
+++ b/tests/hermes_cli/test_plugins_admission_setter.py
@@ -60,7 +60,8 @@ def sync_calls(monkeypatch):
calls = []
def _sync(extras=None, *, explicit=False, plugin_dirs=None, before_publish=None):
- calls.append(list(plugin_dirs or []))
+ members = plugin_dirs() if callable(plugin_dirs) else plugin_dirs
+ calls.append(list(members or []))
if before_publish is not None:
before_publish() # same contract: config commits under the sync
diff --git a/tests/hermes_cli/test_update_inventory.py b/tests/hermes_cli/test_update_inventory.py
index 92302d5311f..156a79b6601 100644
--- a/tests/hermes_cli/test_update_inventory.py
+++ b/tests/hermes_cli/test_update_inventory.py
@@ -160,7 +160,7 @@ class TestReceiptIntegration:
home = tmp_path / "receipt_home"
home.mkdir()
monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: home, raising=False)
- ur._current = None
+ ur._current.set(None)
ur.begin_update_receipt()
plan = ui.collect_runtime_inventory()
ui.record_plan_in_receipt(plan)
@@ -172,5 +172,5 @@ class TestReceiptIntegration:
def test_noop_without_active_receipt(self, fleet):
import hermes_cli.update_receipt as ur
- ur._current = None
+ ur._current.set(None)
ui.record_plan_in_receipt(ui.collect_runtime_inventory()) # must not raise
diff --git a/tests/hermes_cli/test_update_receipt.py b/tests/hermes_cli/test_update_receipt.py
index f2a3cd5fa70..3e65d9ed809 100644
--- a/tests/hermes_cli/test_update_receipt.py
+++ b/tests/hermes_cli/test_update_receipt.py
@@ -29,9 +29,9 @@ def receipt_home(tmp_path, monkeypatch):
"hermes_cli.config.get_hermes_home", lambda: home, raising=False
)
# ensure no receipt bleeds between tests
- ur._current = None
+ ur._current.set(None)
yield home
- ur._current = None
+ ur._current.set(None)
def _finalize(outcome="success", fleet=None):
@@ -132,11 +132,33 @@ class TestReceiptLifecycle:
ur.record_gateway_restart(restarted_services=[])
assert _finalize("success") is None
+ def test_copied_context_records_do_not_leak_into_the_parent(self, receipt_home):
+ """Invariant: a copied context (copy_context / asyncio.to_thread)
+ inherits the SAME receipt object — record_* must copy-on-write, so
+ a child's records land in the child's copy only and the parent's
+ receipt is untouched (mirrors pm.receipt's isolation rule)."""
+ import contextvars
+
+ ur.begin_update_receipt()
+ ur.record_step("parent", True)
+ before = json.loads(json.dumps(ur._current.get().data))
+
+ def child():
+ ur.record_step("child", False)
+ return [s["name"] for s in ur._current.get().data["steps"]]
+
+ child_steps = contextvars.copy_context().run(child)
+ assert child_steps == ["parent", "child"] # child saw ambient receipt...
+ current = ur._current.get().data
+ assert [s["name"] for s in current["steps"]] == ["parent"] # ...in ITS copy only
+ assert current == before
+
def test_finalize_clears_current(self, receipt_home):
ur.begin_update_receipt()
- assert ur._current is not None
+ assert ur._current.get() is not None
_finalize("success")
- assert ur._current is None
+ assert ur._current.get() is None
+ assert ur.current_correlation_id() is None
def test_pruning_keeps_recent(self, receipt_home, monkeypatch):
monkeypatch.setattr(ur, "_RECEIPT_KEEP", 3)
@@ -179,7 +201,7 @@ class TestCommandBoundaryFinalization:
assert payload["exit_code"] == 2
assert payload["stop_reason"] == "sys.exit(2)"
assert payload["finished_at"] is not None
- assert ur._current is None
+ assert ur._current.get() is None
def test_pending_receipt_persisted_on_exit_1_failure(self, receipt_home):
ur.begin_update_receipt()
@@ -259,7 +281,7 @@ class TestCommandBoundaryFinalization:
assert latest["exit_code"] == 2
assert latest["stop_reason"] == "sys.exit(2)"
assert latest["steps"][0]["name"] == "windows_preflight"
- assert ur._current is None
+ assert ur._current.get() is None
# exactly-once: exactly one receipt file
directory = receipt_home / "logs" / "update_receipts"
assert len(list(directory.glob("update_*.json"))) == 1
diff --git a/tests/hermes_cli/test_update_receipt_pm_embed.py b/tests/hermes_cli/test_update_receipt_pm_embed.py
index bfec095818b..83ba188b50a 100644
--- a/tests/hermes_cli/test_update_receipt_pm_embed.py
+++ b/tests/hermes_cli/test_update_receipt_pm_embed.py
@@ -1,14 +1,15 @@
-"""Tests: update receipts embed the pm sync sections (the settled contract).
+"""Tests: update receipts embed ONLY their own pm sync sections.
-finalize_update_receipt folds the newest pm sync receipt's
-venv_rebuild / plugin_bisect / feature_list into the update receipt
-(pm_*-prefixed), so one latest.json carries the whole story.
+The updater embeds the sync receipt that carries ITS correlation id —
+read from pm.receipt's per-context completions, never from latest.json.
+A sync that finished before the update began, or one running in a
+concurrent thread, must never be misattributed to the invoking update.
"""
from __future__ import annotations
import json
-from pathlib import Path
+import threading
import pytest
@@ -27,7 +28,24 @@ def homed(tmp_path, monkeypatch):
return tmp_path
-def _seed_sync_receipt(homed, **sections):
[email protected](autouse=True)
+def _isolated_receipt_state():
+ """No leaked in-flight receipts, completion maps, or correlation
+ between tests."""
+ import pm.receipt as pm_receipt_mod
+
+ pm_receipt_mod._current.set(None)
+ pm_receipt_mod._completed_by_update.set(None)
+ ur._current.set(None)
+ yield
+ pm_receipt_mod._current.set(None)
+ pm_receipt_mod._completed_by_update.set(None)
+ ur._current.set(None)
+
+
+def _sync_under_update(**sections):
+ """A pm sync that runs WHILE the update receipt is open — the real
+ in-process update flow (sync_venv / bisect rebuilds)."""
import pm.receipt as pm_receipt_mod
pm_receipt_mod.begin("sync")
@@ -35,16 +53,20 @@ def _seed_sync_receipt(homed, **sections):
pm_receipt_mod.record_venv_rebuild(**sections.pop("venv_rebuild"))
if "bisect" in sections:
pm_receipt_mod.record_bisect(sections.pop("bisect"))
+ if "warnings" in sections:
+ for message in sections.pop("warnings"):
+ pm_receipt_mod.record_warning(message)
+ if "refusal" in sections:
+ pm_receipt_mod.record_refusal(*sections.pop("refusal"))
pm_receipt_mod.finalize("ok")
def test_update_receipt_embeds_pm_sections(homed):
- _seed_sync_receipt(
- homed,
+ ur.begin_update_receipt()
+ _sync_under_update(
venv_rebuild={"ok": True, "reason": ""},
bisect=[{"plugin": "bad", "action": "disabled", "reason": "conflict"}],
)
- ur.begin_update_receipt()
ur.record_step("git-pull", True)
path = ur.finalize_update_receipt("success")
@@ -53,6 +75,7 @@ def test_update_receipt_embeds_pm_sections(homed):
assert data["pm_venv_rebuild"] == {"ok": True, "reason": ""}
assert data["pm_plugin_bisect"][0]["plugin"] == "bad"
assert data["pm_sync_outcome"] == "ok"
+ assert data["update_id"]
def test_update_receipt_without_sync_embeds_nothing(homed):
@@ -63,13 +86,154 @@ def test_update_receipt_without_sync_embeds_nothing(homed):
assert data["outcome"] == "success"
+def test_stale_sync_from_before_the_update_is_never_embedded(homed):
+ """The audit defect: an old sync receipt on disk (latest.json's newest)
+ must not ride along on an update that caused no sync of its own."""
+ import pm.receipt as pm_receipt_mod
+
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(True, "stale run")
+ pm_receipt_mod.finalize("ok")
+ assert pm_receipt_mod.latest()["venv_rebuild"]["reason"] == "stale run"
+
+ ur.begin_update_receipt()
+ path = ur.finalize_update_receipt("success")
+
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert "pm_venv_rebuild" not in data
+ assert "pm_sync_outcome" not in data
+
+
+def test_concurrent_thread_sync_is_never_embedded(homed):
+ """A sync finalizing in another thread (cadence plugin-check, parallel
+ ensure) finalizes into ITS context — the invoking update must not
+ embed it, even though it hit latest.json first."""
+ import pm.receipt as pm_receipt_mod
+
+ ur.begin_update_receipt()
+ seen: dict = {}
+
+ def concurrent_sync():
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(True, "not my update")
+ seen["path"] = pm_receipt_mod.finalize("ok")
+
+ t = threading.Thread(target=concurrent_sync)
+ t.start()
+ t.join()
+ assert seen["path"] is not None # it did write a receipt...
+
+ path = ur.finalize_update_receipt("success")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert "pm_venv_rebuild" not in data # ...but not into THIS update
+
+
+def test_nested_update_ids_do_not_cross_embed(homed):
+ """The steering-required scenario: outer update → outer sync → nested
+ update → nested sync → finalize inner → finalize outer. BOTH update
+ receipts finalize with a path, and each embeds ONLY its own sync —
+ the nested sync never displaces the outer update's."""
+ import pm.receipt as pm_receipt_mod
+
+ ur.begin_update_receipt()
+ outer_id = ur.current_correlation_id()
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(True, "outer rebuild")
+ pm_receipt_mod.finalize("ok")
+
+ ur.begin_update_receipt() # nested update — new id, outer preserved behind the token
+ inner_id = ur.current_correlation_id()
+ assert inner_id != outer_id
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(True, "inner rebuild")
+ pm_receipt_mod.finalize("ok")
+
+ inner_path = ur.finalize_update_receipt("success")
+ assert inner_path is not None
+ assert json.loads(inner_path.read_text(encoding="utf-8"))["pm_venv_rebuild"]["reason"] == "inner rebuild"
+
+ # outer finalize: the outer sync is STILL its own completion — the
+ # nested update's finalize restored the outer receipt and must not
+ # have dropped it or let the inner sync ride along.
+ outer_path = ur.finalize_update_receipt("partial")
+ assert outer_path is not None
+ outer_data = json.loads(outer_path.read_text(encoding="utf-8"))
+ assert outer_data["update_id"] == outer_id
+ assert outer_data["pm_venv_rebuild"]["reason"] == "outer rebuild"
+ assert "inner rebuild" not in json.dumps(outer_data)
+
+ # outermost finalize popped the last receipt: no correlation remains
+ assert ur.current_correlation_id() is None
+
+
+def test_both_nested_receipts_still_read_correctly_after_all_finalizations(homed):
+ """Invariant: inner and outer receipts have UNIQUE file names (same
+ process, possibly the same second) and each exact path still reads its
+ own story AFTER every finalize — no overwrite, no cross-contamination,
+ including the latest.json pointer (outer finished last)."""
+ import pm.receipt as pm_receipt_mod
+
+ ur.begin_update_receipt()
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(True, "outer rebuild")
+ pm_receipt_mod.finalize("ok")
+
+ ur.begin_update_receipt()
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(True, "inner rebuild")
+ pm_receipt_mod.finalize("ok")
+
+ inner_path = ur.finalize_update_receipt("success")
+ outer_path = ur.finalize_update_receipt("success")
+
+ assert inner_path != outer_path
+ assert inner_path.is_file() and outer_path.is_file()
+ inner_data = json.loads(inner_path.read_text(encoding="utf-8"))
+ outer_data = json.loads(outer_path.read_text(encoding="utf-8"))
+ assert inner_data["pm_venv_rebuild"]["reason"] == "inner rebuild"
+ assert outer_data["pm_venv_rebuild"]["reason"] == "outer rebuild"
+ # latest.json points at the LAST finalization (the outer run)
+ latest = json.loads((homed / "logs" / "update_receipts" / "latest.json").read_text(encoding="utf-8"))
+ assert latest["update_id"] == outer_data["update_id"]
+ assert latest["pm_venv_rebuild"]["reason"] == "outer rebuild"
+
+
+def test_sync_after_nested_update_finalizes_embeds_into_outer(homed):
+ """Continuing the outer update after the nested one closed: a sync
+ begun under the restored outer id embeds into the outer receipt."""
+ import pm.receipt as pm_receipt_mod
+
+ ur.begin_update_receipt()
+ ur.begin_update_receipt()
+ ur.finalize_update_receipt("success")
+ pm_receipt_mod.begin("sync")
+ pm_receipt_mod.record_venv_rebuild(False, "already in sync")
+ pm_receipt_mod.finalize("ok")
+ path = ur.finalize_update_receipt("success")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert data["pm_venv_rebuild"] == {"ok": False, "reason": "already in sync"}
+
+
+def test_pm_warnings_and_refusal_embed(homed):
+ ur.begin_update_receipt()
+ _sync_under_update(
+ warnings=["shim quarantine skipped: file locked"],
+ refusal=("lazy-install", "extras outside the frozen feature set"),
+ )
+ path = ur.finalize_update_receipt("success")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert data["pm_warnings"][0]["message"] == "shim quarantine skipped: file locked"
+ assert data["pm_refusal"]["code"] == "lazy-install"
+ assert data["pm_refusal"]["detail"] == "extras outside the frozen feature set"
+
+
def test_embed_failure_never_breaks_the_update_receipt(homed, monkeypatch):
def boom():
raise RuntimeError("pm import exploded")
import pm.receipt as pm_receipt_mod
- monkeypatch.setattr(pm_receipt_mod, "latest", boom)
+ monkeypatch.setattr(pm_receipt_mod, "last_for_update", boom)
ur.begin_update_receipt()
path = ur.finalize_update_receipt("success")
assert path is not None # receipt written despite the embed failure
diff --git a/tests/hermes_cli/test_update_receipt_scope.py b/tests/hermes_cli/test_update_receipt_scope.py
new file mode 100644
index 00000000000..16b538135b6
--- /dev/null
+++ b/tests/hermes_cli/test_update_receipt_scope.py
@@ -0,0 +1,34 @@
+"""Nested command boundaries and copied contexts cannot close an outer receipt."""
+import contextvars
+
+from hermes_cli import update_receipt as receipts
+
+
+def test_command_scope_retains_outer_receipt(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(receipts, "_code_identity", lambda **kw: {})
+ receipts.begin_update_receipt()
+ outer = receipts.current_correlation_id()
+ try:
+ with receipts.update_receipt_scope():
+ receipts.begin_update_receipt()
+ receipts.finalize_update_receipt("success")
+ assert receipts.finalize_pending_update_receipt(0) is None
+ assert receipts.current_correlation_id() == outer
+ assert receipts._current.get().data["outcome"] == "running"
+ finally:
+ receipts.finalize_update_receipt("success")
+
+
+def test_copied_context_finalize_does_not_mutate_parent(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(receipts, "_code_identity", lambda **kw: {})
+ receipts.begin_update_receipt()
+ try:
+ contextvars.copy_context().run(receipts.finalize_pending_update_receipt, 1, "child failed")
+ parent = receipts._current.get().data
+ assert parent["outcome"] == "running"
+ assert "exit_code" not in parent
+ assert "stop_reason" not in parent
+ finally:
+ receipts.finalize_update_receipt("success")
diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.py
index de68900ba3b..abf4273c371 100644
--- a/tests/hermes_cli/test_update_yes_flag.py
+++ b/tests/hermes_cli/test_update_yes_flag.py
@@ -16,6 +16,10 @@ import pytest
from hermes_cli.main import cmd_update
+pytestmark = pytest.mark.usefixtures(
+ "isolated_update_uv", "isolated_update_processes", "isolated_update_checkout",
+)
+
@pytest.fixture(autouse=True)
def _isolate_venv_holders(monkeypatch):
diff --git a/tests/pm/test_admission_members_locked.py b/tests/pm/test_admission_members_locked.py
new file mode 100644
index 00000000000..dea6301e4ad
--- /dev/null
+++ b/tests/pm/test_admission_members_locked.py
@@ -0,0 +1,46 @@
+"""Admission includes profile changes committed before its install lock is acquired."""
+from contextlib import contextmanager
+import importlib
+from types import SimpleNamespace
+
+
+def test_admission_reads_other_profiles_after_taking_lock(tmp_path, monkeypatch):
+ from hermes_cli import plugins_admission as admission
+ from hermes_cli import runtime_state
+ import pm.paths as paths
+
+ ensure = importlib.import_module("pm.ensure")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setattr(paths, "repo_root", lambda: repo)
+ monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: True)
+ monkeypatch.setattr(ensure, "_facts", lambda: {})
+ sibling = tmp_path / "sibling-plugin"
+ state = {"members": [], "inside": False}
+ real_lock = runtime_state.runtime_lock
+
+ @contextmanager
+ def after_competing_publication(project):
+ with real_lock(project):
+ state["members"] = [sibling]
+ state["inside"] = True
+ try:
+ yield
+ finally:
+ state["inside"] = False
+
+ def members(*args, **kwargs):
+ return list(state["members"])
+
+ def apply(extras, *, plugin_dirs):
+ assert state["inside"]
+ assert plugin_dirs == [sibling]
+ return {}
+
+ monkeypatch.setattr(runtime_state, "runtime_lock", after_competing_publication)
+ monkeypatch.setattr(admission, "candidate_member_dirs", members)
+ monkeypatch.setattr(ensure, "get_package", lambda _: SimpleNamespace(
+ expected_stamp=lambda *args, **kwargs: "new", apply=apply,
+ ))
+ admission.admit_plugin_set_change({"requested"}, set())
diff --git a/tests/pm/test_downloader.py b/tests/pm/test_downloader.py
index 06ae8644db2..fb1461610a9 100644
--- a/tests/pm/test_downloader.py
+++ b/tests/pm/test_downloader.py
@@ -418,7 +418,9 @@ def test_gc_protected_names_live_partial(tmp_path):
assert "abc.ranges" in protected # either half protects the pair
assert "old.part" not in protected
- # A grace window of zero protects nothing.
+ # Filesystem timestamps can be slightly ahead of the wall clock.
+ future = time.time() + 60
+ os.utime(partials / "abc.part", (future, future))
assert gc_protected_names(partials, grace_seconds=0) == set()
diff --git a/tests/pm/test_receipt.py b/tests/pm/test_receipt.py
index e23fb5ce89f..18e7f960a53 100644
--- a/tests/pm/test_receipt.py
+++ b/tests/pm/test_receipt.py
@@ -15,11 +15,26 @@ import pm.receipt as receipt
@pytest.fixture(autouse=True)
def _isolated_receipt_context():
- """The ContextVar is module state — tests must not see each other's
- in-flight receipt (a leaked begin would corrupt the next test)."""
+ """The ContextVars are module state — tests must not see each other's
+ in-flight/completed receipts (a leaked begin or finalize would corrupt
+ the next test)."""
receipt._current.set(None)
+ receipt._completed_by_update.set(None)
+ try:
+ import hermes_cli.update_receipt as _ur
+
+ _ur._current.set(None)
+ except Exception:
+ pass
yield
receipt._current.set(None)
+ receipt._completed_by_update.set(None)
+ try:
+ import hermes_cli.update_receipt as _ur
+
+ _ur._current.set(None)
+ except Exception:
+ pass
@pytest.fixture
@@ -243,3 +258,165 @@ def test_finalize_without_token_pops_receipt():
assert receipt.finalize("ok") is not None
assert receipt.snapshot() is None
assert receipt.finalize("ok") is None # nothing begun
+
+
+# --- correlation with the invoking update (update_id stamping) ----------
+
+
+def test_begin_stamps_ambient_update_correlation_id(homed):
+ """A sync begun while an update receipt is open is stamped with THAT
+ update's correlation id — the embed matches on it."""
+ import hermes_cli.update_receipt as ur
+
+ ur.begin_update_receipt()
+ my_id = ur.current_correlation_id()
+ assert my_id
+ receipt.begin("sync")
+ assert receipt.snapshot()["update_id"] == my_id
+ receipt.finalize("ok")
+ # the completion is filed under the update's id
+ assert receipt.last_for_update(my_id)["update_id"] == my_id
+
+
+def test_standalone_sync_has_no_update_id(homed):
+ receipt.begin("sync")
+ assert receipt.snapshot()["update_id"] is None
+
+
+def test_standalone_sync_is_never_filed_for_an_update(homed):
+ """A sync with no invoking update (update_id None) can never be
+ embedded into any update — it is not filed in the map at all."""
+ receipt.begin("sync")
+ receipt.finalize("ok")
+ assert receipt.last_for_update("any-id") is None
+ assert receipt.last_for_update(None) is None
+
+
+def test_sync_begin_after_update_finalized_has_no_update_id(homed, monkeypatch):
+ """The correlation id comes from the OPEN update receipt: after its
+ finalize pops it, a sync begun is standalone."""
+ import hermes_cli.update_receipt as ur
+
+ monkeypatch.setattr(ur, "_receipt_dir", lambda: homed / "logs" / "update_receipts")
+ ur.begin_update_receipt()
+ ur.finalize_update_receipt("success")
+ assert ur.current_correlation_id() is None
+ receipt.begin("sync")
+ assert receipt.snapshot()["update_id"] is None
+
+
+def test_completion_map_is_per_context(homed):
+ """Another thread's finalize must not enter THIS context's completion
+ map — concurrency cannot misattribute its receipt to us."""
+ import threading
+ import hermes_cli.update_receipt as ur
+
+ ur.begin_update_receipt()
+ my_id = ur.current_correlation_id()
+ receipt.begin("sync")
+ receipt.finalize("ok")
+ mine = receipt.last_for_update(my_id)
+ assert mine is not None
+
+ def other():
+ ur.begin_update_receipt()
+ receipt.begin("sync")
+ receipt.record_step("theirs", True)
+ receipt.finalize("ok")
+
+ t = threading.Thread(target=other)
+ t.start()
+ t.join()
+ assert receipt.last_for_update(my_id)["steps"] == mine["steps"]
+
+
+def test_nested_update_syncs_do_not_displace_each_other(homed, monkeypatch):
+ """outer sync → nested update → nested sync → finalize inner →
+ finalize outer: BOTH completions stay filed under their own update
+ id; the nested one never overwrites the outer's entry."""
+ import hermes_cli.update_receipt as ur
+
+ monkeypatch.setattr(ur, "_receipt_dir", lambda: homed / "logs" / "update_receipts")
+ ur.begin_update_receipt()
+ outer_id = ur.current_correlation_id()
+ receipt.begin("sync")
+ receipt.record_step("outer-sync", True)
+ receipt.finalize("ok")
+
+ ur.begin_update_receipt() # nested
+ inner_id = ur.current_correlation_id()
+ receipt.begin("sync")
+ receipt.record_step("inner-sync", True)
+ receipt.finalize("ok")
+
+ # both entries exist while the inner update is still open
+ assert [s["name"] for s in receipt.last_for_update(outer_id)["steps"]] == ["outer-sync"]
+ assert [s["name"] for s in receipt.last_for_update(inner_id)["steps"]] == ["inner-sync"]
+
+ ur.finalize_update_receipt("success")
+ # and after the nested finalize restored the outer receipt
+ assert ur.current_correlation_id() == outer_id
+ assert [s["name"] for s in receipt.last_for_update(outer_id)["steps"]] == ["outer-sync"]
+ assert receipt.last_for_update(inner_id) is None
+ path = ur.finalize_update_receipt("success")
+ assert receipt.last_for_update(outer_id) is None
+ assert json.loads(path.read_text())["pm_steps"][0]["name"] == "outer-sync"
+
+
+def test_last_for_update_returns_a_copy(homed):
+ import hermes_cli.update_receipt as ur
+
+ ur.begin_update_receipt()
+ my_id = ur.current_correlation_id()
+ receipt.begin("sync")
+ receipt.finalize("ok")
+ snap = receipt.last_for_update(my_id)
+ snap["outcome"] = "tampered"
+ assert receipt.last_for_update(my_id)["outcome"] == "ok"
+
+
+# --- failures, refusals, surfaced warnings ------------------------------
+
+
+def test_record_warning_appends(homed):
+ receipt.begin("sync")
+ receipt.record_warning("shim quarantine skipped: file locked")
+ receipt.record_warning("second")
+ receipt.finalize("ok")
+ warnings = receipt.latest()["warnings"]
+ assert [w["message"] for w in warnings] == [
+ "shim quarantine skipped: file locked", "second"
+ ]
+ assert all(w["at"] for w in warnings)
+
+
+def test_record_warning_without_begin_is_noop(homed):
+ receipt.record_warning("orphan")
+ receipt.record_refusal("x", "y")
+ assert receipt.latest() is None
+
+
+def test_record_refusal_names_the_policy_conflict(homed):
+ """A refusal record names WHY the sync refused (policy conflict) while
+ the outcome stays a failure — network/build InstallErrors stay plain
+ failures and must never be recorded as refusals."""
+ receipt.begin("sync")
+ receipt.record_refusal("lazy-install", "venv out of sync")
+ path = receipt.finalize("failed", 1)
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert data["outcome"] == "failed"
+ assert data["refusal"]["code"] == "lazy-install"
+ assert data["refusal"]["detail"] == "venv out of sync"
+
+
+def test_warnings_and_refusal_survive_finalize_rotation(homed):
+ """Failure receipts must survive: recorded, written to latest.json,
+ and present on the stamped file after rotation."""
+ receipt.begin("sync")
+ receipt.record_warning("uv exited 1")
+ receipt.record_refusal("lazy-install", "extras outside frozen set")
+ receipt.finalize("refused", 2)
+ latest = receipt.latest()
+ assert latest["outcome"] == "refused"
+ assert latest["warnings"] and latest["refusal"]["code"] == "lazy-install"
+ assert latest["update_id"] is None
diff --git a/tests/pm/test_runtime_boot_gc.py b/tests/pm/test_runtime_boot_gc.py
new file mode 100644
index 00000000000..5a09e25ecb6
--- /dev/null
+++ b/tests/pm/test_runtime_boot_gc.py
@@ -0,0 +1,49 @@
+"""A real bootstrap reader pins its generation before GC can select victims."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+
+def test_bootstrap_lease_survives_selection_change(tmp_path, monkeypatch):
+ from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path, site_packages
+ from hermes_cli.runtime_state import collect_generations
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ state = install_state_dir(repo)
+ for name in ("first", "second"):
+ venv = state / "environments" / name / "venv"
+ site_packages(venv).mkdir(parents=True)
+ (venv / "pyvenv.cfg").write_text("version = 3.11")
+ (venv.parent / ".lease-managed").touch()
+
+ def select(name):
+ environment = state / "environments" / name / "venv"
+ runtime_facts_path(repo).write_text(json.dumps({"packages": {"venv": {"environment": str(environment)}}}))
+ return environment
+
+ first = select("first")
+ code = '''
+import sys
+from pathlib import Path
+from hermes_cli.runtime_paths import activate_dependencies
+activate_dependencies(Path(sys.argv[1]))
+print("ready", flush=True)
+sys.stdin.readline()
+'''
+ child = subprocess.Popen([sys.executable, "-c", code, str(repo)], env=dict(os.environ),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ assert child.stdout.readline().strip() == "ready"
+ select("second")
+ collect_generations(repo, min_age_seconds=0)
+ assert first.is_dir()
+ finally:
+ child.communicate("done\n", timeout=15)
+ assert child.returncode == 0
+ collect_generations(repo, min_age_seconds=0)
+ assert not first.exists()
+ assert (state / "environments" / "second").is_dir()
diff --git a/tests/pm/test_runtime_journal_concurrent_edit.py b/tests/pm/test_runtime_journal_concurrent_edit.py
new file mode 100644
index 00000000000..1b92f2f841c
--- /dev/null
+++ b/tests/pm/test_runtime_journal_concurrent_edit.py
@@ -0,0 +1,24 @@
+"""Recovery does not overwrite a config edited after interrupted publication."""
+import pytest
+
+
+def test_recovery_refuses_to_replace_newer_config(tmp_path, monkeypatch):
+ from hermes_cli.runtime_state import recover_publication, runtime_lock
+ from hermes_cli.plugins_admission import _config_commit
+ import pm.paths as paths
+ from hermes_cli.runtime_paths import install_state_dir
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setattr(paths, "repo_root", lambda: repo)
+ config = tmp_path / "config.yaml"
+ config.write_bytes(b"plugins:\n enabled: [old]\n")
+ with runtime_lock(repo):
+ _config_commit({"new"}, set())
+ config.write_bytes(config.read_bytes() + b"model: user-choice\n")
+ changed = config.read_bytes()
+ with pytest.raises(RuntimeError, match="config changed"):
+ recover_publication(repo)
+ assert config.read_bytes() == changed
+ assert (install_state_dir(repo) / "publication.json").is_file()
diff --git a/tests/pm/test_runtime_journal_safety.py b/tests/pm/test_runtime_journal_safety.py
new file mode 100644
index 00000000000..e2352801529
--- /dev/null
+++ b/tests/pm/test_runtime_journal_safety.py
@@ -0,0 +1,23 @@
+"""Recovery refuses corrupted metadata and never overwrites unrelated config."""
+import json
+
+import pytest
+
+from hermes_cli.runtime_paths import install_state_dir
+from hermes_cli.runtime_state import recover_publication, runtime_lock
+
+
+def test_invalid_journal_cannot_write_outside_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ repo = tmp_path / "repo"
+ outside = tmp_path / "outside" / "config.yaml"
+ outside.parent.mkdir()
+ outside.write_text("untouched")
+ state = install_state_dir(repo)
+ state.mkdir(parents=True)
+ journal = state / "publication.json"
+ journal.write_text(json.dumps({"config": str(outside), "previous": "eA==", "facts_before": None}))
+ with runtime_lock(repo), pytest.raises(RuntimeError, match="outside Hermes state"):
+ recover_publication(repo)
+ assert outside.read_text() == "untouched"
+ assert journal.exists()
diff --git a/tests/pm/test_runtime_recovery.py b/tests/pm/test_runtime_recovery.py
new file mode 100644
index 00000000000..7f534943b1d
--- /dev/null
+++ b/tests/pm/test_runtime_recovery.py
@@ -0,0 +1,90 @@
+"""Publication survives process death; live dependency generations survive GC."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+
[email protected]("commit_facts", [False, True])
+def test_killed_publication_recovers_before_boot(tmp_path, commit_facts):
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ home = tmp_path / "home"
+ home.mkdir()
+ config = home / "config.yaml"
+ config.write_text("plugins:\n enabled: [old]\n")
+ original = config.read_bytes()
+ env = dict(os.environ, HERMES_HOME=str(home))
+ code = '''
+import os, sys
+from pathlib import Path
+from hermes_cli.plugins_admission import _config_commit
+from hermes_cli.runtime_paths import runtime_facts_path
+import pm.paths as paths
+from pm.lock import Facts
+repo, config = map(Path, sys.argv[1:3])
+paths.repo_root = lambda: repo
+change = _config_commit({"new"}, set())
+if sys.argv[3] == "True":
+ Facts(runtime_facts_path(repo)).record_state("venv", "new", [])
+os._exit(17)
+'''
+ proc = subprocess.run([sys.executable, "-c", code, str(repo), str(config), str(commit_facts)], env=env, capture_output=True, text=True)
+ assert proc.returncode == 17, proc.stderr
+ boot = """
+import sys
+from pathlib import Path
+from hermes_cli.runtime_paths import activate_dependencies, site_packages
+repo, config = map(Path, sys.argv[1:3])
+site_packages(repo / "venv").mkdir(parents=True, exist_ok=True)
+activate_dependencies(repo)
+print(config.read_text(), end="")
+"""
+ recovered = subprocess.run([sys.executable, "-c", boot, str(repo), str(config)],
+ env=env, capture_output=True, text=True, timeout=30)
+ assert recovered.returncode == 0, recovered.stderr
+ assert ("old" in recovered.stdout) is not commit_facts
+ assert (config.read_bytes() == original) is not commit_facts
+
+
+def test_generation_gc_keeps_selected_and_live_leases(tmp_path, monkeypatch):
+ from hermes_cli.runtime_paths import install_state_dir
+ from hermes_cli.runtime_state import collect_generations
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ state = install_state_dir(repo)
+ gens = state / "environments"
+ for name in ("selected", "live", "unused"):
+ env = gens / name / "venv"
+ env.mkdir(parents=True)
+ (env / "pyvenv.cfg").write_text("version=3.11")
+ (env.parent / ".lease-managed").touch()
+ (gens / "old-unleased").mkdir()
+ (state / "facts.json").write_text(json.dumps({"packages": {"venv": {"environment": str(gens / "selected" / "venv")}}}))
+ code = '''
+from pathlib import Path
+from hermes_cli.runtime_state import lease_generation
+import sys
+lease_generation(Path(sys.argv[1]))
+print("leased", flush=True)
+sys.stdin.readline()
+'''
+ child = subprocess.Popen([sys.executable, "-c", code, str(gens / "live" / "venv")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ assert child.stdout.readline().strip() == "leased"
+ collect_generations(repo, min_age_seconds=0)
+ assert (gens / "selected").exists()
+ assert (gens / "live").exists()
+ assert not (gens / "unused").exists()
+ finally:
+ child.communicate("stop\n", timeout=15)
+ assert child.returncode == 0
+ collect_generations(repo, min_age_seconds=0)
+ assert not (gens / "live").exists()
+ assert (gens / "selected").exists()
+ assert (gens / "old-unleased").is_dir()
diff --git a/tests/pm/test_sync_failure_detail.py b/tests/pm/test_sync_failure_detail.py
new file mode 100644
index 00000000000..3a1c9d441a3
--- /dev/null
+++ b/tests/pm/test_sync_failure_detail.py
@@ -0,0 +1,25 @@
+"""A refused sync retains an actionable reason in its persisted receipt."""
+import importlib
+
+import pytest
+
+
+def test_lazy_refusal_records_reason_without_installing(tmp_path, monkeypatch):
+ from pm import receipt
+ from pm.package import InstallError
+
+ ensure = importlib.import_module("pm.ensure")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: False)
+ monkeypatch.setattr("pm.features.read_features", lambda: ["base"])
+
+ with pytest.raises(InstallError):
+ ensure.sync_venv(["new-extra"])
+
+ saved = receipt.latest()
+ assert saved["refusal"]["code"] == "lazy-install"
+ assert saved["outcome"] == "failed"
+ assert saved["exit_code"] != 0
+ assert saved["steps"][-1]["ok"] is False
+ assert "new-extra" in saved["steps"][-1]["detail"]
+ assert "hermes pm install" in saved["steps"][-1]["detail"]
diff --git a/tests/run_agent/test_tool_activity_heartbeat.py b/tests/run_agent/test_tool_activity_heartbeat.py
index 6a93f4a0516..e6c7eb05c00 100644
--- a/tests/run_agent/test_tool_activity_heartbeat.py
+++ b/tests/run_agent/test_tool_activity_heartbeat.py
@@ -110,10 +110,13 @@ def test_heartbeat_touches_periodically_and_stops():
touches: list = []
stop = threading.Event()
+ repeated = threading.Event()
class _Agent:
def _touch_activity(self, desc):
touches.append(desc)
+ if len(touches) >= 2:
+ repeated.set()
thread = threading.Thread(
target=te._run_tool_activity_heartbeat,
@@ -122,15 +125,15 @@ def test_heartbeat_touches_periodically_and_stops():
daemon=True,
)
thread.start()
- time.sleep(0.12)
- stop.set()
- thread.join(timeout=1.0)
+ try:
+ assert repeated.wait(5), "heartbeat did not repeat"
+ finally:
+ stop.set()
+ thread.join(timeout=5)
assert not thread.is_alive(), "heartbeat thread did not exit on stop"
assert len(touches) >= 2, f"expected periodic touches, got {len(touches)}"
- n = len(touches)
- time.sleep(0.1)
- assert len(touches) == n, "heartbeat kept touching after stop_event set"
+ assert all(touch == "tool running: terminal" for touch in touches)
def test_slow_tool_call_refreshes_activity_during_execution(monkeypatch):
diff --git a/tests/scripts/test_mint_launchers.py b/tests/scripts/test_mint_launchers.py
index 4162936f88f..54f34cbab79 100644
--- a/tests/scripts/test_mint_launchers.py
+++ b/tests/scripts/test_mint_launchers.py
@@ -30,7 +30,7 @@ _REPO = Path(__file__).resolve().parents[2]
_MINT = _REPO / "scripts" / "desktop-cli" / "mint-launchers.py"
pytestmark = [
- pytest.mark.skipif(sys.platform != "win32", reason="distlib launcher minting is win32-only"),
+ pytest.mark.platforms("windows"),
]
@@ -80,7 +80,10 @@ def payload_tree(tmp_path: Path):
ignore=shutil.ignore_patterns("__pycache__", "site-packages", "test", "idlelib", "tkinter", "turtledemo", "config-*"),
)
- (repo / "hermes_cli" / "__init__.py").write_text("", encoding="utf-8")
+ # Exercise the real bootstrap before the fixture entry point.
+ for relative in ("hermes_bootstrap.py", "hermes_constants.py", "hermes_cli/__init__.py",
+ "hermes_cli/runtime_paths.py", "hermes_cli/runtime_state.py"):
+ shutil.copy2(_REPO / relative, repo / relative)
(repo / "hermes_cli" / "main.py").write_text(
"import os, sys\n"
"def main():\n"
@@ -154,7 +157,7 @@ def test_minted_launcher_runs_relocated_and_forwards_exit_code(payload_tree, tmp
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "PYTHONHOME", "PYTHONPYCACHEPREFIX")}
env["LOCALAPPDATA"] = str(payload_tree["tmp"] / "lad")
- proc = subprocess.run([str(exe), "--version"], capture_output=True, text=True, cwd=os.path.expanduser("~"), env=env)
+ proc = subprocess.run([str(exe), "--version"], capture_output=True, text=True, cwd=tmp_path, env=env)
assert proc.returncode == 7, proc.stderr[-800:]
assert proc.stdout.strip() == "OK None" # PYTHONHOME was dropped
diff --git a/tests/test_installers_delegate_to_pm.py b/tests/test_installers_delegate_to_pm.py
deleted file mode 100644
index 79c5fccfaed..00000000000
--- a/tests/test_installers_delegate_to_pm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""Desired behavior: the installers delegate the python/venv/tools install
-to pm, and keep the bootstrap config hygiene, instead of hand-rolling a
-`uv sync`. The ambient-config-doesn't-affect-uv contract itself is tested
-behaviorally at the pm layer (tests/pm/test_venv_sync_ambient_config.py);
-these assertions only pin the delegation shape so a future edit can't
-silently reintroduce a second uv-sync path.
-
-The installer scripts are fetched standalone (`curl | sh`, `irm | iex`)
-before any checkout exists, so this is a static guard on the shipped
-bytes — the same approach test_bootstrap_pins_fragment.py takes.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-import pytest
-
-
-REPO_ROOT = Path(__file__).resolve().parent.parent
-INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
-INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
-
-
-def test_installers_delegate_to_pm_cli() -> None:
- """The single install authority is `python -m pm.cli install`; the
- installers must forward to it rather than run `uv sync` themselves."""
- for path in (INSTALL_SH, INSTALL_PS1):
- text = path.read_text(encoding="utf-8")
- assert "python -m pm.cli install" in text, f"{path.name}: missing pm delegation"
- # A raw project sync must not reappear as an INVOCATION in the
- # installers — pm owns it. (Comments may mention the words; the
- # command shape is what we ban.)
- for banned in ('uv sync --', 'uv sync -', '"$UV_CMD" sync', '& $uv sync'):
- assert banned not in text, f"{path.name}: hand-rolled uv sync reappeared ({banned!r})"
-
-
-def test_install_sh_keeps_bootstrap_config_hygiene() -> None:
- """#21269: the bootstrap uv call stays isolated from ambient config."""
- text = INSTALL_SH.read_text(encoding="utf-8")
- assert "export UV_NO_CONFIG=1" in text
-
-
[email protected]("path", [INSTALL_SH, INSTALL_PS1])
-def test_installers_still_create_the_venv_stage(path: Path) -> None:
- """pm's sync targets the venv dir the installer creates; the stage must
- survive (Hermes-Setup's manifest lists it)."""
- text = path.read_text(encoding="utf-8")
- assert "venv" in text # both keep a venv-creating stage / delegate to pm
diff --git a/tests/test_mcp_serve.py b/tests/test_mcp_serve.py
index e31838111f6..b83f2542ea7 100644
--- a/tests/test_mcp_serve.py
+++ b/tests/test_mcp_serve.py
@@ -1259,7 +1259,8 @@ class TestEventBridgePollE2E:
conn.commit()
conn.close()
# Touch the DB file to update mtime (WAL mode may not update mtime on small writes)
- os.utime(db_path, None)
+ before = db_path.stat()
+ os.utime(db_path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000))
# Update sessions.json updated_at to trigger re-check
sessions_data["agent:main:telegram:dm:new"]["updated_at"] = "2026-03-29T15:00:10"
@@ -1374,7 +1375,8 @@ class TestEventBridgePollE2E:
"id": 2, "role": "assistant", "content": "arrived after start",
"timestamp": "2026-03-29T15:05:00",
})
- os.utime(db_path, None) # bump mtime so the poll gate opens
+ before = db_path.stat()
+ os.utime(db_path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000)) # bump mtime so the poll gate opens
bridge._poll_once(DB())
events = bridge.poll_events(after_cursor=0)["events"]
assert len(events) == 1
@@ -1412,7 +1414,8 @@ class TestEventBridgePollE2E:
"id": 1, "role": "user", "content": "hello after baseline",
"timestamp": "2026-03-29T15:10:00",
}]
- os.utime(db_path, None)
+ before = db_path.stat()
+ os.utime(db_path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000))
bridge._poll_once(DB())
events = bridge.poll_events(after_cursor=0)["events"]
diff --git a/tests/tools/test_file_read_guards.py b/tests/tools/test_file_read_guards.py
index 029d73f6da0..030022a7a03 100644
--- a/tests/tools/test_file_read_guards.py
+++ b/tests/tools/test_file_read_guards.py
@@ -58,8 +58,8 @@ def _make_fake_ops(content="hello\n", total_lines=1, file_size=6):
def _make_safe_tempdir(prefix: str) -> str:
- """Create a temp dir outside macOS system-sensitive /private/var paths."""
- return tempfile.mkdtemp(prefix=prefix, dir=os.getcwd())
+ """Keep transient fixtures outside the checkout walked by other pytest workers."""
+ return tempfile.mkdtemp(prefix=prefix)
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_interrupt.py b/tests/tools/test_interrupt.py
index 899a7f570db..04747d8525d 100644
--- a/tests/tools/test_interrupt.py
+++ b/tests/tools/test_interrupt.py
@@ -283,13 +283,14 @@ class TestSIGKILLEscalation:
not __import__("shutil").which("bash"),
reason="Requires bash"
)
- def test_sigterm_trap_killed_within_2s(self):
+ @pytest.mark.platforms("posix")
+ def test_sigterm_trap_killed_within_2s(self, tmp_path):
"""A process that traps SIGTERM should be SIGKILL'd after 1s grace."""
from tools.interrupt import set_interrupt
from tools.environments.local import LocalEnvironment
set_interrupt(False)
- env = LocalEnvironment(cwd="/tmp", timeout=30)
+ env = LocalEnvironment(cwd=str(tmp_path), timeout=30)
# Start execution in a thread, interrupt after 0.5s
result_holder = {"value": None}
diff --git a/tests/tools/test_terminal_bounded_execute.py b/tests/tools/test_terminal_bounded_execute.py
index 83ff9cdb1d5..1a95434fd19 100644
--- a/tests/tools/test_terminal_bounded_execute.py
+++ b/tests/tools/test_terminal_bounded_execute.py
@@ -57,7 +57,7 @@ def test_execute_parent_interrupt_still_kills_wait_on_deadline_worker(monkeypatc
seen = {"parent": False}
- def _wait(_proc, timeout=120, *, bounded_capture=False, watch_interrupt_tid=None):
+ def _wait(_proc, timeout=120, *, bounded_capture=False, watch_interrupt_tid=None, output=None):
deadline = time.monotonic() + 2.0
while time.monotonic() < deadline:
from tools.interrupt import is_thread_interrupted
@@ -80,9 +80,13 @@ def test_execute_parent_interrupt_still_kills_wait_on_deadline_worker(monkeypatc
import threading
- threading.Thread(target=_interrupt_soon, daemon=True).start()
- result = env.execute("sleep 30", timeout=5)
- set_interrupt(False, thread_id=parent_tid)
+ interrupter = threading.Thread(target=_interrupt_soon, daemon=True)
+ interrupter.start()
+ try:
+ result = env.execute("sleep 30", timeout=5)
+ finally:
+ interrupter.join(timeout=5)
+ set_interrupt(False, thread_id=parent_tid)
assert seen["parent"] is True
assert result["returncode"] == 130
diff --git a/tests/tools/test_transcription_tools.py b/tests/tools/test_transcription_tools.py
index e9d7b50b326..9492358b4d9 100644
--- a/tests/tools/test_transcription_tools.py
+++ b/tests/tools/test_transcription_tools.py
@@ -1208,7 +1208,7 @@ class TestRunCommandSttIdleTimeout:
"import sys, time",
"for idx in range(4):",
" print(f'tick {idx}', file=sys.stderr, flush=True)",
- " time.sleep(0.04)",
+ " time.sleep(0.6)",
"print('done', flush=True)",
]),
encoding="utf-8",
@@ -1216,7 +1216,7 @@ class TestRunCommandSttIdleTimeout:
result = _run_command_stt(
self._shell_command(sys.executable, "-u", str(script)),
- timeout=0.1,
+ timeout=2.0,
)
assert result.returncode == 0
@@ -1241,7 +1241,7 @@ class TestRunCommandSttIdleTimeout:
with pytest.raises(subprocess.TimeoutExpired) as excinfo:
_run_command_stt(
self._shell_command(sys.executable, "-u", str(script)),
- timeout=0.1,
+ timeout=2.0,
)
assert "starting pass 1" in (excinfo.value.stderr or "")
diff --git a/tests/tools/test_tts_streaming.py b/tests/tools/test_tts_streaming.py
index 2db7531a6aa..e715c4ca5c4 100644
--- a/tests/tools/test_tts_streaming.py
+++ b/tests/tools/test_tts_streaming.py
@@ -741,26 +741,15 @@ def test_hybrid_playback_serialized_no_overlap(monkeypatch):
)
- sys.platform == "darwin",
- reason="macOS deliberately skips the sounddevice OutputStream path (PR #62601)",
-)
[email protected]("not macos")
def test_hybrid_prefetch_fires_http_immediately(monkeypatch):
- """The prefetch thread must start consuming the generator (firing the
- HTTP request) the moment _enqueue_audio is called, NOT when the
- playback worker gets to it.
-
- We verify by recording the wall-clock time when stream() first yields
- and asserting that the second call's first yield happens before the
- first call's playback completes.
- """
- import time
+ """The second request starts before the first sentence finishes synthesis."""
from tools import tts_tool
from tools.tts_tool_speaker import stream_tts_to_speaker
- stream_start_times: list[float] = []
- playback_done_times: list[float] = []
- block_first_playback = threading.Event()
+ second_started = threading.Event()
+ first_saw_prefetch = []
+ started = []
class _BlockingFirst(ts.StreamingTTSProvider):
sample_rate = 24000
@@ -770,46 +759,23 @@ def test_hybrid_prefetch_fires_http_immediately(monkeypatch):
return True
def stream(self, text):
- stream_start_times.append(time.monotonic())
- # First sentence: block until the test signals playback to proceed.
- # This simulates a long audio segment still playing.
- if len(stream_start_times) == 1:
- block_first_playback.wait(timeout=5.0)
+ started.append(text)
+ if text.startswith("First"):
+ first_saw_prefetch.append(second_started.wait(timeout=5))
+ else:
+ second_started.set()
yield b"\x00\x00" * 10
- sd, out = _sd_mock()
- write_count = [0]
-
- def _mock_write(_data):
- write_count[0] += 1
- if write_count[0] == 1:
- # First write of first sentence — unblock so playback can finish.
- block_first_playback.set()
-
- out.write.side_effect = _mock_write
-
- # Two sentences: first blocks, second should prefetch while first plays.
+ sd, _ = _sd_mock()
q = _drain_queue(["First sentence here. ", "Second sentence here. "])
stop, done = threading.Event(), threading.Event()
-
- with patch("tools.tts_streaming.resolve_streaming_provider",
- return_value=_BlockingFirst({}, {})), \
+ with patch("tools.tts_streaming.resolve_streaming_provider", return_value=_BlockingFirst({}, {})), \
patch.object(tts_tool, "_import_sounddevice", return_value=sd):
stream_tts_to_speaker(q, stop, done)
assert done.is_set()
- assert len(stream_start_times) == 2, (
- f"expected 2 stream() calls, got {len(stream_start_times)}"
- )
- # The second stream() call must have started (HTTP fired) while the
- # first was still blocked/playing. Since the first blocks until
- # playback starts, and the second is enqueued immediately after,
- # the second's start time should be very close to the first's.
- # We just assert both fired (the timing is inherently tested by the
- # fact that block_first_playback was needed to unblock the first).
- assert stream_start_times[1] > stream_start_times[0], (
- "second stream() should start after the first"
- )
+ assert len(started) == 2
+ assert first_saw_prefetch == [True], "prefetch waited for first-sentence playback"
@pytest.mark.skipif(
diff --git a/tests/tui_gateway/test_hosted_room_peer_http.py b/tests/tui_gateway/test_hosted_room_peer_http.py
index c43e85e287c..767e68539ad 100644
--- a/tests/tui_gateway/test_hosted_room_peer_http.py
+++ b/tests/tui_gateway/test_hosted_room_peer_http.py
@@ -619,9 +619,11 @@ def test_peer_success_and_error_reads_are_bounded(monkeypatch):
def test_real_http_drip_cannot_extend_the_whole_response_deadline():
+ stopped = threading.Event()
+
class DripPeer(BaseHTTPRequestHandler):
def do_GET(self):
- body = json.dumps({"pad": "x" * 200}).encode()
+ body = json.dumps({"pad": "x" * 2000}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
@@ -632,7 +634,8 @@ def test_real_http_drip_cannot_extend_the_whole_response_deadline():
self.wfile.flush()
except OSError:
break
- time.sleep(0.02)
+ if stopped.wait(0.02):
+ break
def log_message(self, *_args):
return None
@@ -640,20 +643,25 @@ def test_real_http_drip_cannot_extend_the_whole_response_deadline():
server = ThreadingHTTPServer(("127.0.0.1", 0), DripPeer)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
- started = time.monotonic()
try:
client = PeerRunsHTTPClient(
base_url=f"http://127.0.0.1:{server.server_port}",
api_key="",
- timeout_seconds=0.1,
+ # Leave time for headers on a loaded runner. The body still
+ # takes much longer, even though each byte arrives promptly.
+ timeout_seconds=2.0,
)
+ started = time.monotonic()
with pytest.raises(PeerRunsHTTPError, match="time budget") as caught:
client._request("/drip")
+ elapsed = time.monotonic() - started
finally:
+ stopped.set()
server.shutdown()
+ server.server_close()
thread.join(timeout=2)
- assert time.monotonic() - started < 2.0
+ assert elapsed < 6.0
assert caught.value.retryable is True
diff --git a/tests/tui_gateway/test_slash_worker_mcp_discovery.py b/tests/tui_gateway/test_slash_worker_mcp_discovery.py
index 28bb0dd15d6..5050eb5a157 100644
--- a/tests/tui_gateway/test_slash_worker_mcp_discovery.py
+++ b/tests/tui_gateway/test_slash_worker_mcp_discovery.py
@@ -51,6 +51,8 @@ def test_profile_local_mcp_tool_is_visible_in_slash_worker(tmp_path):
(profile_home / "config.yaml").write_text(
yaml.safe_dump(
{
+ # Let real discovery finish before the CLI snapshots its tools.
+ "mcp_discovery_timeout": 30,
"mcp_servers": {
"profileprobe": {
"enabled": True,
@@ -91,19 +93,31 @@ def test_profile_local_mcp_tool_is_visible_in_slash_worker(tmp_path):
try:
assert proc.stdin is not None
assert proc.stdout is not None
- stdout = proc.stdout
- threading.Thread(
- target=lambda: output.put(stdout.readline()),
- daemon=True,
- ).start()
- proc.stdin.write(json.dumps({"id": 1, "command": "/tools"}) + "\n")
- proc.stdin.flush()
- try:
- line = output.get(timeout=10)
- except queue.Empty:
- pytest.fail("slash worker produced no /tools response within 10 seconds")
- response = json.loads(line)
- assert response["ok"] is True
+
+ def read_responses():
+ for line in proc.stdout:
+ output.put(line)
+ output.put("")
+
+ threading.Thread(target=read_responses, daemon=True).start()
+
+ def request(request_id, command, timeout):
+ proc.stdin.write(json.dumps({"id": request_id, "command": command}) + "\n")
+ proc.stdin.flush()
+ try:
+ line = output.get(timeout=timeout)
+ except queue.Empty:
+ pytest.fail(f"slash worker did not answer {command} within {timeout}s")
+ assert line, f"slash worker exited before answering {command}"
+ response = json.loads(line)
+ assert response["id"] == request_id
+ assert response["ok"] is True, response
+ return response
+
+ # Cold imports and real MCP startup have their own budget; the warm
+ # command must still answer promptly, with the tool already present.
+ request(1, "/version", 60)
+ response = request(2, "/tools", 10)
assert "mcp__profileprobe__hermes_61922_profile_probe" in response["output"]
finally:
proc.terminate()
diff --git a/ui-tui/src/__tests__/terminalParity.test.ts b/ui-tui/src/__tests__/terminalParity.test.ts
index d1f36f49d97..b2933733e76 100644
--- a/ui-tui/src/__tests__/terminalParity.test.ts
+++ b/ui-tui/src/__tests__/terminalParity.test.ts
@@ -19,7 +19,8 @@ describe('terminalParityHints', () => {
const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {
fileOps: { readFile },
- homeDir: '/tmp/fake-home'
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
expect(hints.some(h => h.key === 'ide-setup')).toBe(true)
@@ -69,7 +70,8 @@ describe('terminalParityHints', () => {
const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {
fileOps: { readFile },
- homeDir: '/tmp/fake-home'
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
expect(hints.some(h => h.key === 'ide-setup')).toBe(false)
@@ -119,7 +121,8 @@ describe('terminalParityHints', () => {
const hints = await terminalParityHints({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv, {
fileOps: { readFile },
- homeDir: '/tmp/fake-home'
+ homeDir: '/tmp/fake-home',
+ platform: 'darwin'
})
// Legacy bindings don't match current CSI u targets, so setup is still needed
diff --git a/ui-tui/src/__tests__/terminalSetup.test.ts b/ui-tui/src/__tests__/terminalSetup.test.ts
index 84e5a553dc2..4579f4c9964 100644
--- a/ui-tui/src/__tests__/terminalSetup.test.ts
+++ b/ui-tui/src/__tests__/terminalSetup.test.ts
@@ -41,10 +41,11 @@ describe('terminalSetup helpers', () => {
getVSCodeStyleConfigDir(
'Code',
'win32',
- { APPDATA: 'C:/Users/me/AppData/Roaming' } as NodeJS.ProcessEnv,
+ // Explicit win32-style platform data; win32.join yields backslash separators.
+ { APPDATA: 'C:\\Users\\me\\AppData\\Roaming' } as NodeJS.ProcessEnv,
'/home/me'
)
- ).toBe('C:/Users/me/AppData/Roaming/Code/User')
+ ).toBe('C:\\Users\\me\\AppData\\Roaming\\Code\\User')
})
it('strips line comments from keybindings JSON', () => {
@@ -340,7 +341,9 @@ describe('configureTerminalKeybindings', () => {
await expect(
shouldPromptForTerminalSetup({
env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,
- fileOps: { readFile: readMissing }
+ fileOps: { readFile: readMissing },
+ homeDir: '/Users/me',
+ platform: 'darwin'
})
).resolves.toBe(true)
@@ -388,7 +391,9 @@ describe('configureTerminalKeybindings', () => {
await expect(
shouldPromptForTerminalSetup({
env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,
- fileOps: { readFile: readComplete }
+ fileOps: { readFile: readComplete },
+ homeDir: '/Users/me',
+ platform: 'darwin'
})
).resolves.toBe(false)
})
@@ -448,7 +453,9 @@ describe('configureTerminalKeybindings', () => {
await expect(
shouldPromptForTerminalSetup({
env: { TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv,
- fileOps: { readFile: readLegacy }
+ fileOps: { readFile: readLegacy },
+ homeDir: '/Users/me',
+ platform: 'darwin'
})
).resolves.toBe(true)
})
diff --git a/ui-tui/src/lib/editor.test.ts b/ui-tui/src/lib/editor.test.ts
index dc18be716ad..bd870def86a 100644
--- a/ui-tui/src/lib/editor.test.ts
+++ b/ui-tui/src/lib/editor.test.ts
@@ -38,7 +38,7 @@ describe('resolveEditor', () => {
it('ignores whitespace-only env vars', () => {
const expected = exe(dir, 'editor')
- expect(resolveEditor({ EDITOR: ' ', PATH: dir, VISUAL: '' })).toEqual([expected])
+ expect(resolveEditor({ EDITOR: ' ', PATH: dir, VISUAL: '' }, 'linux')).toEqual([expected])
})
it('prefers `editor` over nano over vi on $PATH', () => {
@@ -46,18 +46,18 @@ describe('resolveEditor', () => {
exe(dir, 'vi')
const expected = exe(dir, 'editor')
- expect(resolveEditor({ PATH: dir })).toEqual([expected])
+ expect(resolveEditor({ PATH: dir }, 'linux')).toEqual([expected])
})
it('falls back to nano before vi when both exist', () => {
exe(dir, 'vi')
const expected = exe(dir, 'nano')
- expect(resolveEditor({ PATH: dir })).toEqual([expected])
+ expect(resolveEditor({ PATH: dir }, 'linux')).toEqual([expected])
})
it('returns ["vi"] when $PATH is empty', () => {
- expect(resolveEditor({ PATH: '' })).toEqual(['vi'])
+ expect(resolveEditor({ PATH: '' }, 'linux')).toEqual(['vi'])
})
it('walks multi-entry $PATH', () => {
@@ -65,7 +65,7 @@ describe('resolveEditor', () => {
const b = mkdtempSync(join(tmpdir(), 'editor-b-'))
const expected = exe(b, 'editor')
- expect(resolveEditor({ PATH: [a, b].join(delimiter) })).toEqual([expected])
+ expect(resolveEditor({ PATH: [a, b].join(delimiter) }, 'linux')).toEqual([expected])
})
it('uses notepad.exe on Windows when no env override', () => {
diff --git a/ui-tui/src/lib/terminalParity.ts b/ui-tui/src/lib/terminalParity.ts
index 9010dedfc77..56ca5294845 100644
--- a/ui-tui/src/lib/terminalParity.ts
+++ b/ui-tui/src/lib/terminalParity.ts
@@ -31,14 +31,19 @@ export function detectMacTerminalContext(env: NodeJS.ProcessEnv = process.env):
export async function terminalParityHints(
env: NodeJS.ProcessEnv = process.env,
- options?: { fileOps?: Partial<FileOps>; homeDir?: string }
+ options?: { fileOps?: Partial<FileOps>; homeDir?: string; platform?: NodeJS.Platform }
): Promise<MacTerminalHint[]> {
const ctx = detectMacTerminalContext(env)
const hints: MacTerminalHint[] = []
if (
ctx.vscodeLike &&
- (await shouldPromptForTerminalSetup({ env, fileOps: options?.fileOps, homeDir: options?.homeDir }))
+ (await shouldPromptForTerminalSetup({
+ env,
+ fileOps: options?.fileOps,
+ homeDir: options?.homeDir,
+ platform: options?.platform
+ }))
) {
hints.push({
key: 'ide-setup',
diff --git a/ui-tui/src/lib/terminalSetup.ts b/ui-tui/src/lib/terminalSetup.ts
index ed8cba2673f..f1966313ae0 100644
--- a/ui-tui/src/lib/terminalSetup.ts
+++ b/ui-tui/src/lib/terminalSetup.ts
@@ -1,6 +1,6 @@
import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { join, posix, win32 } from 'node:path'
export type SupportedTerminal = 'cursor' | 'vscode' | 'windsurf'
@@ -214,15 +214,18 @@ export function getVSCodeStyleConfigDir(
env: NodeJS.ProcessEnv = process.env,
homeDir: string = homedir()
): null | string {
+ // Explicit platform inputs must not inherit the host path separators.
+ const targetJoin = platform === 'win32' ? win32.join : posix.join
+
if (platform === 'darwin') {
- return join(homeDir, 'Library', 'Application Support', appName, 'User')
+ return targetJoin(homeDir, 'Library', 'Application Support', appName, 'User')
}
if (platform === 'win32') {
- return env['APPDATA'] ? join(env['APPDATA'], appName, 'User') : null
+ return env['APPDATA'] ? targetJoin(env['APPDATA'], appName, 'User') : null
}
- return join(homeDir, '.config', appName, 'User')
+ return targetJoin(homeDir, '.config', appName, 'User')
}
function isKeybinding(value: unknown): value is Keybinding {