Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernet9f837d298bba
diff --cc agent/bedrock_adapter.py
index ba4f673677b,017af30c3ab..512811e82d2
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@@ -22,17 -22,17 +22,17 @@@ import http
logger = logging.getLogger(__name__)
-# boto3 is not in the [all] extras; lazy_deps installs it on demand.
+# ---------------------------------------------------------------------------
+# Ensure boto3/botocore are installed before any code in this module runs.
+# Upstream removed boto3 from [all] extras (PRs #24220, #24515); pm
+# handles on-demand installation so the Bedrock provider still works in the
+# EKS deployment without baking boto3 into the base image.
+# ---------------------------------------------------------------------------
try:
- # --------------------------------------------------------------------------- Ensure boto3/botocore are
- # installed before any code in this module runs. Upstream removed boto3 from [all] extras (PRs #24220,
- # #24515); lazy_deps handles on-demand installation so the Bedrock provider still works in the EKS
- # deployment without baking boto3 into the base image.
- # ---------------------------------------------------------------------------
- from tools.lazy_deps import ensure
- ensure("provider.bedrock", prompt=False)
+ from pm import ensure_import
+ ensure_import("bedrock")
- except Exception:
- pass # pm unavailable or install failed — let downstream imports surface the real error
+ except Exception as exc: # downstream imports surface the real error
+ logger.warning("boto3 lazy install did not complete: %s", exc)
_bedrock_runtime_client_cache: Dict[str, Any] = {}
diff --cc apps/desktop/src/app/settings/about-settings.tsx
index d5baf9f26db,fda946eaa21..57812566a1e
--- a/apps/desktop/src/app/settings/about-settings.tsx
+++ b/apps/desktop/src/app/settings/about-settings.tsx
@@@ -1,47 -1,252 +1,67 @@@
import { useStore } from '@nanostores/react'
-import { useEffect, useState } from 'react'
+import { type ReactElement, useEffect } from 'react'
-import { BrandMark } from '@/components/brand-mark'
-import { Button } from '@/components/ui/button'
-import { Codicon } from '@/components/ui/codicon'
-import { type Translations, useI18n } from '@/i18n'
-import { AlertTriangle, CheckCircle2, ExternalLink, Loader2, RefreshCw } from '@/lib/icons'
-import { cn } from '@/lib/utils'
-import {
- $desktopVersion,
- $updateApply,
- $updateChecking,
- $updateStatus,
- checkUpdates,
- openUpdatesWindow,
- refreshDesktopVersion,
- startActiveUpdate
-} from '@/store/updates'
+import { UpdateStatusCard, VersionHero } from '@/components/update-status'
+import { VersionDetails } from '@/components/version-details'
+import { useI18n } from '@/i18n'
+import { RefreshCw } from '@/lib/icons'
+import { $connection } from '@/store/session'
+import { $desktopVersion, checkBackendUpdates, refreshDesktopVersion } from '@/store/updates'
-import { ListRow, SectionHeading, SettingsContent } from './primitives'
+import { SectionHeading, SettingsContent } from './primitives'
import { UninstallSection } from './uninstall-section'
- export function AboutSettings(): ReactElement {
-const RELEASE_NOTES_URL = 'https://github.com/NousResearch/hermes-agent/releases'
-const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'
-
-function relativeTime(ms: number | undefined, a: Translations['settings']['about']) {
- if (!ms) {
- return a.never
- }
-
- const diff = Date.now() - ms
-
- if (diff < 60_000) {
- return a.justNow
- }
-
- if (diff < 3_600_000) {
- return a.minAgo(Math.round(diff / 60_000))
- }
-
- if (diff < 86_400_000) {
- return a.hoursAgo(Math.round(diff / 3_600_000))
- }
-
- return a.daysAgo(Math.round(diff / 86_400_000))
-}
-
+ interface AboutSettingsProps {
+ subpage?: string
+ }
+
-export function AboutSettings({ subpage }: AboutSettingsProps = {}) {
++export function AboutSettings({ subpage }: AboutSettingsProps = {}): ReactElement {
+ if (subpage === 'uninstall') {
+ return (
+ <SettingsContent>
+ <UninstallSection />
+ </SettingsContent>
+ )
+ }
+
+ return <AppUpdatesSettings includeUninstall={subpage === undefined} />
+ }
+
-function AppUpdatesSettings({ includeUninstall }: { includeUninstall: boolean }) {
++interface AppUpdatesSettingsProps {
++ includeUninstall: boolean
++}
++
++function AppUpdatesSettings({ includeUninstall }: AppUpdatesSettingsProps): ReactElement {
const { t } = useI18n()
- const a = t.settings.about
const version = useStore($desktopVersion)
- const status = useStore($updateStatus)
- const apply = useStore($updateApply)
- const checking = useStore($updateChecking)
- const [justChecked, setJustChecked] = useState(false)
+ const connection = useStore($connection)
+ const remote = connection?.mode === 'remote'
- // The version atom is loaded once at app boot, which makes About show a
- // stale number after a self-update (the running binary is current, the
- // displayed string is not). Re-read on mount so opening About always
- // reflects the running build.
- useEffect(() => {
+ // Refresh the running version when About opens or the active gateway changes.
+ useEffect((): void => {
void refreshDesktopVersion()
- }, [])
-
- const behind = status?.behind ?? 0
- // behind is null when the exact count is unknowable (shallow clone): the
- // backend flags that case via updateAvailable instead of a number.
- const updateAvailable = behind > 0 || Boolean(status?.updateAvailable)
- const supported = status?.supported !== false
- const applying = apply.applying || apply.stage === 'restart'
-
- const handleCheck = async () => {
- setJustChecked(false)
- const next = await checkUpdates({ force: true })
- setJustChecked(Boolean(next))
- }
-
- let statusLine: string
- let statusTone: 'idle' | 'available' | 'error' = 'idle'
- if (!supported) {
- statusLine = status?.message ?? a.cantUpdate
- statusTone = 'error'
- } else if (status?.error) {
- // A git that never ran is a local problem; leading with "couldn't reach
- // the update server" would misdiagnose it as a network failure.
- statusLine = [status.error === 'git-unusable' ? '' : a.cantReach, status.message].filter(Boolean).join(' ')
- statusTone = 'error'
- } else if (applying) {
- statusLine = a.installing
- statusTone = 'available'
- } else if (updateAvailable) {
- statusLine = behind > 0 ? a.updateReady(behind) : a.updateReadyUnknown
- statusTone = 'available'
- } else if (status) {
- statusLine = a.onLatest
- } else {
- statusLine = a.tapCheck
- }
+ if (remote) {
+ void checkBackendUpdates()
+ }
+ }, [connection, remote])
return (
<SettingsContent>
- <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">
- <BrandMark className="size-16" />
- <div>
- <h2 className="text-lg font-semibold tracking-tight">{a.heading}</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- {version?.appVersion ? a.version(version.appVersion) : a.versionUnavailable}
- </p>
- </div>
- {(version?.bundleOutOfSync || version?.bundleSwapPending) && (
- <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
- <div className="min-w-0">
- {version?.bundleSwapPending ? (
- // The updated app is already on disk — the updater swapped it
- // under this running process — so a restart loads it. Saying
- // "App build out of date" here would repeat the contradiction
- // this banner is meant to resolve: the Updates card below
- // already reports the runtime as current.
- <>
- <p className="font-medium">{a.bundleSwapPending}</p>
- <p className="mt-1 text-xs text-muted-foreground">{a.bundleSwapPendingDesc}</p>
- <Button
- className="mt-2"
- onClick={() => void window.hermesDesktop?.relaunchApp?.()}
- size="sm"
- variant="textStrong"
- >
- <RefreshCw className="size-3" />
- {a.bundleSwapPendingAction}
- </Button>
- </>
- ) : (
- <>
- <p className="font-medium">{a.bundleOutOfSync}</p>
- <p className="mt-1 text-xs text-muted-foreground">{a.bundleOutOfSyncDesc}</p>
- <Button asChild className="mt-2" size="sm" variant="textStrong">
- <a
- href={INSTALLER_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(INSTALLER_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.bundleOutOfSyncAction}
- </a>
- </Button>
- </>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
+ <VersionHero version={version} />
<div className="mx-auto mt-4 w-full max-w-2xl">
- <SectionHeading icon={RefreshCw} title={a.updates} />
-
- <div
- className={cn(
- 'rounded-xl border px-4 py-3 text-sm',
- statusTone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',
- statusTone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',
- statusTone === 'idle' && 'border-border/70 bg-muted/20 text-foreground'
- )}
- >
- <div className="flex items-start gap-2">
- {statusTone === 'available' ? (
- <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />
- ) : statusTone === 'error' ? null : (
- <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
- )}
- <div className="min-w-0">
- <p className="font-medium">{statusLine}</p>
- <p className="mt-1 text-xs text-muted-foreground">
- {a.lastChecked(relativeTime(status?.fetchedAt, a))}
- {justChecked && !checking ? a.justNowSuffix : ''}
- </p>
- </div>
- </div>
-
- <div className="mt-3 flex flex-wrap items-center gap-4">
- <Button
- disabled={checking || applying || !supported}
- onClick={() => void handleCheck()}
- size="sm"
- variant="textStrong"
- >
- {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
- {checking ? a.checking : a.checkNow}
- </Button>
-
- {updateAvailable && supported && !applying && (
- <>
- <Button onClick={() => startActiveUpdate()} size="sm">
- {a.updateNow}
- </Button>
- <Button onClick={() => openUpdatesWindow('client')} size="sm" variant="textStrong">
- {a.seeWhatsNew}
- </Button>
- </>
- )}
+ <SectionHeading icon={RefreshCw} title={t.settings.about.updates} />
- <Button asChild className="ml-auto" size="sm" variant="text">
- <a
- href={RELEASE_NOTES_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.releaseNotes}
- </a>
- </Button>
- </div>
+ <div className="grid gap-3">
+ <UpdateStatusCard target="client" />
+ {/* Client and remote backend updates are independent. Only the client has release notes. */}
+ {remote && <UpdateStatusCard showReleaseNotes={false} target="backend" />}
</div>
- <ListRow
- description={a.automaticUpdatesDesc}
- hint={a.branchCommit(status?.branch ?? 'unknown', status?.currentSha?.slice(0, 7) ?? 'unknown')}
- title={a.automaticUpdates}
- />
+ {version && <VersionDetails version={version} />}
- <UninstallSection />
+ {includeUninstall && <UninstallSection />}
</div>
</SettingsContent>
)
diff --cc apps/desktop/src/app/settings/connections-registry.tsx
index 50ef119495e,29660a02f5d..d14644626cf
--- a/apps/desktop/src/app/settings/connections-registry.tsx
+++ b/apps/desktop/src/app/settings/connections-registry.tsx
@@@ -1,8 -1,6 +1,8 @@@
import { useStore } from '@nanostores/react'
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+ import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+import { RemoteSetupFields } from '@/components/remote-setup/fields'
+import { useRemoteSetup } from '@/components/remote-setup/use-remote-setup'
import { Button } from '@/components/ui/button'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { Input } from '@/components/ui/input'
diff --cc apps/desktop/src/app/settings/uninstall-section.tsx
index 595c8119f89,dc60b3cc2cb..4d33e62b539
--- a/apps/desktop/src/app/settings/uninstall-section.tsx
+++ b/apps/desktop/src/app/settings/uninstall-section.tsx
@@@ -1,7 -1,7 +1,7 @@@
- import { type ReactElement, useEffect, useState } from 'react'
-import { useContext, useEffect, useState } from 'react'
++import { type ReactElement, useContext, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
-import type { DesktopUninstallMode, DesktopUninstallSummary } from '@/global'
+import type { DesktopUninstallMode, DesktopUninstallResult, DesktopUninstallSummary } from '@/global'
import { useI18n } from '@/i18n'
import { AlertTriangle, Loader2, Trash2 } from '@/lib/icons'
import { cn } from '@/lib/utils'
@@@ -46,18 -46,22 +46,19 @@@ const OPTIONS: ModeOption[] =
}
]
-export function UninstallSection() {
+export function UninstallSection(): ReactElement | null {
+ const hasBreadcrumb = useContext(SettingsBreadcrumbContext)
const { t } = useI18n()
const [summary, setSummary] = useState<DesktopUninstallSummary | null>(null)
- const [loading, setLoading] = useState(true)
const [pending, setPending] = useState<DesktopUninstallMode | null>(null)
- const [running, setRunning] = useState(false)
+ const [running, setRunning] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null)
- useEffect(() => {
- let alive = true
- const bridge = window.hermesDesktop?.uninstall
+ useEffect((): (() => void) | undefined => {
+ let alive: boolean = true
+ const bridge: Window['hermesDesktop']['uninstall'] | undefined = window.hermesDesktop?.uninstall
if (!bridge) {
- setLoading(false)
-
return
}
@@@ -114,14 -121,19 +115,14 @@@
}
}
- const pendingOption = OPTIONS.find(opt => opt.mode === pending) ?? null
+ const pendingOption: ModeOption | null = OPTIONS.find((opt: ModeOption): boolean => opt.mode === pending) ?? null
return (
- <div className="mx-auto mt-8 w-full max-w-2xl">
- <SectionHeading icon={AlertTriangle} title={t.settings.uninstallSection.dangerZone} />
+ <div className={cn('mx-auto w-full max-w-2xl', !hasBreadcrumb && 'mt-8')}>
+ <SectionHeading icon={AlertTriangle} page title={t.settings.uninstallSection.dangerZone} />
<div className="rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3">
- {loading ? (
- <div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">
- <Loader2 className="size-3.5 animate-spin" />
- Checking what&apos;s installed…
- </div>
- ) : pendingOption ? (
+ {pendingOption ? (
<div>
<p className="text-sm font-medium text-destructive">{t.settings.uninstallSection.confirmUninstall}</p>
<p className="mt-1 text-xs text-muted-foreground">
diff --cc gateway/run.py
index 082e0411ae1,6e12bd02022..d03e22da59d
--- a/gateway/run.py
+++ b/gateway/run.py
@@@ -4675,12 -4689,11 +4699,13 @@@ def _start_gateway_housekeeping
# already ended (#111010). Runs every tick so the outage is bounded by one housekeeping interval.
chores.append((1, "Cron ticker supervisor", cron_thread.restart_if_dead))
chores += [
- (60, "Curator tick", _housekeeping_curator),
- (60, "Sync pull tick", _housekeeping_skill_sync),
- (60, "Org sync pull tick", _housekeeping_org_skill_sync),
+ # Per served profile: each profile has its own skills tree, curator state and Nous login.
+ (60, "Curator tick", profile_scoped_chore(runner, _housekeeping_curator)),
+ (60, "Sync pull tick", profile_scoped_chore(runner, _housekeeping_skill_sync)),
+ (60, "Org sync pull tick", profile_scoped_chore(runner, _housekeeping_org_skill_sync)),
(60, "Auto-archive tick", _housekeeping_auto_archive),
+ # Due-gated inside: the first tick after startup runs an overdue check, not tick 60.
+ (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),
(1, "MCP config reconcile", _mcp_config_reconciler(runner)),
diff --cc hermes_cli/gateway.py
index 5f6c6604734,faf4d92dac2..f17594ae141
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@@ -1122,10 -1121,11 +1122,11 @@@ def _systemctl_show(properties: tuple[s
return _parse_kv_pairs(result.stdout.splitlines()) if result.returncode == 0 else {}
- def _hermes_home_pinned_by_unit(unit_path: Path) -> str | None:
- """``HERMES_HOME`` pinned by the unit file at *unit_path*, or None when absent/unreadable."""
+ def _unit_environment_value(unit_path: Path, name: str) -> str | None:
+ """Value of one ``Environment="NAME=…"`` directive in the unit file at *unit_path*, with
+ systemd's ``\\"``/``\\\\``/``%%`` quoting undone; None when the file or the key is absent."""
try:
- text = unit_path.read_text(encoding="utf-8")
+ text = unit_path.read_text(encoding="utf-8-sig")
except OSError:
return None
for line in text.splitlines():
@@@ -2776,10 -2784,74 +2785,51 @@@ def launchd_gateway_labels_for_install(
return root_label + sorted(profile_labels)
+ def legacy_launchd_labels_for_install(exclude=()) -> list[str]:
+ """Launchd labels of THIS install that the profile-layout derivation can't map (#115254).
+
+ A unit whose label predates the profile-name suffix scheme (``ai.hermes.gateway-<8hex>`` from the
+ historical hash suffix) is invisible to ``launchd_gateway_labels_for_install()`` and therefore to
+ the update restart pass. This reads the account's LaunchAgents and credits a plist only when its
+ pinned ``HERMES_HOME`` is this install's root or one of its ``profiles/<name>`` homes — ownership
+ judged from the plist's content, never from label shape or directory membership — so the
+ derivation's boundary holds: a sandboxed HERMES_HOME (tests, side-by-side installs) never
+ enumerates, let alone restarts, another install's fleet (#41403).
+ """
+ import plistlib
+ import pwd
+
+ from hermes_constants import get_default_hermes_root
+
+ try:
+ home = Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — POSIX launchd (macOS) helper, never invoked on Windows
+ root = get_default_hermes_root().resolve()
+ except Exception:
+ return []
+ agents_dir = home / "Library" / "LaunchAgents"
+ if not agents_dir.is_dir():
+ return []
+ excluded = set(exclude)
+ labels: set[str] = set()
+ for plist_path in sorted(agents_dir.glob("ai.hermes.gateway*.plist")):
+ try:
+ data = plistlib.loads(plist_path.read_bytes())
+ label = data["Label"]
+ pinned = Path(str(data["EnvironmentVariables"]["HERMES_HOME"])).expanduser().resolve()
+ rel = pinned.relative_to(root).parts
+ except Exception:
+ continue # unreadable plist, no pinned home, or a home outside this root: not ours — fail closed
+ if not isinstance(label, str) or label in excluded or not label.startswith("ai.hermes.gateway"):
+ continue
+ if not rel or (len(rel) == 2 and rel[0] == "profiles"):
+ labels.add(label)
+ return sorted(labels)
+
+
-def _detect_venv_dir() -> Path | None:
- """Active virtualenv dir: ``sys.prefix``, then ``VIRTUAL_ENV`` (uv sets it without changing
- sys.prefix), then .venv/venv under PROJECT_ROOT; None if none found."""
- candidates: list[Path] = []
- if sys.prefix != sys.base_prefix:
- candidates.append(Path(sys.prefix))
- if os.environ.get("VIRTUAL_ENV"):
- candidates.append(Path(os.environ["VIRTUAL_ENV"]))
- candidates += [PROJECT_ROOT / ".venv", PROJECT_ROOT / "venv"]
- return next((venv for venv in candidates if venv.is_dir()), None)
-
-
def get_python_path() -> str:
- venv = _detect_venv_dir()
- if venv is not None:
- try:
- from hermes_constants import venv_python_path
- except ImportError:
- # Update-boundary: a gateway restarted mid-update can hold a stale hermes_constants
- # without this symbol; see _reload_hermes_constants() in hermes_cli/managed_uv.py.
- from hermes_cli.managed_uv import _reload_hermes_constants
- venv_python_path = _reload_hermes_constants().venv_python_path
+ from hermes_cli._launchers import resolve_store_python
- venv_python = venv_python_path(venv, windows=is_windows())
- if venv_python.exists():
- return str(venv_python)
- return sys.executable
+ return str(resolve_store_python(PROJECT_ROOT) or sys.executable)
# =============================================================================
@@@ -3071,10 -3106,6 +3148,12 @@@ def generate_systemd_unit(system: bool
path_entries.extend(_build_wsl_interop_paths(path_entries))
path_entries.extend(["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"])
sane_path = ":".join(path_entries)
+ start = installation_command(project_root, [*shlex.split(profile_arg), "gateway", "run"],
+ python=python_path, home=hermes_home)
+ cleanup = installation_command(project_root, module="gateway.cgroup_cleanup",
+ python=python_path, home=hermes_home)
++ stop_mark = installation_command(project_root, module="gateway.systemd_stop_mark",
++ python=python_path, home=hermes_home)
return f"""[Unit]
Description={SERVICE_DESCRIPTION}
After=network-online.target
@@@ -3097,7 -3128,8 +3176,8 @@@ RestartPreventExitStatus={GATEWAY_FATAL
KillMode=mixed
KillSignal=SIGTERM
ExecReload=/bin/kill -USR1 $MAINPID
-ExecStop=-{python_path} -m gateway.systemd_stop_mark
-ExecStopPost=-{python_path} -m gateway.cgroup_cleanup
++ExecStop=-{_systemd_command(stop_mark)}
+ExecStopPost=-{_systemd_command(cleanup)}
TimeoutStopSec={restart_timeout}
StandardOutput=journal
StandardError=journal
diff --cc hermes_cli/update_cmd_stash.py
index 26328a31b3c,1c5b2841cf2..8b785523ab6
--- a/hermes_cli/update_cmd_stash.py
+++ b/hermes_cli/update_cmd_stash.py
@@@ -57,8 -73,8 +73,8 @@@ def _print_first_line(text: str) -> Non
def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[str]:
- from hermes_cli.update_cmd import _git_run
+ from hermes_cli.update_cmd_git import _git_run
- status = _git_run(git_cmd, ["status", "--porcelain"], cwd, check=True)
+ status = _git_run(git_cmd, ["status", "--porcelain", "-z"], cwd, check=True)
if not status.stdout.strip():
return None
# Unmerged index entries (interrupted merge/rebase) make `git stash` fail with
@@@ -317,8 -360,11 +360,9 @@@ def _drop_restored_stash(git_cmd: list[
def _restore_stashed_changes(
git_cmd: list[str], cwd: Path, stash_ref: str, prompt_user: bool = False, input_fn=None,
) -> bool:
- from hermes_cli.update_cmd import (
- _critical_module_import_failures, _git_untracked_paths, _restored_python_paths, _validate_python_files_syntax,
- )
+ from hermes_cli.update_cmd import _critical_module_import_failures, _git_untracked_paths, _restored_python_paths, _validate_python_files_syntax
if prompt_user and not _confirm_restore(stash_ref, input_fn):
+ _record_stash_disposition("parked", stash_ref, "restore declined")
return False
preexisting_untracked = _git_untracked_paths(git_cmd, cwd)
if preexisting_untracked is None:
diff --cc hermes_cli/update_receipt.py
index bd1c000f991,06d7ed86363..403d5220d7e
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@@ -266,47 -197,17 +266,54 @@@ def finalize_update_receipt(outcome: st
receipt.data["stop_reason"] = stop_reason
if fleet is not None:
receipt.data["fleet"] = fleet
++ # Manual serve restart obligations outlive one receipt rotation: carry the previous
++ # receipt's still-pending rows forward so the startup warning survives (see
++ # update_serve_obligations).
+ from hermes_cli.update_serve_obligations import retain_receipt_manual_serves
+ pending = retain_receipt_manual_serves(read_latest_receipt() or {})
+ if pending:
+ receipt.data["pending_manual_serves"] = pending
+ # EMBED the pm sync sections (the settled receipts contract): the
+ # update's rebuild/bisect ran through pm's own sync receipt, which
+ # finalizes before this one. Fold in only the completion filed
+ # under THIS update's correlation id (pm.receipt.last_for_update,
+ # per-context, never latest.json) — a sync from before this update
+ # began, a standalone sync, or one in a concurrent thread cannot
+ # be misattributed, and a nested update's sync cannot displace
+ # this update's own. ONE file still carries the whole story
+ # (desktop reads a single latest.json).
+ try:
+ from pm import receipt as pm_receipt
+
+ sync = pm_receipt.last_for_update(receipt.correlation_id, consume=True)
+ if isinstance(sync, dict):
+ for key in ("venv_rebuild", "plugin_bisect", "feature_list", "steps", "exit_code"):
+ if sync.get(key) is not None:
+ receipt.data[f"pm_{key}"] = sync[key]
+ if sync.get("outcome") is not None:
+ receipt.data["pm_sync_outcome"] = sync.get("outcome")
+ if sync.get("warnings"):
+ receipt.data["pm_warnings"] = sync["warnings"]
+ if sync.get("refusal") is not None:
+ receipt.data["pm_refusal"] = sync["refusal"]
+ except Exception as exc: # pragma: no cover — embedding is additive
+ logger.debug("pm sync-section embed skipped: %s", exc)
directory = _receipt_dir()
directory.mkdir(parents=True, exist_ok=True)
- path = directory / f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}.json"
- body = json.dumps(receipt.data, indent=2, default=str)
- path.write_text(body, encoding="utf-8")
- with suppress(OSError): # stable pointer for the dashboard/desktop
- (directory / "latest.json").write_text(body, encoding="utf-8")
+ # Unique name: stamp+pid collides for nested/concurrent receipts in
+ # the same process+second — the correlation id makes the name unique
+ # per update run. Atomic write for BOTH the stamped receipt and the
+ # latest.json pointer (no torn readers).
+ from hermes_cli.runtime_state import _atomic_bytes
+
+ path = directory / (
+ f"update_{time.strftime('%Y%m%d_%H%M%S')}_{os.getpid()}_"
+ f"{receipt.correlation_id}.json"
+ )
+ payload = (json.dumps(receipt.data, indent=2, default=str) + "\n").encode("utf-8")
+ _atomic_bytes(path, payload)
+ with suppress(Exception): # stable pointer for the dashboard/desktop
+ _atomic_bytes(directory / "latest.json", payload)
_prune_old_receipts(directory)
return path
except Exception as exc:
diff --cc scripts/run_tests.sh
index b39a3255d46,77eedc6d1cc..937e2556fc7
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@@ -108,6 -108,6 +108,21 @@@ if [ -f "$HOME/.hermes/pytest_live_guar
fi
++# ── Real-home PATH entries (computed before we drop env) ────────────────────
++# An installed Hermes puts ~/.hermes/{bin,node/bin} on the shell PATH. Tests
++# run under the real-home I/O tripwire, so a `shutil.which()` walking those
++# entries fails as "I/O against the REAL hermes home" — CI has none of them.
++TEST_PATH=""
++_IFS_SAVE="$IFS"; IFS=':'
++for _entry in $PATH; do
++ case "$_entry" in
++ "$HOME/.hermes"|"$HOME/.hermes/"*) ;;
++ *) TEST_PATH="${TEST_PATH:+$TEST_PATH:}$_entry" ;;
++ esac
++done
++IFS="$_IFS_SAVE"
++
++
# ── Windows location variables (computed before we drop env) ───────────────
# `env -i` forwards HOME, which is enough on POSIX. Native Windows CPython
# resolves Path.home() from USERPROFILE (or HOMEDRIVE+HOMEPATH), stdlib
@@@ -171,7 -167,7 +186,7 @@@ echo "▶ pre-compiling bytecode cache
echo "▶ launching test runner"
exec env -i \
-- PATH="$PATH" \
++ PATH="$TEST_PATH" \
HOME="$HOME" \
${WIN_ENV[@]+"${WIN_ENV[@]}"} \
${TEST_ENV[@]+"${TEST_ENV[@]}"} \
diff --cc tests/agent/lsp/test_windows_binary_resolution.py
index b7ba51e3b1a,b7ba51e3b1a..f33088a2172
--- a/tests/agent/lsp/test_windows_binary_resolution.py
+++ b/tests/agent/lsp/test_windows_binary_resolution.py
@@@ -41,7 -41,7 +41,7 @@@ def test_windows_resolution_picks_cmd_w
assert spec is not None and spec.command[0] == str(langserver_cmd)
def test_existing_binary_resolves_runnable_cmd_over_posix_shim(tmp_path: Path, monkeypatch):
"""Live: staging dir holds npm's shim AND its .cmd; the resolved path must actually run."""
monkeypatch.setattr(install, "hermes_lsp_bin_dir", lambda: tmp_path)
diff --cc tests/agent/test_anthropic_keychain.py
index 1029f1006d5,4bf04e38502..7177a99dc6e
--- a/tests/agent/test_anthropic_keychain.py
+++ b/tests/agent/test_anthropic_keychain.py
@@@ -402,7 -402,7 +402,7 @@@ class TestFindClaudeCodeKeychainItem
"""``_find_claude_code_keychain_item`` parses one ``find-generic-password -g`` call. ``security``
prints plain-ASCII attributes quoted but UNescaped, anything else as ``0x<HEX> "<echo>"``."""
-- @pytest.mark.macos_only
++ @pytest.mark.platforms("macos")
@pytest.mark.parametrize(
"acct_line, expected_account",
[
@@@ -424,7 -424,7 +424,7 @@@ class TestMirrorClaudeCodeCredentialsTo
"""The #98334 write mirror shells out to ``security``; ``subprocess.run`` is mocked so no
real Keychain is touched."""
-- @pytest.mark.macos_only
++ @pytest.mark.platforms("macos")
def test_no_write_when_no_entry_exists(self, monkeypatch):
"""Never create a Keychain item the user has not."""
monkeypatch.setattr("agent.anthropic_credentials._find_claude_code_keychain_item", lambda: None)
@@@ -435,7 -435,7 +435,7 @@@
run.assert_not_called()
-- @pytest.mark.macos_only
++ @pytest.mark.platforms("macos")
def test_only_the_item_holding_the_spent_pair_is_updated(self, monkeypatch):
"""A different pair in the Keychain is another login or a rotation Claude Code already made;
overwriting it would be the bug in the other direction."""
diff --cc tests/cron/test_cron_bot_chat_delivery.py
index bf80f9632e2,69f8aa1afbe..8abd7d3487d
--- a/tests/cron/test_cron_bot_chat_delivery.py
+++ b/tests/cron/test_cron_bot_chat_delivery.py
@@@ -285,6 -286,92 +286,92 @@@ def test_turn_that_never_ends_is_still_
assert time.monotonic() - started < 8
+ def test_bot_chat_turn_keeps_failure_tail_under_non_utf8_parent(tmp_path):
+ """The gateway parent's locale codec, not the child's UTF-8, decides the decode: a parent
+ outside UTF-8 mode with a C locale (the Linux twin of the cp1252 gateway parent on Windows)
+ used to lose the failing child's accented stderr entirely — the drain thread died on the
+ first undecodable byte and ``_format_failure_streams`` recorded nothing but the exit code
+ (#115894). Lossy decoding keeps the tail: on POSIX the accented characters degrade to
+ U+FFFD (the locale default stays, #66566) but the diagnostic text and exit code survive.
+
+ ``PYTHONUTF8=0`` alone is not enough on 3.11 — PEP 538 coerces the C locale to UTF-8, so
+ the nested parent also sets ``PYTHONCOERCECLOCALE=0`` and asserts it is really ASCII."""
+ nested = textwrap.dedent("""
+ import json, locale, os, sys
+ from cron.scheduler_delivery import _run_bot_chat_turn
+ child = "import sys; sys.stderr.buffer.write({!r}); sys.exit(3)".format(
+ bytes.fromhex(sys.argv[1]))
+ result = _run_bot_chat_turn(
+ [sys.executable, "-c", child], dict(os.environ), sys.argv[2], timeout=30)
+ print(json.dumps({"preferred": locale.getpreferredencoding(False),
+ "returncode": result.returncode, "stderr": result.stderr}))
+ """)
+ env = {**_child_env(), "LC_ALL": "C", "LANG": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0"}
+ env.pop("PYTHONIOENCODING", None)
+ tail = "relatório nº 3: falhou\n"
+ res = subprocess.run(
+ [sys.executable, "-X", "utf8=0", "-c", nested, tail.encode("utf-8").hex(), str(tmp_path / "turn.json")],
+ env=env, timeout=60, check=True, capture_output=True, encoding="utf-8")
+
+ result = json.loads(res.stdout)
+ assert result["preferred"].lower() in ("ansi_x3.4-1968", "ascii", "us-ascii"), result
+ assert result["returncode"] == 3
+ assert result["stderr"] == "relat\ufffd\ufffdrio n\ufffd\ufffd 3: falhou\n"
+
+
+ def test_bot_chat_turn_failure_tail_decodes_lossily(tmp_path):
+ """The exit-1 tail is still surfaced (with U+FFFD for the bad byte) instead of
+ vanishing when the drain thread dies at the first undecodable byte (#105582)."""
+ child = "import os, sys; os.write(2, b'boom before \\x80 after\\n'); sys.exit(1)"
+ result = sched_delivery._run_bot_chat_turn(
+ [sys.executable, "-c", child], _child_env(), str(tmp_path / "turn.json"), timeout=15)
+
+ assert result.returncode == 1
+ assert result.stderr == "boom before \ufffd after\n"
+
+
+ def test_bot_chat_turn_roundtrips_accented_utf8_reply(tmp_path):
+ """The delivery child writes UTF-8 unconditionally — hermes_cli reconfigures its
+ own streams via hermes_bootstrap on Windows even under PYTHONIOENCODING=cp1252 —
+ while the gateway parent there is NOT started in UTF-8 mode, so text=True alone
+ decoded the pipes with the ANSI code page: the reply came back mojibake'd, or the
+ reader thread died on bytes undefined in cp1252 and the reply was silently lost
+ while the delivery still booked as delivered (#115894).
+
+ The gateway parent is a nested interpreter explicitly NOT in UTF-8 mode
+ (``PYTHONUTF8=0`` / ``-X utf8=0``), so its Popen(text=True) decodes with the
+ ANSI code page exactly like the production parent; the stand-in child writes
+ raw UTF-8 bytes through sys.stdout.buffer the way the bootstrapped hermes_cli
+ child does, independent of any locale. On the pre-fix branch the decode dies
+ on 0x8D (second byte of UTF-8 "Í", undefined in cp1252) inside the drain
+ thread and stdout comes back empty — RED; with the win32 UTF-8 pin the text
+ round-trips byte-for-byte. The JSON verdict rides the nested stdout with
+ ensure_ascii escapes, so the outer pipe encoding cannot distort it."""
+ text = "AÇÃO ÍNDICE: relatório nº 3\n"
+ nested = textwrap.dedent("""
+ import json, os, sys
+ from cron.scheduler_delivery import _run_bot_chat_turn
+ child = "import sys; sys.stdout.buffer.write({!r})".format(sys.argv[1].encode("utf-8"))
+ result = _run_bot_chat_turn(
+ [sys.executable, "-c", child], dict(os.environ), sys.argv[2], timeout=30)
+ print(json.dumps(
+ {"returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr}))
+ """)
+ env = {**_child_env(), "PYTHONUTF8": "0"}
+ env.pop("PYTHONIOENCODING", None)
+ res = subprocess.run(
+ [sys.executable, "-X", "utf8=0", "-c", nested, text, str(tmp_path / "turn.json")],
+ env=env, timeout=60, check=True, capture_output=True, encoding="utf-8")
+
+ result = json.loads(res.stdout)
+ assert result["returncode"] == 0
+ assert result["stdout"] == text
+ assert result["stderr"] == ""
+
+
# ── delivery-targets listing (UI pickers) ────────────────────────────────────
def test_delivery_targets_include_local_profiles():
diff --cc tests/gateway/test_shutdown_forensics.py
index b6b4776e836,8bd69e6380e..f42b2dfbceb
--- a/tests/gateway/test_shutdown_forensics.py
+++ b/tests/gateway/test_shutdown_forensics.py
@@@ -131,7 -131,7 +131,7 @@@ class TestSpawnAsyncDiagnostic
def test_spawns_subprocess_and_writes_output(self, tmp_path):
self._assert_diagnostic_written(tmp_path)
-- @pytest.mark.macos_only
++ @pytest.mark.platforms("macos")
def test_spawns_without_gnu_timeout_on_macos(self, tmp_path):
"""Stock macOS has no ``timeout`` binary and BSD ``ps``; the diagnostic still lands."""
self._assert_diagnostic_written(tmp_path)
diff --cc tests/gateway/test_systemd_stop_mark.py
index 00000000000,2a73feef449..2409a10ba6b
mode 000000,100644..100644
--- a/tests/gateway/test_systemd_stop_mark.py
+++ b/tests/gateway/test_systemd_stop_mark.py
@@@ -1,0 -1,58 +1,59 @@@
+ """Supervisor-ordered stops exit cleanly instead of logging a failure.
+
+ Raw ``systemctl restart/stop`` sends SIGTERM with no marker, so the gateway
+ used to classify it as an unexpected kill (exit 1, ``Failed with result
+ exit-code``). The generated unit now marks the stop via ``ExecStop=`` first.
+ """
+
+ from __future__ import annotations
+
+ import pytest
+
+ from gateway import systemd_stop_mark
+
+
+ def test_stop_mark_writes_planned_stop_for_supervised_pid(monkeypatch):
+ """MAINPID (or an explicit argv PID) is marked; the helper owns identity."""
+ marked: list[int] = []
+ monkeypatch.setattr(
+ "gateway.status.write_planned_stop_marker",
+ lambda pid: marked.append(pid) or True,
+ )
+ monkeypatch.setenv("MAINPID", "4242")
+ assert systemd_stop_mark.main(["systemd_stop_mark"]) == 0
+ assert marked == [4242]
+
+ marked.clear()
+ monkeypatch.delenv("MAINPID")
+ assert systemd_stop_mark.main(["systemd_stop_mark", "7777"]) == 0
+ assert marked == [7777]
+
+
+ def test_stop_mark_never_blocks_restart_and_unit_wires_exec_stop(monkeypatch):
+ """Unknown PIDs mark nothing but still exit 0; the unit runs the marker."""
+ marked: list[int] = []
+ monkeypatch.setattr(
+ "gateway.status.write_planned_stop_marker",
+ lambda pid: marked.append(pid) or True,
+ )
+ for argv, env in ((["m"], None), (["m", "0"], None), (["m", "abc"], None)):
+ if env is None:
+ monkeypatch.delenv("MAINPID", raising=False)
+ assert systemd_stop_mark.main(argv) == 0
+ assert marked == []
+
+ def _boom(_pid):
+ raise OSError("disk gone")
+
+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", _boom)
+ monkeypatch.setenv("MAINPID", "4242")
+ assert systemd_stop_mark.main(["m"]) == 0
+
+ from hermes_cli import gateway as gateway_cli
+
+ unit = gateway_cli.generate_systemd_unit(system=False)
- assert "ExecStop=-" in unit and "-m gateway.systemd_stop_mark" in unit
++ # Both modules run through the installation launcher (`hermes --run-module <mod>`).
++ assert "ExecStop=-" in unit and "gateway.systemd_stop_mark" in unit
+ # The cgroup reaper still runs after the main process exits.
- assert "-m gateway.cgroup_cleanup" in unit
++ assert "ExecStopPost=-" in unit and "gateway.cgroup_cleanup" in unit
+ assert unit.index("systemd_stop_mark") < unit.index("cgroup_cleanup")
diff --cc tests/hermes_cli/test_desktop_half_installed_get_windows.py
index 7554534946c,820e590da8e..00000000000
deleted file mode 100644,100644
--- a/tests/hermes_cli/test_desktop_half_installed_get_windows.py
+++ /dev/null
@@@ -1,42 -1,107 +1,0 @@@
--"""A half-extracted ``node_modules/get-windows`` self-heals before the desktop npm install (#90829).
--
--An in-place Windows update with the Desktop/gateway holding files open fails tar extraction
--mid-package, leaving the dir without ``package.json``; npm never revisits an existing dir, so
--the optional dep stayed broken on every later update until a manual repair.
--"""
-
-import shutil
-from pathlib import Path
--
--from hermes_cli import main_desktop
-
-
-def _desktop_checkout(tmp_path: Path, monkeypatch, *, electron_dir: Path | None = None) -> Path:
- """A minimal checkout with a staged Electron package; returns the electron dir."""
- import hermes_cli.main as main_mod
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
- (tmp_path / "home").mkdir()
- monkeypatch.setattr(main_mod, "PROJECT_ROOT", tmp_path)
- monkeypatch.setattr(main_desktop, "_nixos_build_env", lambda: {})
- (tmp_path / "package.json").write_text('{"workspaces": ["apps/*"]}', encoding="utf-8")
- (tmp_path / "package-lock.json").write_text("{}", encoding="utf-8")
- (tmp_path / "apps" / "desktop").mkdir(parents=True)
- (tmp_path / "apps" / "desktop" / "package.json").write_text("{}", encoding="utf-8")
- electron = electron_dir or tmp_path / "node_modules" / "electron"
- electron.mkdir(parents=True)
- (electron / "package.json").write_text("{}", encoding="utf-8")
- return electron
--
--
--def test_half_installed_dir_is_removed_and_a_complete_one_is_kept(tmp_path):
-- half = tmp_path / "node_modules" / "get-windows" / "lib" / "binding"
-- half.mkdir(parents=True)
-- complete = tmp_path / "apps" / "desktop" / "node_modules" / "get-windows"
-- complete.mkdir(parents=True)
-- (complete / "package.json").write_text('{"name": "get-windows"}', encoding="utf-8")
--
-- removed = main_desktop._remove_half_installed_get_windows(tmp_path)
--
-- assert removed == [tmp_path / "node_modules" / "get-windows"]
-- assert not (tmp_path / "node_modules" / "get-windows").exists()
-- assert (complete / "package.json").exists()
--
--
--def test_install_removes_the_half_installed_dir_before_npm_runs(tmp_path, monkeypatch):
-- half = tmp_path / "node_modules" / "get-windows"
-- half.mkdir(parents=True)
-- seen: list[bool] = []
--
-- def _fake_npm(npm, cwd, **kwargs):
-- seen.append(half.exists())
-- return type("R", (), {"returncode": 0})()
--
-- import hermes_cli.main as main_mod
-- import hermes_cli.main_web_build as web_build
-- monkeypatch.setattr(main_mod, "PROJECT_ROOT", tmp_path)
-- monkeypatch.setattr(web_build, "_run_npm_install_deterministic", _fake_npm)
-- monkeypatch.setattr(main_desktop, "_nixos_build_env", lambda: {})
--
-- main_desktop._install_desktop_workspace_deps("npm", {})
--
-- assert seen == [False], "npm must run only after the stale dir is gone"
-
-
-def test_install_is_skipped_while_manifests_and_electron_are_unchanged(tmp_path, monkeypatch):
- """Root `npm ci` re-reifies the whole graph; only manifest changes or a pruned Electron warrant it. See #43837."""
- import hermes_cli.main_web_build as web_build
- # Electron under the workspace-local hoist, where electronDist points (_electron_dir).
- electron = _desktop_checkout(tmp_path, monkeypatch, electron_dir=tmp_path / "apps" / "desktop" / "node_modules" / "electron")
- calls: list[Path] = []
- monkeypatch.setattr(web_build, "_run_npm_install_deterministic",
- lambda npm, cwd, **kw: calls.append(cwd) or type("R", (), {"returncode": 0})())
-
- main_desktop._install_desktop_workspace_deps("npm", {})
- main_desktop._install_desktop_workspace_deps("npm", {})
- assert calls == [tmp_path], "second build with unchanged manifests must not npm ci again"
-
- shutil.rmtree(electron) # pass 1 pruned Electron → the full install must run even with a matching stamp
- main_desktop._install_desktop_workspace_deps("npm", {})
- assert calls == [tmp_path, tmp_path]
- electron.mkdir(parents=True)
- (electron / "package.json").write_text("{}", encoding="utf-8")
-
- (tmp_path / "apps" / "desktop" / "package.json").write_text('{"name": "bumped"}', encoding="utf-8")
- main_desktop._install_desktop_workspace_deps("npm", {})
- assert calls == [tmp_path] * 3, "a changed manifest must reinstall"
-
-
-def test_failed_reinstall_drops_the_stamp_so_the_next_update_repairs(tmp_path, monkeypatch):
- """The stamp is written on success only; an interrupted full `npm ci` after a code-only update
- must not leave an older matching stamp behind, or the half-installed tree is never revisited."""
- import pytest
-
- import hermes_cli.main_web_build as web_build
- electron = _desktop_checkout(tmp_path, monkeypatch)
- codes = [0, 1, 0]
- monkeypatch.setattr(web_build, "_run_npm_install_deterministic",
- lambda npm, cwd, **kw: type("R", (), {"returncode": codes.pop(0)})())
-
- main_desktop._install_desktop_workspace_deps("npm", {}) # success → stamp
- (electron / "package.json").unlink() # pass 1 pruned Electron → full install needed
- with pytest.raises(SystemExit):
- main_desktop._install_desktop_workspace_deps("npm", {}) # interrupted mid-extract
- (electron / "package.json").write_text("{}", encoding="utf-8") # partially reified tree
-
- main_desktop._install_desktop_workspace_deps("npm", {})
- assert codes == [], "the next update must run the install again, not skip on the stale stamp"
diff --cc tests/hermes_cli/test_gateway.py
index 5d67b5316d1,b5b7cf185bd..c853316783c
--- a/tests/hermes_cli/test_gateway.py
+++ b/tests/hermes_cli/test_gateway.py
@@@ -1297,7 -1322,7 +1297,7 @@@ def test_find_windows_gateway_services_
)
def test_find_windows_gateway_services_ignores_task_scheduler_ancestor(monkeypatch):
"""gateway <- cmd.exe <- svchost.exe(Schedule) <- services.exe: the Task Scheduler host is not the
gateway's supervisor, so a task-launched gateway is a plain process (#97208); the same tree under a
diff --cc tests/hermes_cli/test_gateway_service.py
index 1522ee43825,72798684e26..7932a44fbca
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@@ -1457,16 -1441,43 +1472,46 @@@ class TestSystemUnitHermesHome
assert "[email protected]" in unit_section
assert "user@" not in user_unit
+ def test_installed_unit_keeps_ld_library_path_when_the_shell_lacks_it(self, monkeypatch, tmp_path):
+ """The unit is regenerated and compared on every start/restart/status; a later shell without
+ the export (ssh, cron, sudo) must see the installed unit as current, not "repair" the line away."""
+ unit_path = tmp_path / "hermes-gateway.service"
+ monkeypatch.setattr(gateway_cli, "get_systemd_unit_path", lambda system=False: unit_path)
+ monkeypatch.setenv("LD_LIBRARY_PATH", "/opt/cuda/lib64:/opt/pct%dir/lib")
+ unit_path.write_text(gateway_cli.generate_systemd_unit(system=False), encoding="utf-8")
+ assert 'Environment="LD_LIBRARY_PATH=/opt/cuda/lib64:/opt/pct%%dir/lib"' in unit_path.read_text()
+
+ monkeypatch.delenv("LD_LIBRARY_PATH")
+
+ assert gateway_cli.systemd_unit_is_current(system=False)
+ assert 'LD_LIBRARY_PATH=/opt/cuda/lib64:/opt/pct%%dir/lib' in gateway_cli.generate_systemd_unit(system=False)
+
+ def test_system_unit_remaps_caller_home_ld_library_path_components(self, monkeypatch):
+ """#14613: under sudo the caller's /root/... library dirs are unreadable to the target
+ user, so each colon-separated component is remapped like the PATH entries are."""
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: Path("/root")))
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ monkeypatch.setattr(
+ gateway_cli, "_system_service_identity",
+ lambda run_as_user=None: ("alice", "alice", "/home/alice", 1001),
+ )
+ monkeypatch.setattr(gateway_cli, "_build_service_path_dirs", lambda: [])
+ monkeypatch.setenv("LD_LIBRARY_PATH", "/root/cuda/lib:/opt/cuda/lib64")
+
+ unit = gateway_cli.generate_systemd_unit(system=True, run_as_user="alice")
+
+ assert 'Environment="LD_LIBRARY_PATH=/home/alice/cuda/lib:/opt/cuda/lib64"' in unit
+
- def test_system_unit_uses_target_user_home_not_calling_user(self, monkeypatch):
- # Simulate sudo: Path.home() returns /root, target user is alice
- monkeypatch.setattr(Path, "home", staticmethod(lambda: Path("/root")))
- monkeypatch.delenv("HERMES_HOME", raising=False)
+ def test_system_unit_uses_target_user_home_not_calling_user(self, monkeypatch, tmp_path):
+ caller_home = tmp_path / "root"
+ target_home = tmp_path / "alice"
+ caller_home.mkdir()
+ target_home.mkdir()
+ monkeypatch.setattr(Path, "home", staticmethod(lambda: caller_home))
+ monkeypatch.setenv("HERMES_HOME", str(caller_home / ".hermes"))
monkeypatch.setattr(
gateway_cli, "_system_service_identity",
- lambda run_as_user=None: ("alice", "alice", "/home/alice", 1001),
+ lambda run_as_user=None: ("alice", "alice", str(target_home), 1001),
)
monkeypatch.setattr(
gateway_cli, "_build_user_local_paths",
diff --cc tests/hermes_cli/test_manual_serve_deferral.py
index 218c2e8298a,aea484fff8c..3462bac41b1
--- a/tests/hermes_cli/test_manual_serve_deferral.py
+++ b/tests/hermes_cli/test_manual_serve_deferral.py
@@@ -166,7 -168,7 +168,14 @@@ def test_historical_retention_failure_w
elif failure == "write":
broken.setattr(obligations.json, "dump", fail)
else:
-- broken.setattr(obligations.os, "replace", fail)
++ # Only the obligations file: the receipt itself is written atomically through the
++ # same os.replace and must keep succeeding.
++ original_replace = obligations.os.replace
++ def replace(src, dst, *args, **kwargs):
++ if Path(dst).parent == directory:
++ fail()
++ return original_replace(src, dst, *args, **kwargs)
++ broken.setattr(obligations.os, "replace", replace)
fleet._warn_pending_fleet_restart_on_startup()
warning = capsys.readouterr().err
assert "serve [work] pid 900" in warning
diff --cc tests/hermes_cli/test_serve_runtime_inventory.py
index 5b588a9cf35,9e8bf6f871c..c7d665dd6b6
--- a/tests/hermes_cli/test_serve_runtime_inventory.py
+++ b/tests/hermes_cli/test_serve_runtime_inventory.py
@@@ -4,8 -11,15 +4,11 @@@ from __future__ import annotation
import sys
from types import SimpleNamespace
-from unittest.mock import patch # noqa: F401 - kept for parity with siblings
+ import pytest
-
-import hermes_cli.update_cmd as update_cmd
-import hermes_cli.update_inventory as update_inventory
-from hermes_cli import main as cli_main
-import hermes_cli.main_install_repair as main_install_repair
++from unittest.mock import patch
+ import hermes_cli.main_dashboard as main_dashboard
+import hermes_cli.update_inventory as update_inventory
def _ledger_entry(**over):
@@@ -166,3 -247,43 +169,43 @@@ def test_inventory_records_the_serve_pr
plan = update_inventory.collect_runtime_inventory()
serves = [r for r in plan.runtimes if r.kind == "serve"]
assert serves and serves[0].detail["create_time"] == 1712345678.5
+
+
+ # ---------------------------------------------------------------------------
+ # update_inventory: launchd-owned serve/dashboard classification (#116503)
+ # ---------------------------------------------------------------------------
+
+ def test_inventory_classifies_launchd_job_owned_serve(monkeypatch):
+ """A KeepAlive LaunchAgent backend's recorded spawner (the bootstrap shell) is long dead,
+ so the spawner probe alone reads manual-serve — and the update plan then restarts it as a
+ detached argv respawn that fights the job's own KeepAlive respawn. A loaded job whose
+ ProgramArguments match the ledger argv must classify the row launchd (kickstart restart)."""
+ entry = _ledger_entry(spawner_pid=999, spawner_create=1.0)
+ fake_pi = SimpleNamespace(
+ ledger_entries=lambda **k: [entry],
+ spawner_is_dead=lambda e: True, # bootstrap shell provably gone
+ )
+ jobs = [("gui/501", "ai.hermes.dashboard",
+ ["hermes", "serve", "--host", "100.94.65.93", "--port", "9119"], None)]
+ monkeypatch.setitem(sys.modules, "hermes_cli.process_identity", fake_pi)
+ with patch.object(main_dashboard, "_loaded_launchd_backend_jobs", return_value=jobs), \
+ patch("hermes_cli.dashboard_procs._process_ancestors", return_value=[]):
+ plan = update_inventory.collect_runtime_inventory()
+ serves = [r for r in plan.runtimes if r.kind == "serve"]
+ assert serves, "launchd-owned serve must appear in the inventory"
+ row = serves[0]
+ assert row.supervisor == "launchd"
+ assert row.restart_via == "launchd"
+ assert row.detail["launchd_domain"] == "gui/501"
+ assert row.detail["launchd_label"] == "ai.hermes.dashboard"
+
+
+ def test_stale_serve_warning_names_the_launchd_kickstart_command(capsys):
+ """#116503: a launchd-owned survivor gets the launchctl kickstart hint, not only the
+ manual relaunch advice (a KeepAlive job fights a hand relaunch)."""
+ from hermes_cli import update_abort_recovery
+
+ update_abort_recovery._warn_stale_serve_runtimes(
+ [{"pid": 4321, "kind": "dashboard", "profile": "default", "supervisor": "launchd"}])
+ assert "launchctl kickstart -k gui/$UID/<label>" in capsys.readouterr().out
diff --cc tests/hermes_cli/test_update_autostash.py
index 4cdb0f55637,8d48a6d12df..0848ee42749
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@@ -1,6 -1,6 +1,7 @@@
+"""Real Git local-work safety: caller divergence, restore faults and rescue retention."""
++import contextlib
from pathlib import Path
-from subprocess import CalledProcessError
-from types import SimpleNamespace
+import subprocess
from unittest.mock import patch
import pytest
@@@ -230,6 -691,6 +231,7 @@@ def test_update_autostash_survives_unde
"""Behavioral E2E of the whole permission-denied class with real git:
root-owned-style undeletable untracked dir → stash succeeds, update-style
reset works, restore round-trips, nothing lost. (#70127 follow-up)"""
++ import contextlib
import os
import shutil
import subprocess
@@@ -384,3 -1274,113 +386,159 @@@ def test_prune_orphan_rescue_refs_with_
# And gc can now reclaim the snapshot's objects.
git("gc", "-q", "--prune=now")
assert git("cat-file", "-e", snap_sha, check=False).returncode != 0
+
+
-# ---------------------------------------------------------------------------
-# Autostash disposition must be visible in the update receipt (#115363): an
-# unattended update whose restore hits conflicts parks the stash and reports
-# success — the receipt is the only channel an operator reads.
-# ---------------------------------------------------------------------------
++def test_autostash_survives_intent_to_add_entries(tmp_path):
++ """An index entry from `git add -N` must not block the update autostash.
++
++ Reported: `hermes update` aborted with "Entry 'tests/...' not uptodate. Cannot merge." because
++ `git add -N` records a path with the empty blob and zeroed stat data, which `git stash push`
++ refuses outright. Editors that show new files in diffs leave exactly that state behind, and the
++ update must not require the user to repair their index by hand.
++ """
++ import subprocess
++
++ def git(*args, check=True):
++ return subprocess.run(
++ ["git", *args], cwd=tmp_path, capture_output=True, text=True, check=check
++ )
++
++ git("init", "-q", "-b", "main")
++ git("config", "user.email", "[email protected]")
++ git("config", "user.name", "t")
++ (tmp_path / "tracked.txt").write_text("v1\n", encoding="utf-8")
++ git("add", "-A")
++ git("commit", "-qm", "init")
++
++ # The reported shape: a new local file recorded with `git add -N`, alongside a normal edit.
++ (tmp_path / "tracked.txt").write_text("v2 local\n", encoding="utf-8")
++ local_test = tmp_path / "tests" / "test_live_custom_provider_poll.py"
++ local_test.parent.mkdir()
++ body = "def test_poll():\n assert True\n"
++ local_test.write_text(body, encoding="utf-8")
++ git("add", "-N", "tests/test_live_custom_provider_poll.py")
++ # Precondition: git reports it as " A" (present in the worktree, absent from the index) - the
++ # intent-to-add shape that `git stash push` refuses.
++ assert " A tests/test_live_custom_provider_poll.py" in git("status", "--porcelain").stdout.splitlines()
++
++ stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
++
++ assert stash_ref, "the update must be able to stash an intent-to-add entry"
++ # The stash must have taken everything, so the pull cannot be blocked by a dirty tree.
++ assert git("status", "--porcelain").stdout == ""
++ assert hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)
++ assert local_test.read_text(encoding="utf-8") == body
++ assert (tmp_path / "tracked.txt").read_text(encoding="utf-8") == "v2 local\n"
+
+
+ class _ReceiptProbe:
- """Minimal stand-in for the active update receipt: records steps."""
++ """Minimal stand-in for the active update receipt: records steps.
++
++ ``record_step`` clones the active receipt before mutating it (copy-on-write per context),
++ so the steps list is shared by reference for the probe to observe.
++ """
+
+ def __init__(self):
+ self.steps = []
++ self.data = {} # copied per record; ``steps`` is shared by reference
+
+ def step(self, name, ok, detail=""):
+ self.steps.append({"name": name, "ok": ok, "detail": detail})
+
+
++def _active_receipt(probe):
++ from hermes_cli import update_receipt
++
++ token = update_receipt._current.set(probe)
++ try:
++ yield
++ finally:
++ update_receipt._current.reset(token)
++
++
+ def test_conflicted_restore_records_parked_step_in_receipt(monkeypatch, tmp_path):
+ import subprocess
+ from hermes_cli import update_receipt
+
+ def git(*args, check=True):
+ return subprocess.run(["git", *args], cwd=tmp_path, capture_output=True, text=True, check=check)
+
+ git("init", "-q", "-b", "main")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ source = tmp_path / "tools" / "terminal_tool.py"
+ source.parent.mkdir()
+ source.write_text("VALUE = 1\n", encoding="utf-8")
+ git("add", "-A")
+ git("commit", "-qm", "init")
+
+ # Local edit whose restore will conflict with the pulled change.
+ source.write_text("VALUE = 2\n", encoding="utf-8")
+ stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
+ assert stash_ref
+ # Simulate the pull moving the same lines: the stash apply now conflicts.
+ git("checkout", "HEAD")
+ source.write_text("VALUE = 3\n", encoding="utf-8")
+ git("add", "-A")
+ git("commit", "-qm", "pulled change")
+
+ probe = _ReceiptProbe()
- monkeypatch.setattr(update_receipt, "_current", probe, raising=False)
-
- restored = hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)
++ with _active_receipt(probe):
++ restored = hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)
+
+ assert restored is False
+ disposition = [s for s in probe.steps if s["name"] == "local_changes_stash"]
+ assert len(disposition) == 1
+ assert disposition[0]["ok"] is False
+ assert "parked" in disposition[0]["detail"]
+ assert stash_ref in disposition[0]["detail"]
+ assert git("stash", "list").stdout.strip(), "stash must survive for manual recovery"
+
+
+ def test_clean_restore_records_restored_step_in_receipt(monkeypatch, tmp_path):
+ import subprocess
+ from hermes_cli import update_receipt
+
+ def git(*args, check=True):
+ return subprocess.run(["git", *args], cwd=tmp_path, capture_output=True, text=True, check=check)
+
+ git("init", "-q", "-b", "main")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ source = tmp_path / "tools" / "terminal_tool.py"
+ source.parent.mkdir()
+ source.write_text("VALUE = 1\n", encoding="utf-8")
+ git("add", "-A")
+ git("commit", "-qm", "init")
+
+ source.write_text("VALUE = 2\n", encoding="utf-8")
+ stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)
+ assert stash_ref
+
+ probe = _ReceiptProbe()
- monkeypatch.setattr(update_receipt, "_current", probe, raising=False)
-
- restored = hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)
++ with _active_receipt(probe):
++ restored = hermes_main._restore_stashed_changes(["git"], tmp_path, stash_ref, prompt_user=False)
+
+ assert restored is True
+ disposition = [s for s in probe.steps if s["name"] == "local_changes_stash"]
+ assert len(disposition) == 1
+ assert disposition[0]["ok"] is True
+ assert "restored" in disposition[0]["detail"]
+ assert stash_ref in disposition[0]["detail"]
+
+
+ def test_keep_stash_park_records_parked_step_in_receipt(capsys):
+ probe = _ReceiptProbe()
+ import hermes_cli.update_cmd_stash as stash_mod
+ from hermes_cli import update_receipt
+
- original = update_receipt._current
- update_receipt._current = probe
- try:
++ with _active_receipt(probe):
+ stash_mod._park_stashed_changes("deadbeefcafe")
- finally:
- update_receipt._current = original
+
+ out = capsys.readouterr().out
+ assert "--keep-stash" in out
+ disposition = [s for s in probe.steps if s["name"] == "local_changes_stash"]
+ assert len(disposition) == 1
+ assert disposition[0]["ok"] is False
+ assert "parked" in disposition[0]["detail"]
diff --cc tests/hermes_cli/test_update_fleet_restart_pending.py
index 964f20ff73b,b760a04a6d0..87a6c4dcb2a
--- a/tests/hermes_cli/test_update_fleet_restart_pending.py
+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py
@@@ -29,12 -29,34 +29,32 @@@ import hermes_cli.update_cmd_fleet as u
from hermes_cli.update_receipt import COMMAND_BOUNDARY_STOP_REASON
from hermes_constants import get_hermes_home
+pytestmark = pytest.mark.usefixtures("isolated_source_completion")
-def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
- """Simulate git commands where HEAD advances from pre_sha to post_sha."""
- calls = {"n": 0}
+
++def _make_up_to_date_side_effect(sha="abc123"):
++ """Simulate git commands where origin is already at HEAD."""
+
+ def side_effect(cmd, **kwargs):
+ joined = " ".join(str(c) for c in cmd)
+
+ if "rev-parse" in joined and "--abbrev-ref" in joined:
+ return SimpleNamespace(returncode=0, stdout="main\n", stderr="")
+
+ if "rev-list" in joined:
- return SimpleNamespace(returncode=0, stdout="3\n", stderr="")
++ return SimpleNamespace(returncode=0, stdout="0\n", stderr="")
+
+ if joined.endswith("rev-parse HEAD"):
- if calls["n"] == 0:
- calls["n"] += 1
- return SimpleNamespace(returncode=0, stdout=f"{pre_sha}\n", stderr="")
- return SimpleNamespace(returncode=0, stdout=f"{post_sha}\n", stderr="")
++ return SimpleNamespace(returncode=0, stdout=f"{sha}\n", stderr="")
+
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ return side_effect
+
+
-def _make_up_to_date_side_effect(sha="abc123"):
- """Simulate git commands where origin is already at HEAD."""
+def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
+ """Simulate git commands where HEAD advances from pre_sha to post_sha."""
+ calls = {"n": 0}
def side_effect(cmd, **kwargs):
joined = " ".join(str(c) for c in cmd)
diff --cc tests/hermes_cli/test_update_scoped_reconciliation.py
index cd6aab320ae,87078da6507..6aee6f62c08
--- a/tests/hermes_cli/test_update_scoped_reconciliation.py
+++ b/tests/hermes_cli/test_update_scoped_reconciliation.py
@@@ -63,25 -64,264 +63,59 @@@ def test_scoped_reconciliation_matrix(m
assert target.read_bytes() == before
- @pytest.mark.parametrize("suffix", ["inventory=not-json", "expected_sha=", "inventory={}", "stray=1"])
[email protected]("alive", [True, False, None], ids=["alive", "dead", "unknown"])
[email protected]("sha", ["old", "new", None], ids=["different-sha", "same-sha", "no-sha"])
-def test_empty_marker_never_inherits_receipt_ownership(monkeypatch, capsys, alive, sha):
- old = {"outcome": "success", "plan": {"runtimes": [MANUAL]}, "post_update": {"sha": sha}}
- target = seed(monkeypatch, old, "new", [], alive)
- before = target.read_bytes()
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" in warning
- assert ("serve [work] pid 900" in warning) is (alive is not False)
- assert fleet._fleet_restart_pending_marker_path().exists()
- assert target.read_bytes() == before
-
-
[email protected]("consumer", ["predicate", "startup"])
-def test_reconciliation_uses_one_receipt_snapshot(monkeypatch, capsys, consumer):
- old = {"outcome": "partial", "plan": {"runtimes": [MANUAL]}, "fleet": []}
- seed(monkeypatch, old, None, [])
- reads = []
-
- def read_rotating_receipt():
- reads.append(True)
- return old if len(reads) == 1 else {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
-
- monkeypatch.setattr(update_receipt, "read_latest_receipt", read_rotating_receipt)
- if consumer == "predicate":
- assert not fleet._pending_fleet_restart_needed()
- else:
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" not in warning
- assert "serve [work] pid 900" in warning
- assert len(reads) == 1
- assert list((get_hermes_home() / "serve_restart_pending").glob("*.json"))
-
-
[email protected]("marker", [None, "new"])
[email protected]("blocked_storage", [False, True])
-def test_probe_exception_does_not_hide_manual_warning(monkeypatch, capsys, marker, blocked_storage):
- old = {"outcome": "partial", "plan": {"runtimes": [GATEWAY, MANUAL]}}
- target = seed(monkeypatch, old, marker, [])
- if marker is not None:
- fleet._write_fleet_restart_pending_marker(expected_sha=marker, runtimes=[GATEWAY])
- before = target.read_bytes()
- if blocked_storage:
- (get_hermes_home() / "serve_restart_pending").write_text("not a directory")
-
- def unavailable(**kwargs):
- raise OSError("gateway probe unavailable")
-
- monkeypatch.setattr(update_receipt, "collect_fleet_versions", unavailable)
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" in warning
- assert "serve [work] pid 900" in warning
- assert ("could not be saved" in warning) is blocked_storage
- assert target.read_bytes() == before
-
-
[email protected]("completed_restart", [False, True])
-def test_new_marker_cannot_borrow_old_alpha_receipt(monkeypatch, capsys, completed_restart):
- """N owns alpha; N+1 owns alpha and beta but dies before writing its receipt."""
- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
- if completed_restart:
- old.update(post_update={"sha": "new"}, gateway_restart={"incomplete": False})
- live = [CURRENT]
- target = seed(monkeypatch, old, "new", live)
[email protected]("suffix", ["inventory=not-json", "expected_sha=", "inventory={}", 'inventory=null\ninventory={"version":1,"runtimes":[]}', "broken-line"])
+def test_malformed_marker_stays_pending(monkeypatch, suffix):
+ seed(monkeypatch, {}, "new", [CURRENT])
marker = fleet._fleet_restart_pending_marker_path()
with marker.open("a") as stream:
- stream.write("inventory=" + json.dumps({"version": 1, "runtimes": [GATEWAY, dict(GATEWAY, profile="beta")]}) + "\n")
- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()
- fleet._warn_pending_fleet_restart_on_startup()
- assert "hermes gateway restart" in capsys.readouterr().err
+ stream.write(suffix + "\n")
assert fleet._pending_fleet_restart_needed()
- fleet._apply_pending_fleet_restart_catchup(defer=True)
- assert "fleet restart deferred" in capsys.readouterr().out
- assert marker.read_bytes() == marker_before
- assert target.read_bytes() == receipt_before
- live.append(dict(CURRENT, profile="beta"))
- assert not fleet._pending_fleet_restart_needed()
- assert not marker.exists()
- assert target.read_bytes() == receipt_before
+ assert marker.exists()
+
+
+def test_marker_reconciliation_collects_one_live_snapshot(monkeypatch):
+ seed(monkeypatch, {}, "new", [CURRENT])
+ fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY])
+ probes = []
+ def collect(**kwargs):
+ probes.append(True)
+ return [CURRENT] if len(probes) == 1 else []
+ monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)
+ assert not fleet._pending_fleet_restart_needed()
+ assert len(probes) == 1
+ @pytest.mark.parametrize("completed_restart", [False, True])
+ def test_legacy_marker_discharges_on_live_fleet_evidence_without_receipt(monkeypatch, capsys, completed_restart):
+ """An inventory-less N+1 marker settles on live-fleet evidence alone (#115638).
+
+ It never borrows the old receipt's ownership: the receipt is left intact and the
+ marker discharges only because every live row is current at its expected SHA.
+ """
+ old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
+ if completed_restart:
+ old.update(post_update={"sha": "new"}, gateway_restart={"incomplete": False})
+ live = [CURRENT]
+ target = seed(monkeypatch, old, "new", live)
+ marker = fleet._fleet_restart_pending_marker_path()
+ receipt_before = target.read_bytes()
+ fleet._warn_pending_fleet_restart_on_startup()
+ assert "hermes gateway restart" not in capsys.readouterr().err
+ assert not fleet._pending_fleet_restart_needed()
+ assert not marker.exists()
+ assert target.read_bytes() == receipt_before
+
+
+ @pytest.mark.parametrize("live,pending", [([CURRENT], False), ([dict(CURRENT, state="stale", code_sha="old")], True), ([], True)], ids=["fleet-current", "fleet-stale", "fleet-empty"])
+ def test_inventory_less_marker_settles_after_out_of_band_pull(monkeypatch, capsys, live, pending):
+ """An inventory-less marker left behind by an old update survives every later out-of-band
+ ``git pull`` (#115638): nothing rewrites it, and its ``expected_sha`` is never HEAD again.
+ It records no owed set, so a fleet that is current on the checkout is the whole of the
+ evidence the warning can be about — a stale or absent fleet still keeps it.
+ """
+ seed(monkeypatch, {}, "old", live)
+ marker = fleet._fleet_restart_pending_marker_path()
+ fleet._warn_pending_fleet_restart_on_startup()
+ assert ("hermes gateway restart" in capsys.readouterr().err) is pending
+ assert fleet._pending_fleet_restart_needed() is pending
+ assert marker.exists() is pending
-
-
-# Explicit `inventory=null` records no obligation either, so it settles on live-fleet
-# evidence like a missing line (#115638), and an explicit empty inventory owes nothing
-# (#115311); the variants below stay fail-closed.
[email protected]("inventory", [{}, [], {"version": 2, "runtimes": [GATEWAY]}, {"version": 1, "runtimes": [GATEWAY, dict(MANUAL, detail={})]}, {"version": 1, "runtimes": [None]}, {"version": 1, "runtimes": [{"kind": "gateway", "profile": "unknown"}]}, {"version": 1, "runtimes": [{"kind": "gateway", "profile": []}]}])
-def test_unverified_marker_inventory_stays_pending(monkeypatch, inventory):
- seed(monkeypatch, {"outcome": "success", "plan": {"runtimes": [GATEWAY]}}, "new", [CURRENT])
- marker = fleet._fleet_restart_pending_marker_path()
- with marker.open("a") as stream:
- stream.write("inventory=" + json.dumps(inventory) + "\n")
- before = marker.read_bytes()
- assert fleet._pending_fleet_restart_needed()
- monkeypatch.setattr("hermes_cli.update_cmd._run_pending_fleet_restart", lambda: True)
- with pytest.raises(SystemExit) as exc:
- fleet._apply_pending_fleet_restart_catchup()
- assert exc.value.code == 1
- assert marker.read_bytes() == before
-
-
[email protected]("suffix", ['inventory={', 'inventory=null\ninventory={"version":1,"runtimes":[]}', 'broken-line'])
-def test_malformed_marker_stays_pending(monkeypatch, suffix):
- seed(monkeypatch, {}, "new", [CURRENT])
- marker = fleet._fleet_restart_pending_marker_path()
- with marker.open("a") as stream:
- stream.write(suffix + "\n")
- assert fleet._pending_fleet_restart_needed()
- assert marker.exists()
-
-
-def test_pulled_update_marker_owns_pre_update_inventory(monkeypatch):
- from types import SimpleNamespace
- from hermes_cli import update_cmd
- from hermes_cli.update_inventory import RuntimeRecord, UpdatePlan
-
- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
- target = seed(monkeypatch, old, None, [CURRENT])
- before = target.read_bytes()
- plan = UpdatePlan(runtimes=[RuntimeRecord(kind="gateway", profile=p) for p in ("alpha", "beta")])
- monkeypatch.setattr(update_cmd, "_invalidate_update_cache", lambda: None)
- monkeypatch.setattr(update_cmd, "_verify_head_after_pull", lambda *a, **k: "new")
-
- def interrupt(*args):
- raise KeyboardInterrupt
-
- monkeypatch.setattr(update_cmd, "_sweep_bytecode_after_update", interrupt)
- with pytest.raises(KeyboardInterrupt):
- update_cmd._apply_pulled_update([], "main", "old", SimpleNamespace(in_place_update=True), None, gateway_mode=False, is_fork=False, desktop_dir=None, had_desktop_app_before_update=False, pre_update_snapshot_id=None, _pre_update_plan=plan, _windows_gateway_resume=None, args=SimpleNamespace())
- marker = fleet._fleet_restart_pending_marker_path()
- fields = dict(line.split("=", 1) for line in marker.read_text().splitlines())
- assert fields["expected_sha"] == "new"
- assert json.loads(fields["inventory"]) == {"version": 1, "runtimes": plan.to_dict()["runtimes"]}
- assert fleet._pending_fleet_restart_needed()
- assert target.read_bytes() == before
-
-
[email protected]("successor", ["missing", "stale", "unknown", "probe-error", "current"])
-def test_catchup_verifies_owned_fleet_after_restart(monkeypatch, successor):
- from hermes_cli import update_cmd
-
- old = {"outcome": "failed", "plan": {"runtimes": [GATEWAY]}}
- live = [CURRENT]
- target = seed(monkeypatch, old, "new", live)
- fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY, dict(GATEWAY, profile="beta")])
- marker = fleet._fleet_restart_pending_marker_path()
- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()
- restarted = []
-
- def restart():
- restarted.append("alpha")
- live[:] = [CURRENT]
- if successor not in ("missing", "probe-error"):
- live.append(dict(CURRENT, profile="beta", state=successor, code_sha="old" if successor == "stale" else "new"))
- return True
-
- def collect(**kwargs):
- if restarted and successor == "probe-error":
- raise OSError("fleet unavailable")
- return live
-
- monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", restart)
- monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)
- if successor == "current":
- fleet._apply_pending_fleet_restart_catchup()
- assert not marker.exists()
- else:
- with pytest.raises(SystemExit) as exc:
- fleet._apply_pending_fleet_restart_catchup()
- assert exc.value.code == 1
- assert marker.read_bytes() == marker_before
- live[:] = [CURRENT, dict(CURRENT, profile="beta")]
- monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **k: live)
- fleet._apply_pending_fleet_restart_catchup()
- assert not marker.exists()
- assert restarted == ["alpha"]
- assert target.read_bytes() == receipt_before
-
-
[email protected]("blocked_storage", [False, True])
-def test_verified_restart_surviving_marker_preserves_manual_debt(monkeypatch, capsys, blocked_storage):
- from hermes_cli import update_cmd
-
- manual = [MANUAL, dict(MANUAL, pid=901)]
- old = {"outcome": "partial", "post_update": {"sha": "new"}, "gateway_restart": {"incomplete": False, "phase_error": ""}, "plan": {"runtimes": [GATEWAY, *manual]}, "fleet": [CURRENT]}
- target = seed(monkeypatch, old, "new", [CURRENT])
- fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY, *manual])
- marker = fleet._fleet_restart_pending_marker_path()
- receipt_before, marker_before = target.read_bytes(), marker.read_bytes()
- directory = get_hermes_home() / "serve_restart_pending"
- if blocked_storage:
- directory.write_text("not a directory")
- restarted = []
- monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", lambda: restarted.append(True) or True)
- if blocked_storage:
- with pytest.raises(SystemExit) as exc:
- fleet._apply_pending_fleet_restart_catchup()
- assert exc.value.code == 1
- assert marker.read_bytes() == marker_before
- directory.unlink()
- restarted.clear()
- fleet._apply_pending_fleet_restart_catchup()
- assert not restarted
- assert not marker.exists()
- assert {json.loads(path.read_text())["pid"] for path in directory.glob("*.json")} == {900, 901}
- fleet._warn_pending_fleet_restart_on_startup()
- warning = capsys.readouterr().err
- assert "hermes gateway restart" not in warning
- assert "pid 900" in warning and "pid 901" in warning
- assert target.read_bytes() == receipt_before
-
-
-def test_marker_reconciliation_collects_one_live_snapshot(monkeypatch):
- seed(monkeypatch, {}, "new", [CURRENT])
- fleet._write_fleet_restart_pending_marker(expected_sha="new", runtimes=[GATEWAY])
- probes = []
-
- def collect(**kwargs):
- probes.append(True)
- return [CURRENT] if len(probes) == 1 else []
-
- monkeypatch.setattr(update_receipt, "collect_fleet_versions", collect)
- assert not fleet._pending_fleet_restart_needed()
- assert len(probes) == 1
diff --cc tests/hermes_state/test_deleted_wal_generation_guard.py
index 1536a533085,d6731cb7dc5..ec855404530
--- a/tests/hermes_state/test_deleted_wal_generation_guard.py
+++ b/tests/hermes_state/test_deleted_wal_generation_guard.py
@@@ -112,6 -112,56 +112,56 @@@ def test_iter_finds_self_after_wal_unli
db.close()
+ def test_second_sessiondb_open_refuses_through_symlinked_home(tmp_path, force_wal):
+ """Regression for #116450. End to end through the real open path: SessionDB stores the
+ alias verbatim and calls the guard with it before connect, so the refusal must fire via the
+ alias — /proc reports the kernel-resolved dentry while the caller holds only the symlink."""
+ real_home = tmp_path / "hermes-real"
+ real_home.mkdir()
+ link_home = tmp_path / "hermes-link"
+ link_home.symlink_to(real_home)
+ alias_db = link_home / "state.db"
+
+ writer = make_db(alias_db, "s", "held")
+ require_wal(writer)
+ lose_sidecars(alias_db, rename=False)
+ try:
+ with pytest.raises(DeletedWalGenerationError, match="deleted state.db-wal"):
+ SessionDB(db_path=alias_db)
+ assert not Path(os.fspath(alias_db) + "-wal").exists()
+ finally:
+ writer.close()
+
+
+ def test_iter_finds_holder_when_db_file_itself_is_symlink(tmp_path):
+ """SQLite canonicalizes the db filename before naming sidecars, so a symlinked
+ state.db puts the WAL under the target's name. The scan must still match."""
+ db_dir = tmp_path / "dbdir"
+ db_dir.mkdir()
+ target_dir = tmp_path / "targetdir"
+ target_dir.mkdir()
+ link_db = db_dir / "state.db"
+ link_db.symlink_to(target_dir / "x.db")
+
+ conn = sqlite3.connect(os.fspath(link_db))
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("CREATE TABLE t(x)")
+ conn.execute("INSERT INTO t VALUES (1)")
+ conn.commit()
+ target_wal = target_dir / "x.db-wal"
+ if not target_wal.exists():
+ conn.close()
+ pytest.skip("this SQLite did not canonicalize the symlinked db path")
+ target_wal.unlink()
+ try:
+ holders = iter_deleted_sqlite_sidecar_holders(link_db)
+ assert holders, "deleted WAL under the resolved target name must be found"
+ finally:
+ conn.close()
+
+
@pytest.mark.skipif(
not sys.platform.startswith("linux"),
reason="deleted-WAL /proc scan is Linux-only",
diff --cc tests/home_io_guard.py
index 9a82b0b5003,00000000000..daebdb8f32c
mode 100644,000000..100644
--- a/tests/home_io_guard.py
+++ b/tests/home_io_guard.py
@@@ -1,102 -1,0 +1,107 @@@
+"""Guard Python filesystem calls in tests, not arbitrary native/subprocess I/O."""
+from __future__ import annotations
+
+import builtins
+from functools import wraps
+import io
+import os
+from pathlib import Path
+import shutil
+import sqlite3
+import threading
+
+
+class HomeIOGuard:
+ def __init__(self, roots):
+ self.roots = roots
+ self.checking = threading.local()
+ self.directories: dict[int, Path] = {}
+
+ def check(self, value, *, dir_fd=None, metadata=False):
+ if value is None or isinstance(value, int) or getattr(self.checking, "active", False):
+ return
+ self.checking.active = True
+ try:
+ candidate = Path(os.fsdecode(value)).expanduser()
+ if dir_fd is not None and not candidate.is_absolute():
+ parent = self.directories.get(dir_fd)
+ if parent is None:
+ raise AssertionError("TEST BUG: untracked dir_fd in guarded filesystem I/O")
+ candidate = parent / candidate
+ absolute = Path(os.path.abspath(candidate))
++ # /proc/<pid>/fd/N is descriptor inspection (deleted-WAL holder scans stat the magic
++ # link to compare inode identity); resolving it names whatever file that fd holds,
++ # which is not I/O against the home.
++ if metadata and absolute.is_relative_to("/proc"):
++ return
+ roots = self.roots()
+ # Resolving the root itself (get_default_hermes_root's relative_to
+ # probe) reads no state; only its contents are guarded.
+ if metadata and absolute in roots:
+ return
+ # Check the lexical path first: resolving must not probe a protected
+ # tree merely to decide that the original path was forbidden.
+ if any(absolute.is_relative_to(root) for root in roots):
+ self.refuse(value)
+ resolved = absolute.resolve()
+ if metadata and resolved in roots:
+ return
+ if any(resolved.is_relative_to(root) for root in roots):
+ self.refuse(value)
+ finally:
+ self.checking.active = False
+
+ @staticmethod
+ def refuse(value):
+ raise AssertionError(
+ f"TEST BUG: file I/O against the REAL hermes home: {value}\n"
+ "Use the isolated HERMES_HOME or a temporary fixture instead."
+ )
+
+ def install(self, monkeypatch):
+ def wrap(module, name, parameters, *, metadata=False):
+ original = getattr(module, name)
+
+ @wraps(original)
+ def guarded(*args, **kwargs):
+ for index, (parameter, descriptor) in enumerate(parameters):
+ value = args[index] if index < len(args) else kwargs.get(parameter)
+ self.check(value, dir_fd=kwargs.get(descriptor) if descriptor else None, metadata=metadata)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(module, name, guarded)
+
+ for module in (builtins, io):
+ wrap(module, "open", (("file", None),))
+ for name in ("mkdir", "unlink", "remove", "rmdir", "chmod", "utime"):
+ wrap(os, name, (("path", "dir_fd"),))
+ for name in ("stat", "lstat", "readlink", "access"):
+ wrap(os, name, (("path", "dir_fd"),), metadata=True)
+ for name in ("makedirs", "listdir", "scandir"):
+ wrap(os, name, (("name" if name == "makedirs" else "path", None),))
+ for name in ("rename", "replace"):
+ wrap(os, name, (("src", "src_dir_fd"), ("dst", "dst_dir_fd")))
+ wrap(shutil, "rmtree", (("path", "dir_fd"),))
+ wrap(sqlite3, "connect", (("database", None),))
+
+ original_open, original_close = os.open, os.close
+
+ @wraps(original_open)
+ def guarded_open(path, flags, *args, **kwargs):
+ self.check(path, dir_fd=kwargs.get("dir_fd"))
+ fd = original_open(path, flags, *args, **kwargs)
+ candidate = Path(os.fsdecode(path))
+ if kwargs.get("dir_fd") is not None and not candidate.is_absolute():
+ candidate = self.directories[kwargs["dir_fd"]] / candidate
+ self.directories[fd] = candidate.absolute()
+ return fd
+
+ @wraps(original_close)
+ def guarded_close(fd):
+ # Forget the old owner before close releases the number for reuse
+ # by another thread's open; afterwards we could erase its mapping.
+ self.directories.pop(fd, None)
+ return original_close(fd)
+
+ monkeypatch.setattr(os, "open", guarded_open)
+ monkeypatch.setattr(os, "close", guarded_close)
diff --cc tests/tools/test_bot_relay_windows_paths.py
index a60461f4c03,8592afcbfb0..aa0086e687f
--- a/tests/tools/test_bot_relay_windows_paths.py
+++ b/tests/tools/test_bot_relay_windows_paths.py
@@@ -25,72 -22,26 +22,28 @@@ Two failures on a Windows desktop insta
import shlex
from pathlib import Path
+ import pytest
+
import tools.bot_mode_dm as bot_mode_dm
import tools.bot_relay as bot_relay
+import pytest
ENV = {"id": "d" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}
- def _waiter_code(root, env=None) -> str:
- cmd = bot_relay.waiter_command(root, env or ENV)
- parts = shlex.split(cmd)
- return parts[parts.index("-c") + 1]
-
+ def test_waiter_argv_uses_forward_slashes_on_windows():
+ """On native Windows the reply path rides as a forward-slash argv element, like the delivery
+ runner's paths: Git Bash runs those, and parses a backslash path as a command name."""
+ parts = shlex.split(bot_relay.waiter_command("C:\\Users\\joshu\\.hermes", ENV))
- def test_waiter_windows_path_compiles_after_backslash_folding():
- """A Windows reply path must survive the execution layer folding the
- repr-escaped double backslash back to a single one — the exact shape
- that SyntaxErrored with ``\\U`` on #93590's reporter setup."""
- code = _waiter_code("C:\\Users\\joshu\\.hermes")
- assert "C:" in code # sanity: the Windows path made it into the payload
- folded = code.replace("\\\\", "\\")
- # Raw literals: `p = r'C:\Users\joshu\...'` — no unicode-escape crash.
- compile(folded, "<waiter>", "exec")
-
-
- @pytest.mark.platforms("linux")
- def test_waiter_posix_path_and_label_values_roundtrip():
- """On POSIX (backslash-free paths) the raw prefix changes nothing."""
- root = Path("/tmp/hermes-home")
- code = _waiter_code(root)
- assigns = {
- t.targets[0].id: t.value
- for t in ast.parse(code).body
- if isinstance(t, ast.Assign) and isinstance(t.targets[0], ast.Name)
- }
- expected = str(root / "bot_relay" / "replies" / f"{ENV['id']}.json")
- assert assigns["p"].value == expected
- assert assigns["label"].value == "@researcher on ssh-vps"
- # The literals are raw-prefixed in the generated source.
- assert "\np = r'" in code
- assert "\nlabel = r'" in code
-
-
- def test_waiter_raw_prefix_keeps_injection_defense():
- """Hostile roster fields must stay data under the raw prefix too."""
- inj = {
- "id": "e" * 32,
- "target_handle": "researcher",
- "target_connection": "x'); __import__('sys').exit(2); print('x",
- }
- code = _waiter_code(Path("/tmp/hermes-home"), inj)
- compile(code, "<waiter>", "exec")
- calls = [
- n.func.id
- for n in ast.walk(ast.parse(code))
- if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
- ]
- # The generated waiter only calls str/print/compile-free builtins by
- # name; the payload's __import__ must remain a string literal, not a
- # live call — parse it back and confirm it stayed data.
- assert "__import__" not in calls
- assert "x'); __import__('sys').exit(2); print('x" in code
+ assert "-c" not in parts and "--wait-reply" in parts
+ assert parts[parts.index("--wait-reply") + 1] == f"C:/Users/joshu/.hermes/bot_relay/replies/{ENV['id']}.json"
+ assert not any("\\" in part for part in parts)
def test_local_delivery_resolves_sibling_hermes(tmp_path, monkeypatch):
bin_dir = tmp_path / "venv" / "bin"
bin_dir.mkdir(parents=True)
diff --cc tests/tools/test_drain_fd_windows.py
index 690d29c986e,690d29c986e..a53b757e247
--- a/tests/tools/test_drain_fd_windows.py
+++ b/tests/tools/test_drain_fd_windows.py
@@@ -16,7 -16,7 +16,7 @@@ import pytes
from tools.environments.base_output import _BoundedOutputCollector, _drain_fd_windows
def test_drain_fd_windows_returns_promptly_when_writer_remains_open():
"""Data already in the pipe is captured; the drain stops shortly after the
process reports exit even though the write end is still open."""
@@@ -40,7 -40,7 +40,7 @@@
os.close(w)
def test_local_environment_returns_while_background_grandchild_holds_pipe(tmp_path):
"""End-to-end on Git Bash: ``execute()`` returns promptly with the marker while a
backgrounded grandchild still holds the stdout pipe (issues #105865 / #67362)."""
diff --cc tests/tui_gateway/test_config_profile_scope.py
index 41f89849f87,1325eb8b6a4..b31078cad88
--- a/tests/tui_gateway/test_config_profile_scope.py
+++ b/tests/tui_gateway/test_config_profile_scope.py
@@@ -10,9 -10,10 +10,10 @@@ from __future__ import annotation
from pathlib import Path
-import yaml
+import hermes_yaml as yaml
import tui_gateway.server as server
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
LAUNCH_CWD = "/workspace/default"
diff --cc tools/bot_mode_dm.py
index d4e84ed018f,4a761678cc0..68de9869c01
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@@ -730,8 -729,41 +730,41 @@@ def _persist_reply_when_done(proc_id: s
return True
+ def _wait_reply_main(reply_path: str, label: str, budget_seconds: str) -> int:
+ """The relay reply waiter (``tools/bot_relay.waiter_command``): block until the sender-side
+ reply file exists, print it as the completion notification the sender wakes on, exit 1 on a
+ delivery error or when the budget runs out. Stdlib only: this runs as a background process
+ from any bot turn, and the sender's completion notification is exactly its stdout."""
+ try:
+ deadline = time.time() + float(budget_seconds)
+ except ValueError:
+ return 2
+ while time.time() < deadline:
+ if os.path.exists(reply_path):
- with open(reply_path, encoding="utf-8") as fh:
++ with open(reply_path, encoding="utf-8-sig") as fh:
+ d = json.load(fh)
+ if d.get("error"):
+ # Typed reason code rides ahead of the free text so the sender can branch on it
+ # without parsing provider prose. See #93091.
+ code = str(d.get("reason") or "").strip()
+ tag = f" [reason: {code}]" if code else ""
+ print(f"Delivery to {label} failed{tag}: {d['error']}")
+ return 1
+ print(f"Reply from {label}:")
+ print(d.get("reply") or "(empty reply)")
+ return 0
+ # 250ms cadence: stat is cheap and a longer sleep is pure dead air.
+ time.sleep(0.25)
+ print(f"No reply from {label} within {budget_seconds}s. The message may still be delivered when "
+ "the Desktop reconnects; do not resend blindly.")
+ return 1
+
+
def _delivery_main(args: list[str]) -> int:
- """Runner entry for the argv ``_delivery_command`` builds. Malformed argv exits 2 without touching the DM file."""
+ """Runner entry for the argv ``_delivery_command`` and ``bot_relay.waiter_command`` build.
+ Malformed argv exits 2 without touching the DM file."""
+ if args[:1] == ["--wait-reply"]:
+ return _wait_reply_main(*args[1:]) if len(args) == 4 else 2
if not args or args[0] != "--run-delivery":
return 2
rest, author = args[1:], None
diff --cc tui_gateway/methods_prompt.py
index debaa945e9c,093aa906a8a..78a35df9e4d
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@@ -696,15 -696,15 +696,6 @@@ def _(rid, params: dict) -> dict
return _ok(rid, {"status": "streaming", **survivor_fields})
--# ── attachments ─────────────────────────────────────────────────────────────
--
--def _attached_image_result(session, image_path, **extra) -> dict:
-- """Common ``{attached, path, count, ...meta}`` reply after queuing an image."""
-- return {
-- "attached": True, "path": str(image_path), "count": len(session["attached_images"]),
-- **extra, **_image_meta(image_path)}
--
--
@method("clipboard.paste")
def _(rid, params: dict) -> dict:
session, err = _sess_building(params, rid)
@@@ -788,53 -788,53 +779,6 @@@ def _(rid, params: dict) -> dict
remainder="", text=f"[User attached image: {img_path.name}]", bytes=len(img_bytes)))
--def _pdf_attach_source(rid, params, td_path, raw_path, raw_b64):
-- """Materialize the PDF to render: ``(pdf_path, display_name, err)``."""
-- if raw_b64:
-- pdf_bytes, err = _decode_attach_payload(
-- rid, raw_b64, mime_prefix="application/pdf", max_bytes=_PDF_ATTACH_MAX_BYTES,
-- label="PDF", empty_msg="decoded PDF is empty")
-- if err is not None:
-- return None, None, err
-- if pdf_bytes[:5] != b"%PDF-":
-- return None, None, _err(rid, 4017, "payload is not a PDF (missing %PDF- magic bytes)")
-- pdf_path = td_path / "input.pdf"
-- pdf_path.write_bytes(pdf_bytes)
-- return pdf_path, str(params.get("filename", "") or "uploaded.pdf"), None
-- try:
-- from cli import _resolve_attachment_path
-- resolved = _resolve_attachment_path(raw_path)
-- except Exception:
-- resolved = None
-- if resolved is None or not (pdf := Path(resolved)).is_file():
-- return None, None, _err(rid, 4016, f"PDF not found: {raw_path}")
-- if pdf.suffix.lower() != ".pdf":
-- return None, None, _err(rid, 4016, f"not a PDF: {pdf.name}")
-- if pdf.stat().st_size > _PDF_ATTACH_MAX_BYTES:
-- mb = _PDF_ATTACH_MAX_BYTES // (1024 * 1024)
-- return None, None, _err(rid, 4018, f"PDF too large; cap is {mb} MB")
-- return pdf, pdf.name, None
--
--
--def _pdf_page_range(rid, params):
-- """Validate first/last page against the per-call cap: ``(first, last, err)``."""
-- try:
-- first_page = int(params.get("first_page") or 1)
-- last_page = None if params.get("last_page") is None else int(params.get("last_page"))
-- except (TypeError, ValueError):
-- return None, None, _err(rid, 4015, "first_page/last_page must be integers")
-- if first_page < 1:
-- return None, None, _err(rid, 4015, "first_page must be >= 1")
-- if last_page is None:
-- last_page = first_page + _PDF_ATTACH_MAX_PAGES - 1
-- if last_page < first_page:
-- return None, None, _err(rid, 4015, "last_page must be >= first_page")
-- if last_page - first_page + 1 > _PDF_ATTACH_MAX_PAGES:
-- return None, None, _err(
-- rid, 4019, f"page range exceeds cap of {_PDF_ATTACH_MAX_PAGES} pages per attach call")
-- return first_page, last_page, None
--
--
@method("pdf.attach")
def _(rid, params: dict) -> dict:
"""Attach a PDF by rendering each page to PNG (``pdftoppm``; 5028 if missing) and
@@@ -957,56 -957,56 +901,6 @@@ def _(rid, params: dict) -> dict
return _err(rid, 5027, str(e))
--# ── side agents (background / btw / preview.restart) ────────────────────────
--
--def _final_response_text(result) -> str:
-- return (result.get("final_response", str(result)) if isinstance(result, dict) else str(result))
--
--
--def _spawn_side_agent(
-- rid, session, task_id, parent, event, body, *, cwd="", extra=None, cleanup=None):
-- """Run ``body()`` on a daemon thread under the session's profile home (the ContextVar
-- doesn't propagate across threads) and cwd; its text — or ``error: <exc>`` — lands on
-- ``parent`` as ``event`` with ``task_id`` (+ ``extra``). Replies ``{task_id}``."""
-- extra = extra or {}
--
-- def run():
-- session_tokens = _set_session_context(task_id, cwd=(cwd or _session_cwd(session)))
-- # Bug #50233: ephemeral agent threads don't inherit the session's ContextVar scopes (set on the
-- # session-create thread), so a side turn under a non-default profile ran against the wrong home.
-- # Bind the profile's home + secrets + terminal policy for the whole body, exactly as a prompt turn
-- # does: home alone left terminal_tool on the launch process's ambient TERMINAL_* (a docker
-- # secondary's background/btw/preview agent ran local). NOTE: we deliberately do NOT close this
-- # agent through task-wide process cleanup — the whole point of preview.restart is to leave a
-- # background server running under this task_id, and AIAgent.close() would kill every process for
-- # the task_id and tear down the very server the restart just started.
-- try:
-- with _session_profile_runtime_scope(session):
-- text = body()
-- _emit(event, parent, {"task_id": task_id, **extra, "text": text})
-- except Exception as e:
-- _emit(event, parent, {"task_id": task_id, **extra, "text": f"error: {e}"})
-- finally:
-- if cleanup is not None:
-- cleanup()
-- _clear_session_context(session_tokens)
--
-- if _start_session_work(run, name=f"side-agent-{task_id}") is None:
-- return _err(rid, 5035, "backend is retiring; reconnect to continue")
-- return _ok(rid, {"task_id": task_id})
--
--
--def _side_agent_args(rid, params, prefix):
-- """Shared admission for the side-agent RPCs: ``(session, text, parent, task_id, err)``."""
-- session, err = _sess(params, rid)
-- if err:
-- return None, None, None, None, err
-- text, parent = params.get("text", ""), params.get("session_id", "")
-- if not text:
-- return None, None, None, None, _err(rid, 4012, "text required")
-- return session, text, parent, f"{prefix}_{uuid.uuid4().hex[:6]}", None
--
--
@method("prompt.background")
def _(rid, params: dict) -> dict:
session, text, parent, task_id, err = _side_agent_args(rid, params, "bg")
@@@ -1046,28 -1046,28 +940,6 @@@ def _(rid, params: dict) -> dict
rid, session, task_id, parent, "btw.complete", body, extra={"question": text})
--_PREVIEW_RESTART_RULES = (
-- "Restart exactly the app intended for the Preview URL, not Hermes Desktop itself.",
-- "The Preview URL and port are the target. Preserve that target unless you conclude it is impossible.",
-- "If the prior conversation shows a specific command that bound this URL/port, prefer re-running THAT exact command (in the same cwd) over guessing a new one.",
-- "First inspect what process, if any, owns the Preview URL port. If a stale server exists, inspect its cwd and prefer that cwd over the Hermes/Desktop process cwd.",
-- "The Current working directory is only a hint. Do not assume it is the preview app root when the port owner or files indicate another root.",
-- "If the console shows a module-script MIME error for src/main.tsx or similar, a static server is serving source files. Do not restart python -m http.server or any dumb static server for that app.",
-- "For module-script MIME failures, inspect package.json/vite config in the candidate app root and start the real dev server/bundler (for example npm/pnpm/yarn dev) so module transforms happen.",
-- "Before declaring success, verify the Preview URL responds with the intended app, not Hermes Desktop. If it serves Hermes/Desktop UI or another unrelated app, stop that process and report failure.",
-- "Do not modify files. Do not ask the user unless blocked.",
-- "Prefer existing project scripts or commands when they are clear.",
-- "If a stale process owns the needed port, handle it safely.",
-- "Start long-running servers detached/in the background, then return immediately.",
-- "Do not run a foreground dev server command that blocks this background task.",
-- "Keep the final response short: what command/server was started, or why it could not be restarted.",
--)
--
--_PREVIEW_RESTART_HISTORY_NOTE = (
-- "The conversation history above is from the user's main session — including the commands you (the assistant) previously ran to start servers, edit files, or check ports. Use it to figure out exactly which server should be running at this Preview URL. The user did not start a brand new task; recover what they had working."
--)
--
--
@method("preview.restart")
def _(rid, params: dict) -> dict:
session, err = _sess(params, rid)
@@@ -1128,12 -1128,12 +1000,6 @@@
cwd=preview_cwd, cleanup=cleanup)
--# ── batch clarify locks ─────────────────────────────────────────────────────
--# A batch ``clarify`` server request is answered one question at a time: each lock is a normal RPC
--# (update-in-place, editable until every qid is locked); the LAST lock resolves the request itself.
--# A cancel-all is the plain response frame with no ``answers``.
--
--
@method("clarify.lock")
def _(rid, params: dict) -> dict:
request_id = str(params.get("request_id") or "")
@@@ -1171,17 -1171,17 +1037,6 @@@ def _(rid, params: dict) -> dict
return _ok(rid, {"status": "expired"})
--# ── approvals ───────────────────────────────────────────────────────────────
--
--def _approval_reply(rid, result_key, call):
-- """``_ok({result_key: call(tools.approval)})``, 5004 on any failure."""
-- try:
-- import tools.approval as approval
-- return _ok(rid, {result_key: call(approval)})
-- except Exception as e:
-- return _err(rid, 5004, str(e))
--
--
@method("approval.pending")
def _(rid, params: dict) -> dict:
session, err = _sess(params, rid)
@@@ -1202,6 -1202,6 +1057,168 @@@ def _(rid, params: dict) -> dict
rid, "acknowledged", lambda a: a.ack_gateway_approval(session["session_key"], request_id))
++@method("approval.respond")
++def _(rid, params: dict) -> dict:
++ session, err = _sess(params, rid)
++ if err:
++ # Session-not-found (4001) only: resolve by durable identity before failing.
++ if (err.get("error") or {}).get("code") != 4001:
++ return err
++ session = _approval_respond_session_fallback(params)
++ if session is None:
++ return err
++ return _approval_reply(
++ rid, "resolved",
++ lambda a: a.resolve_gateway_approval(
++ session["session_key"], params.get("choice", "deny"),
++ resolve_all=params.get("all", False), request_id=params.get("request_id")))
++
++
++# ── attachments ─────────────────────────────────────────────────────────────
++
++def _attached_image_result(session, image_path, **extra) -> dict:
++ """Common ``{attached, path, count, ...meta}`` reply after queuing an image."""
++ return {
++ "attached": True, "path": str(image_path), "count": len(session["attached_images"]),
++ **extra, **_image_meta(image_path)}
++
++
++def _pdf_attach_source(rid, params, td_path, raw_path, raw_b64):
++ """Materialize the PDF to render: ``(pdf_path, display_name, err)``."""
++ if raw_b64:
++ pdf_bytes, err = _decode_attach_payload(
++ rid, raw_b64, mime_prefix="application/pdf", max_bytes=_PDF_ATTACH_MAX_BYTES,
++ label="PDF", empty_msg="decoded PDF is empty")
++ if err is not None:
++ return None, None, err
++ if pdf_bytes[:5] != b"%PDF-":
++ return None, None, _err(rid, 4017, "payload is not a PDF (missing %PDF- magic bytes)")
++ pdf_path = td_path / "input.pdf"
++ pdf_path.write_bytes(pdf_bytes)
++ return pdf_path, str(params.get("filename", "") or "uploaded.pdf"), None
++ try:
++ from cli import _resolve_attachment_path
++ resolved = _resolve_attachment_path(raw_path)
++ except Exception:
++ resolved = None
++ if resolved is None or not (pdf := Path(resolved)).is_file():
++ return None, None, _err(rid, 4016, f"PDF not found: {raw_path}")
++ if pdf.suffix.lower() != ".pdf":
++ return None, None, _err(rid, 4016, f"not a PDF: {pdf.name}")
++ if pdf.stat().st_size > _PDF_ATTACH_MAX_BYTES:
++ mb = _PDF_ATTACH_MAX_BYTES // (1024 * 1024)
++ return None, None, _err(rid, 4018, f"PDF too large; cap is {mb} MB")
++ return pdf, pdf.name, None
++
++
++def _pdf_page_range(rid, params):
++ """Validate first/last page against the per-call cap: ``(first, last, err)``."""
++ try:
++ first_page = int(params.get("first_page") or 1)
++ last_page = None if params.get("last_page") is None else int(params.get("last_page"))
++ except (TypeError, ValueError):
++ return None, None, _err(rid, 4015, "first_page/last_page must be integers")
++ if first_page < 1:
++ return None, None, _err(rid, 4015, "first_page must be >= 1")
++ if last_page is None:
++ last_page = first_page + _PDF_ATTACH_MAX_PAGES - 1
++ if last_page < first_page:
++ return None, None, _err(rid, 4015, "last_page must be >= first_page")
++ if last_page - first_page + 1 > _PDF_ATTACH_MAX_PAGES:
++ return None, None, _err(
++ rid, 4019, f"page range exceeds cap of {_PDF_ATTACH_MAX_PAGES} pages per attach call")
++ return first_page, last_page, None
++
++
++# ── side agents (background / btw / preview.restart) ────────────────────────
++
++def _final_response_text(result) -> str:
++ return (result.get("final_response", str(result)) if isinstance(result, dict) else str(result))
++
++
++def _spawn_side_agent(
++ rid, session, task_id, parent, event, body, *, cwd="", extra=None, cleanup=None):
++ """Run ``body()`` on a daemon thread under the session's profile home (the ContextVar
++ doesn't propagate across threads) and cwd; its text — or ``error: <exc>`` — lands on
++ ``parent`` as ``event`` with ``task_id`` (+ ``extra``). Replies ``{task_id}``."""
++ extra = extra or {}
++
++ def run():
++ session_tokens = _set_session_context(task_id, cwd=(cwd or _session_cwd(session)))
++ # Bug #50233: ephemeral agent threads don't inherit the session's ContextVar scopes (set on the
++ # session-create thread), so a side turn under a non-default profile ran against the wrong home.
++ # Bind the profile's home + secrets + terminal policy for the whole body, exactly as a prompt turn
++ # does: home alone left terminal_tool on the launch process's ambient TERMINAL_* (a docker
++ # secondary's background/btw/preview agent ran local). NOTE: we deliberately do NOT close this
++ # agent through task-wide process cleanup — the whole point of preview.restart is to leave a
++ # background server running under this task_id, and AIAgent.close() would kill every process for
++ # the task_id and tear down the very server the restart just started.
++ try:
++ with _session_profile_runtime_scope(session):
++ text = body()
++ _emit(event, parent, {"task_id": task_id, **extra, "text": text})
++ except Exception as e:
++ _emit(event, parent, {"task_id": task_id, **extra, "text": f"error: {e}"})
++ finally:
++ if cleanup is not None:
++ cleanup()
++ _clear_session_context(session_tokens)
++
++ if _start_session_work(run, name=f"side-agent-{task_id}") is None:
++ return _err(rid, 5035, "backend is retiring; reconnect to continue")
++ return _ok(rid, {"task_id": task_id})
++
++
++def _side_agent_args(rid, params, prefix):
++ """Shared admission for the side-agent RPCs: ``(session, text, parent, task_id, err)``."""
++ session, err = _sess(params, rid)
++ if err:
++ return None, None, None, None, err
++ text, parent = params.get("text", ""), params.get("session_id", "")
++ if not text:
++ return None, None, None, None, _err(rid, 4012, "text required")
++ return session, text, parent, f"{prefix}_{uuid.uuid4().hex[:6]}", None
++
++
++_PREVIEW_RESTART_RULES = (
++ "Restart exactly the app intended for the Preview URL, not Hermes Desktop itself.",
++ "The Preview URL and port are the target. Preserve that target unless you conclude it is impossible.",
++ "If the prior conversation shows a specific command that bound this URL/port, prefer re-running THAT exact command (in the same cwd) over guessing a new one.",
++ "First inspect what process, if any, owns the Preview URL port. If a stale server exists, inspect its cwd and prefer that cwd over the Hermes/Desktop process cwd.",
++ "The Current working directory is only a hint. Do not assume it is the preview app root when the port owner or files indicate another root.",
++ "If the console shows a module-script MIME error for src/main.tsx or similar, a static server is serving source files. Do not restart python -m http.server or any dumb static server for that app.",
++ "For module-script MIME failures, inspect package.json/vite config in the candidate app root and start the real dev server/bundler (for example npm/pnpm/yarn dev) so module transforms happen.",
++ "Before declaring success, verify the Preview URL responds with the intended app, not Hermes Desktop. If it serves Hermes/Desktop UI or another unrelated app, stop that process and report failure.",
++ "Do not modify files. Do not ask the user unless blocked.",
++ "Prefer existing project scripts or commands when they are clear.",
++ "If a stale process owns the needed port, handle it safely.",
++ "Start long-running servers detached/in the background, then return immediately.",
++ "Do not run a foreground dev server command that blocks this background task.",
++ "Keep the final response short: what command/server was started, or why it could not be restarted.",
++)
++
++_PREVIEW_RESTART_HISTORY_NOTE = (
++ "The conversation history above is from the user's main session — including the commands you (the assistant) previously ran to start servers, edit files, or check ports. Use it to figure out exactly which server should be running at this Preview URL. The user did not start a brand new task; recover what they had working."
++)
++
++
++# ── batch clarify locks ─────────────────────────────────────────────────────
++# A batch ``clarify`` server request is answered one question at a time: each lock is a normal RPC
++# (update-in-place, editable until every qid is locked); the LAST lock resolves the request itself.
++# A cancel-all is the plain response frame with no ``answers``.
++
++
++# ── approvals ───────────────────────────────────────────────────────────────
++
++def _approval_reply(rid, result_key, call):
++ """``_ok({result_key: call(tools.approval)})``, 5004 on any failure."""
++ try:
++ import tools.approval as approval
++ return _ok(rid, {result_key: call(approval)})
++ except Exception as e:
++ return _err(rid, 5004, str(e))
++
++
def _approval_respond_session_fallback(params: dict):
"""Durable-identity fallback for a stale live sid (re-minted after a reconnect while
the prompt stayed on screen): (1) the ``request_id`` against every live session's
@@@ -1232,23 -1232,23 +1249,6 @@@
return None
--@method("approval.respond")
--def _(rid, params: dict) -> dict:
-- session, err = _sess(params, rid)
-- if err:
-- # Session-not-found (4001) only: resolve by durable identity before failing.
-- if (err.get("error") or {}).get("code") != 4001:
-- return err
-- session = _approval_respond_session_fallback(params)
-- if session is None:
-- return err
-- return _approval_reply(
-- rid, "resolved",
-- lambda a: a.resolve_gateway_approval(
-- session["session_key"], params.get("choice", "deny"),
-- resolve_all=params.get("all", False), request_id=params.get("request_id")))
--
--
def register(server) -> None:
"""Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
bind_module(globals(), server, skip=("_",))