Skip to content

The agent that grows with you

fix(desktop): read the Windows SSH inventory through the runtime helper

yoniebans7f72db17af52
diff --git a/apps/desktop/electron/windows-remote-inventory.test.ts b/apps/desktop/electron/windows-remote-inventory.test.ts
index e5b90ced0e2..d7de69f0104 100644
--- a/apps/desktop/electron/windows-remote-inventory.test.ts
+++ b/apps/desktop/electron/windows-remote-inventory.test.ts
@@ -6,47 +6,18 @@ import path from 'node:path'
import { test } from 'vitest'
-import { WINDOWS_PROFILE_LIST_PY, windowsInventoryScript } from './windows-remote-inventory'
+import { listWindowsRemoteProfiles, readWindowsRemoteInstallId } from './windows-remote-inventory'
import { atomicWindowsSpawn, atomicWindowsSpawnCommand, compressedPowerShellCommand, decodePowerShellCommand, encodedPowerShell, probeWindowsFiles, probeWindowsRemote } from './windows-remote-lifecycle'
-import { WINDOWS_NO_REPARSE_PS, windowsHelperArgv, windowsRuntimeProgramArgv } from './windows-runtime-command'
+import { WINDOWS_NO_REPARSE_PS } from './windows-runtime-command'
-const repo = path.resolve(import.meta.dirname, '../../..')
-const python = process.env.HERMES_TEST_PYTHON || path.join(repo, '.venv/bin/python')
+const python = process.env.HERMES_TEST_PYTHON || process.env.HERMES_PYTHON || 'python'
const runtime = { os: 'Windows', arch: 'AMD64', hermesHome: 'C:\\hermes', hermesPath: 'C:\\hermes\\bin\\hermes.exe', python: 'C:\\runtime\\python.exe' }
-const bootstrap = "import os, sys, runpy; os.environ['HERMES_TEST_BOOT']='selected'; runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)"
-const selected = { ...runtime, runtimeCommand: [python, '-I', '-c', bootstrap] }
+const bootstrap = "import os, sys, runpy; runpy.run_module('hermes_cli.main', run_name='__main__', alter_sys=True)"
function streamed(command: string) {
return decodePowerShellCommand(command)
}
-test('the canonical runtime prefix is actually executed, including bootstrap and Unicode arguments', () => {
- // Windows Python writes a pipe in the ANSI code page, and -I ignores PYTHONIOENCODING.
- const program = "import json, os, sys; sys.stdout.reconfigure(encoding='utf-8'); print(json.dumps([os.environ['HERMES_TEST_BOOT'], sys.argv[1], '$&'], ensure_ascii=False))"
- const argv = windowsRuntimeProgramArgv(selected, program)
- const result = spawnSync(argv[0], [...argv.slice(1), '用户/한글'], { encoding: 'utf8' })
-
- assert.equal(result.status, 0, result.stderr)
- assert.deepEqual(JSON.parse(result.stdout), ['selected', '用户/한글', '$&'])
- assert.ok(windowsHelperArgv(selected, 'inspect', [runtime.hermesPath]).includes('inspect'))
- assert.throws(() => windowsRuntimeProgramArgv({ ...runtime, runtimeCommand: [python, '-c', 'print(0)'] }, 'pass'), (e: any) => e.kind === 'update-required')
-})
-
-test('injected Python program survives the observed PowerShell 5.1 double-quote loss', () => {
- const program = `import json, sys; sys.stdout.reconfigure(encoding='utf-8'); print(json.dumps({'marker': '用户/quote"path'}, ensure_ascii=False))`
- const argv = windowsRuntimeProgramArgv(selected, program)
- const tail = argv.at(-1)!
-
- assert.match(tail, /exec\(bytes\.fromhex\('[0-9a-f]+'\)\.decode\('utf-8'\)\)$/)
- assert.equal(tail.startsWith(bootstrap.split('runpy.run_module')[0]), true)
- // The transport failure was observed on real Windows by Polaris; this is its loss-channel regression,
- // not a claim to execute PowerShell 5.1 on a Mac.
- const result = spawnSync(argv[0], [...argv.slice(1, -1), tail.replace(/"/g, '')], { encoding: 'utf8' })
-
- assert.equal(result.status, 0, result.stderr)
- assert.deepEqual(JSON.parse(result.stdout), { marker: '用户/quote"path' })
-})
-
test('PATH bin launcher is resolved independently of its absent sibling Python, after the marker gate', async () => {
const calls: string[] = []
@@ -154,47 +125,23 @@ test('Connect refuses an older helper before token upload or backend spawn on a
assert.equal(writes, 0)
})
-test('canonical profile predicate really filters tombstones, markerless dirs and rollback junk under a pinned home', () => {
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-canonical-inventory-'))
- const root = path.join(home, 'state-root')
- const profiles = path.join(root, 'profiles')
- fs.mkdirSync(path.join(profiles, '.deleted'), { recursive: true })
- fs.writeFileSync(path.join(root, 'config.yaml'), '')
-
- for (const name of ['bob', 'win-research', 'ghost', 'tombstoned', '.rollback-1', 'bad name']) {
- fs.mkdirSync(path.join(profiles, name))
-
- if (name !== 'ghost') {fs.writeFileSync(path.join(profiles, name, 'config.yaml'), '')}
- }
-
- fs.writeFileSync(path.join(profiles, '.deleted', 'tombstoned'), '')
-
- try {
- for (const hermesHome of [root, path.join(profiles, 'bob')]) {
- const result = spawnSync(python, ['-c', WINDOWS_PROFILE_LIST_PY], {
- cwd: repo, encoding: 'utf8', env: { PATH: process.env.PATH || '', HOME: home, HERMES_HOME: hermesHome, PYTHONPATH: repo }
- })
+test('inventory reads profiles and install identity through the runtime helper after the marker gate', async () => {
+ const calls: string[] = []
- assert.equal(result.status, 0, result.stderr)
- assert.deepEqual(JSON.parse(result.stdout).profiles, ['default', 'bob', 'win-research'])
- }
+ const ssh = { exec: async (command: string, options: { stdinData?: string } = {}) => {
+ assert.equal(options.stdinData, undefined)
+ const script = streamed(command)
+ calls.push(script)
- assert.equal(fs.existsSync(path.join(root, 'install_id')), false, 'inventory must not mint an identity')
- } finally {
- fs.rmSync(home, { recursive: true, force: true })
- }
-})
+ if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
+ assert.match(script, /'--run-module' 'hermes_cli\.windows_ssh_runtime' 'inventory'/)
-test('inventory programs guard ancestors, keep install-root anchoring and open identity no-follow', () => {
- const roster = windowsInventoryScript(runtime, 'profiles')
- const identity = windowsInventoryScript({ ...runtime, hermesHome: 'C:\\hermes\\profiles\\bob' }, 'install-id')
+ return JSON.stringify({ profiles: ['default', 'bob'], installId: 'A'.repeat(32) })
+ } }
- assert.match(roster, /Assert-NoReparse \$profilesDir \$true/)
- assert.match(roster, /_iter_named_profile_dirs/)
- assert.match(identity, /Split-Path -Leaf \$parent\) -ieq "profiles"/)
- assert.match(identity, /GetFinalPathNameByHandle/)
- assert.match(identity, /0x00200000/)
- assert.doesNotMatch(identity, /read_or_create_install_id|WriteAllText|CreateDirectory/)
+ assert.deepEqual(await listWindowsRemoteProfiles(ssh, runtime), ['default', 'bob'])
+ assert.equal(await readWindowsRemoteInstallId(ssh, runtime), 'a'.repeat(32))
+ assert.deepEqual(calls.map(script => script.includes('.hermes-update-in-progress')), [true, false, true, false])
})
test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real local PowerShell runs a long compressed script, preserving Unicode and piped JSON', () => {
@@ -237,19 +184,16 @@ test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real outer PowerShell rejects
}
})
-test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real PowerShell parser accepts emitted probe, inventory, spawn and no-follow C# programs', async () => {
+test.runIf(Boolean(process.env.HERMES_TEST_PWSH))('real PowerShell parser accepts emitted probe and spawn programs', async () => {
const pwsh = String(process.env.HERMES_TEST_PWSH)
- const scripts = [windowsInventoryScript(runtime, 'profiles'), windowsInventoryScript(runtime, 'install-id')]
- scripts.push(streamed(atomicWindowsSpawnCommand(runtime)))
+ const scripts = [streamed(atomicWindowsSpawnCommand(runtime))]
await probeWindowsFiles({ exec: async (command: string) => {
scripts.push(streamed(command))
return JSON.stringify(runtime)
} })
const list = scripts.map(script => `'${encodedPowerShell(script)}'`).join(',')
- const compile = windowsInventoryScript(runtime, 'install-id').match(/Add-Type -TypeDefinition @'[\s\S]*?'@/)?.[0]
- assert.ok(compile)
- const program = `$errorsFound=@();foreach($b in @(${list})){$text=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b));$tokens=$null;$parseErrors=$null;[Management.Automation.Language.Parser]::ParseInput($text,[ref]$tokens,[ref]$parseErrors)|Out-Null;$errorsFound+=@($parseErrors)};${compile};if($errorsFound.Count){$errorsFound|ForEach-Object {$_.Message};exit 1};'HERMES_PS_PROGRAMS_PARSE_OK'`
+ const program = `$errorsFound=@();foreach($b in @(${list})){$text=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($b));$tokens=$null;$parseErrors=$null;[Management.Automation.Language.Parser]::ParseInput($text,[ref]$tokens,[ref]$parseErrors)|Out-Null;$errorsFound+=@($parseErrors)};if($errorsFound.Count){$errorsFound|ForEach-Object {$_.Message};exit 1};'HERMES_PS_PROGRAMS_PARSE_OK'`
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-ps-parse-'))
const file = path.join(dir, 'parse.ps1')
diff --git a/apps/desktop/electron/windows-remote-inventory.ts b/apps/desktop/electron/windows-remote-inventory.ts
index 43eef8c2299..56f5a14ceed 100644
--- a/apps/desktop/electron/windows-remote-inventory.ts
+++ b/apps/desktop/electron/windows-remote-inventory.ts
@@ -1,97 +1,29 @@
import { parseRemoteProfileListing } from './connection-registry'
-import { assertWindowsRemoteInstallUpdateClear, compressedPowerShellCommand, psLiteral, stripPowerShellNoise } from './windows-remote-lifecycle'
-import { WINDOWS_NO_REPARSE_PS, type WindowsRuntime, windowsRuntimeProgramArgv } from './windows-runtime-command'
+import { assertWindowsRemoteInstallUpdateClear, helper } from './windows-remote-lifecycle'
+import type { WindowsRuntime } from './windows-runtime-command'
-// Use the canonical identity/tombstone predicate without list_profile_names' OSError suppression.
-// No configs, credentials or sessions are opened, and inventory never creates a home or identity.
-export const WINDOWS_PROFILE_LIST_PY = [
- 'import json, sys',
- 'sys.dont_write_bytecode = True',
- 'from hermes_cli.profiles import _iter_named_profile_dirs',
- "print(json.dumps({'profiles': ['default', *[p.name for p in _iter_named_profile_dirs()]]}, ensure_ascii=False))"
-].join('\n')
-
-const ID_NOFOLLOW_PS = `Add-Type -TypeDefinition @'
-using System;
-using System.IO;
-using System.Text;
-using System.Runtime.InteropServices;
-using Microsoft.Win32.SafeHandles;
-public static class HermesInventoryNoFollow {
- [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
- private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
- [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
- private static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, StringBuilder path, uint size, uint flags);
- public static FileStream OpenRead(string name) {
- var handle=CreateFile(name, 0x80000000, 0x00000007, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero);
- if(handle.IsInvalid) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
- try {
- var path=new StringBuilder(32768);
- var size=GetFinalPathNameByHandle(handle,path,32768,0);
- var actual=path.ToString();
- if(actual.StartsWith(@"\\\\?\\")) actual=actual.Substring(4);
- if(size==0 || size>=32768 || !String.Equals(actual,Path.GetFullPath(name),StringComparison.OrdinalIgnoreCase)) throw new IOException("Inventory path escaped its expected location");
- return new FileStream(handle, FileAccess.Read);
- } catch { handle.Dispose(); throw; }
- }
-}
-'@
-`
-
-export function windowsInventoryScript(runtime: WindowsRuntime, operation: 'install-id' | 'profiles'): string {
- const prefix = [
- '$ProgressPreference="SilentlyContinue"',
- '$ErrorActionPreference="Stop"',
- '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)',
- WINDOWS_NO_REPARSE_PS,
- `$hermesHome=${psLiteral(runtime.hermesHome)}`,
- 'if($hermesHome -notmatch "^[a-zA-Z]:[\\\\/]"){throw "Unsafe Windows Hermes home"}',
- 'Assert-NoReparse $hermesHome $false',
- '$installRoot=$hermesHome;$parent=Split-Path -Parent $hermesHome',
- 'if((Split-Path -Leaf $parent) -ieq "profiles"){$installRoot=Split-Path -Parent $parent}',
- 'Assert-NoReparse $installRoot $false'
- ]
-
- if (operation === 'profiles') {
- const argv = windowsRuntimeProgramArgv(runtime, WINDOWS_PROFILE_LIST_PY)
- prefix.push(
- '$profilesDir=Join-Path $installRoot "profiles"',
- 'Assert-NoReparse $profilesDir $true',
- // Only metadata: reject links before the canonical predicate can follow any directory.
- 'if(Test-Path -LiteralPath $profilesDir -PathType Container){foreach($entry in Get-ChildItem -LiteralPath $profilesDir -Force){Assert-NoReparse $entry.FullName $false;if($entry.PSIsContainer){foreach($child in Get-ChildItem -LiteralPath $entry.FullName -Force){Assert-NoReparse $child.FullName $false}}}}',
- '$env:HERMES_HOME=$hermesHome',
- `& ${argv.map(psLiteral).join(' ')}`,
- 'if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}'
- )
- } else {
- prefix.push(
- ID_NOFOLLOW_PS,
- '$file=Join-Path $installRoot "install_id";$id=$null',
- 'Assert-NoReparse $file $true',
- 'if(Test-Path -LiteralPath $file -PathType Leaf){$stream=$null;$memory=$null;try{$stream=[HermesInventoryNoFollow]::OpenRead($file);Assert-NoReparse $file $false;$memory=New-Object IO.MemoryStream;$buffer=New-Object byte[] 256;$count=$stream.Read($buffer,0,256);if($count -lt 256){$id=[Text.Encoding]::UTF8.GetString($buffer,0,$count).Trim([char]0xFEFF).Trim().ToLowerInvariant()}}finally{if($memory){$memory.Dispose()};if($stream){$stream.Dispose()}}}',
- '[ordered]@{id=$id}|ConvertTo-Json -Compress'
- )
- }
-
- return prefix.join('\r\n')
-}
-
-async function readInventory(ssh: any, runtime: WindowsRuntime, operation: 'install-id' | 'profiles'): Promise<any> {
+// The runtime helper reads through the install's own root and profile predicate;
+// it opens no configs, credentials or sessions and never creates a home or identity.
+async function readInventory(ssh: any, runtime: WindowsRuntime): Promise<any> {
await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
- const output = await ssh.exec(compressedPowerShellCommand(windowsInventoryScript(runtime, operation)))
-
- const parsed = JSON.parse(stripPowerShellNoise(output).pop() || 'null')
+ const parsed = await helper(ssh, runtime, 'inventory')
- if (!parsed || typeof parsed !== 'object' || parsed.error) {throw new Error('Windows inventory did not return valid JSON.')}
+ if (!parsed || typeof parsed !== 'object') {
+ throw new Error('Windows inventory did not return valid JSON.')
+ }
return parsed
}
export async function listWindowsRemoteProfiles(ssh: any, runtime: WindowsRuntime): Promise<string[]> {
- const result = await readInventory(ssh, runtime, 'profiles')
+ const result = await readInventory(ssh, runtime)
- if (!Array.isArray(result.profiles) || !result.profiles.every((name: unknown) => typeof name === 'string') || !result.profiles.includes('default')) {
+ if (
+ !Array.isArray(result.profiles) ||
+ !result.profiles.every((name: unknown) => typeof name === 'string') ||
+ !result.profiles.includes('default')
+ ) {
throw new Error('Windows inventory did not return canonical profile names.')
}
@@ -99,10 +31,13 @@ export async function listWindowsRemoteProfiles(ssh: any, runtime: WindowsRuntim
}
export async function readWindowsRemoteInstallId(ssh: any, runtime: WindowsRuntime): Promise<string | undefined> {
- const result = await readInventory(ssh, runtime, 'install-id')
+ const result = await readInventory(ssh, runtime)
+
+ if (!Object.hasOwn(result, 'installId')) {
+ throw new Error('Windows inventory did not report its install identity.')
+ }
- if (!Object.hasOwn(result, 'id')) {throw new Error('Windows inventory did not report its install identity.')}
- const id = typeof result.id === 'string' ? result.id.trim().toLowerCase() : ''
+ const id = typeof result.installId === 'string' ? result.installId.trim().toLowerCase() : ''
return /^[0-9a-f]{32}$/.test(id) ? id : undefined
}
diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.ts
index 0c97f3c5e48..a45409888c6 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.ts
@@ -4,7 +4,7 @@ import zlib from 'node:zlib'
import { resolveReadyTimeoutMs } from './remote-lifecycle'
import { WINDOWS_CHECKOUT_LOCK_PS, WINDOWS_MARKER_JUDGE_PS } from './remote-update-marker-programs'
import { assertBootstrapNotSuperseded, redactSecrets, SSH_ERROR } from './ssh-connection'
-import { WINDOWS_NO_REPARSE_PS, windowsHelperArgv, windowsRuntimeProgramArgv } from './windows-runtime-command'
+import { WINDOWS_NO_REPARSE_PS, windowsHelperArgv } from './windows-runtime-command'
const LOCKFILE_SCHEMA_VERSION = 2
const PROTOCOL_VERSION = 1
@@ -218,8 +218,6 @@ async function resolveWindowsLauncher(ssh: any, runtime: any) {
if (!Array.isArray(resolved?.runtimeCommand) || !resolved.runtimeCommand.every(part => typeof part === 'string' && !part.includes('\0')) || typeof resolved.python !== 'string' || !/^[a-z]:[\\/]/i.test(resolved.python)) {
throw new Error('Invalid Windows launcher runtime response.')
}
-
- windowsRuntimeProgramArgv({ ...runtime, ...resolved }, 'pass')
} catch (cause: any) {
if (TRANSPORT_KINDS.has(cause?.kind)) {throw cause}
const error: any = new Error('Refresh the remote Windows Hermes launcher: its boot-selecting runtime could not be resolved.')
diff --git a/apps/desktop/electron/windows-runtime-command.ts b/apps/desktop/electron/windows-runtime-command.ts
index 2bf1bf0cfb3..eec0dbe9ed3 100644
--- a/apps/desktop/electron/windows-runtime-command.ts
+++ b/apps/desktop/electron/windows-runtime-command.ts
@@ -9,27 +9,6 @@ export interface WindowsRuntime {
runtimeCommand?: string[]
}
-export function windowsRuntimeProgramArgv(runtime: WindowsRuntime, program: string): string[] {
- if (!runtime.runtimeCommand) {return [runtime.python, '-c', program]}
- const command = [...runtime.runtimeCommand]
- const codeIndex = command.indexOf('-c')
- const entry = /runpy\.run_module\((['"])hermes_cli\.main\1,\s*run_name=(['"])__main__\2,\s*alter_sys=True\)\s*$/
-
- if (codeIndex >= 1 && codeIndex === command.length - 2 && entry.test(command[codeIndex + 1])) {
- // PowerShell 5.1 strips embedded double quotes when forming native argv.
- // ASCII hex carries the program losslessly without changing the launcher bootstrap.
- const encodedProgram = Buffer.from(program, 'utf8').toString('hex')
- command[codeIndex + 1] = command[codeIndex + 1].replace(entry, () => `exec(bytes.fromhex('${encodedProgram}').decode('utf-8'))`)
-
- return command
- }
-
- // An unrecognized launcher is a capability gap, not permission to drop its bootstrap.
- const error: any = new Error('The Windows launcher does not expose a supported boot-selecting runtime command; refresh its launcher.')
- error.kind = 'update-required'
- throw error
-}
-
// Helpers enter through the launcher's own module dispatch, which owns PM activation;
// every caller then needs only the launcher path it already carries.
export function windowsHelperArgv(runtime: WindowsRuntime, operation: string, args: string[] = []): string[] {
diff --git a/apps/desktop/electron/windows-ssh-repair.test.ts b/apps/desktop/electron/windows-ssh-repair.test.ts
index 0c74c98ff59..844c8db66b8 100644
--- a/apps/desktop/electron/windows-ssh-repair.test.ts
+++ b/apps/desktop/electron/windows-ssh-repair.test.ts
@@ -52,7 +52,7 @@ test('Windows roster and install id never dispatch POSIX syntax or hide a failed
if (script.includes('.hermes-update-in-progress')) {return 'CLEAR'}
- return script.includes('install_id') ? JSON.stringify({ id: 'a'.repeat(32) }) : JSON.stringify({ profiles: ['default', 'bob', 'not legal', '.rollback', 'bob'] })
+ return JSON.stringify({ profiles: ['default', 'bob', 'not legal', '.rollback', 'bob'], installId: 'a'.repeat(32) })
} }
assert.deepEqual(await listRemoteHermesProfiles(ssh, runtime), ['default', 'bob'])
diff --git a/hermes_cli/windows_ssh_runtime.py b/hermes_cli/windows_ssh_runtime.py
index 592fb1370b4..859b62a2e67 100644
--- a/hermes_cli/windows_ssh_runtime.py
+++ b/hermes_cli/windows_ssh_runtime.py
@@ -435,6 +435,14 @@ def _probe(*_: str) -> dict[str, Any]:
return {"os": "Windows", "arch": platform.machine(), "hermesHome": str(get_default_hermes_root()), "python": sys.executable}
+def _inventory(*_: str) -> dict[str, Any]:
+ """Desktop's read-only roster: the canonical root and profile predicate; never mints an identity."""
+ from hermes_cli.install_identity import _INSTALL_ID_FILENAME, _read_existing
+ from hermes_cli.profiles import _iter_named_profile_dirs
+ install_id, _ = _read_existing(get_default_hermes_root() / _INSTALL_ID_FILENAME)
+ return {"profiles": ["default", *[p.name for p in _iter_named_profile_dirs()]], "installId": install_id}
+
+
def _read_log(ownership_id: str, spawn_nonce: str) -> dict[str, Any]:
win32con = _win32().win32con
data = _read_shared(_log_path(ownership_id, spawn_nonce), _MAX_LOG,
@@ -450,6 +458,7 @@ def _write_lock_op(ownership_id: str) -> dict[str, Any]:
# operation -> (argument count or None for "any", handler(*args)).
_OPERATIONS: dict[str, tuple[int | None, Any]] = {
"probe": (None, _probe),
+ "inventory": (None, _inventory),
"upload-token": (2, lambda o, n: upload_token(o, n, sys.stdin.buffer.read(65))),
"read-lock": (1, read_lock),
"write-lock": (1, _write_lock_op),
diff --git a/tests/hermes_cli/test_windows_ssh_runtime_inventory.py b/tests/hermes_cli/test_windows_ssh_runtime_inventory.py
new file mode 100644
index 00000000000..783d5604f86
--- /dev/null
+++ b/tests/hermes_cli/test_windows_ssh_runtime_inventory.py
@@ -0,0 +1,53 @@
+"""Desktop's Windows SSH inventory reads through the canonical root and profile predicate."""
+from __future__ import annotations
+
+import os
+
+import pytest
+
+import hermes_constants
+from hermes_cli.windows_ssh_runtime import dispatch
+
+
+def _roster(root):
+ profiles = root / "profiles"
+ (profiles / ".deleted").mkdir(parents=True)
+ (root / "config.yaml").write_text("")
+ for name in ("bob", "win-research", "ghost", "tombstoned", ".rollback-1", "bad name"):
+ (profiles / name).mkdir()
+ if name != "ghost":
+ (profiles / name / "config.yaml").write_text("")
+ (profiles / ".deleted" / "tombstoned").write_text("")
+ return profiles
+
+
[email protected]("pinned", [False, True])
+def test_inventory_lists_live_profiles_without_minting_an_identity(monkeypatch, tmp_path, pinned):
+ root = tmp_path / "state-root"
+ profiles = _roster(root)
+ monkeypatch.setenv("HERMES_HOME", str(profiles / "bob" if pinned else root))
+
+ result = dispatch(["inventory"])
+
+ assert result == {"profiles": ["default", "bob", "win-research"], "installId": None}
+ assert not (root / "install_id").exists()
+
+
+def test_a_link_inside_a_profile_does_not_hide_the_roster(monkeypatch, tmp_path):
+ root = tmp_path / "state-root"
+ profiles = _roster(root)
+ os.symlink(tmp_path, profiles / "bob" / "workspace")
+ monkeypatch.setenv("HERMES_HOME", str(root))
+
+ assert dispatch(["inventory"])["profiles"] == ["default", "bob", "win-research"]
+
+
+def test_a_nested_home_reads_the_identity_of_its_install_root(monkeypatch, tmp_path):
+ native = tmp_path / "native"
+ (native / "work").mkdir(parents=True)
+ (native / "install_id").write_text("A" * 32 + "\n")
+ monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: native)
+ monkeypatch.setenv("HERMES_HOME", str(native / "work"))
+
+ assert dispatch(["inventory"])["installId"] == "a" * 32