Skip to content

The agent that grows with you

Merge origin/main into ethie/pm-clean

ethernet97de4b4ef8a1
diff --cc .github/workflows/tests.yml
index 99a25e7a52d,191bf29d025..0752fc28dc4
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@@ -41,13 -41,68 +41,22 @@@ jobs
rm -rf "$RG_TARBALL" "ripgrep-${RG_VERSION}-x86_64-unknown-linux-musl"
rg --version
- - name: Install uv
- uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
+ - name: Set up locked Python and test dependencies
+ uses: ./.github/actions/setup-pm
with:
- # Pin the uv version: unpinned, setup-uv resolves "latest" by
- # fetching a manifest from raw.githubusercontent.com on EVERY job —
- # a transient fetch failure fails the whole job (2026-07-28 slice-5
- # incident). Pinned, the binary downloads directly; no manifest hop.
- #
- # The uv pin also fixes which CPython `uv python install 3.11`
- # resolves, and with it the linked SQLite. uv 0.9.28 resolved
- # 3.11.14 / SQLite 3.50.4, which has the WAL-reset bug, so Hermes
- # ran every state.db in DELETE mode here and the WAL path went
- # untested. 0.12.13 resolves 3.11.16 / SQLite 3.53.1. The
- # "Check SQLite runs WAL" step fails the job if a bump regresses it.
- version: "0.12.13"
- # Persist uv's download/wheel cache (~/.cache/uv) across runs.
- # Keyed on the dependency manifests, so the cache is reused until
- # pyproject.toml or uv.lock changes. `uv sync` still runs every
- # time, but resolves from the warm cache instead of re-downloading
- # and re-building wheels.
- enable-cache: true
- cache-dependency-glob: |
- pyproject.toml
- uv.lock
-
- - name: Set up Python 3.11
- uses: ./.github/actions/retry
- with:
- command: uv python install 3.11
-
- - name: Install dependencies
- # `uv sync --locked` installs the exact pinned set from uv.lock (and
- # fails if the lock is out of sync with pyproject.toml), giving a
- # reproducible env. It also creates .venv itself, so no separate
- # `uv venv` step is needed.
- #
- # The trailing extras beyond all/dev are the lazy-install features
- # (tools/lazy_deps.py) that tests exercise for real: provider.anthropic,
- # stt/tts.mistral, image.fal, terminal.modal, terminal.daytona,
- # search.parallel, provider.bedrock. The hermetic test env forbids
- # mid-run pip installs (HERMES_DISABLE_LAZY_INSTALLS=1 in
- # tests/conftest.py), so the SDKs those tests need must be in the
- # venv up front — resolved from uv.lock like everything else, which
- # also honors the exact supply-chain pins these extras carry.
- uses: ./.github/actions/retry
- with:
- command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web --extra bedrock
-
- - name: Minimize uv cache
- # Optimized for CI: prunes pre-built wheels that are cheap to
- # re-download, keeping the persisted cache small and fast to restore.
- run: uv cache prune --ci
+ extras: '["all", "anthropic", "bedrock", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'
+ test-environment: 'true'
+ prune-python-cache: true
+ - name: Check SQLite runs WAL
+ # Hermes picks DELETE journal mode on a SQLite with the WAL-reset
- # bug. If this interpreter links one, every WAL test silently runs
- # DELETE (or skips), so fail loudly instead. Tests that need DELETE
++ # bug. If the PM-pinned interpreter links one, every WAL test silently
++ # runs DELETE (or skips), so fail loudly instead. Tests that need DELETE
+ # select it explicitly (journal_mode config, a pinned vulnerable
+ # version), so they run on any interpreter.
+ run: |
- .venv/bin/python -c "import sqlite3, sys, hermes_state_wal as w; v = w.is_sqlite_wal_reset_vulnerable(); print(f'Python {sys.version.split()[0]}, SQLite {sqlite3.sqlite_version}, WAL-reset vulnerable: {v}'); sys.exit(1 if v else 0)"
++ "$HERMES_PYTHON" -c "import sqlite3, sys, hermes_state_wal as w; v = w.is_sqlite_wal_reset_vulnerable(); print(f'Python {sys.version.split()[0]}, SQLite {sqlite3.sqlite_version}, WAL-reset vulnerable: {v}'); sys.exit(1 if v else 0)"
+
- name: Restore per-file duration cache
# scripts/run_tests_parallel.py raises a file's timeout to
# 3x its last healthy duration (_effective_file_timeout) so a
@@@ -135,17 -196,75 +153,34 @@@
rm -rf "$RG_TARBALL" "ripgrep-${RG_VERSION}-x86_64-unknown-linux-musl"
rg --version
- - name: Install uv
- uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- with:
- # Pin the uv version: unpinned, setup-uv resolves "latest" by
- # fetching a manifest from raw.githubusercontent.com on EVERY job —
- # a transient fetch failure fails the whole job (2026-07-28 slice-5
- # incident). Pinned, the binary downloads directly; no manifest hop.
- # Newer than the unit job's pin on purpose: 0.9.28 only knows CPython
- # 3.11.14, whose bundled SQLite has the WAL-reset bug, so Hermes runs
- # state.db in DELETE mode and the WAL torture chamber would skip.
- version: "0.12.13"
- # Persist uv's download/wheel cache (~/.cache/uv) across runs.
- # Keyed on the dependency manifests, so the cache is reused until
- # pyproject.toml or uv.lock changes. `uv sync` still runs every
- # time, but resolves from the warm cache instead of re-downloading
- # and re-building wheels.
- enable-cache: true
- # Own cache entry: the unit job's older uv would otherwise share and
- # overwrite this key with a cache this uv version did not write.
- cache-suffix: e2e
- cache-dependency-glob: |
- pyproject.toml
- uv.lock
-
- - name: Set up Python 3.11
- run: uv python install 3.11.15
-
- - name: Install dependencies
- # `uv sync --locked` installs the exact pinned set from uv.lock (and
- # fails if the lock is out of sync with pyproject.toml), giving a
- # reproducible env. It also creates .venv itself, so no separate
- # `uv venv` step is needed.
- #
- # Same extras as the test job's sync above: the hermetic test env
- # forbids mid-run pip installs (HERMES_DISABLE_LAZY_INSTALLS=1 in
- # tests/conftest.py), so lazy-install SDKs exercised by tests must be
- # in the venv up front.
- uses: ./.github/actions/retry
+ - name: Set up locked Python and test dependencies
+ uses: ./.github/actions/setup-pm
with:
- command: uv sync --locked --python 3.11.15 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web --extra bedrock
-
- - name: Minimize uv cache
- # Optimized for CI: prunes pre-built wheels that are cheap to
- # re-download, keeping the persisted cache small and fast to restore.
- run: uv cache prune --ci
+ extras: '["all", "anthropic", "bedrock", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'
+ test-environment: 'true'
+ prune-python-cache: true
+ - name: Require a WAL-capable SQLite
+ # The state.db suites skip on a WAL-reset-vulnerable SQLite; fail
+ # instead of reporting green over zero coverage.
+ run: |
- source .venv/bin/activate
- python -c "import sqlite3, hermes_state_wal as w; print('sqlite', sqlite3.sqlite_version); assert not w.is_sqlite_wal_reset_vulnerable()"
++ "$HERMES_PYTHON" -c "import sqlite3, hermes_state_wal as w; print('sqlite', sqlite3.sqlite_version); assert not w.is_sqlite_wal_reset_vulnerable()"
+
- name: Run e2e tests
+ # One subprocess per file, in parallel: the core suites spawn real
+ # processes (serve, gateway, tui_gateway, MCP servers, SQLite writers)
+ # and must not share interpreter state.
run: |
- scripts/run_tests.sh tests/e2e/ -v --tb=short
- source .venv/bin/activate
+ scripts/run_tests.sh --include-integration tests/e2e
env:
+ # Multi-process episodes (torture chamber, compaction kill -9,
+ # gateway liveness, delivery exactly-once through a real gateway,
+ # the cron virtual-clock soak) legitimately run past the 300 s default.
+ HERMES_TEST_FILE_TIMEOUT: "900"
+ # No automatic re-run of a failed file: the torture chamber and the
+ # exactly-once/compaction suites are race detectors, and a rare
+ # corruption that passes on retry is still a corruption.
+ HERMES_TEST_FILE_RETRIES: "0"
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
NOUS_API_KEY: ""
diff --cc apps/desktop/electron/main.ts
index dc04270d330,b6b23d8d4cb..9cf6a194501
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -228,24 -213,27 +228,24 @@@ import
} from './find-in-page'
import { createFirstRunSetupGate } from './first-run-setup-gate'
import { registerFsIpc } from './fs-ipc'
+import type {
+ GatewayFileSaveContext,
+ GatewayFileSaveDeps,
+ GatewayFileSaveResult,
+ GatewaySaveDialogOptions,
+ GatewaySaveDialogResult
+} from './gateway-file-download'
import {
- filenameFromContentDisposition,
- fsPumpDeps,
gatewayFilePath,
gatewayFileRequestPaths,
- isNotFoundError,
- parseDataUrlToBuffer,
- pumpStreamToFile,
resolveGatewayFileBackend,
- writeBufferToFile
+ saveGatewayDownload
} from './gateway-file-download'
-import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
+import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'
+import { stopGatewayBeforeUpdate } from './gateway-stop-before-update'
+import { resolveGatewayVersion } from './gateway-version'
- import { probeGatewayWebSocket } from './gateway-ws-probe'
+ import { probeGatewayWebSocket, spawnedBackendProbeOptions } from './gateway-ws-probe'
import { registerGitIpc } from './git-ipc'
-import {
- describeGitHubCredentialSource,
- forgetGhCliToken,
- githubApiHeaders,
- githubTokenRejected,
- resolveGitHubCredential
-} from './github-api-auth'
import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'
import { readAndConsumeHandoffResult } from './handoff-result'
import {
@@@ -11733,11 -12799,13 +11733,13 @@@ async function spawnPoolBackend
const baseUrl = `http://127.0.0.1:${port}`
await Promise.race([waitForHermes(baseUrl, token), startFailed])
- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })
+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
ready = true
+ const childAlive = () => child.exitCode === null && !child.killed
+
const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive: () => child.exitCode === null && !child.killed,
+ childAlive,
label: `Hermes backend for profile "${profile}"`,
rememberLog
})
@@@ -11749,8 -12817,14 +11751,13 @@@
// Verify the WebSocket session token before declaring backend ready.
// HTTP /api/status can pass while WS auth fails (separate transport, separate guards).
const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
- const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })
+
+ // Our own child: a cold start can stall its loop past the base budget (#96177).
+ const wsProbe = await probeGatewayWebSocket(wsUrl, {
+ WebSocketImpl: globalThis.WebSocket,
+ ...spawnedBackendProbeOptions(childAlive)
+ })
-
- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })
+ assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
if (!wsProbe.ok) {
throw new Error(
diff --cc apps/desktop/scripts/after-pack.mjs
index 504f7d4faaf,56a471c74bd..e1735069787
--- a/apps/desktop/scripts/after-pack.mjs
+++ b/apps/desktop/scripts/after-pack.mjs
@@@ -1,94 -1,30 +1,120 @@@
-/** Restore the empty app-level localizations dropped during Electron extraction.
- * Run after language filtering and before signing; derive the markers from the
- * packaged framework, not the host's Electron (which may be another version).
- * Windows identity stamping stays in afterExtract, before ASAR integrity.
+/**
+ * after-pack.mjs — electron-builder afterPack hook.
+ *
+ * Per-platform post-pack work on the unpacked app: payload relocation, nested
+ * Chromium + wheel signing on macOS, PE signature sanitizing and batch signing
+ * on Windows. The exe identity stamp lives in after-extract.mjs (#105629).
+ *
+ * electron-builder passes a context with:
+ * - electronPlatformName: 'win32' | 'darwin' | 'linux'
+ * - appOutDir: the unpacked app directory for this target
+ * - packager.appInfo.productFilename: the exe basename (e.g. 'Hermes')
*/
-import { mkdir, readdir } from 'node:fs/promises'
+
import path from 'node:path'
+import fs from 'node:fs'
++import { mkdir, readdir } from 'node:fs/promises'
+import { runPython } from '../../../scripts/build/python.mjs'
-export default async function afterPack({ electronPlatformName, appOutDir, packager }) {
- if (electronPlatformName !== 'darwin') {
- return
- }
+import { batchSignAppTree } from './batch-sign-binaries.mjs'
+import { rehashPayloadDigests } from './payload-digests.mjs'
+import { resolveSigningIdentity, signNestedChromium } from './sign-nested-chromium.mjs'
+import { signWheelZipMembers } from './sign-wheel-zips.mjs'
+import { sanitizeTree } from './sanitize-pe-signatures.mjs'
++/**
++ * Restore the empty app-level localizations dropped during Electron extraction.
++ * Runs after language filtering and before signing; the markers come from the
++ * packaged framework, not the host's Electron (which may be another version).
++ * Non-blocking: a failed restore leaves a usable package and says so.
++ */
++export async function restoreMacLocaleMarkers({ appOutDir, packager }) {
+ try {
+ const resources = packager.getResourcesDir(appOutDir)
+ const framework = packager.getMacOsElectronFrameworkResourcesDir(appOutDir)
+ const entries = await readdir(framework, { withFileTypes: true })
+ // Chromium also ships grammatical-gender packs; these are not macOS locales.
+ const locales = entries.filter(
+ entry =>
+ entry.isDirectory() && entry.name.endsWith('.lproj') && !/_(FEMININE|MASCULINE|NEUTER)\.lproj$/.test(entry.name)
+ )
+ await Promise.all(locales.map(entry => mkdir(path.join(resources, entry.name), { recursive: true })))
+ } catch (error) {
- // Keep an otherwise usable package, but make failed locale restoration visible.
+ console.warn(
+ `[after-pack] macOS locale markers were not restored: ${error instanceof Error ? error.message : String(error)}`
+ )
+ }
+ }
++
+export default async function afterPack(context) {
+ const platform = context.electronPlatformName
+ const resources = platform === 'darwin'
+ ? path.join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources')
+ : path.join(context.appOutDir, 'resources')
+ const payload = path.join(resources, 'agent-payload')
+ if (platform !== 'win32' && fs.existsSync(path.join(payload, 'manifest.json'))) {
+ runPython([
+ path.resolve(import.meta.dirname, '../../../scripts/bundles/payload.py'), 'relocate', payload], { stdio: 'inherit' })
+ }
+ if (platform === 'darwin') {
++ await restoreMacLocaleMarkers(context)
+ if (fs.existsSync(payload)) {
+ const entitlements = path.join(import.meta.dirname, '..', 'electron', 'entitlements.mac.inherit.plist')
+ const { identity, keychain } = await resolveSigningIdentity(context.packager)
+ const nested = signNestedChromium(payload, { entitlements, identity, keychain })
+ console.log(
+ `[after-pack] repaired ${nested.repaired} framework links; signed ${nested.signed} nested chromium targets` +
+ (identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)')
+ )
+ // uv-cache wheel zips carry Mach-O members the notary validates but
+ // electron-osx-sign cannot reach; sign them in place (see module doc).
+ const wheels = signWheelZipMembers(payload, { identity, keychain })
+ if (wheels.signed > 0) {
+ console.log(
+ `[after-pack] signed ${wheels.signed} Mach-O members across ${wheels.wheels} payload wheel zips` +
+ (identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)'))
+ }
+ // The macOS signer refreshes this again before sealing the outer app.
+ // Unsigned builds end here and still need final-byte facts.
+ rehashPayloadDigests(payload)
+ }
+ return
+ }
+ if (platform === 'linux') {
+ return
+ }
+ if (platform !== 'win32') {
+ return
+ }
+
+ const productName = context.packager?.appInfo?.productFilename || 'Hermes'
+ const exe = path.join(context.appOutDir, `${productName}.exe`)
+
+ // Repair dangling PE certificate tables BEFORE electron-builder signs the
+ // tree. A stripped-but-still-declared signature makes signtool reject the
+ // file with 0x800700C1, and AppxSIP inspects every PE inside the MSIX, so
+ // one bad payload DLL fails the whole package. Unlike the stamp below this
+ // is NOT best-effort: shipping past it means shipping an unsignable bundle.
+ // this is a hack until https://github.com/astral-sh/python-build-standalone/pull/1217 is merged.
+ const { scanned, repaired } = sanitizeTree(context.appOutDir)
+ console.log(`[after-pack] ${scanned} PEs scanned, ${repaired.length} dangling certificate tables cleared`)
+ for (const file of repaired) {
+ console.log(` ${file}`)
+ }
+
+ // The identity stamp already ran from afterExtract on the pristine exe
+ // (scripts/after-extract.mjs, #105629); rcedit cannot commit to the
+ // ASAR-integrity-rewritten PE we hold here.
+
+ // Batch-sign every payload binary AFTER sanitize (above) and the rcedit
+ // stamp: a dangling certificate table or a subsequent resource edit would
+ // invalidate the signature. The product exe is excluded here and signed
+ // per-file by the customSign hook (scripts/batch-sign-binaries.mjs) after
+ // electron-builder's own rcedit + fuses pass. No-op with a loud warning when
+ // the AZURE_SIGN_* environment is absent (unsigned/fork/canary lanes).
+ await batchSignAppTree(context.appOutDir, exe, {
+ config: context.packager.config,
+ resourcesDir: context.packager.buildResourcesDir,
+ })
+ rehashPayloadDigests(payload)
+}
diff --cc apps/desktop/scripts/after-pack.test.mjs
index 00000000000,3ef0500ee77..b908856c110
mode 000000,100644..100644
--- a/apps/desktop/scripts/after-pack.test.mjs
+++ b/apps/desktop/scripts/after-pack.test.mjs
@@@ -1,0 -1,66 +1,66 @@@
+ import { mkdtemp, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'
++import { createRequire } from 'node:module'
+ import os from 'node:os'
+ import path from 'node:path'
-import { Platform } from 'app-builder-lib'
-import { PlatformPackager } from 'app-builder-lib/out/platformPackager.js'
++import { Platform, PlatformPackager } from 'app-builder-lib'
+ import { expect, it, vi } from 'vitest'
+
-import pkg from '../package.json' with { type: 'json' }
++const require = createRequire(import.meta.url)
++const desktopRoot = path.resolve(import.meta.dirname, '..')
++// The builder config is electron-builder.config.cjs (package.json carries no `build` block).
++const builderConfig = require(path.join(desktopRoot, 'electron-builder.config.cjs'))
+
+ async function configuredHook(context) {
- if (pkg.build.afterPack) {
- const hook = await import(new URL(`../${pkg.build.afterPack}`, import.meta.url).href)
- await hook.default(context)
- }
++ const hook = await import(new URL(`../${builderConfig.afterPack}`, import.meta.url).href)
++ await hook.default(context)
+ }
+
+ function context(appOutDir, productFilename = 'Hermes Preview') {
+ // Use electron-builder's real bundle path resolution, including branding.
+ const packager = Object.assign(Object.create(PlatformPackager.prototype), {
+ platform: Platform.MAC,
+ appInfo: { productFilename },
+ info: { framework: { distMacOsAppName: 'Electron.app' } }
+ })
+ return { appOutDir, electronPlatformName: 'darwin', packager }
+ }
+
+ it('restores app localizations from the filtered framework without copying locale data', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-locale-pack-'))
+ try {
+ const ctx = context(root)
+ const framework = ctx.packager.getMacOsElectronFrameworkResourcesDir(root)
+ const resources = ctx.packager.getResourcesDir(root)
+ await mkdir(resources, { recursive: true })
+ for (const name of ['nb.lproj', 'en_GB.lproj', 'nb_FEMININE.lproj']) {
+ await mkdir(path.join(framework, name), { recursive: true })
+ await writeFile(path.join(framework, name, 'locale.pak'), 'untouched locale data')
+ }
+ await writeFile(path.join(framework, 'not-a-directory.lproj'), 'not a locale')
+ await mkdir(path.join(framework, 'other'), { recursive: true })
+ await configuredHook(ctx)
+ await configuredHook(ctx)
+ expect((await readdir(resources)).sort()).toEqual(['en_GB.lproj', 'nb.lproj'])
+ expect(await readdir(path.join(resources, 'nb.lproj'))).toEqual([])
+ expect(await readFile(path.join(framework, 'nb.lproj', 'locale.pak'), 'utf8')).toBe('untouched locale data')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
-it('leaves other platforms alone and reports a missing framework without failing packaging', async () => {
++it('leaves Linux alone and reports a missing framework without failing packaging', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-locale-pack-'))
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
- for (const electronPlatformName of ['linux', 'win32']) {
- await configuredHook({ appOutDir: root, electronPlatformName })
- }
++ // win32 is not a no-op here: the same hook sanitizes and batch-signs the PE tree.
++ await configuredHook({ appOutDir: root, electronPlatformName: 'linux' })
+ expect(await readdir(root)).toEqual([])
+ expect(warn).not.toHaveBeenCalled()
+ await configuredHook(context(root))
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('macOS locale markers were not restored'))
+ expect(await readdir(root)).toEqual([])
+ } finally {
+ warn.mockRestore()
+ await rm(root, { recursive: true, force: true })
+ }
+ })
diff --cc apps/desktop/src/app/shell/model-catalog-menu.tsx
index c5505a984de,1caf3d9bbab..10e21bc3036
--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx
@@@ -36,15 -28,11 +36,16 @@@ import { catalogProviderMatches, modelO
import { displayModelName, modelDisplayParts } from '@/lib/model-status-label'
import { reasoningEffortLabel } from '@/lib/reasoning-effort'
import { foldIncludes, normalize } from '@/lib/text'
-import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
+ import { $customModels, addCustomModel, customModelCandidate, withCustomModels } from '@/store/custom-models'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs, runningModelDownloads, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
+import {
+ type LocalModelsOwner,
+ runningModelDownloads,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
import {
$visibleModels,
collapseModelFamilies,
@@@ -151,7 -139,12 +152,12 @@@ export function ModelCatalogMenu(
const copy = t.shell.modelMenu
const copyPicker = t.modelPicker
const closeMenu = useContext(ModelMenuCloseContext)
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState<string>('')
+ // "Add custom model…" turns the search box into slug entry: the catalog
+ // steps aside until something is typed, and the placeholder says what to
+ // type. Typing a slug without this works too; the row just makes it findable.
+ const [slugEntry, setSlugEntry] = useState(false)
+ const searchRef = useRef<HTMLInputElement>(null)
const collapsedProviders = useStoreCollapsed()
const defaultEffort = useDefaultEffort()
// Which models the user curated in Edit Models. Read HERE rather than taken
diff --cc apps/desktop/src/components/model-picker.tsx
index 2a8a0768c9f,99a65357a85..95c67b4b4cc
--- a/apps/desktop/src/components/model-picker.tsx
+++ b/apps/desktop/src/components/model-picker.tsx
@@@ -1,24 -1,22 +1,26 @@@
import type { ModelOptionProvider, ModelPricing } from '@hermes/shared'
import { fuzzyRank, modelSearchText } from '@hermes/shared'
+ import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
- import { type ReactElement, useMemo, useState } from 'react'
-import { useEffect, useMemo, useRef, useState } from 'react'
++import { type ReactElement, useMemo, useRef, useState } from 'react'
-import { getLocalModelsStatus } from '@/hermes'
import { useI18n } from '@/i18n'
import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { currentPickerSelection } from '@/lib/model-status-label'
import { foldIncludes, normalize } from '@/lib/text'
-import { useStoreSelector } from '@/lib/use-session-slice'
+import { cn } from '@/lib/utils'
+ import { $customModels, addCustomModel, customModelCandidate, withCustomModels } from '@/store/custom-models'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import { $localRuntimeJobs, runningModelDownloads, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
-import type { LocalModelLoadProgress } from '@/types/hermes'
+import {
+ type LocalModelsOwner,
+ runningModelDownloads,
+ useLocalModelsOwner,
+ useLocalModelsStatus,
+ useLocalRuntimeJobs
+} from '@/store/local-runtime-jobs'
+import type { LocalModelLoadProgress, LocalRuntimeJob } from '@/types/hermes'
import type { HermesGateway } from '../hermes'
-import { cn } from '../lib/utils'
import { startManualOnboarding } from '../store/onboarding'
import { InlineNotice } from './notifications'
@@@ -68,7 -66,11 +70,11 @@@ export function ModelPickerDialog(
// an empty query), which destroys the backend's curated order. We disable
// it: an empty query shows the curated list verbatim (like the `hermes
// model` CLI picker) and a query ranks with the shared fuzzyRank.
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState<string>('')
+ // "Add custom model…" flips the search into slug entry: the typed id is
+ // offered per provider even while it fuzzy-matches catalog rows.
+ const [slugEntry, setSlugEntry] = useState(false)
+ const searchRef = useRef<HTMLInputElement>(null)
const modelOptions = useQuery({
queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),
@@@ -119,7 -123,38 +125,8 @@@
[downloadsKey]
)
- const providers = modelOptions.data?.providers ?? []
- // Rediscover in-flight work on open: the poller idles when nothing was
- // running, and a download can start from any surface.
- useEffect(() => {
- if (open && localModelsEnabled) {
- watchLocalRuntimeJobs()
- }
- }, [open, localModelsEnabled])
-
- // A finished download turns into a real selectable model — refetch the
- // options so the placeholder row is replaced while the picker is open.
- const refetchOptions = modelOptions.refetch
-
- useEffect(() => {
- if (!open) {
- return
- }
-
- let prevActive = runningModelDownloads($localRuntimeJobs.get()).length > 0
-
- return $localRuntimeJobs.listen(next => {
- const active = runningModelDownloads(next).length > 0
-
- if (prevActive && !active) {
- void refetchOptions()
- }
-
- prevActive = active
- })
- }, [open, refetchOptions])
-
+ const customModels = useStore($customModels)
+ const providers = withCustomModels(modelOptions.data?.providers ?? [], customModels)
const { model: optionsModel, provider: optionsProvider } = currentPickerSelection(
{ model: currentModel, provider: currentProvider },
@@@ -173,8 -224,9 +196,10 @@@
error={error}
loading={loading}
loadingModels={loadingModels}
+ offerCustom={slugEntry}
+ onSelectCustomModel={selectCustomModel}
onSelectModel={selectModel}
+ owner={owner}
providers={providers}
search={search}
/>
@@@ -204,19 -258,23 +232,24 @@@ function ModelResults(
downloads,
loadingModels,
onSelectModel,
+ onSelectCustomModel,
+ offerCustom,
search
}: {
+ owner: LocalModelsOwner
loading: boolean
error: string | null
- providers: ModelOptionProvider[]
+ providers: readonly ModelOptionProvider[]
currentModel: string
currentProvider: string
downloads: { jobId: string; target: string }[]
loadingModels: Record<string, LocalModelLoadProgress>
onSelectModel: (provider: ModelOptionProvider, model: string) => void
+ onSelectCustomModel: (provider: ModelOptionProvider, model: string) => void
+ /** Offer the typed id as a custom model even while catalog rows match. */
+ offerCustom: boolean
search: string
-}) {
+}): ReactElement {
const { t } = useI18n()
const copy = t.modelPicker
diff --cc apps/desktop/src/i18n/en.ts
index 41f6e33bd30,69a653318ad..a63c1d4d0f4
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -3,44 -3,40 +3,46 @@@ import { FIELD_DESCRIPTIONS, FIELD_LABE
import type { Translations } from './types'
export const en: Translations = {
+ externalOpenFailed: {
+ title: 'Couldn’t open this link',
+ message: 'No browser is registered to open this address. Copy the link and open it manually.',
+ copyUrl: 'Copy link',
+ close: 'Close'
+ },
+ // English editorial copy stays in the shipped JSONL; other locales override it.
+ intro: { stock: {}, custom: () => [] },
connectors: {
-- title: 'Connect your apps',
-- connect: 'Connect',
-- skip: 'Not now',
-- cancel: 'Stop waiting',
-- retry: 'Try again',
-- grant: 'Reconnect',
-- connected: 'Connected',
-- checking: 'Checking your apps…',
-- notConnected: 'Not connected',
-- skipped: 'Skipped',
-- disabled: 'Unavailable',
-- failed: 'Could not connect',
-- needsAuth: 'Access expired',
-- opening: 'Opening sign-in…',
-- waiting: 'Waiting for your browser…',
-- timeout: 'Still waiting for authorization.',
-- refresh: 'Refresh status',
-- connectError: 'Could not start authorization. Try again.',
-- connectErrorFor: (app: string) => `Could not start authorization for ${app}.`,
-- unavailable: 'Connectors are unavailable for this session.',
-- ownerMissing: 'Reopen this conversation to manage its connections.',
-- search: 'Find an app',
-- empty: 'No matching apps',
-- disclaimer: 'Connecting is optional. Only authorize the apps you want Hermes to use.',
-- execution: 'Connector tools',
-- setup: server => `Set up ${server}`,
-- openInBrowser: 'Open in browser',
-- setupCancel: 'Cancel',
-- authorizedToolsUnavailable: 'Authorized. Tools unavailable.',
-- required: 'Required'
-- },
++ title: 'Connect your apps',
++ connect: 'Connect',
++ skip: 'Not now',
++ cancel: 'Stop waiting',
++ retry: 'Try again',
++ grant: 'Reconnect',
++ connected: 'Connected',
++ checking: 'Checking your apps…',
++ notConnected: 'Not connected',
++ skipped: 'Skipped',
++ disabled: 'Unavailable',
++ failed: 'Could not connect',
++ needsAuth: 'Access expired',
++ opening: 'Opening sign-in…',
++ waiting: 'Waiting for your browser…',
++ timeout: 'Still waiting for authorization.',
++ refresh: 'Refresh status',
++ connectError: 'Could not start authorization. Try again.',
++ connectErrorFor: (app: string) => `Could not start authorization for ${app}.`,
++ unavailable: 'Connectors are unavailable for this session.',
++ ownerMissing: 'Reopen this conversation to manage its connections.',
++ search: 'Find an app',
++ empty: 'No matching apps',
++ disclaimer: 'Connecting is optional. Only authorize the apps you want Hermes to use.',
++ execution: 'Connector tools',
++ setup: server => `Set up ${server}`,
++ openInBrowser: 'Open in browser',
++ setupCancel: 'Cancel',
++ authorizedToolsUnavailable: 'Authorized. Tools unavailable.',
++ required: 'Required'
++},
// `connectors.*` above stays the onboarding and chat vocabulary; these are the page's own, and the two are not shared.
connectorsPage: {
diff --cc apps/desktop/src/i18n/ja.ts
index 6512faec004,6e2616fb671..19de059ff9c
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -1,14 -1,10 +1,16 @@@
import { defineFieldCopy } from '@/app/settings/field-copy'
import { defineLocale } from './define-locale'
+ import { introJa } from './intro-ja'
export const ja = defineLocale({
+ externalOpenFailed: {
+ title: 'このリンクを開けませんでした',
+ message: 'このアドレスを開くブラウザが登録されていません。リンクをコピーして手動で開いてください。',
+ copyUrl: 'リンクをコピー',
+ close: '閉じる'
+ },
+ intro: introJa,
sessionImport: {
title: '別のアプリから続ける',
subtitle: '会話をHermesに取り込み、続きを始めましょう。',
diff --cc apps/desktop/src/i18n/types.ts
index 519743568c2,2128bacc844..54b89c27734
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@@ -59,11 -59,9 +59,15 @@@ interface AuxTaskCopy
}
export interface Translations {
+ externalOpenFailed: {
+ title: string
+ message: string
+ copyUrl: string
+ close: string
++ };
+ intro: {
+ stock: Record<string, string[]>
+ custom: (label: string) => string[]
}
connectors: {
title: string
diff --cc apps/desktop/src/i18n/zh-hant.ts
index 0ed36abbd6e,3a2e274c299..3f9141d48ab
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -1,14 -1,10 +1,16 @@@
import { defineFieldCopy } from '@/app/settings/field-copy'
import { defineLocale } from './define-locale'
+ import { introZhHant } from './intro-zh-hant'
export const zhHant = defineLocale({
+ externalOpenFailed: {
+ title: '無法開啟此連結',
+ message: '沒有註冊用於開啟此位址的瀏覽器。請複製連結並手動開啟。',
+ copyUrl: '複製連結',
+ close: '關閉'
+ },
+ intro: introZhHant,
sessionImport: {
title: '從其他應用程式繼續',
subtitle: '將對話匯入 Hermes,接著上次的進度繼續。',
diff --cc apps/desktop/src/i18n/zh.ts
index 8f809119015,70d0fbbf21b..94fb3f61dfb
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -1,14 -1,10 +1,16 @@@
import { defineFieldCopy } from '@/app/settings/field-copy'
import { defineLocale } from './define-locale'
+ import { introZh } from './intro-zh'
export const zh = defineLocale({
+ externalOpenFailed: {
+ title: '无法打开此链接',
+ message: '没有注册用于打开此地址的浏览器。请复制链接并手动打开。',
+ copyUrl: '复制链接',
+ close: '关闭'
+ },
+ intro: introZh,
connectors: {
title: '连接你的应用',
connect: '连接',
diff --cc apps/desktop/src/lib/chat-messages/reconciliation.ts
index a60e3126d92,f320c5ff778..dac288a682a
--- a/apps/desktop/src/lib/chat-messages/reconciliation.ts
+++ b/apps/desktop/src/lib/chat-messages/reconciliation.ts
@@@ -207,23 -208,31 +207,42 @@@ function mergeStoredAssistantErrors
pending: false
}
})
+}
- const existingIds = new Set(mergedNextMessages.map(message => message.id))
+const normalizedMessageText = (message: ChatMessage): string => chatMessageText(message).replace(/\s+/g, ' ').trim()
- // Renderer ids are positional, so a hydrated page can carry a local row under
- // a new id; its durable rowId still names the same row (#119326).
- const hydratedIdByRowId = new Map(
++// Renderer ids are positional, so a hydrated page can carry a local row under
++// a new id; its durable rowId still names the same row (#119326).
++function hydratedIdResolver(mergedNextMessages: ChatMessage[]): (message: ChatMessage) => string | undefined {
++ const existingIds: Set<string> = new Set(mergedNextMessages.map(message => message.id))
++
++ const hydratedIdByRowId: Map<number, string> = new Map(
+ mergedNextMessages.flatMap(message => (message.rowId === undefined ? [] : [[message.rowId, message.id] as const]))
+ )
+
- const hydratedIdFor = (message: ChatMessage): string | undefined =>
++ return (message: ChatMessage): string | undefined =>
+ existingIds.has(message.id)
+ ? message.id
+ : message.rowId === undefined
+ ? undefined
+ : hydratedIdByRowId.get(message.rowId)
++}
++
+function localAssistantErrorIdsToPreserve(
+ mergedNextMessages: ChatMessage[],
+ currentMessages: ChatMessage[]
+): Set<string> {
+ const existingIds = new Set(mergedNextMessages.map(message => message.id))
++ const hydratedIdFor: (message: ChatMessage) => string | undefined = hydratedIdResolver(mergedNextMessages)
+
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') === tailUserRefs
for (let index = 0; index < currentMessages.length; index += 1) {
@@@ -263,20 -277,10 +287,20 @@@
}
}
+ 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 hydratedIdFor: (message: ChatMessage) => string | undefined = hydratedIdResolver(mergedNextMessages)
++
// 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.
diff --cc hermes_cli/_subprocess_compat.py
index f0daa8eb7be,3c050c8e86e..d03944f654c
--- a/hermes_cli/_subprocess_compat.py
+++ b/hermes_cli/_subprocess_compat.py
@@@ -27,9 -26,9 +27,10 @@@ __all__ =
"windows_detach_popen_kwargs",
"bounded_git_probe",
"bounded_probe_run",
+ "selected_git_env",
"noninteractive_git_env",
"NO_DRIVER_DIFF_FLAGS",
+ "NO_LAZY_FETCH_ENV",
"pid_is_hermes",
]
diff --cc hermes_cli/config.py
index 92a0b1c6a67,bb29e67b375..370d5c9e14e
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@@ -50,33 -54,6 +54,22 @@@ from hermes_cli.config_read_errors impo
logger = logging.getLogger(__name__)
+
+def is_uv_tool_install() -> bool:
+ # Shim to stop the old updater doing work until relaunch, not select uv tool.
+ return False
+
+
+def is_unsupported_install_method(method: str) -> bool:
+ # Shim to stop the old updater doing work until relaunch. no legacy detection.
+ return False
+
+
+def format_unsupported_install_warning(method: str) -> str:
+ # Shim to stop the old updater doing work until relaunch. no obsolete advice.
+ return ""
+
+
- # (config_path, mtime_ns, size) tuples already warned about, so concurrent CLI/gateway
- # loads of a broken config.yaml don't spam stderr. A changed file (new mtime) warns again.
- _CONFIG_PARSE_WARNED: set = set()
-
- # path -> (mtime_ns, size, error message) of active parse failures. Written by
- # _warn_config_parse_failure() (the single funnel for every load-path parse failure) and
- # probed by get_active_config_parse_failure() so provider auto-resolution can refuse to
- # adopt a paid provider from env keys while the user's REAL config is unreadable.
- _CONFIG_PARSE_FAILURES: dict = {}
-
-
class InvalidUserConfigError(RuntimeError):
"""Raised when a run that cannot repair config finds invalid user YAML."""
@@@ -2372,8 -2271,9 +2287,9 @@@ def _load_config_impl(*, want_deepcopy
if user_sig is not None:
try:
- with open(config_path, encoding="utf-8") as f:
+ with open(config_path, encoding="utf-8-sig") as f:
user_config = fast_safe_load(f) or {}
+ _CONFIG_PARSE_FAILURES.pop(path_key, None) # the file reads now (a transient error left the record)
if "max_turns" in user_config:
agent_user_config = dict(user_config.get("agent") or {})
diff --cc hermes_cli/source_check.py
index 42b432e28db,00000000000..bab00823a6b
mode 100644,000000..100644
--- a/hermes_cli/source_check.py
+++ b/hermes_cli/source_check.py
@@@ -1,332 -1,0 +1,338 @@@
+"""Passive source update decisions for one exact installation and profile.
+
+No fetch, lock repair, or Git writes. Desktop, CLI, and dashboard share this owner.
+"""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import time
+from pathlib import Path
+from typing import Optional
+from urllib.parse import quote
+import urllib.error
+import urllib.request
+
+from hermes_constants import get_hermes_home
+from hermes_cli.source_releases import OFFICIAL_REPOSITORY, _GITHUB_ORIGIN, resolve_source_target
+
+logger = logging.getLogger(__name__)
+UPDATE_AVAILABLE_NO_COUNT = -1
+_UPDATE_CHECK_CACHE_SECONDS = 24 * 3600
+_UPDATE_CHECK_FAILURE_CACHE_SECONDS = 3600
+
+
+def _quiet(fn, default=None):
+ try:
+ return fn()
+ except Exception:
+ return default
+
+
+def source_git_env() -> dict[str, str]:
- """Keep read-only Git probes in their explicit cwd, not an inherited worktree."""
- from hermes_cli._subprocess_compat import noninteractive_git_env
++ """Keep read-only Git probes in their explicit cwd, not an inherited worktree.
++
++ No probe may lazy-fetch from a partial clone's promisor remote: asking about
++ an upstream tip the clone never fetched would download its history, and the
++ probe timeout kills only git itself, orphaning the fetch (see NO_LAZY_FETCH_ENV).
++ """
++ from hermes_cli._subprocess_compat import NO_LAZY_FETCH_ENV, noninteractive_git_env
+
+ env = noninteractive_git_env()
+ for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE",
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_SHALLOW_FILE", "GIT_NAMESPACE"):
+ env.pop(key, None)
+ env["GIT_OPTIONAL_LOCKS"] = "0"
++ env.update(NO_LAZY_FETCH_ENV)
+ return env
+
+
+_GIT_TEXT_KW = {"text": True, "encoding": "utf-8", "errors": "replace"}
+
+
+def _git_run(args: list[str], *, cwd: Optional[Path] = None, timeout: int = 5, text: bool = True,
+ git: str = "git"):
+ """Read Git state without prompts, optional index writes, or inherited targeting."""
+ from hermes_cli._subprocess_compat import windows_hide_flags
+
+ kwargs: dict = {"creationflags": windows_hide_flags(), "env": source_git_env(), "stdin": subprocess.DEVNULL}
+ try:
+ return subprocess.run(
+ [git, *args], capture_output=True, timeout=timeout, cwd=str(cwd) if cwd is not None else None,
+ **(_GIT_TEXT_KW if text else {}), **kwargs)
+ except Exception:
+ return None
+
+
+def _git_stdout(args: list[str], *, cwd: Path, timeout: int = 5, git: str = "git") -> Optional[str]:
+ result = _git_run(args, cwd=cwd, timeout=timeout, git=git)
+ if result is None or result.returncode != 0:
+ return None
+ return (result.stdout or "").strip()
+
+
+def _git_ok(args: list[str], **kw) -> bool:
+ """True when ``git <args>`` ran and exited 0 (output discarded)."""
+ result = _git_run(args, text=False, **kw)
+ return result is not None and result.returncode == 0
+
+
+def _git_count(args: list[str], *, cwd: Path) -> Optional[int]:
+ """``int`` of a successful ``git rev-list --count``-style command, else None."""
+ result = _git_run(args, cwd=cwd)
+ if result is not None and result.returncode == 0:
+ return _quiet(lambda: int(result.stdout.strip()))
+ return None
+
+
+def _is_full_sha(value: Optional[str]) -> bool:
+ return isinstance(value, str) and len(value) == 40 and all(c in "0123456789abcdefABCDEF" for c in value)
+
+
+def _github_compare(current_rev: str, target_rev: str, repository: str = OFFICIAL_REPOSITORY) -> Optional[dict]:
+ # Do not memoize this separately: force must bypass failed AND successful network results.
+ if not (_is_full_sha(current_rev) and _is_full_sha(target_rev)):
+ return None
+ payload = _quiet(lambda: json.loads(_request(
+ f"https://api.github.com/repos/{repository}/compare/{current_rev}...{target_rev}")))
+ return payload if isinstance(payload, dict) else None
+
+
+def _github_compare_behind(current_rev: str, target_rev: str, repository: str = OFFICIAL_REPOSITORY) -> Optional[int]:
+ payload = _github_compare(current_rev, target_rev, repository)
+ ahead = payload.get("ahead_by") if payload else None
+ return ahead if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0 else None
+
+
+def _request(url: str, accept: str = "application/vnd.github+json") -> str:
+ """GET an api.github.com resource with the credential ladder in hermes_cli.github_api.
+
+ A token GitHub rejects (401) drops this request to anonymous rather than
+ failing the check on a stale credential.
+ """
+ from hermes_cli.github_api import github_token
+
+ token = github_token()
+ try:
+ return _request_with(url, accept, token)
+ except urllib.error.HTTPError as exc:
+ if token is None or exc.code != 401:
+ raise
+ logger.debug("GitHub rejected the configured token; retrying anonymously")
+ return _request_with(url, accept, None)
+
+
+def _request_with(url: str, accept: str, token: str | None) -> str:
+ headers = {"Accept": accept, "User-Agent": "hermes-update-check"}
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ req = urllib.request.Request(url, headers=headers)
+ with urllib.request.urlopen(req, timeout=10) as response:
+ return response.read(2 * 1024 * 1024).decode("utf-8-sig").strip()
+
+
+def _branch_tip(repository: str | None, branch: str, root: Path, git: str,
+ remote: str = "origin") -> tuple[str | None, bool, str | None]:
+ """``(sha, missing, failure)``: ``missing`` only on a confirmed empty advertisement;
+ ``failure`` names why no tip could be read, for the user-facing message."""
+ # A successful empty ref advertisement alone proves a branch was deleted.
+ # GitHub 404 can also mean a private repository: it must not heal a branch.
+ failure = None
+ if repository:
+ from hermes_cli.github_api import describe_github_failure, github_token
+ try:
+ sha = _request(f"https://api.github.com/repos/{repository}/commits/{quote(branch, safe='')}",
+ "application/vnd.github.sha")
+ except Exception as exc:
+ sha = None
+ failure = describe_github_failure(exc, authenticated=github_token() is not None)
+ if _is_full_sha(sha):
+ return sha, False, None
+ if failure is None:
+ failure = "api.github.com returned no commit for the branch."
+ if branch == "main" and remote == "origin":
+ return None, False, failure
+ result = _git_run(["ls-remote", "--exit-code", "--heads", remote, f"refs/heads/{branch}"],
+ cwd=root, git=git, timeout=10)
+ if result is None:
+ return None, False, failure or f"`git ls-remote {remote}` could not run."
+ sha = result.stdout.split()[0] if result.returncode == 0 and result.stdout else None
+ if _is_full_sha(sha):
+ return sha, False, None
+ if result.returncode == 2:
+ return None, True, None
+ detail = (result.stderr or "").strip().splitlines()
+ return None, False, failure or (f"`git ls-remote {remote}` failed: {detail[-1]}" if detail
+ else f"`git ls-remote {remote}` returned no tip.")
+
+
+def _commits(payload: dict | None) -> list[dict]:
+ from datetime import datetime
+ rows = []
+ entries = (payload or {}).get("commits", [])
+ for entry in entries if isinstance(entries, list) else []:
+ if not isinstance(entry, dict) or not isinstance(entry.get("sha"), str):
+ continue
+ commit = entry.get("commit") or {}
+ when = (commit.get("committer") or {}).get("date") or ""
+ at = _quiet(lambda: int(datetime.fromisoformat(when.replace("Z", "+00:00")).timestamp() * 1000), 0)
+ rows.append({"sha": entry["sha"], "summary": str(commit.get("message", "")).split("\n", 1)[0],
+ "author": str((commit.get("author") or {}).get("name", "")), "at": at})
+ return rows[::-1]
+
+
+def check_for_updates(*, install_root: Path | None = None, home: Path | None = None,
+ branch: str | None = None, channel: str | None = None,
+ cache_path: Path | None = None, branch_config_path: Path | None = None,
+ force: bool = False,
+ passive: bool = False, git: str = "git") -> dict:
+ """Return a presentation-ready status. Omitted branch follows the current checkout.
+
+ Only the default (running installation) may use HERMES_REVISION. An explicit
+ target must never inherit the host process's embedded revision or stamp.
+ """
+ from hermes_cli.config import detect_install_method, get_project_root, require_readable_config_before_write
+ from hermes_cli.steward import read_install_stamp
+ from hermes_cli.update_channel import install_id, resolve_update_channel
+ from hermes_cli.release_channels import validate_name
+ from hermes_cli.update_contract import COMMIT_BUILD_UPDATE_MESSAGE
+
+ embedded = (os.environ.get("HERMES_REVISION") or None) if install_root is None else None
+ root = Path(install_root if install_root is not None else get_project_root()).resolve()
+ home = Path(home if home is not None else get_hermes_home()).resolve()
+ stamp = read_install_stamp(root)
+ result = {"supported": False, "hermesRoot": str(root), "behind": None, "commits": []}
+ if stamp.get("source") == "commit-build":
+ return {**result, "reason": "commit-build", "message": COMMIT_BUILD_UPDATE_MESSAGE}
+ if stamp.get("payload") in {"bundled", "light", "runtime"} or (install_root is None and detect_install_method(root) in {"docker", "apt"}):
+ return {**result, "reason": "not-a-git-checkout"}
+ if not embedded and not (root / ".git").exists():
+ return {**result, "reason": "not-a-git-checkout",
+ "message": "This install has no git checkout to update."}
+ if stamp.get("updateMechanism") not in (None, "self") and not embedded:
+ return {**result, "reason": "update-root-steward-owned-git-tree",
+ "message": "This installation is managed by its install method; use its updater.", "advice": "git pull"}
+ config = require_readable_config_before_write(home / "config.yaml")
+ if passive and (config.get("updates") or {}).get("check") is False:
+ return {**result, "reason": "disabled"}
+ channel = resolve_update_channel(config, root) if channel is None else validate_name(channel)
+ head = embedded or _git_stdout(["rev-parse", "HEAD"], cwd=root, git=git)
+ current_branch = None if embedded else _git_stdout(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root, git=git)
+ desktop_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8-sig"))) if branch_config_path else None
+ configured_branch = desktop_config.get("branch") if isinstance(desktop_config, dict) else None
+ if isinstance(configured_branch, str):
+ configured_branch = configured_branch.strip() or None
+ else:
+ configured_branch = None
+ selected_branch = branch or configured_branch or (current_branch if current_branch and current_branch != "HEAD" else "main")
+ origin = "" if embedded else (_git_stdout(["remote", "get-url", "origin"], cwd=root, git=git) or "")
+ match = _GITHUB_ORIGIN.fullmatch(origin)
+ repository = OFFICIAL_REPOSITORY if embedded else (match[1] if match else None)
+ dirty = False if embedded else bool(_git_stdout(["status", "--porcelain"], cwd=root, git=git))
+ result.update(supported=True, currentSha=head, currentBranch=current_branch, dirty=dirty)
+ if channel != "main":
+ result["channel"] = channel
+ else:
+ result["branch"] = selected_branch
+ identity = {"root": str(root), "home": str(home), "head": head, "origin": origin, "branch": selected_branch,
+ "channel": channel, "embedded": embedded, "branchOverride": branch is not None, "channelProtocol": 1}
+ cache_file = Path(cache_path) if cache_path is not None else home / "source-checks" / f"{install_id(root)}.json"
+ cached = _quiet(lambda: json.loads(cache_file.read_text(encoding="utf-8-sig")))
+ now = time.time()
+ if (not force and isinstance(cached, dict) and cached.get("identity") == identity
+ and isinstance(cached.get("status"), dict) and cached["status"].get("supported") is True):
+ status = cached.get("status", {})
+ ttl = _UPDATE_CHECK_FAILURE_CACHE_SECONDS if status.get("error") else _UPDATE_CHECK_CACHE_SECONDS
+ ts = cached.get("ts")
+ if isinstance(ts, (float, int)) and 0 <= now - ts < ttl:
+ return {**status, "dirty": dirty, "currentBranch": current_branch}
+ result["fetchedAt"] = int(now * 1000)
+ source_target = None
+ if not _is_full_sha(head):
+ result.update(error="head-unavailable", message="Could not read the installed revision.")
+ elif branch is None:
+ try:
+ source_target = resolve_source_target(channel, [git] if not embedded else None, root,
+ repository=repository or OFFICIAL_REPOSITORY)
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
+ result.update(error="release-unavailable", message=f"Could not resolve the {channel} source channel: {exc}")
+ else:
+ if source_target.commit:
+ target = source_target.commit
+ result.pop("branch", None)
+ result.update(channel=channel, targetSha=target, updateAvailable=head != target,
+ behind=0 if head == target else UPDATE_AVAILABLE_NO_COUNT,
+ sourceVersion=source_target.version, buildId=source_target.build_id)
+ if source_target.retired:
+ result["retirement"] = {"destination": source_target.channel, "sourceOnly": True}
+ else:
+ # The record supplies a default, not permission to leave the user's branch.
+ selected_branch = configured_branch or (
+ current_branch if current_branch and current_branch != "HEAD" else source_target.branch)
+ if "error" not in result and (source_target is None or source_target.branch is not None):
+ result["branch"] = selected_branch
+ official_ssh = (repository and repository.lower() == OFFICIAL_REPOSITORY.lower()
+ and origin.lower().startswith(("git@", "ssh://")))
+ # The public official repo does not require the user's SSH credentials.
+ # Forks must keep their own origin, including its authentication.
+ remote = (f"https://github.com/{OFFICIAL_REPOSITORY}.git"
+ if embedded or (official_ssh and selected_branch != "main") else "origin")
+ target, missing, failure = _branch_tip(repository, selected_branch, root, git, remote)
+ if missing and selected_branch != "main":
+ result["branch"] = "main"
+ if branch_config_path and not branch and configured_branch == selected_branch:
+ # Do not overwrite a concurrent choice made while the network probe ran.
+ current_config = _quiet(lambda: json.loads(branch_config_path.read_text(encoding="utf-8-sig")))
+ if current_config == desktop_config:
+ from utils import atomic_json_write
+ atomic_json_write(branch_config_path, {**desktop_config, "branch": "main"})
+ target, _, failure = _branch_tip(repository, "main", root, git, remote if embedded else "origin")
+ if target is None:
+ result.update(error="fetch-failed",
+ message=f"Could not resolve the remote branch tip: {failure}" if failure
+ else "Could not resolve the remote branch tip.")
+ else:
+ behind = UPDATE_AVAILABLE_NO_COUNT
+ if head == target or (not embedded and _git_ok(
+ ["merge-base", "--is-ancestor", target, head], cwd=root, git=git)):
+ behind = 0
+ elif repository:
+ payload = _github_compare(head, target, repository)
+ ahead = (payload or {}).get("ahead_by")
+ if isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0:
+ behind = ahead
+ result["commits"] = _quiet(lambda: _commits(payload), []) if behind else []
+ result.update(targetSha=target, behind=behind, updateAvailable=behind != 0)
+ try:
+ from utils import atomic_json_write
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
+ atomic_json_write(cache_file, {"identity": identity, "ts": now, "status": result})
+ except OSError as exc:
+ logger.debug("Could not cache source check: %s", exc)
+ return result
+
+
+def main() -> None:
+ import argparse
+ import contextlib
+ import sys
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--install-root", type=Path, required=True)
+ parser.add_argument("--home", type=Path, required=True)
+ parser.add_argument("--git", default="git")
+ parser.add_argument("--branch")
+ from hermes_cli.release_channels import validate_name
+ parser.add_argument("--channel", type=validate_name)
+ parser.add_argument("--cache-path", type=Path)
+ parser.add_argument("--branch-config-path", type=Path)
+ parser.add_argument("--force", action="store_true")
+ args = parser.parse_args()
+ with contextlib.redirect_stdout(sys.stderr):
+ result = check_for_updates(**vars(args))
+ print(json.dumps(result))
+
+
+if __name__ == "__main__":
+ main()
diff --cc hermes_cli/xai_retirement.py
index 6ef2cc269a1,957ad7c382a..ee38f4a7834
--- a/hermes_cli/xai_retirement.py
+++ b/hermes_cli/xai_retirement.py
@@@ -138,9 -138,11 +138,11 @@@ def apply_migration
if not issues:
return unchanged
- from utils import ROUNDTRIP_YAML_WIDTH
++ from hermes_yaml import ROUNDTRIP_YAML_WIDTH
yaml = YAML(typ="rt")
+ yaml.width = ROUNDTRIP_YAML_WIDTH
yaml.preserve_quotes = True
- with config_path.open("r", encoding="utf-8") as fh:
+ with config_path.open("r", encoding="utf-8-sig") as fh:
doc = yaml.load(fh)
if doc is None:
return unchanged
diff --cc hermes_yaml.py
index 48b94826241,00000000000..bae447df100
mode 100644,000000..100644
--- a/hermes_yaml.py
+++ b/hermes_yaml.py
@@@ -1,89 -1,0 +1,98 @@@
+"""Shared YAML 1.1 policy for config, manifests, and frontmatter.
+
+Ruamel's native schema includes bare y/n booleans and rejects duplicate keys.
+Every operation owns its parser/emitter; instances must not be shared by threads.
+"""
+
+from io import StringIO
+from typing import Any, IO, overload
+
+from ruamel.yaml import YAML
+from ruamel.yaml.error import YAMLError as YAMLError
+from ruamel.yaml.resolver import VersionedResolver
+
+
+class _Yaml11Resolver(VersionedResolver):
+ # Quote strings like "off" without adding a %YAML directive to every config/snippet.
+ @property
+ def processing_version(self) -> tuple[int, int]:
+ return (1, 1)
+
+
+def _load(document: str | bytes, *, pure: bool) -> Any:
+ yaml = YAML(typ="safe", pure=pure)
+ yaml.version = (1, 1)
+ return yaml.load(document)
+
+
+def safe_load(stream: str | bytes | IO[str] | IO[bytes]) -> Any:
+ """Read standard YAML data; existing configs use YAML 1.1 booleans.
+
+ The pure parser defines what parses: Windows ARM64 has no C extension, and libyaml rejects
+ documents the pure parser accepts (``[{url: http://h}]``), so a C rejection is re-read pure.
+ """
+ document = stream if isinstance(stream, (str, bytes)) else stream.read()
+ try:
+ return _load(document, pure=False)
+ except YAMLError:
+ return _load(document, pure=True)
+
+
+@overload
+def safe_dump(
+ data: Any, stream: None = None, *, default_flow_style: bool = False,
+ sort_keys: bool = True, allow_unicode: bool = True, width: int = 80,
+) -> str: ...
+
+
+@overload
+def safe_dump(
+ data: Any, stream: IO[str], *, default_flow_style: bool = False,
+ sort_keys: bool = True, allow_unicode: bool = True, width: int = 80,
+) -> None: ...
+
+
+def safe_dump(
+ data: Any,
+ stream: IO[str] | None = None,
+ *,
+ default_flow_style: bool = False,
+ sort_keys: bool = True,
+ allow_unicode: bool = True,
+ width: int = 80,
+) -> str | None:
+ """Write standard YAML data with readable Unicode and indented block lists."""
+ # The C emitter ignores sequence offsets and escapes astral Unicode.
+ yaml = YAML(typ="safe", pure=True)
+ yaml.Resolver = _Yaml11Resolver
+ yaml.default_flow_style = default_flow_style
+ yaml.allow_unicode = allow_unicode
+ yaml.width = width
+ yaml.sort_base_mapping_type_on_output = sort_keys
+ yaml.indent(mapping=2, sequence=4, offset=2)
+ if stream is not None:
+ yaml.dump(data, stream)
+ return None
+ output = StringIO()
+ yaml.dump(data, output)
+ return output.getvalue()
+
+
++# ruamel's emitter can change a double-quoted value when it folds a long line right after an
++# escaped backslash (``D:\\Cent…`` → ``D:\\`` + bare newline): the fold reloads as a literal space
++# and a no-op save mutates the stored value (#119844). Config writes must be value-preserving, so
++# every round-trip emitter in the tree keeps scalars on one line instead of folding (``None``
++# does NOT disable folding on 0.18.x; only a large width does).
++ROUNDTRIP_YAML_WIDTH = 2**31 - 1
++
++
+def roundtrip_yaml() -> YAML:
+ """Create a fresh comment/quote-preserving editor for user-authored YAML."""
+ yaml = YAML(typ="rt")
++ yaml.width = ROUNDTRIP_YAML_WIDTH
+ yaml.Resolver = _Yaml11Resolver
+ yaml.preserve_quotes = True
+ yaml.allow_unicode = True
+ yaml.default_flow_style = False
+ yaml.indent(mapping=2, sequence=4, offset=2)
+ return yaml
diff --cc tests/agent/test_anthropic_third_party_oauth_guard.py
index 76b4c6ee303,19959b73b0e..6a77b1c8548
--- a/tests/agent/test_anthropic_third_party_oauth_guard.py
+++ b/tests/agent/test_anthropic_third_party_oauth_guard.py
@@@ -72,6 -75,59 +72,57 @@@ class TestOAuthFlagOnRefresh
# And the flag is untouched regardless.
assert agent._is_anthropic_oauth is False
+ @pytest.mark.parametrize("base_url", [
+ "https://llmbox.bytedance.net",
+ "http://127.0.0.1:8080/anthropic.com", # substring spoof: the host is still foreign
+ "https://llmbox.bytedance.net/anthropic", # accepted proxy shape, but holds a custom key
+ ])
+ def test_third_party_endpoint_skips_refresh(self, agent, base_url):
+ """provider == 'anthropic' on a third-party endpoint must not refresh: the refresh
+ would swap in native Anthropic credentials the endpoint was never given."""
+ agent.api_mode = "anthropic_messages"
+ agent.provider = "anthropic"
+ agent._anthropic_api_key = "custom-api-key"
+ agent._anthropic_base_url = base_url
+ agent._anthropic_client = MagicMock()
+ agent._is_anthropic_oauth = False
+
+ with (
+ patch("agent.anthropic_credentials.resolve_anthropic_token",
+ return_value=_OAUTH_LIKE_TOKEN),
+ patch("agent.anthropic_adapter.build_anthropic_client",
+ return_value=MagicMock()),
+ ):
+ result = agent._try_refresh_anthropic_client_credentials()
+
+ assert result is False
+ assert agent._anthropic_api_key == "custom-api-key"
+ assert agent._is_anthropic_oauth is False
+
+ @pytest.mark.parametrize("base_url", [
+ "https://api.claude.com",
+ "https://llm.corp.example/anthropic",
+ ])
+ def test_accepted_native_proxy_keeps_rotating_anthropic_token(self, agent, base_url):
+ """Hosts the resolver accepts as native Anthropic already hold the Anthropic token, so
+ blocking the refresh would strand an expiring OAuth token (401 with no recovery)."""
+ old, new = "sk-ant-oat01-old-token-aaaaaaaa", "sk-ant-oat01-new-token-bbbbbbbb"
+ agent.api_mode = "anthropic_messages"
+ agent.provider = "anthropic"
+ agent._anthropic_api_key = old
+ agent._anthropic_base_url = base_url
+ agent._anthropic_client = MagicMock()
+ agent._is_anthropic_oauth = True
+
+ with (
+ patch("agent.anthropic_credentials.resolve_anthropic_token", return_value=new),
+ patch("agent.anthropic_adapter.build_anthropic_client", return_value=MagicMock()),
+ ):
+ result = agent._try_refresh_anthropic_client_credentials()
+
+ assert result is True
+ assert agent._anthropic_api_key == new
+
-
-
class TestOAuthFlagOnCredentialSwap:
"""Site 4 — _swap_credential (credential pool rotation)."""
diff --cc tests/e2e/core/parity/_helpers.py
index 00000000000,db04772e2a7..ab9020ba914
mode 000000,100644..100644
--- a/tests/e2e/core/parity/_helpers.py
+++ b/tests/e2e/core/parity/_helpers.py
@@@ -1,0 -1,469 +1,469 @@@
+ """Shared fixture HERMES_HOME + invariant checks for the entrypoint-parity suite.
+
+ One fixture home carries every feature that has historically been wired into
+ some entrypoints and forgotten in others (issue class C19): a shell hook and a
+ Python-plugin hook on ``pre_llm_call`` (both write a marker AND inject a
+ context canary), an ``AGENTS.md`` context file in the working directory, a
+ skill, a memory entry, a stdio MCP server (issue class C15) whose tool returns a
+ canary, the custom provider pointed at the recording fake, and a toolset
+ restriction (``agent.disabled_toolsets``).
+
+ Every entrypoint driver runs ONE turn against the scripted fake provider
+ (turn 1: call the MCP tool; turn 2: answer) and hands the recorded requests to
+ :func:`collect_observation`; the test then asserts the same invariants for
+ every entrypoint, so any red cell is a wiring-parity bug.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import os
+ import re
+ import signal
+ import subprocess
+ import sys
+ import time
+ import uuid
+ from dataclasses import dataclass, field
+ from pathlib import Path
+ from typing import Any, Callable, Iterable
+
-import yaml
++import hermes_yaml as yaml
+
+ from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall, write_hermes_home
+
+ REPO_ROOT = Path(__file__).resolve().parents[4]
+ FIXTURE_MCP_SERVER = Path(__file__).with_name("fixture_mcp_server.py")
+
+ MCP_SERVER_NAME = "parity"
+ MCP_TOOL_NAME = "mcp__parity__parity_canary"
+ FINAL_ANSWER = "PARITY-TURN-COMPLETE"
+ PLUGIN_NAME = "parity-plugin"
+ # Always-available (no credential/check_fn gate) toolset the fixture disables.
+ DISABLED_TOOLSET = "todo"
+
+ _SECRET_ENV_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")
+ _PASSTHROUGH_ENV = frozenset({
+ "PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ",
+ "SYSTEMROOT", "SystemRoot", "COMSPEC", "PATHEXT", "WINDIR", "TEMP", "TMP",
+ })
+
+
+ TURN_TIMEOUT = 240.0
+
+
+ @dataclass
+ class DriveResult:
+ """What an entrypoint driver reports back (see ``_drive_cli`` for the contract)."""
+
+ final_text: str | None
+ toolset: str # the platform toolset this surface documents (a toolsets.py key)
+ cwd_channel: str = "launch dir"
+ graceful_exit: bool = True
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+ @dataclass
+ class ParityHome:
+ """Filesystem layout + canaries of one fixture home."""
+
+ root: Path
+ home: Path
+ hermes_home: Path
+ project: Path
+ markers: Path
+ pid_log: Path
+ tag: str
+ canaries: dict[str, str] = field(default_factory=dict)
+
+ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:
+ """Hermetic env for a subprocess Hermes: fake HOME, no real credentials."""
+ import pwd # POSIX-only; the suite is Linux-gated
+
+ # Refuse only a home the real install would read as live state (its root or a profile).
+ # A tmp_path under ``~/.hermes/cache/scratch`` (TMPDIR when Hermes itself runs the suite)
+ # is fine: the child's HOME is the fixture home, so its ``~/.hermes`` never resolves there.
+ real_root = Path(pwd.getpwuid(os.getuid()).pw_dir, ".hermes").resolve()
+ fixture = self.hermes_home.resolve()
+ assert fixture != real_root and fixture.parent != real_root / "profiles", (
+ f"fixture HERMES_HOME {self.hermes_home} is the real install's live home")
+ assert fixture == (self.home / ".hermes").resolve(), (
+ f"fixture HERMES_HOME {self.hermes_home} is not <fixture HOME>/.hermes")
+ # Allowlist, not denylist: the runner may itself be a Hermes process whose
+ # TERMINAL_CWD / HERMES_* / credential env would silently reroute the child.
+ env = {
+ k: v for k, v in os.environ.items()
+ if (k in _PASSTHROUGH_ENV or k.startswith("LC_")) and not k.endswith(_SECRET_ENV_SUFFIXES)
+ }
+ env.update({
+ "HOME": str(self.home),
+ "HERMES_HOME": str(self.hermes_home),
+ "PYTHONPATH": str(REPO_ROOT),
+ "PYTHONUNBUFFERED": "1",
+ "NO_COLOR": "1",
+ "TERM": "dumb",
+ # Orphan-scan tag: every process in the spawned tree inherits it.
+ "PARITY_TREE_TAG": self.tag,
+ # The child's HOME is the fixture home, so its ``~/.hermes/state.db`` IS
+ # the tmp HERMES_HOME's db; under a pytest ancestor the live-DB guard
+ # (hermes_state_guard) would refuse it. This is the guard's documented
+ # child-process escape hatch; the path is tmp_path by construction.
+ "HERMES_STATE_DB_GUARD_BYPASS": "1",
+ })
+ env.update(extra or {})
+ return env
+
+ def update_config(self, mutate: Callable[[dict], None]) -> None:
+ """Apply ``mutate`` to config.yaml (for surfaces with a documented config-only channel)."""
+ path = self.hermes_home / "config.yaml"
+ cfg = yaml.safe_load(path.read_text(encoding="utf-8"))
+ mutate(cfg)
+ path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")
+
+ def pin_terminal_cwd(self) -> None:
+ """Documented cwd channel for daemon surfaces (gateway, api_server): ``terminal.cwd``."""
+ self.update_config(lambda cfg: cfg.setdefault("terminal", {}).__setitem__("cwd", str(self.project)))
+
+
+ def build_parity_home(root: Path, base_url: str, *, grandchild: bool = True,
+ death_tool: bool = False, mcp_timeout: int = 60) -> ParityHome:
+ """Write the full fixture home under ``root`` (a tmp_path)."""
+ home = root / "home"
+ hermes_home = home / ".hermes"
+ project = root / "project"
+ markers = root / "markers"
+ for d in (hermes_home, project, markers):
+ d.mkdir(parents=True, exist_ok=True)
+ tag = uuid.uuid4().hex
+ c = {name: f"{name.upper()}-{uuid.uuid4().hex[:12]}" for name in (
+ "context", "skill", "memory", "shell_hook", "plugin_hook", "mcp")}
+ ph = ParityHome(root=root, home=home, hermes_home=hermes_home, project=project,
+ markers=markers, pid_log=root / "mcp_pids.log", tag=tag, canaries=c)
+
+ write_hermes_home(hermes_home, base_url)
+ cfg = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))
+ cfg["agent"]["disabled_toolsets"] = [DISABLED_TOOLSET]
+ cfg["hooks"] = {"pre_llm_call": [{
+ "command": f"{sys.executable} {hermes_home / 'agent-hooks' / 'shell_hook.py'}",
+ "timeout": 30,
+ }]}
+ cfg["hooks_auto_accept"] = True
+ cfg["plugins"] = {"enabled": [PLUGIN_NAME]}
+ cfg["mcp_servers"] = {MCP_SERVER_NAME: {
+ "command": sys.executable,
+ "args": [str(FIXTURE_MCP_SERVER)],
+ "env": {
+ "PARITY_MCP_CANARY": c["mcp"],
+ "PARITY_MCP_PID_LOG": str(ph.pid_log),
+ "PARITY_MCP_SPAWN_GRANDCHILD": "1" if grandchild else "0",
+ "PARITY_MCP_DEATH_TOOL": "1" if death_tool else "0",
+ "PARITY_TREE_TAG": tag,
+ # Only the MCP server and its descendants carry this one.
+ "PARITY_MCP_TREE_TAG": tag,
+ "PYTHONPATH": str(REPO_ROOT),
+ },
+ "connect_timeout": 60,
+ "timeout": mcp_timeout,
+ }}
+ # Interactive surfaces wait only ~1.5 s (mcp_discovery_timeout) for MCP discovery
+ # before the first agent build, BY DESIGN (a slow server must not block the
+ # shell; late tools arrive via refresh). Under a loaded box the fixture server's
+ # import alone can exceed that, so pin the documented knob high: the join returns
+ # the instant discovery finishes, and the first turn is deterministically complete.
+ cfg["mcp_discovery_timeout"] = 120
+ cfg["mcp_single_query_discovery_timeout"] = 120
+ # Keep turns hermetic and short: no title/aux model chatter decides anything here.
+ cfg.setdefault("display", {})["compact"] = True
+ cfg["updates"] = {"check": False} # offline: no GitHub round-trip or git lazy fetch
+ (hermes_home / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")
+
+ hooks_dir = hermes_home / "agent-hooks"
+ hooks_dir.mkdir()
+ (hooks_dir / "shell_hook.py").write_text(
+ "import json, os, sys\n"
+ "payload = json.load(sys.stdin)\n"
+ f"with open({str(markers / 'shell_hook.log')!r}, 'a') as fh:\n"
+ " fh.write(json.dumps({'event': payload.get('hook_event_name'),\n"
+ " 'session_id': payload.get('session_id')}) + '\\n')\n"
+ f"print(json.dumps({{'context': {c['shell_hook']!r}}}))\n",
+ encoding="utf-8",
+ )
+
+ plugin_dir = hermes_home / "plugins" / PLUGIN_NAME
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "plugin.yaml").write_text(
+ f"name: {PLUGIN_NAME}\nversion: 1.0.0\ndescription: parity suite marker plugin\n",
+ encoding="utf-8",
+ )
+ (plugin_dir / "__init__.py").write_text(
+ "import json\n"
+ "def register(ctx):\n"
+ " def _pre_llm_call(**kwargs):\n"
+ f" with open({str(markers / 'plugin_hook.log')!r}, 'a') as fh:\n"
+ " fh.write(json.dumps({'platform': kwargs.get('platform'),\n"
+ " 'session_id': kwargs.get('session_id')}) + '\\n')\n"
+ f" return {{'context': {c['plugin_hook']!r}}}\n"
+ " ctx.register_hook('pre_llm_call', _pre_llm_call)\n",
+ encoding="utf-8",
+ )
+
+ skill_dir = hermes_home / "skills" / "parity-skill"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text(
+ "---\nname: parity-skill\n"
+ f"description: Use when checking entrypoint parity {c['skill']}.\n---\n\n"
+ "# Parity skill\n\nNothing to do.\n",
+ encoding="utf-8",
+ )
+
+ mem_dir = hermes_home / "memories"
+ mem_dir.mkdir()
+ (mem_dir / "MEMORY.md").write_text(f"The parity memory canary is {c['memory']}.", encoding="utf-8")
+
+ (project / "AGENTS.md").write_text(
+ f"# Project rules\n\nThe parity context canary is {c['context']}.\n", encoding="utf-8")
+ return ph
+
+
+ # Scripted provider -----------------------------------------------------------
+
+
+ def parity_responder(nonce: str, tool: str = MCP_TOOL_NAME) -> Callable[[dict[str, Any]], Any]:
+ """Stateless script: call the MCP tool until a tool result exists, then answer.
+
+ Stateless so a retried request (or a second concurrent entrypoint request)
+ cannot desynchronise the script.
+ """
+
+ def respond(record: dict[str, Any]):
+ body = record["body"]
+ if any(m.get("role") == "tool" for m in body.get("messages") or []):
+ return Text(FINAL_ANSWER)
+ args = {"nonce": nonce}
+ if tool in _tool_names(body) or "tool_call" not in _tool_names(body):
+ return ToolCall(tool, args)
+ # Tool Search active: MCP tools sit in the deferred catalog behind the bridge.
+ return ToolCall("tool_call", {"calls": [{"name": tool, "arguments": args}]})
+
+ return respond
+
+
+ def start_provider(nonce: str, tool: str = MCP_TOOL_NAME) -> FakeLLMServer:
+ srv = FakeLLMServer(parity_responder(nonce, tool))
+ srv.start()
+ return srv
+
+
+ # Observation + invariants ----------------------------------------------------
+
+
+ def _text(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "\n".join(p.get("text", "") for p in content if isinstance(p, dict))
+ return ""
+
+
+ def _tool_names(body: dict[str, Any]) -> set[str]:
+ return {(t.get("function") or {}).get("name") or t.get("name") for t in body.get("tools") or []}
+
+
+ _CATALOG_LINE = re.compile(r"^- ([A-Za-z0-9_.:-]+): ", re.M)
+
+
+ def offered_tool_names(body: dict[str, Any]) -> set[str]:
+ """Direct tool schemas plus the Tool Search deferred catalog (names the model may invoke)."""
+ names = _tool_names(body)
+ for t in body.get("tools") or []:
+ fn = t.get("function") or {}
+ if fn.get("name") == "tool_search":
+ names |= set(_CATALOG_LINE.findall(fn.get("description") or ""))
+ return names
+
+
+ @dataclass
+ class Observation:
+ entrypoint: str
+ system: str
+ first_user: str
+ tool_names: set[str]
+ tool_results: list[str]
+ main_requests: int
+ shell_hook_events: list[dict]
+ plugin_hook_events: list[dict]
+ final_text: str | None = None
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+ def _read_jsonl(path: Path) -> list[dict]:
+ if not path.exists():
+ return []
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
+
+
+ def collect_observation(entrypoint: str, ph: ParityHome, srv: FakeLLMServer,
+ final_text: str | None = None) -> Observation:
+ mains = srv.main_requests()
+ assert mains, f"{entrypoint}: no main-turn request reached the provider"
+ first = mains[0]
+ msgs = first.get("messages") or []
+ system = "\n".join(_text(m.get("content")) for m in msgs if m.get("role") == "system")
+ users = [_text(m.get("content")) for m in msgs if m.get("role") == "user"]
+ tool_results = [
+ _text(m.get("content")) for body in mains for m in body.get("messages") or []
+ if m.get("role") == "tool"
+ ]
+ return Observation(
+ entrypoint=entrypoint, system=system, first_user=users[-1] if users else "",
+ tool_names=offered_tool_names(first), tool_results=tool_results, main_requests=len(mains),
+ shell_hook_events=_read_jsonl(ph.markers / "shell_hook.log"),
+ plugin_hook_events=_read_jsonl(ph.markers / "plugin_hook.log"),
+ final_text=final_text,
+ )
+
+
+ def disabled_tool_names() -> set[str]:
+ from toolsets import resolve_toolset
+
+ return set(resolve_toolset(DISABLED_TOOLSET))
+
+
+ # Agent features every surface must carry when its documented toolset includes them.
+ _FEATURE_TOOLS = ("terminal", "read_file", "write_file", "patch", "search_files", "memory",
+ "skills_list", "skill_view")
+
+
+ def required_tool_names(toolset: str) -> set[str]:
+ """The core feature tools the surface's documented toolset promises, plus the MCP tool."""
+ from toolsets import resolve_toolset
+
+ promised = set(resolve_toolset(toolset))
+ return {t for t in _FEATURE_TOOLS if t in promised} | {MCP_TOOL_NAME}
+
+
+ def check_invariants(obs: Observation, ph: ParityHome, *, toolset: str = "hermes-cli",
+ context_file: bool = True) -> dict[str, bool]:
+ """Evaluate every parity invariant; returns {cell: ok} (all must be True)."""
+ c = ph.canaries
+ cells = {
+ "context_file": c["context"] in obs.system,
+ "skill_index": c["skill"] in obs.system,
+ "memory": c["memory"] in obs.system,
+ "shell_hook_fired": bool(obs.shell_hook_events),
+ "shell_hook_injected": c["shell_hook"] in obs.first_user,
+ "plugin_hook_fired": bool(obs.plugin_hook_events),
+ "plugin_hook_injected": c["plugin_hook"] in obs.first_user,
+ "mcp_tool_offered": MCP_TOOL_NAME in obs.tool_names,
+ "mcp_call_returned_canary": any(c["mcp"] in r for r in obs.tool_results),
+ "toolset_restriction": not (obs.tool_names & disabled_tool_names()),
+ "feature_tools": required_tool_names(toolset) <= obs.tool_names,
+ "turn_completed": obs.main_requests >= 2,
+ }
+ if not context_file:
+ cells.pop("context_file")
+ return cells
+
+
+ # Process-tree hygiene --------------------------------------------------------
+
+
+ def tagged_pids(tag: str, var: str = "PARITY_TREE_TAG") -> set[int]:
+ """Live PIDs whose environment carries ``<var>=<tag>`` (reparented orphans included)."""
+ needle = f"{var}={tag}".encode()
+ found: set[int] = set()
+ me = os.getpid()
+ for entry in os.listdir("/proc"):
+ if not entry.isdigit() or int(entry) == me:
+ continue
+ try:
+ with open(f"/proc/{entry}/environ", "rb") as fh:
+ env = fh.read()
+ with open(f"/proc/{entry}/stat", "rb") as fh:
+ state = fh.read().rsplit(b")", 1)[1].split()[0]
+ except OSError:
+ continue
+ if state != b"Z" and needle in env.split(b"\0"):
+ found.add(int(entry))
+ return found
+
+
+ def mcp_pids(ph: ParityHome) -> dict[str, list[int]]:
+ out: dict[str, list[int]] = {}
+ if ph.pid_log.exists():
+ for line in ph.pid_log.read_text(encoding="utf-8").splitlines():
+ kind, pid = line.split()
+ out.setdefault(kind, []).append(int(pid))
+ return out
+
+
+ def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: float = 0.05):
+ deadline = time.monotonic() + timeout
+ while True:
+ value = pred()
+ if value:
+ return value
+ if time.monotonic() >= deadline:
+ raise AssertionError(f"timed out after {timeout}s waiting for {what}")
+ time.sleep(interval)
+
+
+ def wait_no_orphans(ph: ParityHome, timeout: float = 30.0, *, mcp_only: bool = True) -> set[int]:
+ """Poll until no MCP-tree process (or, ``mcp_only=False``, no tagged process at all)
+ survives; returns the survivors (empty = clean)."""
+ var = "PARITY_MCP_TREE_TAG" if mcp_only else "PARITY_TREE_TAG"
+ deadline = time.monotonic() + timeout
+ survivors = tagged_pids(ph.tag, var)
+ while survivors and time.monotonic() < deadline:
+ time.sleep(0.1)
+ survivors = tagged_pids(ph.tag, var)
+ return survivors
+
+
+ def describe_pids(pids: Iterable[int]) -> list[str]:
+ out = []
+ for pid in sorted(pids):
+ try:
+ with open(f"/proc/{pid}/cmdline", "rb") as fh:
+ cmd = fh.read().replace(b"\0", b" ").decode(errors="replace")
+ out.append(f"{pid}: {cmd[:160]}")
+ except OSError:
+ out.append(f"{pid}: <gone>")
+ return out
+
+
+ def kill_tagged(ph: ParityHome) -> None:
+ """Test cleanup: SIGKILL anything this fixture spawned that is still alive."""
+ for pid in tagged_pids(ph.tag):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+
+
+ def hermes_argv(*args: str) -> list[str]:
+ return [sys.executable, "-m", "hermes_cli.main", *args]
+
+
+ def terminate(proc: subprocess.Popen, timeout: float = 30.0) -> int | None:
+ """Graceful SIGTERM (the normal stop), SIGKILL only if it overstays."""
+ if proc.poll() is None:
+ proc.send_signal(signal.SIGTERM)
+ try:
+ proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=10)
+ return proc.returncode
+
+
+ def format_cells(results: Iterable[tuple[str, dict[str, bool]]]) -> str:
+ rows = list(results)
+ cols = sorted({k for _, cells in rows for k in cells})
+ head = "| entrypoint | " + " | ".join(cols) + " |"
+ sep = "|---" * (len(cols) + 1) + "|"
+ body = [
+ f"| {ep} | " + " | ".join(("✅" if cells.get(k) else ("—" if k not in cells else "❌")) for k in cols) + " |"
+ for ep, cells in rows
+ ]
+ return "\n".join([head, sep, *body])
diff --cc tests/hermes_cli/test_config_save_integrity.py
index 00000000000,b3a5426b109..71968f15ec3
mode 000000,100644..100644
--- a/tests/hermes_cli/test_config_save_integrity.py
+++ b/tests/hermes_cli/test_config_save_integrity.py
@@@ -1,0 -1,229 +1,229 @@@
+ """config.yaml write integrity: a failed read never reaches disk, and a save keeps what the user wrote."""
+
+ import errno
+ import os
+ import shutil
+
+ import pytest
-import yaml
++import hermes_yaml as yaml
+
+ import hermes_cli.config as config_mod
+ from hermes_cli.config import DEFAULT_CONFIG, load_config, migrate_config, read_raw_config, save_config
+
+ _CONFIG = """# hand-tuned
+ model:
+ default: my-org/custom-model
+ display:
+ skin: mono
+ terminal:
+ backend: docker
+ approvals:
+ deny:
+ - rm -rf /
+ """
+
+
+ @pytest.fixture
+ def home(tmp_path, monkeypatch):
+ from tui_gateway import server
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(server, "_hermes_home", tmp_path)
+ server._cfg_cache = server._cfg_sig = server._cfg_path = None
+ (tmp_path / "config.yaml").write_text(_CONFIG, encoding="utf-8")
+ yield tmp_path
+ server._cfg_cache = server._cfg_sig = server._cfg_path = None
+
+
+ class _ReadFaults:
+ """Counts parses of config.yaml and fails the chosen one with a transient EMFILE (intact file)."""
+
+ def __init__(self, monkeypatch, path):
+ self.path, self.count, self.fail_at, real = str(path), 0, 0, config_mod.fast_safe_load
+
+ def flaky(stream):
+ if getattr(stream, "name", None) == self.path:
+ self.count += 1
+ if self.count == self.fail_at:
+ raise OSError(errno.EMFILE, "Too many open files")
+ return real(stream)
+ monkeypatch.setattr(config_mod, "fast_safe_load", flaky)
+
+ def arm(self, fail_at=0):
+ self.count, self.fail_at = 0, fail_at
+
+
+ def _fresh_process(home, text, *, keep_last_known_good=False):
+ """*text* on a new inode with cold caches (and no last-known-good copy unless asked)."""
+ from tui_gateway import server
+ config_mod._LOAD_CONFIG_CACHE.clear()
+ config_mod._RAW_CONFIG_CACHE.clear()
+ server._cfg_cache = server._cfg_sig = server._cfg_path = None
+ if not keep_last_known_good:
+ config_mod._LAST_EXPANDED_CONFIG_BY_PATH.clear()
+ shutil.rmtree(home / "backups", ignore_errors=True)
+ tmp = home / ".config.yaml.new"
+ tmp.write_text(text, encoding="utf-8")
+ os.replace(tmp, home / "config.yaml")
+
+
+ def _save_loaded():
+ cfg = load_config()
+ cfg["display"]["skin"] = "ares"
+ save_config(cfg)
+
+
+ def _save_raw(): # the shape every migration step and ``write_platform_config_field(raw=True)`` use
+ cfg = read_raw_config()
+ cfg.setdefault("display", {})["skin"] = "ares"
+ save_config(cfg)
+
+
+ def _tui_config_set():
+ from tui_gateway import server
+ reply = server._methods["config.set"](1, {"key": "skin", "value": "ares"})
+ if "error" in reply:
+ raise RuntimeError(reply["error"]["message"])
+
+
+ def _dashboard_put():
+ from starlette.testclient import TestClient
+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app
+ client = TestClient(app, raise_server_exceptions=False)
+ r = client.put("/api/config", json={"config": {"display": {"skin": "ares"}}},
+ headers={_SESSION_HEADER_NAME: _SESSION_TOKEN})
+ if r.status_code != 200:
+ raise RuntimeError(r.text)
+
+
+ @pytest.mark.parametrize("last_known_good", ["none", "stale"])
+ @pytest.mark.parametrize("write", [_save_loaded, _save_raw, _tui_config_set, _dashboard_put],
+ ids=["load_config", "read_raw_config", "tui-config.set", "dashboard-put"])
+ def test_no_single_transient_read_error_reaches_the_file(write, last_known_good, home, monkeypatch):
+ """Fail each config read the write performs, one at a time: the write either lands exactly as
+ it would have, or is refused with the file byte-identical, and the retry is not poisoned."""
+ path = home / "config.yaml"
+ before = _CONFIG + "timezone: Europe/Paris\n"
+ faults = _ReadFaults(monkeypatch, path)
+
+ def run(k):
+ _fresh_process(home, before)
+ if last_known_good == "stale": # loaded earlier in this process, edited elsewhere since
+ _fresh_process(home, _CONFIG)
+ load_config()
+ _fresh_process(home, before, keep_last_known_good=True)
+ faults.arm(k)
+ try:
+ write()
+ except RuntimeError:
+ return "refused"
+ return "ok"
+
+ assert run(0) == "ok"
+ good_after, reads = path.read_bytes(), faults.count
+ assert b"skin: ares" in good_after and reads >= 1
+ for k in range(1, reads + 1):
+ if run(k) == "refused":
+ assert path.read_text(encoding="utf-8") == before, f"read {k}/{reads} failed, file changed"
+ faults.arm()
+ write() # the retry is not poisoned by a cached fallback
+ assert path.read_bytes() == good_after, f"read {k}/{reads} failed, the saved file differs"
+
+
+ @pytest.mark.parametrize("read", [load_config, read_raw_config], ids=["load_config", "read_raw_config"])
+ def test_transient_read_error_is_not_recorded_as_a_corrupt_config(read, home, monkeypatch, capsys):
+ """One EMFILE on an intact file must not leave the process treating config.yaml as corrupt: the
+ provider auto-resolution refusal (`corrupt_config`) keyed on the file signature would otherwise
+ fire until the file is next edited, and the good file would be copied away as `.corrupt`."""
+ from hermes_cli.auth import _refuse_env_adoption_if_config_corrupt
+ from hermes_cli.config_read_errors import _CONFIG_PARSE_WARNED, get_active_config_parse_failure
+ path = home / "config.yaml"
+ _fresh_process(home, _CONFIG)
+ _CONFIG_PARSE_WARNED.clear()
+ faults = _ReadFaults(monkeypatch, path)
+ faults.arm(1)
+
+ read()
+ assert get_active_config_parse_failure() is not None # unreadable right now: the refusal holds
+ assert read()["display"]["skin"] == "mono"
+
+ assert get_active_config_parse_failure() is None
+ _refuse_env_adoption_if_config_corrupt()
+ assert not list((home / "backups").glob("**/*.corrupt.*"))
+ assert "could not be read" in capsys.readouterr().err
+
+
+ def test_unreadable_config_serves_one_cached_fallback_until_it_reads(home, monkeypatch):
+ """While config.yaml stays unreadable, loads serve one cached fallback (the backup is parsed
+ once, not per call: ~250x slower loads before), and the first load once the file opens again
+ reads the real file even though its signature never changed."""
+ import builtins
+ from hermes_cli import config_backups
+ from hermes_cli.config_read_errors import FailedConfigRead
+ path = home / "config.yaml"
+ _fresh_process(home, _CONFIG)
+ load_config() # leaves the `good` backup a fresh process falls back to
+ config_mod._LOAD_CONFIG_CACHE.clear()
+ config_mod._LAST_EXPANDED_CONFIG_BY_PATH.clear()
+ blocked, rebuilds, real_backup = [True], [], config_backups.load_newest_good_backup
+
+ def guarded_open(file, *args, **kwargs):
+ if blocked[0] and str(file) == str(path):
+ raise OSError(errno.EMFILE, "Too many open files")
+ return builtins.open(file, *args, **kwargs)
+ monkeypatch.setattr(config_mod, "open", guarded_open, raising=False)
+ monkeypatch.setattr(config_backups, "load_newest_good_backup", lambda p: rebuilds.append(p) or real_backup(p))
+
+ for _ in range(5):
+ cfg = load_config()
+ assert isinstance(cfg, FailedConfigRead) and cfg["display"]["skin"] == "mono"
+ assert len(rebuilds) == 1
+ blocked[0] = False
+ assert type(load_config()) is dict
+
+
+ def test_save_refusal_for_bad_yaml_asks_for_an_edit_not_a_retry(home):
+ _fresh_process(home, "model: [unclosed\n")
+ cfg = load_config()
+ cfg["display"]["skin"] = "ares"
+ with pytest.raises(RuntimeError, match="has a formatting error") as refusal:
+ save_config(cfg)
+ assert "hermes config edit" in str(refusal.value) and "Try again" not in str(refusal.value)
+ assert (home / "config.yaml").read_text(encoding="utf-8") == "model: [unclosed\n"
+
+
+ @pytest.mark.parametrize("operation", ["save", "partial_save", "migrate"])
+ def test_authored_nulls_survive_config_writes(tmp_path, monkeypatch, operation):
+ from hermes_cli.resource_limits import configured_nofile_soft_limit
+ from agent.agent_runtime_helpers import prompt_caching_disabled_from_config
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ config_path = tmp_path / "config.yaml"
+ seed = {
+ "_config_version": DEFAULT_CONFIG["_config_version"] - (operation == "migrate"),
+ "runtime": {"nofile_soft_limit": None},
+ "prompt_caching": {"cache_ttl": None},
+ "x_null_preservation": {"nested": {"optional": None}, "keep": "value"},
+ }
+ config_path.write_text(yaml.safe_dump(seed), encoding="utf-8")
+
+ if operation == "migrate":
+ migrate_config(interactive=False, quiet=True)
+ elif operation == "partial_save":
+ save_config({"display": {"skin": "mono"}}, merge_existing=True)
+ else:
+ config = load_config()
+ config["display"]["skin"] = "mono"
+ save_config(config)
+
+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ assert raw["runtime"]["nofile_soft_limit"] is None
+ assert raw["prompt_caching"]["cache_ttl"] is None
+ assert raw["x_null_preservation"] == seed["x_null_preservation"]
+ assert "terminal" not in raw
+ assert "agent" not in raw # no section the user never wrote, not even an empty one
+ assert configured_nofile_soft_limit() is None
+ assert prompt_caching_disabled_from_config() is True
+ if operation == "migrate":
+ assert raw["_config_version"] == DEFAULT_CONFIG["_config_version"]
+ else:
+ assert raw["display"]["skin"] == "mono"
diff --cc tests/hermes_cli/test_git_probe_no_lazy_fetch.py
index 00000000000,7443004d677..e0a5f92a9fe
mode 000000,100644..100644
--- a/tests/hermes_cli/test_git_probe_no_lazy_fetch.py
+++ b/tests/hermes_cli/test_git_probe_no_lazy_fetch.py
@@@ -1,0 -1,75 +1,75 @@@
+ """Read-only git probes never lazy-fetch from a partial clone's promisor remote.
+
+ In a blobless clone, asking about an object the clone has not fetched (the fresh upstream tip the
+ startup update check compares against) makes git download it — for a real install, the whole
+ commit/tree history — and the probe's timeout kills only its own git, orphaning the fetch.
+ """
+
+ import os
+ import re
+ import subprocess
+ from pathlib import Path
+
+ import pytest
+
-from hermes_cli import banner
++from hermes_cli import source_check
+ from hermes_cli._subprocess_compat import bounded_git_probe
+
+ _ENV = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
+
+
+ def _git(*args, cwd=None, env=_ENV):
+ return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=cwd, env=env,
+ check=True, capture_output=True, text=True).stdout.strip()
+
+
+ def _git_supports_no_lazy_fetch() -> bool:
+ m = re.search(r"(\d+)\.(\d+)", _git("--version"))
+ return bool(m) and (int(m[1]), int(m[2])) >= (2, 44)
+
+
+ pytestmark = pytest.mark.skipif(not _git_supports_no_lazy_fetch(), reason="GIT_NO_LAZY_FETCH needs git >= 2.44")
+
+
+ @pytest.fixture
+ def partial_clone(tmp_path: Path):
+ """(clone, local_head, unfetched_upstream_tip) for a blobless clone of a local upstream."""
+ seed, up, clone = tmp_path / "seed", tmp_path / "up.git", tmp_path / "clone"
+ _git("init", "-q", "-b", "main", str(seed))
+ for i in range(2):
+ (seed / f"f{i}.txt").write_text(f"v{i}\n" * 50, encoding="utf-8")
+ _git("add", "-A", cwd=seed)
+ _git("commit", "-qm", f"c{i}", cwd=seed)
+ _git("clone", "-q", "--bare", str(seed), str(up))
+ _git("config", "uploadpack.allowFilter", "true", cwd=up)
+ _git("config", "uploadpack.allowAnySHA1InWant", "true", cwd=up)
+ _git("clone", "-q", "--filter=blob:none", "--no-checkout", up.as_uri(), str(clone))
+ (seed / "new.txt").write_text("upstream moved\n", encoding="utf-8")
+ _git("add", "-A", cwd=seed)
+ _git("commit", "-qm", "upstream", cwd=seed)
+ _git("push", "-q", str(up), "main", cwd=seed)
+ return clone, _git("rev-parse", "HEAD", cwd=clone), _git("rev-parse", "main", cwd=up)
+
+
+ def _fetched(clone: Path, sha: str) -> bool:
+ env = {**_ENV, "GIT_NO_LAZY_FETCH": "1"}
+ return subprocess.run(["git", "cat-file", "-e", sha], cwd=clone, env=env, capture_output=True).returncode == 0
+
+
-def test_update_check_ancestry_probe_never_fetches_from_the_promisor(partial_clone, monkeypatch):
++def test_update_check_ancestry_probe_never_fetches_from_the_promisor(partial_clone):
+ clone, head, upstream_tip = partial_clone
- monkeypatch.setattr(banner, "_github_compare_behind", lambda cur, tgt: None)
+
- assert banner._tips_behind(head, upstream_tip, clone) == banner.UPDATE_AVAILABLE_NO_COUNT
++ # The exact ancestry probe check_for_updates runs before it falls back to the compare API.
++ assert not source_check._git_ok(["merge-base", "--is-ancestor", upstream_tip, head], cwd=clone)
+ assert not _fetched(clone, upstream_tip), "the update check downloaded upstream history"
+ # Control: an upstream tip already in local history still reads as up to date.
+ parent = _git("rev-parse", "HEAD~1", cwd=clone)
- assert banner._tips_behind(head, parent, clone) == 0
++ assert source_check._git_ok(["merge-base", "--is-ancestor", parent, head], cwd=clone)
+
+
+ def test_bounded_git_probe_never_fetches_from_the_promisor(partial_clone):
+ clone, head, upstream_tip = partial_clone
+
+ assert bounded_git_probe(["git", "-C", str(clone), "log", "-1", "--format=%H", upstream_tip], timeout=10) == ""
+ assert not _fetched(clone, upstream_tip), "a session-start git probe downloaded upstream history"
+ assert bounded_git_probe(["git", "-C", str(clone), "log", "-1", "--format=%H", head], timeout=10) == head
diff --cc tests/hermes_cli/test_xai_retirement.py
index d0cf3ca3b34,90d74423600..5354883edca
--- a/tests/hermes_cli/test_xai_retirement.py
+++ b/tests/hermes_cli/test_xai_retirement.py
@@@ -1,7 -1,11 +1,11 @@@
"""Unit tests for hermes_cli.xai_retirement (May 15, 2026 model retirement)."""
from __future__ import annotations
+
-import yaml
++import hermes_yaml as yaml
+
from hermes_cli.xai_retirement import (
+ RetirementIssue,
_RETIRED_MODELS,
_looks_like_xai,
_normalize,
@@@ -8,6 -13,26 +13,25 @@@
find_retired_xai_refs,
)
+
+ def test_apply_migration_preserves_long_double_quoted_scalar(tmp_path, monkeypatch):
+ """Same fold-after-backslash class as #119844: the migration's own emitter must not mutate
+ unrelated long quoted values while it rewrites the model key."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ value = "A" * 74 + r"D:\CentBrowserPortable " + "B" * 40
+ cfg = tmp_path / "config.yaml"
+ cfg.write_text(
+ 'model:\n provider: xai\n model: grok-3\napprovals:\n smart_policy: "'
+ + value.replace("\\", "\\\\") + '"\n',
+ encoding="utf-8",
+ )
+
+ apply_migration(cfg, [RetirementIssue("model.model", "grok-3", "grok-4")], backup=False)
+
+ loaded = yaml.safe_load(cfg.read_text(encoding="utf-8"))
+ assert loaded["model"]["model"] == "grok-4"
+ assert loaded["approvals"]["smart_policy"] == value
+
-
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --cc tests/tui_gateway/test_secondary_profile_model_and_key.py
index 00000000000,23510f1c844..07a6909911d
mode 000000,100644..100644
--- a/tests/tui_gateway/test_secondary_profile_model_and_key.py
+++ b/tests/tui_gateway/test_secondary_profile_model_and_key.py
@@@ -1,0 -1,69 +1,69 @@@
+ """One Desktop backend serving two profiles: a secondary session's key save and model belong to IT.
+
+ ``model.save_key`` bound by ``session_id`` wrote the LAUNCH profile's ``.env`` and exported the key
+ process-wide; ``session.create {profile}`` reported (and first-persisted) the launch profile's model.
+ """
+
+ from __future__ import annotations
+
+ import os
+ from unittest.mock import Mock, patch
+
+ import pytest
-import yaml
++import hermes_yaml as yaml
+
+ import tui_gateway.server as server
+
+
+ @pytest.fixture
+ def homes(tmp_path, monkeypatch):
+ launch, worker = tmp_path / "launch", tmp_path / "profiles" / "worker"
+ for home, model in ((launch, "launch-model"), (worker, "worker-model")):
+ home.mkdir(parents=True)
+ (home / "config.yaml").write_text(yaml.safe_dump({"model": {"default": model}}), encoding="utf-8")
+ (home / ".env").write_text("", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ for seed in ("HERMES_MODEL", "HERMES_INFERENCE_MODEL"):
+ monkeypatch.delenv(seed, raising=False)
+ monkeypatch.setenv("GLM_API_KEY", "launch-own-key")
+ monkeypatch.setattr(server, "_hermes_home", launch)
+ monkeypatch.setattr(server, "_cfg_cache", None)
+ monkeypatch.setattr(server, "_cfg_sig", None)
+ monkeypatch.setattr(server, "_cfg_path", None)
+ monkeypatch.setattr(server, "_profile_home", lambda name: worker if name == "worker" else None)
+ return launch, worker
+
+
+ def test_session_bound_save_key_writes_only_the_session_profiles_env(homes, monkeypatch):
+ launch, worker = homes
+ monkeypatch.setattr("hermes_cli.inventory.build_models_payload", Mock(return_value={"providers": []}))
+ key = "glm-" + "worker-canary"
+ session = {"agent": None, "profile_home": str(worker), "session_key": "worker-session"}
+ with patch.dict(server._sessions, {"s-worker": session}, clear=False):
+ resp = server._methods["model.save_key"](
+ "rid", {"session_id": "s-worker", "slug": "zai", "api_key": key})
+ assert "result" in resp, resp
+ assert key in (worker / ".env").read_text(encoding="utf-8")
+ assert key not in (launch / ".env").read_text(encoding="utf-8")
+ assert os.environ["GLM_API_KEY"] == "launch-own-key", "a secondary's key never reaches the process env"
+
+
+ def test_session_create_for_a_profile_reports_and_persists_its_own_model(homes, monkeypatch, tmp_path):
+ for name in ("_schedule_agent_build", "_schedule_session_cap_enforcement", "_register_session_cwd"):
+ monkeypatch.setattr(server, name, lambda *a, **k: None)
+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
+ monkeypatch.setattr(server, "_completion_cwd", lambda *a, **k: str(tmp_path))
+ known = set(server._sessions)
+ try:
+ worker_resp = server.handle_request(
+ {"id": "1", "method": "session.create", "params": {"profile": "worker", "source": "desktop"}})
+ launch_resp = server.handle_request(
+ {"id": "2", "method": "session.create", "params": {"source": "desktop"}})
+ assert worker_resp["result"]["info"]["model"] == "worker-model"
+ assert launch_resp["result"]["info"]["model"] == "launch-model"
+ worker_session = server._sessions[worker_resp["result"]["session_id"]]
+ assert server._workdir_row_model_config(worker_session)[0] == "worker-model"
+ finally:
+ with server._sessions_lock:
+ for sid in [s for s in server._sessions if s not in known]:
+ server._sessions.pop(sid, None)