The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into ethie/pm-clean
ethernetc6b358592d6d
diff --cc apps/desktop/src/app/chat/transcript-backfill.test.tsindex c8d327a58a7,9d19c711c80..ec5ad591582--- a/apps/desktop/src/app/chat/transcript-backfill.test.ts+++ b/apps/desktop/src/app/chat/transcript-backfill.test.ts@@@ -293,6 -352,6 +352,7 @@@ describe('backfillOlderTranscriptPage'truncatedTail()let resolvePage!: (value: unknown) => voidvi.mocked(getOlderSessionMessages).mockReturnValue(++ // SAFETY: this controlled promise resolves with the exact RPC response shape below.new Promise(resolve => {resolvePage = resolve}) as never@@@ -327,6 -386,6 +387,7 @@@let resolvePage: (value: unknown) => void = () => {}vi.mocked(getOlderSessionMessages).mockReturnValue(++ // SAFETY: this controlled promise resolves with the exact RPC response shape below.new Promise(resolve => {resolvePage = resolve}) as neverdiff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit-view-binding.test.tsindex 00000000000,00000000000..0098177af74new file mode 100644--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit-view-binding.test.ts@@@ -1,0 -1,0 +1,122 @@@++import { afterEach, expect, it, vi } from 'vitest'++++import { type ChatMessage, textPart } from '@/lib/chat-messages'++import { createClientSessionState } from '@/lib/chat-runtime'++import { $activeSessionId, setActiveSessionId } from '@/store/session'++import type { SessionInfo } from '@/types/hermes'++++import type { ClientSessionState } from '../../../types'++++import { rebindPaneToResumedRuntime, type ResumedRuntimeBindingDeps } from './submit'++++const STORED = 'stored-b'++const RESUMED_RUNTIME = 'rt-resumed'++++function row(id: string, role: ChatMessage['role'], text: string): ChatMessage {++ return { id, parts: [textPart(text)], role }++}++++function sessionInfo(id: string, lineageRoot?: string): SessionInfo {++ return {++ _lineage_root_id: lineageRoot,++ ended_at: null,++ id,++ input_tokens: 0,++ is_active: true,++ last_active: 0,++ message_count: 0,++ model: null,++ output_tokens: 0,++ preview: null,++ source: null,++ started_at: 0,++ title: id,++ tool_call_count: 0++ }++}++++interface BoundPaneResult {++ activeSessionIdRef: { current: string | null }++ earlier: ChatMessage[]++ resumed?: ClientSessionState++ updateSessionState: ResumedRuntimeBindingDeps['updateSessionState']++}++++function bindPane({++ paneStoredSessionId,++ sessions = [],++ targetStoredSessionId = STORED++}: {++ paneStoredSessionId: string++ sessions?: SessionInfo[]++ targetStoredSessionId?: string++}): BoundPaneResult {++ const earlier: ChatMessage[] = [++ row('u1', 'user', 'earlier prompt'),++ row('a1', 'assistant', 'earlier reply')++ ]++++ const paneState: ClientSessionState = { ...createClientSessionState(paneStoredSessionId), messages: earlier }++++ const states: Map<string, ClientSessionState> = new Map([++ [RESUMED_RUNTIME, createClientSessionState(targetStoredSessionId)]++ ])++++ const updateSessionState: ResumedRuntimeBindingDeps['updateSessionState'] = (++ sessionId,++ updater,++ storedSessionId++ ) => {++ const current = states.get(sessionId) ?? createClientSessionState(storedSessionId)++ const updated = updater(current)++++ states.set(sessionId, updated)++++ return updated++ }++++ const activeSessionIdRef: BoundPaneResult['activeSessionIdRef'] = { current: 'rt-stale' }++++ setActiveSessionId('rt-stale')++ rebindPaneToResumedRuntime({++ activeSessionIdRef,++ paneState,++ resumedRuntimeId: RESUMED_RUNTIME,++ sessions,++ storedSessionId: targetStoredSessionId,++ updateSessionState: vi.fn(updateSessionState)++ })++++ return { activeSessionIdRef, earlier, resumed: states.get(RESUMED_RUNTIME), updateSessionState }++}++++afterEach((): void => {++ setActiveSessionId(null)++})++++it('moves the pane and carries the selected conversation into an empty resumed runtime', (): void => {++ const { activeSessionIdRef, earlier, resumed } = bindPane({ paneStoredSessionId: STORED })++++ expect(activeSessionIdRef.current).toBe(RESUMED_RUNTIME)++ expect($activeSessionId.get()).toBe(RESUMED_RUNTIME)++ expect(resumed?.messages).toEqual(earlier)++})++++it('recognizes the same conversation after compression rotates its stored id', (): void => {++ const rotatedStoredId = `${STORED}-next`++++ const { earlier, resumed } = bindPane({++ paneStoredSessionId: STORED,++ sessions: [sessionInfo(rotatedStoredId, STORED)],++ targetStoredSessionId: rotatedStoredId++ })++++ expect(resumed?.messages).toEqual(earlier)++})++++it('never carries another conversation into the resumed runtime', (): void => {++ const { resumed } = bindPane({ paneStoredSessionId: 'stored-other' })++++ expect(resumed?.messages).toEqual([])++ expect($activeSessionId.get()).toBe(RESUMED_RUNTIME)++})diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 7c2a00bc0c3,0c4b133aaf1..a5d5b499290--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@@ -33,6 -34,6 +34,7 @@@ importtouchSessionActivity} from '@/store/session'import { $sessionStates } from '@/store/session-states'++import type { SessionInfo } from '@/types/hermes'import type { ClientSessionState } from '../../../types'import { sessionContextDrift } from '../session-context-drift'@@@ -100,6 -101,6 +102,42 @@@ const MAIN_SUBMIT_SCOPE: NonNullable<SusetMessages}++export interface ResumedRuntimeBindingDeps {++ activeSessionIdRef: MutableRefObject<string | null>++ paneState?: ClientSessionState++ resumedRuntimeId: string++ sessions: SessionInfo[]++ storedSessionId: string++ updateSessionState: SubmitPromptDeps['updateSessionState']++}++++export function rebindPaneToResumedRuntime({++ activeSessionIdRef,++ paneState,++ resumedRuntimeId,++ sessions,++ storedSessionId,++ updateSessionState++}: ResumedRuntimeBindingDeps): void {++ if (++ paneState?.messages.length &&++ paneState.storedSessionId &&++ resolveComposerSessionKey(paneState.storedSessionId, sessions) ===++ resolveComposerSessionKey(storedSessionId, sessions)++ ) {++ const carried: ChatMessage[] = paneState.messages++++ updateSessionState(++ resumedRuntimeId,++ state => (state.messages.length ? state : { ...state, messages: carried }),++ storedSessionId++ )++ }++++ activeSessionIdRef.current = resumedRuntimeId++ setActiveSessionId(resumedRuntimeId)++}++/** The prompt submit pipeline, extracted from usePromptActions. */export function useSubmitPrompt(deps: SubmitPromptDeps) {const {@@@ -393,6 -394,36 +431,7 @@@}}- // Point the pane at a runtime this submit just resumed for its stored- // session. ChatView renders the `$sessionStates` slice named by- // `$activeSessionId`, while the optimistic row and every stream event- // land in the resumed runtime's slice — pinning only the ref left the- // chat painting the dead runtime, so the prompt, its reply, and every- // later turn stayed invisible until a relaunch (#71733, #117867).- // `session.resume` omits messages, so carry the transcript the pane is- // showing into the empty slice (same conversation only — lineage-- // matched, since compression rotates the tip id) instead of collapsing- // the thread to the new prompt until the next refresh.- const rebindPaneToResumedRuntime = (sid: string, storedId: string) => {- const paneRuntimeId = $activeSessionId.get()- const paneState = paneRuntimeId && paneRuntimeId !== sid ? $sessionStates.get()[paneRuntimeId] : undefined- const sessions = $sessions.get()-- if (- paneState?.messages.length &&- paneState.storedSessionId &&- resolveComposerSessionKey(paneState.storedSessionId, sessions) ===- resolveComposerSessionKey(storedId, sessions)- ) {- const carried = paneState.messages-- updateSessionState(sid, state => (state.messages.length ? state : { ...state, messages: carried }), storedId)- }-- activeSessionIdRef.current = sid- setActiveSessionId(sid)- }+// Idempotent optimistic insert — re-running with the resolved sessionId// after createBackendSessionForSend just overwrites with the same id.const seedOptimistic = (sid: string) => {@@@ -635,7 -666,7 +674,20 @@@sessionId = resumed.session_idif (targetIsCurrentView()) {- activeSessionIdRef.current = sessionId- rebindPaneToResumedRuntime(sessionId, targetStoredSessionId)++ const paneRuntimeId: string | null = $activeSessionId.get()++++ // ChatView renders the state slice named by `$activeSessionId`,++ // while the resumed turn lands in a new runtime slice. Carry++ // only a lineage-matched transcript before moving the pane.++ rebindPaneToResumedRuntime({++ activeSessionIdRef,++ paneState:++ paneRuntimeId && paneRuntimeId !== sessionId ? $sessionStates.get()[paneRuntimeId] : undefined,++ resumedRuntimeId: sessionId,++ sessions: $sessions.get(),++ storedSessionId: targetStoredSessionId,++ updateSessionState++ })}}} catch {diff --cc apps/desktop/src/lib/chat-messages/reconciliation.tsindex 6e6f98310da,df773498fc3..a60e3126d92--- a/apps/desktop/src/lib/chat-messages/reconciliation.ts+++ b/apps/desktop/src/lib/chat-messages/reconciliation.ts@@@ -177,14 -177,20 +177,19 @@@ function reconcileLocalAssistantTimelin})}- export function preserveLocalAssistantErrors(+ interface PreservedRun {+ after?: string+ before?: string+ rows: ChatMessage[]+ }+-export function preserveLocalAssistantErrors(++function mergeStoredAssistantErrors(nextMessages: ChatMessage[],currentMessages: ChatMessage[]): ChatMessage[] {-- nextMessages = reconcileLocalAssistantTimeline(nextMessages, currentMessages)const localById = new Map(currentMessages.map(message => [message.id, message]))-- const mergedNextMessages = nextMessages.map(message => {++ return nextMessages.map(message => {if (message.role !== 'assistant' || message.error || message.hidden) {return message}@@@ -202,17 -208,17 +207,23 @@@pending: false}})++}+++const normalizedMessageText = (message: ChatMessage): string => chatMessageText(message).replace(/\s+/g, ' ').trim()+++function localAssistantErrorIdsToPreserve(++ mergedNextMessages: ChatMessage[],++ currentMessages: ChatMessage[]++): Set<string> {const existingIds = new Set(mergedNextMessages.map(message => message.id))const preserveIds = new Set<string>()-- const normalize = (value: string) => value.replace(/\s+/g, ' ').trim()const tailUserInNext = [...mergedNextMessages].reverse().find(message => message.role === 'user' && !message.hidden)-- const tailUserText = tailUserInNext ? normalize(chatMessageText(tailUserInNext)) : ''++ const tailUserText = tailUserInNext ? normalizedMessageText(tailUserInNext) : ''const tailUserRefs = tailUserInNext ? (tailUserInNext.attachmentRefs ?? []).join('\n') : ''-- const matchesTailUserInNext = (candidate: ChatMessage) =>++ const matchesTailUserInNext = (candidate: ChatMessage): boolean =>Boolean(tailUserInNext) &&-- normalize(chatMessageText(candidate)) === tailUserText &&++ normalizedMessageText(candidate) === tailUserText &&(candidate.attachmentRefs ?? []).join('\n') === tailUserRefsfor (let index = 0; index < currentMessages.length; index += 1) {@@@ -252,17 -258,57 +263,78 @@@}}++ return preserveIds++}++++function insertPreservedErrorRuns(++ mergedNextMessages: ChatMessage[],++ currentMessages: ChatMessage[],++ preserveIds: Set<string>++): ChatMessage[] {++ const existingIds = new Set(mergedNextMessages.map(message => message.id))++if (preserveIds.size === 0) {return mergedNextMessages}- const preserved = currentMessages- .filter(message => preserveIds.has(message.id))- .map(message => ({ ...message, pending: false }))+ // Put each run of kept rows back after the refreshed row that preceded it+ // locally instead of below newer turns. When the refresh already fills that+ // gap with the same role/text sequence, the turn was stored under new ids.+ // A run with no refreshed successor stays trailing. #118002- const label = (message: ChatMessage) => `${message.role}:${normalize(chatMessageText(message))}`++ const label = (message: ChatMessage): string => `${message.role}:${normalizedMessageText(message)}`+ const runs: PreservedRun[] = []+ let anchor: string | undefined++ for (const message of currentMessages) {+ const open = runs.at(-1)?.after === anchor ? runs.at(-1) : undefined++ if (existingIds.has(message.id)) {+ if (open) {+ open.before = message.id+ }++ anchor = message.id+ } else if (preserveIds.has(message.id)) {+ const kept = { ...message, pending: false }++ if (open) {+ open.rows.push(kept)+ } else {+ runs.push({ after: anchor, rows: [kept] })+ }+ }+ }++ const indexOf = (id?: string) => mergedNextMessages.findIndex(message => message.id === id)+ const keptAfter = new Map<string | undefined, ChatMessage[]>()++ for (const { after, before, rows } of runs) {+ const gap = before === undefined ? [] : mergedNextMessages.slice(indexOf(after) + 1, indexOf(before))++ if (gap.length && gap.map(label).join('\n') === rows.map(label).join('\n')) {+ continue+ }++ keptAfter.set(after, [...(keptAfter.get(after) ?? []), ...rows])+ }++ return [+ ...mergedNextMessages.flatMap(message => [message, ...(keptAfter.get(message.id) ?? [])]),+ ...(keptAfter.get(undefined) ?? [])+ ]+ }+++export function preserveLocalAssistantErrors(++ nextMessages: ChatMessage[],++ currentMessages: ChatMessage[]++): ChatMessage[] {++ const reconciled: ChatMessage[] = reconcileLocalAssistantTimeline(nextMessages, currentMessages)++ const merged: ChatMessage[] = mergeStoredAssistantErrors(reconciled, currentMessages)++ const preserveIds: Set<string> = localAssistantErrorIdsToPreserve(merged, currentMessages)+- return [...mergedNextMessages, ...preserved]++ return insertPreservedErrorRuns(merged, currentMessages, preserveIds)+}+export function branchGroupForUser(userMessage: ChatMessage): string {return `branch:${userMessage.id}`}diff --cc hermes_cli/_startup_fast.pyindex 597a1a3ea41,d4fe0818d5d..37f3b91421b--- a/hermes_cli/_startup_fast.py+++ b/hermes_cli/_startup_fast.py@@@ -28,16 -12,11 +28,17 @@@ import oimport sys__all__ = [- "project_root_str", "normalize_hermes_home_env", "ensure_project_root_on_path", "is_termux_env",- "is_termux_fast_version_argv", "is_global_fast_version_argv",- "is_container_startup_environment", "active_profile_may_override_home",- "container_mode_may_be_active", "read_openai_version", "read_install_method",- "print_fast_version_info", "try_fast_version", "is_desktop_ssh_backend_argv",+ "project_root_str", "normalize_hermes_home_env",+ "ensure_project_root_on_path",+ "is_global_fast_version_argv",+ "is_container_startup_environment",+ "active_profile_may_override_home",+ "container_mode_may_be_active",+ "read_openai_version",+ "read_install_method",+ "print_fast_version_info",+ "try_fast_version",++ "is_desktop_ssh_backend_argv",]@@@ -101,6 -87,20 +102,17 @@@ def is_global_fast_version_argv(argv: lreturn argv in (["--version"], ["-V"])-is_global_fast_version_argv = is_termux_fast_version_argv--+ def is_desktop_ssh_backend_argv(argv: list[str]) -> bool:+ """Is ``argv`` the Desktop client's SSH backend spawn (``serve --ssh-session-token-file``)?++ That child has a fixed identity: Desktop names the remote profile explicitly (or none for+ the root home) and hands its session token through a 0600 FILE, never the+ ``HERMES_DASHBOARD_SESSION_TOKEN`` env var the local pool spawn uses. Every reader of+ "is this process Desktop's backend" needs both shapes; this is the argv half.+ """+ return "--ssh-session-token-file" in argv++def is_container_startup_environment() -> bool:"""True when we're already INSIDE a container (fast path is then safe)."""if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):diff --cc hermes_cli/main.pyindex 09fd6b5c343,be58df9a905..5ea34f4c052--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@@ -588,8 -597,14 +577,9 @@@ def _apply_profile_override() -> Nonehermes_home_env = os.environ.get("HERMES_HOME", "")if profile_name is None and hermes_home_env and Path(hermes_home_env).parent.name == "profiles":return- # The post-swap updater child inherits the home its parent already resolved (possibly the- # root for `-p default`); re-reading the sticky active_profile here would finish the update- # — receipt, config migration, exit code — in another profile's home.- if profile_name is None and hermes_home_env and os.environ.get("HERMES_UPDATE_POST_SWAP") == "1":- return- if (profile_name is None and not _under_gateway_supervisor(argv) and not _desktop_ssh_backend(argv)+ if (profile_name is None and not _under_gateway_supervisor(argv)+ and not _startup_fast.is_desktop_ssh_backend_argv(argv)and not _s6_supervised_gateway_run(argv)):try:from hermes_constants import get_default_hermes_rootdiff --cc hermes_cli/update_cmd_fleet.pyindex 82d4144fe05,578114efaf4..aab627c66b0--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@@ -1352,48 -1524,25 +1378,49 @@@ def _restart_systemd_gateway_unitsf"continuing with remaining gateways")+ # Enumerate every scope first: leftover per-profile units (``hermes-gateway-<profile>``)+ # all point at the SAME live MainPID on a multiplexed host, and restarting each in turn+ # is an N-fold outage from one update. Units sharing a live PID collapse to one restart;+ # the others are named as legacy units to migrate, never silently dropped.+ from hermes_cli.update_host_obligation import collapse_units_to_host_processes+ targets: dict[str, tuple[str, list, str]] = {} # "<scope>/<unit>" -> (scope, scope_cmd, unit)for scope, scope_cmd, result in _systemd_gateway_unit_listings(_on_list_timeout):- # Scope-qualify this scope's additions before the next scope can add a- # same-named unit; ``finally`` so a mid-scope abort keeps settled units.+ _for_each_systemd_gateway_unit(+ result.stdout,+ process_unit=lambda svc_name, _scope=scope, _cmd=scope_cmd: targets.setdefault(+ f"{_scope}/{svc_name}", (_scope, _cmd, svc_name)),+ on_unit_timeout=_on_unit_timeout,+ )+ keys = list(targets)+ covered: dict[str, str] = {}+ if len(keys) > 1:+ # Only worth a `systemctl show` round when several units could be one process.+ keys, covered = collapse_units_to_host_processes(+ keys, lambda key: _unit_main_pid(targets[key][1], targets[key][2]))+ for unit_key, owner_key in covered.items():+ print(+ f" • {unit_key} is a legacy per-profile unit sharing one host gateway process with "+ f"{owner_key}; restarting it again would restart that process twice. Fold the units "+ "together with: hermes gateway migrate"+ )++ for key in keys:+ scope, scope_cmd, svc_name = targets[key]+ # Scope-qualify before the next unit; ``finally`` so a mid-pass abort keeps settled units._scope_mark = len(restarted_services)try:- _for_each_systemd_gateway_unit(- result.stdout,- process_unit=lambda svc_name: _restart_one_systemd_gateway_unit(- svc_name,- scope=scope,- scope_cmd=scope_cmd,- drain_budget=drain_budget,- _manage_cmd_cache=_manage_cmd_cache,- restarted_services=restarted_services,- failed_or_stale_units=failed_or_stale_units,- self_restart_pending=self_restart_pending,- ),- on_unit_timeout=_on_unit_timeout,+ _restart_one_systemd_gateway_unit(+ svc_name,+ scope=scope,+ scope_cmd=scope_cmd,+ drain_budget=drain_budget,+ _manage_cmd_cache=_manage_cmd_cache,+ restarted_services=restarted_services,+ failed_or_stale_units=failed_or_stale_units,++ self_restart_pending=self_restart_pending,)+ except subprocess.TimeoutExpired as exc:+ _on_unit_timeout(svc_name, exc)finally:restarted_scoped_units.update(f"{scope}/{name}" for name in restarted_services[_scope_mark:])diff --cc plugins/platforms/telegram/update_admission.pyindex 0ae321a444a,982f0068a4c..7ffb73ce0b4--- a/plugins/platforms/telegram/update_admission.py+++ b/plugins/platforms/telegram/update_admission.py@@@ -14,9 -20,74 +20,74 @@@ from telegram import Updatfrom telegram.ext import Application, ApplicationHandlerStop, ConversationHandlerfrom gateway.platforms.helpers import bounded_put+ from utils import atomic_json_write+ logger = logging.getLogger(__name__)_DEFAULT_BLOCK = object()+ _SEEN_CAP = 4096+ # The Bot API keeps an unconfirmed update for at most 24 hours (getUpdates), so an older+ # receipt can never match a redelivery. That is also well inside the week of silence after+ # which Telegram may restart update IDs at a random value, so a set lookup stays safe+ # where a persisted numeric high-watermark would not.+ RECEIPT_TTL_SECONDS = 24 * 60 * 60+++ def _receipt_path(adapter, bot_id):+ return adapter._update_receipt_dir / f"telegram_update_receipts_{bot_id}.json"+++ def _load_receipts(adapter, bot_id) -> None:+ """Seed completed history from disk once per bot, before its first admission check."""+ if bot_id in adapter._update_receipts_loaded:+ return+ adapter._update_receipts_loaded.add(bot_id)+ path = _receipt_path(adapter, bot_id)+ try:- payload = json.loads(path.read_text(encoding="utf-8"))++ payload = json.loads(path.read_text(encoding="utf-8-sig"))+ except FileNotFoundError:+ return+ except (OSError, ValueError):+ logger.warning("[Telegram] Ignoring unreadable update receipts at %s", path, exc_info=True)+ return+ ids = payload.get("update_ids") if isinstance(payload, dict) else None+ if not isinstance(ids, dict):+ return+ cutoff = time.time() - RECEIPT_TTL_SECONDS+ fresh = sorted((float(ts), uid) for uid, ts in ids.items()+ if isinstance(ts, (int, float)) and ts > cutoff and str(uid).lstrip("-").isdigit())+ seen = adapter._seen_update_ids+ for ts, uid in fresh:+ key = f"{bot_id}:{uid}"+ if key not in seen:+ bounded_put(seen, key, ts, _SEEN_CAP)+++ def _record_receipt(adapter, key: str) -> None:+ bounded_put(adapter._seen_update_ids, key, time.time(), _SEEN_CAP)+ adapter._update_receipts_dirty.add(key.split(":", 1)[0])+ task = adapter._update_receipt_flush+ if task is None or task.done():+ # One writer per adapter coalesces bursts; the fsync stays off the event loop.+ adapter._update_receipt_flush = asyncio.get_running_loop().create_task(+ _flush_receipts(adapter), name="telegram-update-receipts")+++ async def _flush_receipts(adapter) -> None:+ from hermes_constants import mkdir_under_hermes_home++ while adapter._update_receipts_dirty:+ bot_id = adapter._update_receipts_dirty.pop()+ prefix, cutoff = f"{bot_id}:", time.time() - RECEIPT_TTL_SECONDS+ # Snapshot on the loop: admission mutates this dict only from loop callbacks.+ ids = {key[len(prefix):]: ts for key, ts in adapter._seen_update_ids.items()+ if key.startswith(prefix) and isinstance(ts, float) and ts > cutoff}+ path = _receipt_path(adapter, bot_id)+ try:+ mkdir_under_hermes_home(path.parent)+ await asyncio.to_thread(atomic_json_write, path, {"update_ids": ids}, indent=None)+ except Exception:+ logger.warning("[Telegram] Failed to persist update receipts to %s", path, exc_info=True)@dataclassdiff --cc tests/hermes_cli/test_fleet_matrix_self_restart_pending.pyindex 00000000000,16697101d85..1a092911302mode 000000,100644..100644--- a/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py+++ b/tests/hermes_cli/test_fleet_matrix_self_restart_pending.py@@@ -1,0 -1,104 +1,104 @@@+ """A gateway this updater runs INSIDE (cron update in the gateway tree, #100179) accepted a+ self-restart request and can only restart after the updater exits — so at fleet-matrix time it is+ still on the pre-update code by construction. It used to render STALE and exit 1 on every nightly+ cron update (#119597). Now the ancestor pid set recorded by the restart phase turns that row into+ ``restart_pending``; every OTHER gateway on the old sha keeps its ``stale`` verdict.+ """++ import contextlib+ import io+ import json+ import os++ import pytest++ import hermes_cli.update_cmd_fleet as fleet_mod+ import hermes_cli.update_receipt as ur++ OLD = "a" * 40+ HEAD = "b" * 40+++ def _fleet_homes(monkeypatch, tmp_path, records: dict[str, dict]) -> None:+ """Default home + named profiles, each with a state file the identity resolver verifies as-is."""+ root = tmp_path / ".hermes"+ (root / "profiles").mkdir(parents=True)+ homes = {"default": root}+ for profile, record in records.items():+ home = root if profile == "default" else root / "profiles" / profile+ home.mkdir(exist_ok=True)+ homes[profile] = home+ (home / "gateway_state.json").write_text(json.dumps(record), encoding="utf-8")+ by_home = {str(home): rec["pid"] for profile, home in homes.items() for rec in [records[profile]]}- monkeypatch.setattr("hermes_cli.build_info.get_code_identity", lambda refresh=False: {"sha": HEAD, "version": "1.0"})++ monkeypatch.setattr("hermes_cli.version_info.get_code_identity", lambda refresh=False: {"sha": HEAD, "version": "1.0"})+ monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: root)+ monkeypatch.setattr("hermes_cli.profiles._get_profiles_root", lambda: root / "profiles")+ monkeypatch.setattr("gateway.control_socket.identify_gateway", lambda h, **k: None)+ monkeypatch.setattr("gateway.status.live_gateway_pid_for_home", lambda h: by_home.get(str(h)))+ monkeypatch.setattr(ur, "_gateway_code_root", lambda pid, home: None)+++ def test_ancestor_with_accepted_self_restart_is_pending_while_other_stale_rows_still_fail(monkeypatch, tmp_path):+ ancestor, sibling = os.getpid(), os.getppid()+ _fleet_homes(monkeypatch, tmp_path, {+ "default": {"pid": ancestor, "gateway_state": "running", "code_sha": OLD},+ "ops": {"pid": sibling, "gateway_state": "running", "code_sha": OLD},+ })++ fleet = ur.collect_fleet_versions(pre_restart_pids=[ancestor, sibling], self_restart_pending={ancestor})+ states = {row["profile"]: row["state"] for row in fleet}+ assert states == {"default": ur.RESTART_PENDING_STATE, "ops": "stale"}+ with contextlib.redirect_stdout(io.StringIO()) as out:+ assert ur.print_fleet_version_matrix(fleet) is True # the sibling still fails the update+ assert "restart pending" in out.getvalue() and "1 gateway(s) still running the old code" in out.getvalue()++ # Without the sibling, the pending row alone is not a failure — and the same pid NOT recorded+ # as pending (the restart phase never reached the ancestor branch) is a plain stale verdict.+ only_ancestor = [row for row in fleet if row["profile"] == "default"]+ with contextlib.redirect_stdout(io.StringIO()):+ assert ur.print_fleet_version_matrix(only_ancestor) is False+ plain = ur.collect_fleet_versions(pre_restart_pids=[ancestor, sibling])+ assert {row["state"] for row in plain} == {"stale"}+++ def test_restart_phase_records_accepted_self_restart_and_verify_exits_clean(monkeypatch, tmp_path):+ """The ancestor branch of the drain triage feeds the pid set the matrix reads: end to end the+ verify phase exits 0 (not 1) and clears the pending marker for an update whose only old-code+ gateway is the one it runs inside."""+ import hermes_cli.gateway as gateway+ import hermes_cli.update_cmd as update_cmd++ ancestor = os.getpid()+ monkeypatch.setattr(gateway, "_is_pid_ancestor_of_current_process", lambda pid: pid == ancestor)+ monkeypatch.setattr(gateway, "_request_gateway_self_restart", lambda pid: True)+ pending: set = set()+ with contextlib.redirect_stdout(io.StringIO()):+ assert fleet_mod._drain_or_signal_gateway_for_update(ancestor, 5.0, "default", self_restart_pending=pending)+ assert pending == {ancestor}++ _fleet_homes(monkeypatch, tmp_path, {"default": {"pid": ancestor, "gateway_state": "running", "code_sha": OLD}})+ monkeypatch.setattr(fleet_mod, "_print_legacy_units_warning", lambda: None)- monkeypatch.setattr(update_cmd, "_finish_dashboard_update_cleanup", lambda *a, **k: None)++ monkeypatch.setattr("hermes_cli.update_cmd_maint._refresh_dashboard_after_update", lambda *a, **k: None)+ monkeypatch.setattr(update_cmd, "_surviving_pre_update_serve_runtimes", lambda plan: [])+ monkeypatch.setattr(fleet_mod._time, "sleep", lambda s: None)+ cleared = []+ monkeypatch.setattr(fleet_mod, "_clear_fleet_restart_pending_marker", lambda: cleared.append(True))+ monkeypatch.setattr("hermes_cli.gateway_migrate.maybe_auto_migrate_after_update", lambda: None)+ restart = fleet_mod._GatewayRestartOutcome(+ incomplete=False, phase_errors=[], pre_restart_gateway_pids=[ancestor], restarted_services=["hermes-gateway"],+ failed_or_stale_units=[], relaunched_profiles=[], externally_supervised_profiles=[], killed_pids=set(),+ self_restart_pending_pids=pending,+ )+ with contextlib.redirect_stdout(io.StringIO()) as out:+ fleet_mod._verify_fleet_after_update(- restart, _pre_update_plan=None, _windows_gateway_resume=None, node_failures=[], update_complete=True,++ restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,+ ) # a SystemExit(1) here is the #119597 symptom+ assert "restart pending" in out.getvalue()+ assert "Update not complete" not in out.getvalue()+ assert cleared == [True]+ with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:+ restart.self_restart_pending_pids = set() # same fleet, identity not threaded → STALE, exit 1+ fleet_mod._verify_fleet_after_update(- restart, _pre_update_plan=None, _windows_gateway_resume=None, node_failures=[], update_complete=True,++ restart, _pre_update_plan=None, _windows_gateway_resume=None, update_complete=True,+ )+ assert exc.value.code == 1diff --cc tests/hermes_cli/test_gateway_linger.pyindex 85a070a8a6c,1335d9f7a4a..bf06dff90d9--- a/tests/hermes_cli/test_gateway_linger.py+++ b/tests/hermes_cli/test_gateway_linger.py@@@ -6,14 -7,41 +7,42 @@@ import pytesimport hermes_cli.gateway as gateway+pytestmark = pytest.mark.platforms("linux")++ def _stub_linger_file(monkeypatch, tmp_path, *, exists: bool) -> None:+ """Point the ``/var/lib/systemd/linger/<user>`` probe at a real file under tmp_path.++ ``gateway.Path`` stays ``pathlib.Path`` — every other ``Path(...)`` the code under test makes+ (``.expanduser()``, ``.resolve()`` in service-name resolution) keeps working. A ``SimpleNamespace``+ stand-in broke as soon as the code grew a call the stub did not implement (#119786).+ """+ linger_dir = Path("/var/lib/systemd/linger")+ fake_dir = tmp_path / "linger"+ fake_dir.mkdir()+ if exists:+ (fake_dir / "testuser").write_text("")++ def redirected_path(path, *more):+ candidate = Path(path, *more)+ return fake_dir / candidate.name if candidate.parent == linger_dir else candidate++ monkeypatch.setattr(gateway, "Path", redirected_path)+++ def _root_with_system_unit_pinned_home(monkeypatch, tmp_path) -> None:+ """Take the root/system-unit branch of service-name resolution (``_bare_unit_pinned_home``), the+ path that calls ``Path(...).expanduser()`` while rendering the restart hint."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes-home"))+ monkeypatch.setattr(gateway.os, "geteuid", lambda: 0)+ monkeypatch.setattr(gateway, "_hermes_home_pinned_by_unit", lambda _unit_path: str(tmp_path / "system-home"))++class TestEnsureLingerEnabled:- def test_linger_already_enabled_via_file(self, monkeypatch, capsys):+ def test_linger_already_enabled_via_file(self, monkeypatch, capsys, tmp_path):monkeypatch.setattr(gateway, "is_linux", lambda: True)- monkeypatch.setattr(gateway, "is_termux", lambda: False)monkeypatch.setattr("getpass.getuser", lambda: "testuser")- monkeypatch.setattr(gateway, "Path", lambda _path: SimpleNamespace(exists=lambda: True))+ _stub_linger_file(monkeypatch, tmp_path, exists=True)calls = []monkeypatch.setattr(gateway.subprocess, "run", lambda *args, **kwargs: calls.append((args, kwargs)))@@@ -23,10 -51,11 +52,10 @@@assert calls == []- def test_loginctl_success_enables_linger(self, monkeypatch, capsys):+ def test_loginctl_success_enables_linger(self, monkeypatch, capsys, tmp_path):monkeypatch.setattr(gateway, "is_linux", lambda: True)- monkeypatch.setattr(gateway, "is_termux", lambda: False)monkeypatch.setattr("getpass.getuser", lambda: "testuser")- monkeypatch.setattr(gateway, "Path", lambda _path: SimpleNamespace(exists=lambda: False))+ _stub_linger_file(monkeypatch, tmp_path, exists=False)monkeypatch.setattr(gateway, "get_systemd_linger_status", lambda username=None: (False, ""))monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/loginctl")@@@ -43,10 -72,12 +72,11 @@@assert run_calls == [(["loginctl", "enable-linger", "testuser"], True, True, False)]- def test_loginctl_failure_shows_manual_guidance(self, monkeypatch, capsys):+ def test_loginctl_failure_shows_manual_guidance(self, monkeypatch, capsys, tmp_path):monkeypatch.setattr(gateway, "is_linux", lambda: True)- monkeypatch.setattr(gateway, "is_termux", lambda: False)monkeypatch.setattr("getpass.getuser", lambda: "testuser")- monkeypatch.setattr(gateway, "Path", lambda _path: SimpleNamespace(exists=lambda: False))+ _stub_linger_file(monkeypatch, tmp_path, exists=False)+ _root_with_system_unit_pinned_home(monkeypatch, tmp_path)monkeypatch.setattr(gateway, "get_systemd_linger_status", lambda username=None: (False, ""))monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/loginctl")monkeypatch.setattr(diff --cc tests/hermes_cli/test_process_identity.pyindex df9fc548e18,2ac50a0f017..ad3c18dc70b--- a/tests/hermes_cli/test_process_identity.py+++ b/tests/hermes_cli/test_process_identity.py@@@ -247,7 -247,7 +247,7 @@@ def _holders(*pids)def test_updater_reaps_ledger_proven_orphans():-- from hermes_cli import main as cli_main++ from hermes_cli import update_cmd_windowsentries = [_entry(200, 2.0, spawner_pid=700, spawner_create=7.0), # spawner dead → reap@@@ -258,13 -258,29 +258,29 @@@with patch.dict(sys.modules, {"psutil": fake}), \patch.object(pi, "ledger_entries", return_value=entries), \patch.object(pi, "spawner_is_dead", wraps=pi.spawner_is_dead):-- assert cli_main._ledger_reapable_backend_pids(_holders(200, 201, 202, 203)) == [200]++ assert update_cmd_windows._ledger_reapable_backend_pids(_holders(200, 201, 202, 203)) == [200]def test_updater_ledger_rung_never_raises():-- from hermes_cli import main as cli_main++ from hermes_cli import update_cmd_windowswith patch.object(pi, "ledger_entries", side_effect=RuntimeError("boom")):-- assert cli_main._ledger_reapable_backend_pids(_holders(200)) == []++ assert update_cmd_windows._ledger_reapable_backend_pids(_holders(200)) == []+++ def test_desktop_ssh_backend_spawn_shape_is_desktop_owned(monkeypatch):+ """Desktop's SSH spawn is ``env HERMES_DESKTOP=1 hermes serve --isolated ... --ssh-session-token-file F``+ with NO token env var (its tests assert the var name never appears on the wire). Missing that+ shape made the SSH child claim ROLE_SERVE on the remote host (the #119824 shape there)."""+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)+ ssh_argv = ["serve", "--isolated", "--host", "127.0.0.1", "--port", "0",+ "--ssh-session-token-file", "/home/u/.hermes/desktop-ssh/abc.token"]++ assert pi.is_desktop_owned_backend(ssh_argv) is True+ monkeypatch.setattr(sys, "argv", ["hermes", *ssh_argv])+ assert pi.is_desktop_owned_backend() is True+ # The bare inherited flag (a Desktop terminal pane running `hermes serve`) is still not ownership.+ assert pi.is_desktop_owned_backend(["serve", "--host", "127.0.0.1", "--port", "0"]) is Falsediff --cc tests/hermes_cli/test_update_fleet_restart_pending.pyindex 6fc72772199,49b96664a3c..b15656ebdbb--- a/tests/hermes_cli/test_update_fleet_restart_pending.py+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py@@@ -740,6 -882,69 +740,67 @@@ def test_startup_warn_kept_without_posiassert update_cmd_fleet._fleet_restart_obligation_armed()+ # ── Carried local commits: HEAD past ``expected_sha`` with no pull behind it (#119367) ──+ #+ # A cherry-picked hotfix on top of the pulled SHA moves HEAD without arming a fresh obligation,+ # so an equality gate on ``expected_sha`` could never discharge the old one: every CLI start+ # warned and every no-op ``hermes update`` exited 1 while the gateway verifiably served HEAD.+++ def _checkout_with_carried_commit(monkeypatch, tmp_path):+ """A real checkout: the update's SHA plus one local commit on top; returns (expected, head)."""+ import subprocess++ repo = tmp_path / "checkout"+ repo.mkdir()++ def git(*args):+ return subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True, check=True).stdout.strip()++ git("init", "-q", "-b", "main")+ git("config", "user.email", "t@t")+ git("config", "user.name", "t")+ (repo / "a").write_text("1")+ git("add", "a")+ git("commit", "-qm", "pulled")+ expected = git("rev-parse", "HEAD")+ (repo / "b").write_text("2")+ git("add", "b")+ git("commit", "-qm", "carried hotfix")+ head = git("rev-parse", "HEAD")+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", repo)+ _patch_marker_sha(monkeypatch, head)+ return expected, head+++ def test_obligation_discharges_when_gateway_serves_descendant_of_expected_sha(monkeypatch, tmp_path, capsys):+ expected, head = _checkout_with_carried_commit(monkeypatch, tmp_path)+ update_cmd._write_fleet_restart_pending_marker(expected_sha=expected, runtimes=[{"kind": "gateway", "profile": "default"}])+ monkeypatch.setattr(+ "hermes_cli.update_receipt.collect_fleet_versions",+ lambda **kwargs: [{"profile": "default", "pid": 42, "code_sha": head, "code_version": "0.21.4", "state": "current"}],+ )- monkeypatch.setattr(update_cmd, "_run_pending_fleet_restart", lambda: pytest.fail("nothing to restart"))-- update_cmd._apply_pending_fleet_restart_catchup() # must not sys.exit(1)++ assert update_cmd._pending_fleet_restart_needed() is False+ update_cmd._warn_pending_fleet_restart_on_startup()++ assert capsys.readouterr().err == ""+ assert not update_cmd_fleet._fleet_restart_obligation_armed()+++ def test_obligation_kept_when_gateway_serves_stale_code_on_carried_checkout(monkeypatch, tmp_path, capsys):+ expected, _head = _checkout_with_carried_commit(monkeypatch, tmp_path)+ update_cmd._write_fleet_restart_pending_marker(expected_sha=expected, runtimes=[{"kind": "gateway", "profile": "default"}])+ monkeypatch.setattr(+ "hermes_cli.update_receipt.collect_fleet_versions",+ lambda **kwargs: [{"profile": "default", "pid": 42, "code_sha": "0" * 40, "code_version": "0.21.3", "state": "stale"}],+ )++ update_cmd._warn_pending_fleet_restart_on_startup()++ assert "did not restart running gateways" in capsys.readouterr().err+ assert update_cmd_fleet._fleet_restart_obligation_armed()++def test_startup_warn_kept_when_receipt_owed_gateway_is_down(monkeypatch, capsys):"""A sibling the restart phase killed yields no startup row; the marker still owns it."""disk_sha = "e" * 40@@@ -914,27 -1119,27 +975,15 @@@ def test_empty_inventory_does_not_arm_mdef test_pending_fleet_restart_cleared_instead_of_exit_1(monkeypatch, tmp_path):"""Repro: an already-up-to-date host carrying an empty-inventory marker must exit 0 with-- no restart run — not print 'Fleet restart incomplete' and exit 1 (#115311)."""++ no restart obligation — not print 'Fleet restart incomplete' and exit 1 (#115311)."""args = _update_args()_patch_update_deps(monkeypatch, tmp_path, _make_up_to_date_side_effect())marker = _write_marker_with_inventory("abc123", [])-- seen = {"ran": False}monkeypatch.setattr(update_cmd_fleet, "_current_checkout_sha", lambda: "abc123")-- monkeypatch.setattr(-- update_cmd,-- "_run_pending_fleet_restart",-- lambda: seen.__setitem__("ran", True) or True,-- )-- monkeypatch.setattr(-- update_cmd_fleet,-- "_run_pending_fleet_restart",-- lambda: seen.__setitem__("ran", True) or True,-- )hermes_main.cmd_update(args)-- assert seen["ran"] is Falseassert not marker.exists()diff --cc tests/hermes_cli/test_update_import_guard.pyindex 7954db05616,a90fd96298f..626d7b88677--- a/tests/hermes_cli/test_update_import_guard.py+++ b/tests/hermes_cli/test_update_import_guard.py@@@ -16,15 -16,16 +16,15 @@@ and the syntax guard reported the updatfrom __future__ import annotations--import sys++import secretsfrom pathlib import Pathimport pytestfrom hermes_cli import update_cmd--import hermes_cli.update_cmd_deps as update_cmd_deps++from hermes_cli import update_cmd_validationfrom hermes_constants import partial_update_hint-def _write_skewed_tree(root: Path, *, skewed: bool) -> None:"""Build a tiny two-package tree that mimics the real failure.@@@ -56,7 -58,7 +56,7 @@@ def test_syntax_guard_passes_but_import# The import guard catches it.monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)assert ok is Falseassert module == "consumer"@@@ -65,7 -67,8 +65,7 @@@def test_import_guard_passes_on_consistent_tree(monkeypatch, tmp_path):_write_skewed_tree(tmp_path, skewed=False)monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)@@@ -76,7 -80,7 +76,7 @@@ def test_import_guard_ignores_non_impor"raise RuntimeError('no API key configured')\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, _, _ = update_cmd._validate_critical_modules_import(tmp_path)assert ok is True@@@ -85,7 -90,7 +85,7 @@@ def test_import_guard_can_report_non_im"""Stash restore can compare runtime failures before and after apply."""(tmp_path / "consumer.py").write_text("raise RuntimeError('broken config')\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path, report_runtime_errors=True@@@ -101,7 -107,7 +101,7 @@@ def test_import_guard_can_report_missin"""Stash comparison must see newly introduced missing dependencies."""(tmp_path / "consumer.py").write_text("import totally_not_installed_pkg\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path, report_runtime_errors=True@@@ -114,7 -120,8 +114,7 @@@def test_import_failure_comparison_preserves_exception_type(monkeypatch, tmp_path):source = tmp_path / "consumer.py"monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))source.write_text("raise RuntimeError('stopped')\n")runtime_failure = update_cmd._critical_module_import_failures(tmp_path, report_runtime_errors=True@@@ -133,7 -141,7 +133,7 @@@ def test_import_guard_reports_probe_ter"""A terminating import is unsafe when validating a restored stash."""(tmp_path / "consumer.py").write_text("import os\nos._exit(7)\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path, report_runtime_errors=True@@@ -147,7 -156,7 +147,7 @@@ def test_import_guard_reports_probe_ter"""A missing health marker must not classify a terminated probe as healthy."""(tmp_path / "consumer.py").write_text("import os\nos._exit(9)\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@@ -159,7 -169,7 +159,7 @@@ def test_import_guard_reports_system_ex"""Catchable terminating imports must not complete with a healthy marker."""(tmp_path / "consumer.py").write_text("raise SystemExit('stopped')\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@@ -176,7 -187,7 +176,7 @@@ def test_import_guard_does_not_accept_f"os._exit(7)\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@@ -189,12 -201,12 +189,12 @@@ def test_import_guard_rejects_malformedreturncode = 0stdout = ""-- def malformed(cmd, **_kwargs):-- marker = cmd[-1].split("sys.stdout.write('\\n", 1)[1].split("'", 1)[0]-- Result.stdout = f"{marker}{{}}"++ def malformed(_cmd, **_kwargs):++ Result.stdout = "__HERMES_IMPORT_HEALTH_fixed__{}"return Result()-- monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", malformed)++ monkeypatch.setattr(secrets, "token_hex", lambda _length: "fixed")++ monkeypatch.setattr(update_cmd_validation.subprocess, "run", malformed)ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@@ -204,9 -216,10 +204,9 @@@def test_import_guard_reports_probe_timeout(monkeypatch, tmp_path):def timeout(*_args, **_kwargs):-- return None++ raise update_cmd_validation.subprocess.TimeoutExpired("python", 120)-- monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", timeout)++ monkeypatch.setattr(update_cmd_validation.subprocess, "run", timeout)ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@@ -222,10 -236,13 +222,10 @@@ def test_untracked_enumeration_failure_assert update_cmd._git_untracked_paths(["git"], tmp_path) is None---[email protected](sys.platform == "win32", reason="POSIX exec-bit PermissionError")[email protected]("posix")def test_import_guard_is_non_fatal_when_probe_cannot_run(tmp_path):"""A venv interpreter that exists but cannot be executed must not read as a hung probe:-- spawn failure stays advisory (real ``bounded_probe_run``, real ``Popen``)."""++ spawn failure stays advisory through the real ``subprocess.run`` path."""venv_python = tmp_path / "venv" / "bin" / "python"venv_python.parent.mkdir(parents=True)venv_python.write_text("#!/bin/sh\nexit 0\n")@@@ -251,24 -271,25 +251,15 @@@ def test_hint_stays_silent_for_unrelateexc.name = "requests"assert partial_update_hint(exc) == []---def test_import_guard_prefers_the_project_venv_interpreter(monkeypatch, tmp_path):-- """``hermes update`` can run under a different Python than the install's.---- Probing ``sys.executable`` would then validate a tree the user never-- actually runs -- the same reasoning behind ``_venv_core_imports_healthy``.-- On Windows (the platform this guard exists for) the driving interpreter-- and the venv interpreter routinely differ.-- """-- bin_dir = "Scripts" if update_cmd._m()._is_windows() else "bin"-- name = "python.exe" if update_cmd._m()._is_windows() else "python"-- venv_python = tmp_path / "venv" / bin_dir / name-- venv_python.parent.mkdir(parents=True)-- venv_python.write_text("")--++def test_import_guard_uses_the_selected_runtime_command(monkeypatch, tmp_path):seen: dict = {}++ def fake_runtime_command(root, *, code):++ assert root == tmp_path++ return ["/pm/python", "-I", "-c", code]++def fake_run(cmd, **kwargs):-- seen["interpreter"] = cmd[0]++ seen["command"] = cmdseen["cwd"] = kwargs["cwd"]class R:@@@ -278,12 -299,13 +269,13 @@@return R()-- monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", fake_run)++ monkeypatch.setattr(update_cmd_validation, "runtime_command", fake_runtime_command)++ monkeypatch.setattr(update_cmd_validation.subprocess, "run", fake_run)update_cmd._validate_critical_modules_import(tmp_path)-- assert seen["interpreter"] == str(venv_python)++ assert seen["command"][:3] == ["/pm/python", "-I", "-c"]assert seen["cwd"] == str(tmp_path)-def test_import_guard_ignores_missing_third_party_dependency(monkeypatch, tmp_path):"""A new third-party requirement is not a partially-updated tree.@@@ -293,7 -315,7 +285,7 @@@"""(tmp_path / "consumer.py").write_text("import totally_not_installed_pkg\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)@@@ -315,7 -338,7 +307,7 @@@ def test_import_guard_rejects_module_saupdate_cmd, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",))monkeypatch.setattr(-- update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)++ update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",))monkeypatch.setenv("PYTHONPATH", str(stale))@@@ -337,7 -361,7 +329,7 @@@ def test_import_guard_accepts_candidateupdate_cmd, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",))monkeypatch.setattr(-- update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",)++ update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("hermes_stale_supply",))monkeypatch.setenv("PYTHONPATH", str(stale))@@@ -349,7 -374,7 +341,7 @@@ def test_import_guard_flags_missing_fir(tmp_path / "tools" / "__init__.py").write_text("")(tmp_path / "consumer.py").write_text("import tools.nonexistent_module\n")monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))-- monkeypatch.setattr(update_cmd_deps, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ monkeypatch.setattr(update_cmd_validation, "_UPDATE_CRITICAL_MODULES", ("consumer",))ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)assert ok is Falsediff --cc tests/hermes_cli/test_update_unit_client_budget.pyindex 2f8529fc056,ddf5ddb45f6..0ab9b29a2d0--- a/tests/hermes_cli/test_update_unit_client_budget.py+++ b/tests/hermes_cli/test_update_unit_client_budget.py@@@ -31,7 -34,14 +31,7 @@@ def test_unit_transaction_budget_preserreturn subprocess.CompletedProcess(cmd, 0, "active", "")monkeypatch.setattr(fleet, "_systemctl", systemctl)- monkeypatch.setattr(fleet, "_drain_or_signal_gateway_for_update", lambda *a: True)- if catchup:- monkeypatch.setattr(fleet, "_SYSTEMD_SCOPES", (("user", scope),))- failed = []- fleet._restart_systemd_gateway_units_best_effort(failed, list(fleet._systemd_gateway_unit_listings()))- assert not failed- assert sum("restart" in cmd for cmd, _ in calls) == 1- return+ monkeypatch.setattr(fleet, "_drain_or_signal_gateway_for_update", lambda *a, **kw: True)health = iter([False, True] if retry else [True])monkeypatch.setattr(fleet, "_wait_for_service_active", lambda *a, **kw: next(health))name = "hermes-gateway-test" if graceful else "hermes-serve-test"diff --cc tests/hermes_cli/test_web_server.pyindex 6cd0f848b9e,790590e0313..52de62a3479--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@@ -906,28 -906,28 +906,19 @@@ CONFIG_SCHEMA = ProviderConfigSchemaassert "api_key" not in provider_config-- def test_post_memory_provider_setup_routes_pip_through_lazy_deps(self, monkeypatch):-- """NS-605: dashboard pip installs must use the environment-aware-- lazy_deps pipeline (durable-target redirect on immutable hosted-- images), never a direct `pip install --python sys.executable`."""++ def test_post_memory_provider_setup_routes_python_deps_through_pm(self, monkeypatch):++ """Dashboard dependency setup publishes through PM, never direct pip."""import subprocess as _subprocessimport hermes_cli.web_server as web_server-- from tools import lazy_deps as ld++ from hermes_cli import memory_setup-- # honcho declares pip_dependencies: [honcho-ai]; force it missing.-- monkeypatch.setattr(_web_server_memory, "_dependency_importable", lambda dep: False)---- installed = []---- def fake_install_specs(specs, *, timeout=300):-- installed.append(tuple(specs))-- return ld.InstallSpecsResult(-- ok=True, command="uv pip install --target /opt/data/lazy-packages honcho-ai",-- stdout="ok", stderr="",-- )---- monkeypatch.setattr(ld, "install_specs", fake_install_specs)++ prepared = []++ monkeypatch.setattr(++ memory_setup,++ "prepare_memory_provider_dependencies",++ lambda name: (prepared.append(name) or ({}, "installed")),++ )# Any direct pip/uv subprocess from the memory-provider pip path is# a regression; external-dep checks may still run subprocess, so only@@@ -947,8 -947,8 +938,8 @@@data = resp.json()pip_rows = [row for row in data["results"] if row["kind"] == "pip"]assert pip_rows and pip_rows[0]["status"] == "installed"-- assert "--target /opt/data/lazy-packages" in pip_rows[0]["command"]-- assert installed == [("honcho-ai",)]++ assert pip_rows[0]["command"] == "hermes pm install"++ assert prepared == ["honcho"]def test_put_memory_provider_config_writes_config_and_secret(self):@@@ -4530,6 -4603,6 +4594,7 @@@ def test_resolve_chat_argv_injects_gateimport hermes_cli.main_tui_launch as tui_launchimport hermes_cli.web_server as ws++ monkeypatch.setenv("PATH", "/run/current-system/sw/bin:/usr/bin")monkeypatch.setattr(tui_launch,"_make_tui_argv",diff --cc tests/tui_gateway/test_fast_session_scope.pyindex 47eb3957777,81ab30182d4..ceb09814852--- a/tests/tui_gateway/test_fast_session_scope.py+++ b/tests/tui_gateway/test_fast_session_scope.py@@@ -101,6 -108,16 +102,15 @@@ class TestConfigSetFastSessionScopeassert resp["result"]["value"] == "normal"write_key.assert_called_once_with("agent.service_tier", "normal")+ def test_stale_session_id_is_refused_not_persisted_globally(self) -> None:+ """A runtime id the backend no longer holds (reaped / re-minted) is not "no session": it+ must 4001 so the client resumes, not rewrite the profile's tier for every surface."""+ with patch.dict(server._sessions, {}, clear=True), \+ patch.object(server, "_write_config_key") as write_key:+ resp = _set({"key": "fast", "session_id": "reaped-sid", "value": "normal"})+ assert resp.get("error", {}).get("code") == 4001, resp+ write_key.assert_not_called()+-class TestConfigGetFastSessionScope:def test_reads_prebuild_pin(self) -> None:session = {