Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Hold Hermes identity until every native store is verified (#1120)

Deea847441e566c
diff --git a/cli/e2e/hermesAdmission.e2e.ts b/cli/e2e/hermesAdmission.e2e.ts
index d92e9dfd2..2380da3fb 100644
--- a/cli/e2e/hermesAdmission.e2e.ts
+++ b/cli/e2e/hermesAdmission.e2e.ts
@@ -1,16 +1,38 @@
/** Private daemon, hook credential, process, tmux and Hermes home throughout. */
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'
+import { readLeanBundle } from '../src/harnessd/leanBundle.js'
import { LocalClient } from './harness/client.js'
-import { IsolatedDaemon, until } from './harness/daemon.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { withLean } from './harness/release.js'
let daemon: IsolatedDaemon | undefined
let client: LocalClient | undefined
+let scratch: string, bundle: string
+beforeAll(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'hermes-admission-bundle-'))
+ bundle = join(scratch, 'build', 'cli.js')
+ execFileSync(process.execPath, ['build-bundle.mjs'], { cwd: CLI_ROOT,
+ env: { ...process.env, BUNDLE_OUT_DIR: dirname(bundle) }, stdio: 'pipe' })
+}, 120_000)
afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+afterAll(() => { if (scratch) rmSync(scratch, { recursive: true, force: true }) })
-it('holds unverified Hermes hooks while core remains ready, then rejects a child and admits a verified conversation', async () => {
- const d = daemon = await IsolatedDaemon.create()
+it.each(['missing', 'stalled'] as const)('keeps Hermes admission pending and core ready with %s optional code, then recovers the complete store pool', async mode => {
+ const text = readFileSync(bundle, 'utf8')
+ const lean = readLeanBundle(Buffer.from(text))!
+ const files = Object.fromEntries([...lean.files].map(([name, value]) => [name, value.toString('utf8')]))
+ const chunks = Object.keys(files).filter(name => name.startsWith('core-inProcess-') && files[name]!.includes('HermesReader'))
+ expect(chunks).toHaveLength(1)
+ if (mode === 'missing') delete files[chunks[0]!]
+ else files[chunks[0]!] = "console.error('[fixture] Hermes reader stalled'); await new Promise(() => {});\n"
+ const scriptPath = join(scratch, mode, 'cli.js')
+ mkdirSync(dirname(scriptPath), { recursive: true })
+ writeFileSync(scriptPath, withLean(text, files), { mode: 0o755 })
+ const d = daemon = await IsolatedDaemon.create({ scriptPath })
onTestFailed(() => console.log(d.log()))
d.env.HERMES_HOME = join(d.root, 'hermes')
d.env.HERMES_PATH = join(d.root, 'bin', 'hermes')
@@ -61,7 +83,24 @@ setInterval(() => {}, 1000)
+ 'CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, content TEXT, tool_call_id TEXT, tool_calls TEXT, tool_name TEXT, finish_reason TEXT, reasoning TEXT);')
const insert = db.prepare('INSERT INTO sessions VALUES (?, ?, ?, 0)')
insert.run(child, 'tool', cwd); insert.run(own, 'cli', cwd); db.close()
+ const profile = join(d.env.HERMES_HOME, 'profiles', 'later')
+ mkdirSync(profile, { recursive: true })
+ const otherStore = join(profile, 'state.db')
+ writeFileSync(otherStore, 'unreadable competing profile')
+ // A healthy default row cannot bypass a later unavailable home, even with optional readers gone.
+ await new Promise(resolve => setTimeout(resolve, 1_200))
+ expect((await row()).sessionId).toBeFalsy()
+ expect((await fetch(`http://127.0.0.1:${d.port}/api/health`)).ok).toBe(true)
+ rmSync(otherStore)
+ const competing = new DatabaseSync(otherStore)
+ competing.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, cwd TEXT, started_at REAL)')
+ competing.prepare('INSERT INTO sessions VALUES (?, ?, ?, 0)').run(own, 'cli', cwd)
+ competing.close()
await until('automatic source recheck to reject the child', () => d.log().includes('ignored · hermes_subagent') || null, 10_000, 100)
+ await until('complete but ambiguous parent pool', () => d.log().includes('ambiguous across homes') || null, 10_000, 100)
+ expect((await row()).sessionId).toBeFalsy()
+ const resolved = new DatabaseSync(otherStore)
+ resolved.exec('DELETE FROM sessions'); resolved.close()
await until('automatic parent binding after rejecting the child', async () => (await row()).sessionId === own || null, 10_000, 100)
expect(d.coresStarted()).toBe(1)
}, 90_000)
diff --git a/cli/scripts/handoff-2026-10-08/hermes-pool-cost.ts b/cli/scripts/handoff-2026-10-08/hermes-pool-cost.ts
new file mode 100644
index 000000000..05b251275
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/hermes-pool-cost.ts
@@ -0,0 +1,50 @@
+/** Identical private stores on former and current production; no host engine, process or daemon. */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { performance } from 'node:perf_hooks'
+const root = mkdtempSync(join(tmpdir(), 'hermes-pool-cost-'))
+const workload = process.argv[2] ?? 'single'
+const home = join(root, 'hermes'), cwd = join(root, 'work')
+for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR',
+ 'CODEX_HOME', 'CURSOR_HOME', 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME', 'PI_HOME', 'MUSE_HOME', 'COMMANDCODE_HOME',
+ 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'DEVIN_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {
+ process.env[name] = join(root, name)
+}
+process.env.HERMES_HOME = home
+const { DatabaseSync } = process.getBuiltinModule('node:sqlite') as {
+ DatabaseSync: new (path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: unknown[]): void }; close(): void }
+}
+try {
+ mkdirSync(cwd)
+ const count = workload === 'single' ? 1 : workload === 'limit' ? 66 : 33
+ for (let i = 0; i < count; i++) {
+ const folder = i ? join(home, 'profiles', `profile-${String(i).padStart(3, '0')}`) : home
+ mkdirSync(folder, { recursive: true })
+ const path = join(folder, 'state.db')
+ if (workload === 'unavailable' && i === count - 1) { writeFileSync(path, 'unavailable store'); continue }
+ const db = new DatabaseSync(path)
+ db.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, started_at REAL, source TEXT)')
+ if (i === 0) db.prepare("INSERT INTO sessions VALUES (?, ?, ?, 'cli')").run('20261009_120000_abcd', cwd, 1791547200)
+ db.close()
+ }
+ const { findLiveSession } = await import('../../src/lib/sessionRepair.js')
+ const latenciesMs: number[] = [], outcomes: Record<string, number> = {}
+ const cpu = process.cpuUsage()
+ for (let i = 0; i < 10; i++) {
+ const at = performance.now()
+ let outcome: string
+ try { outcome = await findLiveSession('hermes', cwd, 1791547140000) ? 'exact' : 'absent' }
+ catch (error) {
+ if ((error as { code?: string }).code !== 'IDENTITY_UNAVAILABLE') throw error
+ outcome = 'held'
+ }
+ latenciesMs.push(Number((performance.now() - at).toFixed(2)))
+ outcomes[outcome] = (outcomes[outcome] ?? 0) + 1
+ }
+ const used = process.cpuUsage(cpu)
+ console.log(JSON.stringify({ workload, stores: count, iterations: 10, outcomes, latenciesMs,
+ cpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,
+ node: process.version, platform: process.platform, arch: process.arch }))
+ ;(await import('../../src/lib/sqliteBuiltin.js')).closeSqliteHandles()
+} finally { rmSync(root, { recursive: true, force: true }) }
diff --git a/cli/scripts/handoff-2026-10-08/mutate-hermes-pools.py b/cli/scripts/handoff-2026-10-08/mutate-hermes-pools.py
new file mode 100644
index 000000000..28a59b149
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-hermes-pools.py
@@ -0,0 +1,72 @@
+"""Every broken Hermes control connection must assertion-fail in a disposable worktree."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+pool = 'src/engines/kit/storePool.ts'
+spec = 'src/engines/kit/storePool.spec.ts'
+hook = 'src/hookServer.ts'
+hook_spec = 'src/hookServer.hermes.spec.ts'
+golden = 'src/engines/hermesIdentity.golden.spec.ts'
+mutations = [
+ ('repair lookup disconnected', 'src/lib/sessionRepair.ts', 'const found = await readStorePool(HERMES_HOMES, env.HERMES_HOME, {', 'const found = await readStorePool(HERMES_HOMES, `${env.HERMES_HOME}/missing`, {', golden),
+ ('store declaration disconnected', 'src/engines/hermes/contract.ts', "return join(home, 'state.db')", "return join(home, 'missing.db')", golden),
+ ('source declaration disconnected', 'src/engines/hermes/contract.ts', "column: 'source'", "column: 'missing'", golden),
+ ('new profiles omitted', pool, 'if (info.isDirectory()) homes.push(home)', 'if (false) homes.push(home)', spec),
+ ('unbounded profile pool', pool, 'remaining: declared.max + 1', 'remaining: 4096', spec),
+ ('unreadable query means empty', pool, "if (!result.ok) unavailable('a native store query is unavailable')", 'if (!result.ok) return []', spec),
+ ('multiple rows mean empty', pool, 'for (const row of result.rows) found.push', 'if (result.rows.length === 1) for (const row of result.rows) found.push', spec),
+ ('incomplete paths mean absent', pool, "if (!missing(error)) unavailable('a native store path could not be inspected')", 'if (false) throw error', spec),
+ ('changed pool accepted', pool, 'if (current !== item.stamp)', 'if (false)', spec),
+ ('aliases treated as competing stores', pool, 'if (alias) { alias.aliases.push(home); continue }', 'if (false) { alias!.aliases.push(home); continue }', spec),
+ ('file links accepted', pool, "if (info && ((kind === 'file' && !info.isFile()) || (kind === 'directory' && !info.isDirectory())))", 'if (false)', spec),
+ ('hard links accepted', pool, "if (info && kind === 'file' && info.nlink !== 1)", 'if (false)', spec),
+ ('database byte limit ignored', pool, 'if (bytes > MAX_POOL_BYTES)', 'if (false)', spec),
+ ('repair prefix truncation accepted', 'src/lib/sessionRepair.ts', 'FROM sessions LIMIT 8193;', 'FROM sessions LIMIT 2;', spec),
+ ('delegated repair accepted', 'src/lib/sessionRepair.ts', 'if (!isInteractiveSource(HERMES_SOURCE, row.source)) continue', 'if (false) continue', spec),
+ ('repair custom home omitted', 'src/lib/sessionRepair.ts', 'knownHome: opts?.hermesHome', 'knownHome: undefined', spec),
+ ('hook custom home omitted', hook, 'inspectHermesKind(body.sessionId!, knownHome)', 'inspectHermesKind(body.sessionId!)', hook_spec),
+ ('source bytes normalized', 'src/engines/hermes/contract.ts', "CASE WHEN typeof(source) = 'text' AND length(CAST(source AS BLOB)) <= 128 AND instr(CAST(source AS BLOB), x'00') = 0 THEN source END", 'substr(source, 1, 129)', hook_spec),
+ ('id bytes normalized', 'src/engines/hermes/contract.ts', "CASE WHEN typeof(id) = 'text' AND length(CAST(id AS BLOB)) <= 128 AND instr(CAST(id AS BLOB), x'00') = 0 THEN id END", 'substr(id, 1, 129)', spec),
+ ('pool deadline ignored', pool, 'if (ms <= 0)', 'if (false)', spec),
+ ('first hook home wins', hook, 'if (found.length !== 1)', 'if (false)', hook_spec),
+ ('unavailable hook admitted', hook, "return { kind: 'hold', reason: `Hermes session source is unavailable; keeping the current conversation. ${error.message}` }", "return { kind: 'accept', value: undefined }", hook_spec),
+ ('cached SQLite deadline ignored', 'src/lib/sqliteBuiltin.ts', 'if (cached.busyTimeoutMs !== timeout)', 'if (false)', 'src/lib/sqliteRead.spec.ts'),
+ ('captured profile lost before Stop save', 'src/lib/stopAgentService.ts', 'hermesHome: captured.hermesHome, ', '', spec),
+ ('captured profile lost during forget save', 'src/lib/stoppedAgents.ts', 'hermesHome: previous.hermesHome, boundAt:', 'boundAt:', spec),
+ ('changed home not fenced during Stop', 'src/lib/stopAgentService.ts', ' entry.codexHome ?? null, entry.hermesHome ?? null,\n', '', spec),
+ ('saved home combined with changed authority', 'src/lib/stoppedAgents.ts', ' && (!session.hermesHome || session.hermesHome === previous.hermesHome)\n', '', spec),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+for key in list(env):
+ if key in ['TMUX', 'TMUX_PANE'] or key.startswith('RECORD_'):
+ env.pop(key, None)
+Path(env['TMUX_TMPDIR']).mkdir(parents=True, exist_ok=True)
+
+
+def run(specs):
+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=2'],
+ cwd=cli, env=env, capture_output=True, text=True, timeout=180)
+
+
+baseline = run(list(dict.fromkeys(item[4] for item in mutations)))
+if baseline.returncode:
+ print(baseline.stdout + baseline.stderr)
+ raise SystemExit('baseline failed; no mutants ran')
+print('unchanged baseline passed', flush=True)
+for label, relative, before, after, target in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == 1, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([target])
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ print(output)
+ raise SystemExit(f'{label}: not caught by an assertion')
+ print(f'{label}: caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index 202e46042..20c4fb309 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -655,15 +655,16 @@ describe('binding a running process to its session', () => {
vi.advanceTimersByTime(60_000)
await run.binding.bindObservedAgent(observed())
expect(findLiveSession).toHaveBeenCalledTimes(25)
- expect(findLiveSession).toHaveBeenLastCalledWith('claude', '/work', Date.parse('2026-10-04T10:00:00Z'), { bornOnly: true, pid: 42, codexHome: undefined })
+ expect(findLiveSession).toHaveBeenLastCalledWith('claude', '/work', Date.parse('2026-10-04T10:00:00Z'), { bornOnly: true, pid: 42, codexHome: undefined, hermesHome: undefined })
})
it('binds what it finds, with the Hermes home it was found in, and starts the count over', async () => {
const run = setup()
- vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', codexHome: '/codex' } as Partial<RegisteredSession>))
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', codexHome: '/codex', hermesHome: '/hermes' } as Partial<RegisteredSession>))
vi.mocked(findLiveSession).mockResolvedValueOnce({ sessionId: 'found', transcriptPath: '/t/found.jsonl', hermesHome: '/hermes' } as never)
vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent({ sessionId: 'found' }), ...meta({ isNew: true }) } as never)
await run.binding.bindObservedAgent(observed({ engine: 'hermes' }))
+ expect(findLiveSession).toHaveBeenCalledWith('hermes', '/work', expect.any(Number), expect.objectContaining({ hermesHome: '/hermes' }))
expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({
sessionId: 'found', transcriptPath: '/t/found.jsonl', hermesHome: '/hermes', source: 'process-repair', hookEvent: 'ProcessRepair',
})
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index cf5f92cb7..fec734959 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -343,6 +343,7 @@ export function createBinding({
bornOnly: true,
pid: observed.processIdentity.pid,
codexHome: agent.codexHome ?? undefined,
+ hermesHome: agent.hermesHome ?? undefined,
}))
if (!located) return
const found = located.value
diff --git a/cli/src/engines/__fixtures__/hermes-identity.golden.json b/cli/src/engines/__fixtures__/hermes-identity.golden.json
new file mode 100644
index 000000000..7b7b0234b
--- /dev/null
+++ b/cli/src/engines/__fixtures__/hermes-identity.golden.json
@@ -0,0 +1,41 @@
+{
+ "homes": {
+ "homes": [
+ "<root>/hermes",
+ "<root>/hermes/profiles/work"
+ ],
+ "complete": true
+ },
+ "missing-home": {
+ "homes": [
+ "<root>/missing-home"
+ ],
+ "complete": true
+ },
+ "repair:own": {
+ "sessionId": "20261009_120000_a1b2",
+ "hermesHome": "<root>/hermes"
+ },
+ "repair:profile": {
+ "sessionId": "20261009_120001_c3d4",
+ "hermesHome": "<root>/hermes/profiles/work"
+ },
+ "repair:none": null,
+ "repair:old": null,
+ "repair:both": null,
+ "repair:many": null,
+ "repair:born-only": {
+ "sessionId": "20261009_120001_c3d4",
+ "hermesHome": "<root>/hermes/profiles/work"
+ },
+ "repair:pid": {
+ "sessionId": "20261009_120001_c3d4",
+ "hermesHome": "<root>/hermes/profiles/work"
+ },
+ "source:own": "cli",
+ "source:profile": "tui",
+ "source:child": "subagent",
+ "source:absent": null,
+ "source:unwritten": null,
+ "source:invalid": ""
+}
diff --git a/cli/src/engines/hermes/contract.ts b/cli/src/engines/hermes/contract.ts
index f01c46f87..06b754aee 100644
--- a/cli/src/engines/hermes/contract.ts
+++ b/cli/src/engines/hermes/contract.ts
@@ -25,11 +25,16 @@ export const HERMES_HISTORY_ID_RE =
/**
* Hermes keeps one store per home: `hermes -p <name>` runs against `~/.hermes/profiles/<name>`, with its own
- * `state.db` (engines/hermes/home.ts). Listed by the kit (kit/storeHomes.ts) for the hook server, repair and the
- * readers alike.
+ * `state.db` (engines/hermes/home.ts). Session control verifies fresh pools in kit/storePool.ts;
+ * optional readers may reuse the kit/storeHomes.ts listing for ttlMs.
*/
export const HERMES_HOMES: StoreHomes = { profiles: 'profiles', store: hermesDbPath, max: 64, ttlMs: 30_000 }
+// Validate the original bytes. SQLite text substr/length stop at NUL and would turn a malformed
+// source such as "cli\0tool" into interactive authority, or a malformed id into a valid prefix.
+export const HERMES_ID_SQL = "CASE WHEN typeof(id) = 'text' AND length(CAST(id AS BLOB)) <= 128 AND instr(CAST(id AS BLOB), x'00') = 0 THEN id END"
+export const HERMES_SOURCE_SQL = "CASE WHEN typeof(source) = 'text' AND length(CAST(source AS BLOB)) <= 128 AND instr(CAST(source AS BLOB), x'00') = 0 THEN source END"
+
/**
* A Hermes sub-agent is a full Hermes session of its own and runs the same shell hooks, so it announces itself to
* the adapter from the parent's pane. Measured live: dispatching two sub-agents fired `on_session_start` for
@@ -43,7 +48,7 @@ export const HERMES_HOMES: StoreHomes = { profiles: 'profiles', store: hermesDbP
*/
export const HERMES_SOURCE: StoreSourceRule = {
id: /^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/,
- query: 'SELECT source FROM sessions WHERE id = ?;',
+ query: `SELECT ${HERMES_SOURCE_SQL} AS source FROM sessions WHERE id = ? LIMIT 2;`,
column: 'source',
interactive: ['', 'cli', 'tui'],
maxBuffer: 1 << 20,
diff --git a/cli/src/engines/hermesIdentity.golden.spec.ts b/cli/src/engines/hermesIdentity.golden.spec.ts
new file mode 100644
index 000000000..d42df9b20
--- /dev/null
+++ b/cli/src/engines/hermesIdentity.golden.spec.ts
@@ -0,0 +1,90 @@
+/** Former Hermes pool behavior through declared homes, source reads and live repair.
+ * Linux/UTC/fixed clock, private stores, built-in SQLite, no host process or engine. */
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, expect, it, vi } from 'vitest'
+
+vi.mock('node:child_process', async original => ({ ...await original<object>(),
+ execFile: () => { throw new Error('This golden must never run a host process') },
+ execFileSync: () => { throw new Error('This golden must never run a host process') },
+}))
+vi.mock('./inProcess.js', () => ({ loadEngine: () => { throw new Error('Hermes identity must not load an optional engine') } }))
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/hermes-identity.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_HERMES_IDENTITY_GOLDEN === '1'
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+const AT = Date.parse('2026-10-09T12:00:00Z'), START = AT - 60_000
+const ids = { own: '20261009_120000_a1b2', profile: '20261009_120001_c3d4', child: '20261009_120002_e5f6', missing: '20261009_120003_aabb' }
+let root: string, expected: Record<string, unknown>
+const captured: Record<string, unknown> = {}
+let repair: typeof import('../lib/sessionRepair.js')
+let homes: typeof import('./kit/storeHomes.js')
+let source: typeof import('./kit/storeSource.js')
+let contract: typeof import('./hermes/contract.js')
+const home = () => join(root, 'hermes')
+const cwd = (name: string) => join(root, 'work', name)
+async function check(key: string, work: unknown | Promise<unknown>): Promise<void> {
+ const value = JSON.parse(JSON.stringify(await work ?? null).split(root).join('<root>'))
+ captured[key] = value
+ if (!RECORD) expect({ key, value }).toEqual({ key, value: expected[key] })
+}
+beforeAll(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'hermes-identity-golden-')))
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'HARNESS_AUTH_DIR', 'HARNESS_HOOK_ROUTES_DIR',
+ 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR', 'CODEX_HOME', 'CURSOR_HOME', 'CURSOR_CONFIG_DIR', 'CURSOR_DATA_DIR',
+ 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME', 'AGY_CONFIG_DIR', 'PI_HOME', 'MUSE_HOME', 'COMMANDCODE_HOME',
+ 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'DEVIN_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME']) {
+ vi.stubEnv(name, join(root, name.toLowerCase()))
+ }
+ vi.stubEnv('HERMES_HOME', home()); vi.stubEnv('TZ', 'UTC')
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.useFakeTimers({ toFake: ['Date'], now: AT }); vi.resetModules()
+ repair = await import('../lib/sessionRepair.js')
+ homes = await import('./kit/storeHomes.js')
+ source = await import('./kit/storeSource.js')
+ contract = await import('./hermes/contract.js')
+ const { DatabaseSync } = (process as unknown as { getBuiltinModule(name: string): unknown }).getBuiltinModule('node:sqlite') as {
+ DatabaseSync: new (path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: unknown[]): void }; close(): void }
+ }
+ for (const name of ['own', 'profile', 'child', 'none', 'old', 'both', 'many']) mkdirSync(cwd(name), { recursive: true })
+ for (const [path, records] of [
+ [home(), [[ids.own, 'own', AT, 'cli'], ['20261009_120004_aaaa', 'both', AT, 'cli'], ['20261009_120005_bbbb', 'old', START - 60_000, 'cli']]],
+ [join(home(), 'profiles', 'work'), [[ids.profile, 'profile', AT, 'tui'], [ids.child, 'child', AT, 'subagent'],
+ ['20261009_120006_cccc', 'both', AT, 'cli'], ['20261009_120007_dddd', 'many', AT, 'cli'], ['20261009_120008_eeee', 'many', AT, 'cli']]],
+ ] as const) {
+ mkdirSync(path, { recursive: true })
+ const db = new DatabaseSync(join(path, 'state.db'))
+ db.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, started_at REAL, source TEXT);')
+ const insert = db.prepare('INSERT INTO sessions VALUES (?, ?, ?, ?)')
+ for (const [id, dir, started, kind] of records) insert.run(id, cwd(dir), started / 1000, kind)
+ db.close()
+ }
+ mkdirSync(join(home(), 'profiles', 'unwritten'), { recursive: true })
+ writeFileSync(join(home(), 'profiles', 'unwritten', 'config.yaml'), 'model: fixture\n')
+ expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))
+})
+afterAll(() => {
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(captured, null, 2) + '\n')
+ vi.useRealTimers(); vi.unstubAllEnvs(); Object.defineProperty(process, 'platform', platform)
+ rmSync(root, { recursive: true, force: true })
+})
+
+it('records complete declared homes, excluding profiles without a store', async () => {
+ await check('homes', homes.readStoreHomes(contract.HERMES_HOMES, home()))
+ await check('missing-home', homes.readStoreHomes(contract.HERMES_HOMES, join(root, 'missing-home')))
+})
+it('records live repair in the default and profile stores, with known absence and ambiguity', async () => {
+ for (const name of ['own', 'profile', 'none', 'old', 'both', 'many']) {
+ await check(`repair:${name}`, repair.findLiveSession('hermes', cwd(name), START))
+ }
+ await check('repair:born-only', repair.findLiveSession('hermes', cwd('profile'), START, { bornOnly: true }))
+ await check('repair:pid', repair.findLiveSession('hermes', cwd('profile'), START, { pid: 4242 }))
+})
+it('records native source declarations without optional interpretation', async () => {
+ for (const [label, path, id] of [
+ ['own', home(), ids.own], ['profile', join(home(), 'profiles', 'work'), ids.profile],
+ ['child', join(home(), 'profiles', 'work'), ids.child], ['absent', home(), ids.missing],
+ ['unwritten', join(home(), 'profiles', 'unwritten'), ids.missing], ['invalid', home(), '../escape'],
+ ]) await check(`source:${label}`, source.readStoreSessionSource(contract.HERMES_SOURCE, contract.hermesDbPath(path), id))
+})
diff --git a/cli/src/engines/kit/storeHomes.ts b/cli/src/engines/kit/storeHomes.ts
index 1fc336c3d..0b58d4658 100644
--- a/cli/src/engines/kit/storeHomes.ts
+++ b/cli/src/engines/kit/storeHomes.ts
@@ -1,8 +1,8 @@
/**
* The homes of an engine that keeps one store per home, as its contract declares them: the default, then each
* profile folder below it that has a store (Hermes: `~/.hermes` and `~/.hermes/profiles/<name>`). Listed for
- * whoever reads those stores: the hook server's admission, repair and the readers share one listing per
- * declaration, reused for its `ttlMs`.
+ * optional readers, which may reuse a listing for its `ttlMs`. Session control uses storePool.ts:
+ * a home listing by itself cannot prove a fresh, complete set of database claims.
*
* Moved from engines/hermes/home.ts (`listHermesHomes`), unchanged but for the declaration it reads.
*/
@@ -22,7 +22,7 @@ export interface StoreHomes {
const listings = new WeakMap<StoreHomes, { at: number; homes: string[] }>()
-/** Fresh evidence for admission. An incomplete profile list cannot authorize a profile binding. */
+/** Compatibility listing; even complete listings need database evidence before session control. */
export async function readStoreHomes(declared: StoreHomes, defaultHome: string): Promise<{ homes: string[]; complete: boolean }> {
const homes = [defaultHome]
let complete = true
diff --git a/cli/src/engines/kit/storePool.spec.ts b/cli/src/engines/kit/storePool.spec.ts
new file mode 100644
index 000000000..86a7acdb8
--- /dev/null
+++ b/cli/src/engines/kit/storePool.spec.ts
@@ -0,0 +1,467 @@
+/** Real private SQLite pools and controlled native races. No owner daemon, engine or home. */
+import { linkSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, truncateSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+const control = vi.hoisted(() => ({
+ failures: new Map<string, string>(),
+ afterQuery: undefined as undefined | ((path: string) => void | Promise<void>),
+ afterStat: undefined as undefined | ((path: string) => void),
+ result: undefined as undefined | import('../../lib/sqliteRead.js').SqliteReadResult,
+ now: undefined as number | undefined,
+ queries: [] as Array<{ path: string; options: import('../../lib/sqliteRead.js').SqliteReadOptions }>,
+ processes: [] as import('../../lib/tmux.js').ProcessRow[],
+}))
+vi.mock('../../lib/tmux.js', async original => ({ ...await original<object>(), processRows: async () => control.processes }))
+vi.mock('../../lib/deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn(async () => 'gone') }))
+vi.mock('../../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
+vi.mock('node:child_process', async original => ({ ...await original<object>(),
+ execFile: () => { throw new Error('Native identity tests must not launch a host binary') },
+}))
+vi.mock('../inProcess.js', () => ({ loadEngine: () => { throw new Error('Session control must remain eager') } }))
+vi.mock('node:perf_hooks', async original => {
+ const actual = await original<typeof import('node:perf_hooks')>()
+ return { ...actual, performance: { now: () => control.now ?? actual.performance.now() } }
+})
+vi.mock('node:fs/promises', async original => {
+ const fs = await original<typeof import('node:fs/promises')>()
+ return { ...fs,
+ lstat: async (path: string) => {
+ const code = control.failures.get(`lstat:${path}`)
+ if (code) throw Object.assign(new Error('controlled file inspection failure'), { code })
+ return fs.lstat(path)
+ },
+ stat: async (path: string) => {
+ const code = control.failures.get(`stat:${path}`)
+ if (code) throw Object.assign(new Error('controlled inspection failure'), { code })
+ const answer = await fs.stat(path)
+ control.afterStat?.(path)
+ return answer
+ },
+ opendir: async (...args: Parameters<typeof fs.opendir>) => {
+ const code = control.failures.get(`opendir:${args[0]}`)
+ if (code) throw Object.assign(new Error('controlled listing failure'), { code })
+ return fs.opendir(...args)
+ },
+ }
+})
+vi.mock('node:fs', async original => {
+ const fs = await original<typeof import('node:fs')>()
+ const guarded = (name: 'statSync' | 'lstatSync') => (...args: Parameters<typeof fs.statSync>) => {
+ const code = control.failures.get(`${name}:${args[0]}`)
+ if (code) throw Object.assign(new Error('controlled verification failure'), { code })
+ return fs[name](...args)
+ }
+ return { ...fs, statSync: guarded('statSync'), lstatSync: guarded('lstatSync') }
+})
+vi.mock('../../lib/sqliteRead.js', async original => {
+ const sqlite = await original<typeof import('../../lib/sqliteRead.js')>()
+ return { ...sqlite, sqliteReadAll: async (...args: Parameters<typeof sqlite.sqliteReadAll>) => {
+ if (args[1].includes('sqlite_schema') || args[1].includes('pragma_table_xinfo')) return sqlite.sqliteReadAll(...args)
+ control.queries.push({ path: args[0], options: args[3] ?? {} })
+ const answer = control.result ?? await sqlite.sqliteReadAll(...args)
+ await control.afterQuery?.(args[0])
+ return answer
+ } }
+})
+
+let root: string, home: string
+let pool: typeof import('./storePool.js').readStorePool
+let repair: typeof import('../../lib/sessionRepair.js').findLiveSession
+let declared: import('./storeHomes.js').StoreHomes
+let Database: {
+ new(path: string): { exec(sql: string): void; prepare(sql: string): { run(...args: unknown[]): void }; close(): void }
+}
+const id = '20261009_120000_aaaa', other = '20261009_120001_bbbb'
+const query = { sql: 'SELECT id FROM sessions WHERE cwd = ? LIMIT 2', params: ['/fixture/work'], maxRows: 2, maxBuffer: 4096, columns: ['id', 'cwd'] }
+function store(dir: string, ids: string[] = [id]): string {
+ mkdirSync(dir, { recursive: true })
+ const path = join(dir, 'state.db')
+ const db = new Database(path)
+ db.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, cwd TEXT, started_at REAL)')
+ const insert = db.prepare('INSERT INTO sessions VALUES (?, ?, ?, ?)')
+ for (const value of ids) insert.run(value, 'cli', '/fixture/work', Date.parse('2026-10-09T12:00:00Z') / 1000)
+ db.close()
+ return path
+}
+function update(path: string, sql: string): void {
+ const db = new Database(path)
+ db.exec(sql)
+ db.close()
+}
+const read = () => pool(declared, home, query)
+const find = () => repair('hermes', '/fixture/work', Date.parse('2026-10-09T11:59:00Z'))
+const held = (work: Promise<unknown>) => expect(work).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+beforeEach(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'hermes-store-pool-')))
+ home = join(root, 'hermes')
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR',
+ 'CODEX_HOME', 'CURSOR_HOME', 'CURSOR_CONFIG_DIR', 'CURSOR_DATA_DIR', 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME',
+ 'AGY_CONFIG_DIR', 'PI_HOME', 'MUSE_HOME', 'COMMANDCODE_HOME', 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR',
+ 'KILO_DATA_DIR', 'DEVIN_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME']) vi.stubEnv(name, join(root, name))
+ vi.stubEnv('HERMES_HOME', home)
+ vi.resetModules()
+ Database = (process.getBuiltinModule('node:sqlite') as { DatabaseSync: typeof Database }).DatabaseSync
+ pool = (await import('./storePool.js')).readStorePool
+ repair = (await import('../../lib/sessionRepair.js')).findLiveSession
+ declared = (await import('../hermes/contract.js')).HERMES_HOMES
+})
+afterEach(async () => {
+ ;(await import('../../lib/sqliteBuiltin.js')).closeSqliteHandles()
+ control.failures.clear(); control.afterQuery = undefined; control.afterStat = undefined
+ control.result = undefined; control.now = undefined; control.queries = []
+ control.processes = []
+ vi.clearAllMocks()
+ vi.restoreAllMocks(); vi.unstubAllEnvs()
+ rmSync(root, { recursive: true, force: true })
+})
+
+it('finds a newly created profile despite a warm optional home cache', async () => {
+ store(home, [])
+ const { listStoreHomes } = await import('./storeHomes.js')
+ expect(await listStoreHomes(declared, home)).toEqual([home])
+ const profile = join(home, 'profiles', 'new')
+ store(profile)
+ expect(await find()).toEqual({ sessionId: id, hermesHome: profile })
+ expect(await listStoreHomes(declared, home)).toEqual([home])
+})
+
+it('counts every row, including two matches inside a single store beside a unique profile', async () => {
+ store(home, [id, other]); store(join(home, 'profiles', 'work'))
+ expect(await find()).toBeNull()
+ expect(await read()).toHaveLength(3)
+})
+
+it('excludes proven unrelated editor/gateway rows without turning malformed matching evidence into absence', async () => {
+ const path = store(home)
+ update(path, `INSERT INTO sessions VALUES ('editor', 'acp', NULL, NULL), ('unrelated', NULL, '/elsewhere', NULL)`)
+ expect(await find()).toEqual({ sessionId: id, hermesHome: home })
+ update(path, "UPDATE sessions SET cwd = '/fixture/work' WHERE id = 'unrelated'")
+ await held(find())
+})
+
+it('proves empty homes without creating stores or loading an optional engine', async () => {
+ expect(await read()).toEqual([])
+ mkdirSync(join(home, 'profiles', 'unwritten'), { recursive: true })
+ expect(await find()).toBeNull()
+ expect(control.queries).toEqual([])
+})
+
+it.each(['default', 'earlier', 'later'])('holds an unreadable %s store beside a unique healthy claim, then recovers', async where => {
+ const good = join(home, 'profiles', 'middle')
+ store(good)
+ const bad = where === 'default' ? home : join(home, 'profiles', where === 'earlier' ? 'a' : 'z')
+ mkdirSync(bad, { recursive: true }); writeFileSync(join(bad, 'state.db'), 'not sqlite')
+ await held(find())
+ rmSync(join(bad, 'state.db')); store(bad, [])
+ expect(await find()).toEqual({ sessionId: id, hermesHome: good })
+})
+
+it.each(['stat', 'opendir'])('cannot accept the default answer with incomplete %s evidence', async operation => {
+ store(home)
+ const target = join(home, 'profiles')
+ control.failures.set(`${operation}:${target}`, 'EACCES')
+ await held(find())
+ control.failures.clear()
+ expect(await find()).toEqual({ sessionId: id, hermesHome: home })
+})
+
+it('bounds streamed profile entries rather than truncating an allocated directory listing', async () => {
+ store(home)
+ for (let i = 0; i < 65; i++) mkdirSync(join(home, 'profiles', String(i)), { recursive: true })
+ await expect(find()).rejects.toThrow('entry limit')
+ expect(control.queries).toHaveLength(0)
+ rmSync(join(home, 'profiles', '64'), { recursive: true })
+ expect(await find()).toEqual({ sessionId: id, hermesHome: home })
+})
+
+it('deduplicates aliases to one physical store but retains all path evidence', async () => {
+ const profile = join(home, 'profiles', 'a')
+ store(profile)
+ symlinkSync(profile, join(home, 'profiles', 'alias'), 'dir')
+ expect(await find()).toEqual({ sessionId: id, hermesHome: profile })
+ expect(control.queries).toHaveLength(1)
+ control.afterQuery = () => { rmSync(join(home, 'profiles', 'alias')); control.afterQuery = undefined }
+ await held(find())
+})
+
+it.each(['symlink', 'hardlink'])('holds a database %s whose actual live WAL is outside the declared home', async kind => {
+ store(home)
+ const target = store(join(root, 'outside'), [])
+ const writer = new Database(target)
+ try {
+ writer.exec('PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0;')
+ writer.prepare('INSERT INTO sessions VALUES (?, ?, ?, ?)').run(other, 'cli', '/fixture/work', 1791547200)
+ const profile = join(home, 'profiles', 'linked')
+ mkdirSync(profile, { recursive: true })
+ if (kind === 'symlink') symlinkSync(target, join(profile, 'state.db'))
+ else linkSync(target, join(profile, 'state.db'))
+ await held(find())
+ expect(control.queries).toHaveLength(0)
+ } finally { writer.close() }
+})
+
+it.each(['wal', 'journal'])('holds a linked %s instead of trusting lexical sidecar evidence', async kind => {
+ store(home)
+ const target = join(root, 'sidecar')
+ writeFileSync(target, 'controlled journal')
+ symlinkSync(target, join(home, `state.db-${kind}`))
+ await held(find())
+})
+
+it('fences a regular database changed to a symlink during the query', async () => {
+ const path = store(home)
+ control.afterQuery = () => {
+ control.afterQuery = undefined
+ const target = join(root, 'moved.db')
+ renameSync(path, target); symlinkSync(target, path)
+ }
+ await held(find())
+})
+
+it.each(['store', 'profile', 'wal', 'journal'])('holds a new %s appearing while another store is queried', async change => {
+ store(home)
+ const unwritten = join(home, 'profiles', 'unwritten')
+ mkdirSync(unwritten, { recursive: true })
+ control.afterQuery = () => {
+ control.afterQuery = undefined
+ if (change === 'store') store(unwritten)
+ else if (change === 'profile') store(join(home, 'profiles', 'new'))
+ else writeFileSync(join(home, `state.db-${change}`), 'pending native journal')
+ }
+ await held(find())
+})
+
+it.each(['selected', 'negative'])('holds a changed %s query while a later store is read', async kind => {
+ const first = store(home, kind === 'selected' ? [id] : [])
+ const last = store(join(home, 'profiles', 'last'), kind === 'selected' ? [] : [id])
+ control.afterQuery = path => {
+ if (path !== last) return
+ control.afterQuery = undefined
+ update(first, kind === 'selected' ? 'DELETE FROM sessions' : `INSERT INTO sessions VALUES ('${other}', 'cli', '/fixture/work', 1791547200)`)
+ }
+ await held(find())
+})
+
+it('holds a replaced database even when the old open handle still answers', async () => {
+ const path = store(home)
+ control.afterQuery = () => {
+ control.afterQuery = undefined
+ renameSync(path, join(home, 'old.db')); store(home, [other])
+ }
+ await held(find())
+ expect(await find()).toEqual({ sessionId: other, hermesHome: home })
+})
+
+it('fences profile disappearance and replacement during enumeration', async () => {
+ store(home)
+ const profile = join(home, 'profiles', 'unwritten')
+ mkdirSync(profile, { recursive: true })
+ control.afterStat = path => {
+ if (path !== profile) return
+ control.afterStat = undefined
+ rmSync(profile, { recursive: true })
+ }
+ await held(find())
+})
+
+it.each(['state.db', 'state.db-wal', 'state.db-journal'])('holds nonregular native %s without asking SQLite', async name => {
+ store(join(home, 'profiles', 'good'))
+ mkdirSync(join(home, name))
+ await held(find())
+ expect(control.queries).toEqual([])
+})
+
+it('holds an orphan journal instead of treating its missing database as empty', async () => {
+ mkdirSync(home)
+ writeFileSync(join(home, 'state.db-wal'), 'orphan')
+ await held(find())
+})
+
+it.each(['missing', 'transient'] as const)('keeps unavailable SQLite %s distinct from a known empty pool', async reason => {
+ store(home)
+ control.result = { ok: false, reason }
+ await held(find())
+ control.result = undefined
+ expect(await find()).toEqual({ sessionId: id, hermesHome: home })
+})
+
+it('holds malformed ids and unexpectedly unbounded query results', async () => {
+ store(home)
+ for (const value of [null, 42, '../escape', 'x'.repeat(10_000)]) {
+ control.result = { ok: true, rows: [{ id: value, source: 'cli', cwd: '/fixture/work', started_at: 1791547200 }], via: 'builtin' }
+ await held(find())
+ }
+ control.result = { ok: true, rows: [{ id }, { id }, { id }], via: 'builtin' }
+ await expect(read()).rejects.toThrow('row limit')
+})
+
+it('shares one deadline across stores and passes the remaining budget to SQLite', async () => {
+ store(home); store(join(home, 'profiles', 'later'), [])
+ control.now = 0
+ control.afterQuery = () => { control.now = 2_001 }
+ await expect(find()).rejects.toThrow('deadline')
+ expect(control.queries).toHaveLength(1)
+ expect(control.queries[0].options).toEqual({ busyTimeoutMs: 250, cliTimeoutMs: 2000, maxBuffer: 40 * 1024 * 1024 })
+})
+
+it('holds a failed final inspection even after a successful SQL query', async () => {
+ const path = store(home)
+ control.afterQuery = () => { control.failures.set(`lstatSync:${path}`, 'EACCES') }
+ await held(find())
+})
+
+it.each(['main', 'wal', 'journal', 'aggregate'])('bounds %s database bytes before SQLite executes a query', async kind => {
+ const path = store(home)
+ if (kind === 'aggregate') {
+ truncateSync(path, 33 * 1024 * 1024)
+ truncateSync(store(join(home, 'profiles', 'second'), []), 33 * 1024 * 1024)
+ } else {
+ const target = kind === 'main' ? path : `${path}-${kind}`
+ if (target !== path) writeFileSync(target, '')
+ truncateSync(target, 65 * 1024 * 1024)
+ }
+ await expect(find()).rejects.toThrow('64 MiB read limit')
+ expect(control.queries).toEqual([])
+})
+
+it('refuses an oversized unindexed sessions table after a bounded prefix without sorting it', async () => {
+ const path = store(home, [])
+ update(path, `WITH RECURSIVE rows(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM rows WHERE n<8193)
+ INSERT INTO sessions SELECT printf('20261009_120000_%04x', n), 'cli', '/fixture/work', 1791547200 FROM rows`)
+ await expect(find()).rejects.toThrow('row limit')
+})
+
+it.each(['view', 'virtual', 'generated'])('holds a %s sessions schema before running its control query', async kind => {
+ mkdirSync(home)
+ const db = new Database(join(home, 'state.db'))
+ if (kind === 'view') db.exec("CREATE VIEW sessions AS SELECT 'id' AS id, 'cli' AS source, '/fixture/work' AS cwd, 1791547200 AS started_at")
+ else if (kind === 'virtual') db.exec('CREATE VIRTUAL TABLE sessions USING fts5(id, source, cwd, started_at)')
+ else db.exec("CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT GENERATED ALWAYS AS ('cli') VIRTUAL, cwd TEXT, started_at REAL)")
+ db.close()
+ await held(find())
+ expect(control.queries).toEqual([])
+})
+
+it('requires an indexed point key for hook source lookups', async () => {
+ mkdirSync(home)
+ const db = new Database(join(home, 'state.db'))
+ db.exec('CREATE TABLE sessions (id TEXT, source TEXT)'); db.close()
+ const { HERMES_SOURCE } = await import('../hermes/contract.js')
+ await held(pool(declared, home, { sql: HERMES_SOURCE.query, params: [id], maxRows: 1, maxBuffer: 4096,
+ columns: ['id', 'source'], pointKey: 'id' }))
+ expect(control.queries).toEqual([])
+})
+
+it.each([`${id}\0suffix`, `${id}${'a'.repeat(256)}`])('never projects a malformed stored id into a valid prefix: %j', async malformed => {
+ store(home, [malformed])
+ await held(find())
+})
+
+it.each(['\0tool', 'cli\0tool', null, 'x'.repeat(129)])('holds malformed native source bytes during repair: %j', async source => {
+ const path = store(home)
+ const db = new Database(path)
+ db.prepare('UPDATE sessions SET source = ?').run(source); db.close()
+ await held(find())
+})
+
+it('checks the custom home and never repairs a different home into its process', async () => {
+ store(home)
+ const custom = join(root, 'custom')
+ mkdirSync(custom); writeFileSync(join(custom, 'state.db'), 'unreadable')
+ const known = () => repair('hermes', '/fixture/work', Date.parse('2026-10-09T11:59:00Z'), { hermesHome: custom })
+ await held(known())
+ rmSync(join(custom, 'state.db')); store(custom, [])
+ expect(await known()).toBeNull()
+ update(join(custom, 'state.db'), `INSERT INTO sessions VALUES ('${other}', 'cli', '/fixture/work', 1791547200)`)
+ expect(await known()).toEqual({ sessionId: other, hermesHome: custom })
+})
+
+it('cannot bind a delegated row through directory repair, and retries when an interactive row appears', async () => {
+ const path = store(home)
+ update(path, "UPDATE sessions SET source = 'tool'")
+ const row = { engine: 'hermes', agentId: 'fixture-agent', sessionId: '', cwd: '/fixture/work', runtimes: [],
+ processIdentity: { pid: 4242, executable: 'hermes', startMarker: '2026-10-09T11:59:00Z' } } as unknown as import('../../lib/registry.js').RegisteredSession
+ const register = vi.fn(() => null)
+ const deps = { registry: { byProcess: () => row, bySession: () => undefined, has: () => false, register },
+ homes: { hermes: home } } as unknown as import('../../core/agents/bind.js').BindDeps
+ const observed = { engine: 'hermes', cwd: '/fixture/work', runtimes: [], primaryRuntimeKey: '',
+ args: 'hermes', resumeSessionId: null, processIdentity: row.processIdentity! } as import('../../lib/terminalAgentDiscovery.js').DiscoveredTerminalAgent
+ const binding = (await import('../../core/agents/bind.js')).createBinding(deps)
+ await binding.bindObservedAgent(observed)
+ expect(register).not.toHaveBeenCalled()
+ update(path, `INSERT INTO sessions VALUES ('${other}', 'cli', '/fixture/work', 1791547200)`)
+ await binding.bindObservedAgent(observed)
+ expect(register).toHaveBeenCalledWith(expect.objectContaining({ sessionId: other, hermesHome: home }))
+})
+
+async function stopFixture() {
+ const profile = join(home, 'profiles', 'work')
+ store(profile)
+ const { registry } = await import('../../lib/registry.js')
+ const { stoppedAgents } = await import('../../lib/stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('../../lib/restartAgent.js')
+ const { createForgetSession } = await import('../../core/agents/forget.js')
+ const { createStopAgentService } = await import('../../lib/stopAgentService.js')
+ const { terminateDeletedAgent } = await import('../../lib/deleteAgentFallback.js')
+ const processIdentity = { pid: 4242, executable: 'hermes', startMarker: '2026-10-09T11:59:00Z' }
+ control.processes = [{ ...processIdentity, args: 'hermes', parentPid: 1 }]
+ const live = registry.openProcessAgent({ engine: 'hermes', cwd: '/fixture/work', tmuxPane: '%77', processIdentity })!.entry
+ const forgetSession = createForgetSession({
+ registry, stoppedAgents, syncRecapPool: vi.fn(), normalizers: { forget: vi.fn() },
+ forgetAttach: vi.fn(), turnStartedAt: new Map(), neverFoldedHistory: new Set(), replayedFirstTurn: new Set(),
+ clearAgyIdleWatch: vi.fn(), cursorDiscovery: { remove: vi.fn() }, cursorSubagents: { forget: vi.fn() },
+ runtimeProfiles: { forget: vi.fn() }, watcher: { removeSession: vi.fn(async () => {}) },
+ stopHeartbeat: vi.fn(), teams: { forget: vi.fn() }, input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
+ detachDsh: vi.fn(), mirror: { forget: vi.fn() }, clients: { send: vi.fn(), sendCommander: vi.fn() },
+ dataDir: process.env.ADAPTER_DATA_DIR!,
+ })
+ const kill = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
+ const stop = createStopAgentService({ registry, stoppedAgents, restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(),
+ tmuxBackend: { kill }, agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession, markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: vi.fn(async () => {}),
+ })
+ return { stop, registry, stoppedAgents, live, profile, kill, terminateDeletedAgent }
+}
+
+it('preserves a newly captured Hermes profile through actual Stop, checkpoint and final forget saves', async () => {
+ const f = await stopFixture()
+ await f.stop(f.live.agentId, { checkpoint: async (captured, phase) => {
+ expect(captured).toMatchObject({ sessionId: id, hermesHome: f.profile })
+ if (phase === 'before') {
+ expect(f.live.sessionId).toBe('')
+ expect(f.live.hermesHome).toBeNull()
+ f.stoppedAgents.save(f.live)
+ expect(f.stoppedAgents.get(f.live.agentId)).toMatchObject({ sessionId: id, hermesHome: f.profile })
+ }
+ } })
+ expect(f.registry.byAgent(f.live.agentId)).toBeUndefined()
+ expect(f.stoppedAgents.get(f.live.agentId)).toMatchObject({ sessionId: id, hermesHome: f.profile, active: false })
+ expect(f.terminateDeletedAgent).toHaveBeenCalledOnce()
+ expect(f.kill).toHaveBeenCalledOnce()
+})
+
+it.each(['capture', 'checkpoint'])('cannot combine a captured conversation with a changed live home during %s', async phase => {
+ const f = await stopFixture()
+ const change = () => { f.registry.setHermesHome(f.live.agentId, join(root, 'replacement-home')) }
+ if (phase === 'capture') control.afterQuery = () => { control.afterQuery = undefined; change() }
+ await expect(f.stop(f.live.agentId, { checkpoint: async (_captured, at) => {
+ if (phase === 'checkpoint' && at === 'before') change()
+ } })).rejects.toThrow('changed')
+ expect(f.registry.byAgent(f.live.agentId)).toBe(f.live)
+ expect(f.terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(f.kill).not.toHaveBeenCalled()
+})
+
+it.each(['home', 'process', 'registered', 'codex-home'])('does not carry saved Hermes history across a changed %s authority', async change => {
+ const f = await stopFixture()
+ f.stoppedAgents.save({ ...f.live, sessionId: id, hermesHome: f.profile, source: 'stop-repair' })
+ const current = { ...f.live }
+ if (change === 'home') current.hermesHome = join(root, 'different-home')
+ if (change === 'process') current.processIdentity = { ...current.processIdentity!, startMarker: 'replacement' }
+ if (change === 'registered') current.registeredAt++
+ if (change === 'codex-home') current.codexHome = join(root, 'different-profile')
+ f.stoppedAgents.save(current)
+ expect(f.stoppedAgents.get(f.live.agentId)?.sessionId).toBe('')
+})
diff --git a/cli/src/engines/kit/storePool.ts b/cli/src/engines/kit/storePool.ts
new file mode 100644
index 000000000..cb6f0b947
--- /dev/null
+++ b/cli/src/engines/kit/storePool.ts
@@ -0,0 +1,144 @@
+/** Fresh, complete evidence from every declared native store; no optional reader or home cache. */
+import { lstatSync, statSync, type Stats } from 'node:fs'
+import { lstat, stat } from 'node:fs/promises'
+import { join } from 'node:path'
+import { performance } from 'node:perf_hooks'
+import { sqliteReadAll, type SqliteParam, type SqliteRow } from '../../lib/sqliteRead.js'
+import { identityEntries, IdentityReadUnavailable } from './identityScan.js'
+import type { StoreHomes } from './storeHomes.js'
+
+interface Evidence { path: string; stamp: string | null; file: boolean }
+interface Store { home: string; aliases: string[]; path: string; files: Evidence[] }
+export interface StorePoolRow { home: string; aliases: readonly string[]; row: SqliteRow }
+const MAX_POOL_BYTES = 64 * 1024 * 1024
+const MAX_POOL_ROWS = 8192
+
+function stamp(info: Stats): string {
+ return `${info.dev}:${info.ino}:${info.mode}:${info.nlink}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`
+}
+function unavailable(reason: string): never { throw new IdentityReadUnavailable(reason) }
+function missing(error: unknown): boolean { return (error as NodeJS.ErrnoException).code === 'ENOENT' }
+
+/** A final bounded metadata check has no await between the last query and returning its authority. */
+function verify(evidence: readonly Evidence[]): void {
+ for (const item of evidence) {
+ let current: string | null
+ try { current = stamp(item.file ? lstatSync(item.path) : statSync(item.path)) }
+ catch (error) {
+ if (!missing(error)) unavailable('a native store could not be verified')
+ current = null
+ }
+ if (current !== item.stamp) unavailable('the native store pool changed during lookup')
+ }
+}
+
+/**
+ * Missing stores count as evidence too: a profile's first DB may appear while another DB is read.
+ * Directory stamps fence added/removed profiles; DB, WAL and rollback-journal stamps fence changed
+ * query results and atomic replacement. Work is bounded, not an atomic multi-file snapshot. Any
+ * observed change holds this poll, and the next poll starts from a new pool.
+ */
+export async function readStorePool(
+ declared: StoreHomes,
+ defaultHome: string,
+ query: { sql: string; params: SqliteParam[]; maxRows: number; maxBuffer: number;
+ columns: readonly string[]; pointKey?: string; knownHome?: string },
+): Promise<StorePoolRow[]> {
+ const deadline = performance.now() + 2_000
+ const remaining = (): number => {
+ const ms = Math.floor(deadline - performance.now())
+ if (ms <= 0) unavailable('the native store lookup deadline was reached')
+ return ms
+ }
+ const evidence: Evidence[] = []
+ const inspect = async (path: string, kind: 'file' | 'directory' | 'entry'): Promise<Stats | null> => {
+ remaining()
+ let info: Stats | null
+ try { info = kind === 'file' ? await lstat(path) : await stat(path) }
+ catch (error) {
+ if (!missing(error)) unavailable('a native store path could not be inspected')
+ info = null
+ }
+ if (info && ((kind === 'file' && !info.isFile()) || (kind === 'directory' && !info.isDirectory()))) {
+ unavailable('a native store path has an unexpected file type')
+ }
+ // SQLite resolves file symlinks and names journals beside the target; hard links may have a
+ // journal beside another name. Neither can prove complete WAL evidence from this path.
+ if (info && kind === 'file' && info.nlink !== 1) unavailable('a native store has multiple file links')
+ evidence.push({ path, stamp: info ? stamp(info) : null, file: kind === 'file' })
+ return info
+ }
+ await inspect(defaultHome, 'directory')
+ const profiles = join(defaultHome, declared.profiles)
+ await inspect(profiles, 'directory')
+ const homes = [defaultHome]
+ const entries = []
+ for await (const entry of identityEntries(profiles, { remaining: declared.max + 1 })) entries.push(entry)
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
+ const home = join(profiles, entry.name)
+ const info = await inspect(home, 'entry')
+ if (!info) unavailable('a profile disappeared during lookup')
+ if (info.isDirectory()) homes.push(home)
+ }
+ if (query.knownHome && !homes.includes(query.knownHome)) {
+ await inspect(query.knownHome, 'directory')
+ homes.push(query.knownHome)
+ }
+ const stores: Store[] = []
+ const seen = new Map<string, Store>()
+ let bytes = 0
+ for (const home of homes) {
+ const path = declared.store(home)
+ const start = evidence.length
+ const main = await inspect(path, 'file')
+ const wal = await inspect(`${path}-wal`, 'file')
+ const journal = await inspect(`${path}-journal`, 'file')
+ if (!main) {
+ if (wal || journal) unavailable('a native store is missing beside its journal')
+ continue
+ }
+ const identity = [main, wal, journal].map(info => info ? `${info.dev}:${info.ino}` : '-').join('/')
+ const alias = seen.get(identity)
+ if (alias) { alias.aliases.push(home); continue }
+ bytes += main.size + (wal?.size ?? 0) + (journal?.size ?? 0)
+ if (bytes > MAX_POOL_BYTES) unavailable('the native store pool exceeds the 64 MiB read limit')
+ const store = { home, aliases: [home], path, files: evidence.slice(start) }
+ seen.set(identity, store)
+ stores.push(store)
+ }
+ verify(evidence)
+ const found: StorePoolRow[] = []
+ for (const store of stores) {
+ const read = async (sql: string, params: SqliteParam[], maxBuffer: number): Promise<SqliteRow[]> => {
+ const budget = remaining()
+ verify(store.files)
+ const result = await sqliteReadAll(store.path, sql, params, {
+ busyTimeoutMs: Math.min(250, budget), cliTimeoutMs: budget, maxBuffer,
+ })
+ if (!result.ok) unavailable('a native store query is unavailable')
+ verify(store.files)
+ return result.rows
+ }
+ // A view, virtual table or generated control column can execute unrelated, unbounded work.
+ // Repair scans a bounded prefix of this ordinary table, with no full-table sort. Point reads
+ // require the declared key to lead the primary index. The shared file cap bounds page input.
+ const schema = await read('SELECT type, substr(sql, 1, 16385) AS sql FROM sqlite_schema WHERE name = ? LIMIT 2', ['sessions'], 20_000)
+ if (schema.length !== 1 || schema[0].type !== 'table' || typeof schema[0].sql !== 'string'
+ || schema[0].sql.length > 16384 || !/^CREATE\s+TABLE\s/i.test(schema[0].sql)) unavailable('the native session table schema is unavailable')
+ const columns = await read('SELECT name, hidden, pk FROM pragma_table_xinfo(?) LIMIT 257', ['sessions'], 32_768)
+ if (columns.length > 256 || query.columns.some(name => !columns.some(column => column.name === name && column.hidden === 0))
+ || (query.pointKey && !columns.some(column => column.name === query.pointKey && column.pk === 1))) {
+ unavailable('the native session table has unsupported control columns')
+ }
+ const result = { rows: await read(query.sql, query.params, query.maxBuffer) }
+ if (result.rows.length > query.maxRows) unavailable('a native store query exceeded its row limit')
+ if (found.length + result.rows.length > MAX_POOL_ROWS) unavailable('the native store pool exceeded its row limit')
+ for (const row of result.rows) found.push({ home: store.home, aliases: store.aliases, row })
+ }
+ remaining()
+ // Recheck negative claims and directory membership before the selected store's metadata.
+ const selected = found.length === 1 ? declared.store(found[0].home) : null
+ verify(evidence.filter(item => item.path !== selected && item.path !== `${selected}-wal` && item.path !== `${selected}-journal`))
+ if (selected) verify(evidence.filter(item => item.path === selected || item.path === `${selected}-wal` || item.path === `${selected}-journal`))
+ return found
+}
diff --git a/cli/src/engines/otherAdmission.golden.spec.ts b/cli/src/engines/otherAdmission.golden.spec.ts
index 31ae86b2f..65f3459c9 100644
--- a/cli/src/engines/otherAdmission.golden.spec.ts
+++ b/cli/src/engines/otherAdmission.golden.spec.ts
@@ -44,7 +44,26 @@ const normalize = (value: unknown): unknown => JSON.parse(JSON.stringify(value ?
function check(key: string, value: unknown): void {
const result = normalize(value)
recorded[key] = result
- if (!RECORD) expect({ key, result }).toEqual({ key, result: golden[key] })
+ if (!RECORD) {
+ if (key === 'admission') {
+ // Preserve the former artifact, including its unsafe first-home answer. Complete native
+ // pools deliberately hold this case and explain unreadable evidence; healthy answers stay unchanged.
+ const label = 'one in both homes: the default asked first'
+ const before = golden[key] as unknown[][], after = result as unknown[][]
+ expect(before.filter(row => row[0] === label)).toEqual([[label, 200, { pending: true },
+ [{ sessionId: '20261008_100002_dddddd', engine: 'hermes', hermesHome: null }],
+ ['[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check']]])
+ expect(after.filter(row => row[0] === label)).toEqual([[label, 200, { pending: true }, [],
+ ['[hooks] 20261008 SessionStart held · Hermes session source is ambiguous across homes; keeping the current conversation.']]])
+ const unreadable = 'one whose candidate store cannot be read'
+ const held = '[hooks] 20261008 SessionStart held · Hermes session source is unavailable; keeping the current conversation.'
+ expect(before.filter(row => row[0] === unreadable)).toEqual([[unreadable, 200, { pending: true }, [], [held]]])
+ expect(after.filter(row => row[0] === unreadable)).toEqual([[unreadable, 200, { pending: true }, [],
+ [held + ' Conversation identity is held: a native store query is unavailable.']]])
+ const healthy = (row: unknown[]) => row[0] !== label && row[0] !== unreadable
+ expect(after.filter(healthy)).toEqual(before.filter(healthy))
+ } else expect({ key, result }).toEqual({ key, result: golden[key] })
+ }
}
const saved: Record<string, string | undefined> = {}
diff --git a/cli/src/hookServer.hermes.spec.ts b/cli/src/hookServer.hermes.spec.ts
index 44c97a73e..7ce815dda 100644
--- a/cli/src/hookServer.hermes.spec.ts
+++ b/cli/src/hookServer.hermes.spec.ts
@@ -8,12 +8,12 @@ import type { Server } from 'node:http'
const failures = vi.hoisted(() => new Map<string, string>())
vi.mock('node:fs/promises', async original => {
const fs = await original<typeof import('node:fs/promises')>()
- const guarded = (name: 'stat' | 'readdir') => async (path: string, ...args: unknown[]) => {
+ const guarded = (name: 'lstat' | 'opendir') => async (path: string, ...args: unknown[]) => {
const code = failures.get(`${name}:${path}`)
if (code) throw Object.assign(new Error('controlled filesystem failure'), { code })
return Reflect.apply(fs[name], fs, [path, ...args])
}
- return { ...fs, stat: guarded('stat'), readdir: guarded('readdir') }
+ return { ...fs, lstat: guarded('lstat'), opendir: guarded('opendir') }
})
let root = ''
@@ -76,6 +76,7 @@ async function fixture(options: { waitOnResolution?: number } = {}) {
}
const current = () => registry.byAgent(agent.agentId)!
return { home, store, hook, current, registered, logs, markDeleted, resume: () => resume(),
+ knownHome: (home: string) => registry.setHermesHome(agent.agentId, home),
seed: (sessionId: string) => registry.register({ engine: 'hermes', sessionId, tmuxPane: '%1', cwd: root, processIdentity }),
}
}
@@ -99,16 +100,50 @@ it('holds an unreadable store without binding and retries after the store recove
expect(f.registered).toHaveBeenCalledOnce()
})
-it('cannot let an unreadable home hide a delegated session in a healthy profile', async () => {
+it.each(['\0tool', 'cli\0tool', 'x'.repeat(129)])('holds a malformed original source without accepting its text prefix: %j', async source => {
+ const f = await fixture()
+ const own = '20261009_120000_aabbcc'
+ f.store(f.home, [[own, source]])
+ await f.hook(own)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
+ expect(f.current().sessionId).toBe('')
+ expect(f.registered).not.toHaveBeenCalled()
+})
+
+it('includes the known custom home and cannot authorize its hook from a different home', async () => {
+ const f = await fixture()
+ const own = '20261009_120000_aabbcc'
+ const custom = join(root, 'custom-home')
+ f.knownHome(custom)
+ f.store(f.home, [[own, 'cli']])
+ mkdirSync(custom); writeFileSync(join(custom, 'state.db'), 'unreadable custom store')
+ await f.hook(own)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
+ expect(f.current().sessionId).toBe('')
+ f.store(custom, [])
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('source in its known home'))).toBe(true), { timeout: 4_000 })
+ expect(f.registered).not.toHaveBeenCalled()
+ f.store(custom, [[own, 'tool']])
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ambiguous across homes'))).toBe(true), { timeout: 4_000 })
+ expect(f.current().sessionId).toBe('')
+ f.store(f.home, [])
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ignored · hermes_subagent'))).toBe(true), { timeout: 4_000 })
+ expect(f.registered).not.toHaveBeenCalled()
+})
+
+it('holds incomplete source pools, then rejects a proven delegated session after recovery', async () => {
const f = await fixture()
mkdirSync(f.home, { recursive: true })
writeFileSync(join(f.home, 'state.db'), 'not SQLite')
const child = '20261009_120000_bbbbbb'
f.store(join(f.home, 'profiles', 'work'), [[child, 'tool']])
await f.hook(child)
- await vi.waitFor(() => expect(f.logs.some(line => line.includes('ignored · hermes_subagent'))).toBe(true))
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
expect(f.current().sessionId).toBe('')
expect(f.registered).not.toHaveBeenCalled()
+ f.store(f.home, [])
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ignored · hermes_subagent'))).toBe(true), { timeout: 4_000 })
+ expect(f.registered).not.toHaveBeenCalled()
})
it('keeps a missing source row pending and replaces an older pending hook', async () => {
@@ -154,19 +189,22 @@ it('recovers an equal-time parent after its child has already been held', async
expect(f.registered).toHaveBeenCalledOnce()
})
-it.each(['stat', 'readdir'] as const)('holds incomplete %s evidence, then discovers the recovered profile afresh', async operation => {
+it.each(['lstat', 'opendir'] as const)('holds incomplete %s evidence, then discovers the recovered profile afresh', async operation => {
const f = await fixture()
f.store(f.home, [])
const wanted = '20261009_120000_333333'
const first = join(f.home, 'profiles', 'a'), second = join(f.home, 'profiles', 'b')
f.store(first, [[wanted, 'cli']]); f.store(second, [[wanted, 'cli']])
- failures.set(operation === 'stat' ? `stat:${join(first, 'state.db')}` : `readdir:${join(f.home, 'profiles')}`, 'EACCES')
+ failures.set(operation === 'lstat' ? `lstat:${join(first, 'state.db')}` : `opendir:${join(f.home, 'profiles')}`, 'EACCES')
await f.hook(wanted)
await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
expect(f.current().sessionId).toBe('')
expect(f.current().hermesHome).toBeNull()
expect(f.registered).not.toHaveBeenCalled()
failures.clear()
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ambiguous across homes'))).toBe(true), { timeout: 4_000 })
+ expect(f.current().sessionId).toBe('')
+ f.store(second, [])
await vi.waitFor(() => expect(f.current().sessionId).toBe(wanted), { timeout: 4_000 })
expect(f.current().hermesHome).toBe(first)
})
@@ -214,13 +252,17 @@ it.each([false, true])('reports capacity backpressure without claiming the extra
expect(f.registered).not.toHaveBeenCalled()
})
-it('does not make a verified default-home binding depend on unavailable profiles', async () => {
+it('cannot let the first default-home answer hide unavailable or conflicting profiles', async () => {
const f = await fixture()
const own = '20261009_120000_777777'
f.store(f.home, [[own, 'cli']])
- failures.set(`readdir:${join(f.home, 'profiles')}`, 'EACCES')
+ failures.set(`opendir:${join(f.home, 'profiles')}`, 'EACCES')
await f.hook(own)
- await vi.waitFor(() => expect(f.current().sessionId).toBe(own))
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
+ expect(f.current().sessionId).toBe('')
+ expect(f.registered).not.toHaveBeenCalled()
+ failures.clear()
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(own), { timeout: 4_000 })
expect(f.current().hermesHome).toBeNull()
})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index fbb1ad4e4..6234ae31a 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -9,9 +9,10 @@ import { join } from 'node:path'
import http from 'node:http'
import type { AddressInfo } from 'node:net'
import { admitHook, hooksFor } from './engines/hooks.js'
-import { HERMES_HOMES, HERMES_SOURCE, hermesDbPath } from './engines/hermes/contract.js'
-import { readStoreHomes } from './engines/kit/storeHomes.js'
-import { isInteractiveSource, readStoreSessionSource } from './engines/kit/storeSource.js'
+import { HERMES_HOMES, HERMES_SOURCE } from './engines/hermes/contract.js'
+import { readStorePool } from './engines/kit/storePool.js'
+import { isInteractiveSource } from './engines/kit/storeSource.js'
+import { IdentityReadUnavailable } from './engines/kit/identityScan.js'
import { createPendingAdmissions, type AdmissionDecision } from './core/engines/pendingAdmission.js'
import { paneReadIdentity } from './core/transcripts/readIdentity.js'
import { processIdentityKey } from './lib/terminalRuntime.js'
@@ -365,22 +366,25 @@ async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers
}
/** Read source evidence without binding. Unreadable stores never authorize a conversation. */
-async function inspectHermesKind(sessionId: string): Promise<AdmissionDecision<string | undefined>> {
- const { homes, complete } = await readStoreHomes(HERMES_HOMES, env.HERMES_HOME)
- let unavailable = false
- for (const home of homes) {
- if (home !== env.HERMES_HOME && !complete) unavailable = true
- const answer = await readStoreSessionSource(HERMES_SOURCE, hermesDbPath(home), sessionId)
- if (answer === null) continue
- if (typeof answer === 'object') { unavailable = true; continue }
- if (!isInteractiveSource(HERMES_SOURCE, answer)) return { kind: 'reject', reason: 'hermes_subagent' }
- // An earlier unreadable home may hold the same id; preserve the declared lookup order.
- if (!unavailable) return { kind: 'accept', value: home === env.HERMES_HOME ? undefined : home }
- break
+async function inspectHermesKind(sessionId: string, knownHome?: string): Promise<AdmissionDecision<string | undefined>> {
+ if (!HERMES_SOURCE.id.test(sessionId)) return { kind: 'accept', value: undefined }
+ try {
+ const found = await readStorePool(HERMES_HOMES, env.HERMES_HOME, {
+ sql: HERMES_SOURCE.query, params: [sessionId], maxRows: 1, maxBuffer: HERMES_SOURCE.maxBuffer,
+ columns: ['id', 'source'], pointKey: 'id', knownHome,
+ })
+ if (!found.length) return { kind: 'hold', reason: 'Waiting for the Hermes session source record; keeping the current conversation.' }
+ if (found.length !== 1) return { kind: 'hold', reason: 'Hermes session source is ambiguous across homes; keeping the current conversation.' }
+ const { home, aliases, row } = found[0]
+ if (knownHome && !aliases.includes(knownHome)) return { kind: 'hold', reason: 'Waiting for the Hermes source in its known home; keeping the current conversation.' }
+ const source = row[HERMES_SOURCE.column]
+ if (typeof source !== 'string' || source.length > 128) throw new IdentityReadUnavailable('the Hermes source record is invalid')
+ if (!isInteractiveSource(HERMES_SOURCE, source)) return { kind: 'reject', reason: 'hermes_subagent' }
+ return { kind: 'accept', value: knownHome ?? (home === env.HERMES_HOME ? undefined : home) }
+ } catch (error) {
+ if (!(error instanceof IdentityReadUnavailable)) throw error
+ return { kind: 'hold', reason: `Hermes session source is unavailable; keeping the current conversation. ${error.message}` }
}
- return { kind: 'hold', reason: unavailable || !complete
- ? 'Hermes session source is unavailable; keeping the current conversation.'
- : 'Waiting for the Hermes session source record; keeping the current conversation.' }
}
export interface HookServerOptions {
@@ -546,12 +550,13 @@ export function startHookServer(
// be written yet (measured: a child's hook beat its own INSERT by 110ms). Registering
// optimistically would hand the parent's pane to a sub-agent.
const identity = paneReadIdentity(processAgent)
+ const knownHome = processAgent.hermesHome ?? undefined
const queued = admissions.submit(processAgent.agentId, body.sessionId!, {
order: { ...admissionOrder, scope: admissionProcessScope(processAgent) ?? processAgent.agentId },
binding: { id: processAgent.sessionId, at: processAgent.boundAt },
current: () => !isRecentlyDeleted(processAgent.agentId) && !isRecentlyDeleted(body.sessionId)
&& paneReadIdentity(registeredHookProcess(body, 'hermes')) === identity,
- inspect: () => inspectHermesKind(body.sessionId!),
+ inspect: () => inspectHermesKind(body.sessionId!, knownHome),
held: (reason) => console.log(`[hooks] ${sid(body.sessionId!)} ${body.hookEvent ?? 'session-start'} held · ${reason}`),
reject: (reason) => console.log(`[hooks] ${sid(body.sessionId!)} ${body.hookEvent ?? 'session-start'} ignored · ${reason}`),
accept: (hermesHome) => {
diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.ts
index 77d10ed35..a1d490cff 100644
--- a/cli/src/lib/captureResumeIdentity.spec.ts
+++ b/cli/src/lib/captureResumeIdentity.spec.ts
@@ -40,6 +40,13 @@ it('captures a database-backed engine id read off the live process', async () =>
vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'live' })
expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'live', source: 'stop-repair' })
})
+it('captures and preserves the exact Hermes home before stopping its process', async () => {
+ vi.mocked(engineKeepsTranscriptFile).mockReturnValue(false)
+ Object.assign(row, { engine: 'hermes', hermesHome: '/known-home' })
+ vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'live', hermesHome: '/known-home' })
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'live', hermesHome: '/known-home', source: 'stop-repair' })
+ expect(findLiveSession).toHaveBeenCalledWith('hermes', '/work', expect.any(Number), expect.objectContaining({ hermesHome: '/known-home' }))
+})
it.each([null, '/stale'])('repairs a known id with missing or invalid path %s', async transcriptPath => {
Object.assign(row, { sessionId: 'known', transcriptPath, codexHome: '/profile' })
vi.mocked(validTranscriptPath).mockImplementation((_, path) => path === '/found')
@@ -84,6 +91,12 @@ it.each(['claude', 'codex'] as const)('captures an explicit %s resume without gu
expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'exact', transcriptPath: '/exact', source: 'stop-repair' })
expect(findLiveSession).not.toHaveBeenCalled()
})
+it('keeps an explicit file-backed resume unbound while its transcript is still unwritten', async () => {
+ vi.mocked(resumeSessionId).mockReturnValue('exact')
+ vi.mocked(findResumedTranscript).mockResolvedValue(null)
+ expect(await captureResumeIdentity(row)).toBe(row)
+ expect(findLiveSession).not.toHaveBeenCalled()
+})
it('prefers current Claude native metadata to old resume argv', async () => {
vi.mocked(resumeSessionId).mockReturnValue('old')
vi.mocked(processSessionOf).mockResolvedValue({ sessionId: 'current', transcriptPath: '/current' })
diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.ts
index fce949366..06df32e85 100644
--- a/cli/src/lib/captureResumeIdentity.ts
+++ b/cli/src/lib/captureResumeIdentity.ts
@@ -8,7 +8,7 @@
* including the four that keep theirs in a database rather than a file.
*/
import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
-import { findLiveSession, findResumedTranscript, processSessionOf } from './sessionRepair.js'
+import { findLiveSession, findResumedTranscript, processSessionOf, type RepairedSession } from './sessionRepair.js'
import { processRows, resumeSessionId } from './tmux.js'
import { sameProcessIdentity } from './terminalRuntime.js'
import { isTerminalEngine } from '../engines/types.js'
@@ -35,10 +35,10 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise
const explicit = resumeSessionId(session.engine, live.args)
// An engine whose process names its own session in a record (Claude Code's, removed at exit) is read now.
const native = await processSessionOf(session.engine, expected.pid, session.cwd, Date.parse(expected.startMarker))
- const found = native ?? (explicit
- ? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) }
+ const found: RepairedSession | null = native ?? (explicit
+ ? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) ?? undefined }
: await findLiveSession(session.engine, session.cwd, Date.parse(expected.startMarker), {
- ...options, pid: expected.pid, bornOnly: true,
+ ...options, hermesHome: session.hermesHome ?? undefined, pid: expected.pid, bornOnly: true,
}))
if (!found?.sessionId) return session
// A file-backed engine still has to produce a transcript this daemon can point a resume at; a
@@ -48,6 +48,7 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise
...session,
sessionId: found.sessionId,
...(found.transcriptPath ? { transcriptPath: found.transcriptPath } : {}),
+ ...(found.hermesHome ? { hermesHome: found.hermesHome } : {}),
source: 'stop-repair',
boundAt: Date.now(),
}
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index a9f7c83e9..3d40e7e00 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -23,8 +23,9 @@ import { identityBytes, identityEntries, identityFile, identityHead, identitySca
import { findSessionFileOf, sessionIdentityMetaOf } from '../engines/sessionFiles.js'
import { sessionStoreOf } from '../engines/sessionStoreContracts.js'
import type { AgentEngine } from '../engines/types.js'
-import { HERMES_HOMES, hermesDbPath } from '../engines/hermes/contract.js'
-import { listStoreHomes } from '../engines/kit/storeHomes.js'
+import { HERMES_HOMES, HERMES_HISTORY_ID_RE, HERMES_ID_SQL, HERMES_SOURCE, HERMES_SOURCE_SQL } from '../engines/hermes/contract.js'
+import { readStorePool } from '../engines/kit/storePool.js'
+import { isInteractiveSource } from '../engines/kit/storeSource.js'
import { museSessionIdentity, piSessionFolder, readPiHead } from '../engines/repairIdentities.js'
import { PI_SESSION_ID } from '../engines/pi/contract.js'
import { transcriptOf, processSessionOf as nativeProcessSession } from '../engines/identities.js'
@@ -346,7 +347,7 @@ export async function findLiveSession(
startedAtMs: number,
// codexHome: the specific agent's own profile (its CODEX_HOME), when it isn't this machine's default —
// see RegisteredSession.codexHome. Read only for an engine whose sessions follow one (`sessions.profile`).
- opts?: { bornOnly?: boolean; pid?: number; codexHome?: string },
+ opts?: { bornOnly?: boolean; pid?: number; codexHome?: string; hermesHome?: string },
): Promise<RepairedSession | null> {
const store = sessionStoreOf(engine)
if (store) return storeSession(engine, store, cwd, startedAtMs, opts)
@@ -431,19 +432,34 @@ export async function findLiveSession(
// never rebind a profile agent after a restart (openharness#191). Each store is asked on its
// own and the answers are pooled, so two homes claiming the same cwd is ambiguous — exactly as
// two rows in one store already are — rather than "whichever home was listed first".
- const homes = await listStoreHomes(HERMES_HOMES, env.HERMES_HOME)
- const found: RepairedSession[] = []
- for (const home of homes) {
- const one = await dbEngineSession(
- hermesDbPath(home),
- `SELECT id FROM sessions WHERE cwd IN (${dirList}) AND started_at >= ?`
- + ' ORDER BY started_at DESC LIMIT 2;',
- [...dirs, Math.trunc(sinceMs / 1000)],
- )
- if (one) found.push({ ...one, hermesHome: home })
- if (found.length > 1) return null
+ const found = await readStorePool(HERMES_HOMES, env.HERMES_HOME, {
+ sql: `SELECT ${HERMES_ID_SQL} AS id, ${HERMES_SOURCE_SQL} AS source, started_at, typeof(cwd) AS cwd_type,`
+ + " CASE WHEN typeof(cwd) = 'text' AND length(CAST(cwd AS BLOB)) <= 4096 AND instr(CAST(cwd AS BLOB), x'00') = 0 THEN cwd END AS cwd"
+ + ' FROM sessions LIMIT 8193;',
+ params: [], maxRows: 8192, maxBuffer: 40 * 1024 * 1024,
+ columns: ['id', 'source', 'cwd', 'started_at'], knownHome: opts?.hermesHome,
+ })
+ const candidates: RepairedSession[] = []
+ for (const { home, aliases, row } of found) {
+ // Editor/gateway rows may have no working directory; they cannot claim this process's cwd.
+ if (row.cwd === null && row.cwd_type === 'null') continue
+ if (typeof row.cwd !== 'string') {
+ throw new IdentityReadUnavailable('a Hermes store contains invalid discovery evidence')
+ }
+ if (!dirs.includes(row.cwd)) continue
+ if (typeof row.started_at !== 'number' || !Number.isFinite(row.started_at)) {
+ throw new IdentityReadUnavailable('a Hermes store contains invalid discovery evidence')
+ }
+ if (row.started_at < Math.trunc(sinceMs / 1000)) continue
+ if (typeof row.source !== 'string') throw new IdentityReadUnavailable('a Hermes session source is unavailable')
+ if (!isInteractiveSource(HERMES_SOURCE, row.source)) continue
+ if (typeof row.id !== 'string' || !HERMES_HISTORY_ID_RE.test(row.id)) {
+ throw new IdentityReadUnavailable('a Hermes store contains an invalid conversation id')
+ }
+ if (opts?.hermesHome && !aliases.includes(opts.hermesHome)) continue
+ candidates.push({ sessionId: row.id, hermesHome: opts?.hermesHome ?? home })
}
- return found[0] ?? null
+ return candidates.length === 1 ? candidates[0] : null
}
case 'devin':
// created_at is epoch SECONDS (integer).
diff --git a/cli/src/lib/sqliteBuiltin.ts b/cli/src/lib/sqliteBuiltin.ts
index 6d5b3cbc9..a5faf6c96 100644
--- a/cli/src/lib/sqliteBuiltin.ts
+++ b/cli/src/lib/sqliteBuiltin.ts
@@ -43,7 +43,7 @@ export function builtinSqlite(): DatabaseConstructor | null {
return builtin
}
-interface Handle { db: DatabaseLike; dev: number; ino: number; immutable: boolean; stamp: string }
+interface Handle { db: DatabaseLike; dev: number; ino: number; immutable: boolean; stamp: string; busyTimeoutMs: number }
/** One open handle per store: the readers poll every second, and opening is the expensive part. */
const handles = new Map<string, Handle>()
@@ -59,17 +59,25 @@ function openHandle(Database: DatabaseConstructor, dbPath: string, busyTimeoutMs
// An idle store is read immutable; once its engine opens it again (a `-wal` appears), it is read live.
const immutable = idleWalStore(dbPath)
const cached = handles.get(dbPath)
+ const timeout = Math.max(0, Math.trunc(busyTimeoutMs))
// A writer can open, checkpoint, and close between polls, leaving no WAL. An immutable handle
// never checks for writes itself, so reuse it only while the main file's fingerprint holds.
if (cached && cached.dev === dev && cached.ino === ino && cached.immutable === immutable
- && (!immutable || cached.stamp === stamp)) return cached.db
+ && (!immutable || cached.stamp === stamp)) {
+ // A control lookup may have less time left than the optional reader that opened this handle.
+ if (cached.busyTimeoutMs !== timeout) {
+ cached.db.exec(`PRAGMA busy_timeout = ${timeout}`)
+ cached.busyTimeoutMs = timeout
+ }
+ return cached.db
+ }
if (cached) dropHandle(dbPath)
const url = pathToFileURL(dbPath)
url.search = 'immutable=1'
const db = new Database(immutable ? url : dbPath, { readOnly: true })
// Not a write: the pragma is per-connection state, accepted on a read-only handle.
- db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.trunc(busyTimeoutMs))}`)
- handles.set(dbPath, { db, dev, ino, immutable, stamp })
+ db.exec(`PRAGMA busy_timeout = ${timeout}`)
+ handles.set(dbPath, { db, dev, ino, immutable, stamp, busyTimeoutMs: timeout })
return db
}
diff --git a/cli/src/lib/sqliteRead.spec.ts b/cli/src/lib/sqliteRead.spec.ts
index 1de252cac..ba77e7f3f 100644
--- a/cli/src/lib/sqliteRead.spec.ts
+++ b/cli/src/lib/sqliteRead.spec.ts
@@ -64,6 +64,15 @@ withCli('sqliteReadAll', () => {
]
const withBuiltin = hasBuiltin ? it : it.skip
+ withBuiltin('applies each caller deadline to a cached native handle', async () => {
+ overrideBuiltinSqlite(undefined)
+ for (const busyTimeoutMs of [250, 7, 250]) {
+ expect(await sqliteReadAll(db, 'PRAGMA busy_timeout;', [], { busyTimeoutMs })).toEqual({
+ ok: true, via: 'builtin', rows: [{ timeout: busyTimeoutMs }],
+ })
+ }
+ })
+
for (const [via, select] of paths) {
describe(`via ${via}`, () => {
beforeEach(select)
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index 6df0c78fa..c8fe93986 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -52,6 +52,7 @@ export interface StopAgentOptions {
// identity or property ordering, while retaining the exact PID-reuse guard.
const runtimeIdentity = (entry: RegisteredSession | undefined, withProcess = true) => entry ? JSON.stringify([
entry.engine, entry.registeredAt,
+ entry.codexHome ?? null, entry.hermesHome ?? null,
...(withProcess ? [entry.processIdentity?.pid, entry.processIdentity?.executable, entry.processIdentity?.startMarker] : []),
entry.runtimes.map(terminalRouteKey).sort(),
]) : null
@@ -93,7 +94,7 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
}
const current = registry.resolve(sessionId)!
const s = current.sessionId && current.sessionId !== captured.sessionId ? { ...current } : { ...current, sessionId: captured.sessionId,
- transcriptPath: captured.transcriptPath, boundAt: captured.boundAt, source: captured.source }
+ transcriptPath: captured.transcriptPath, hermesHome: captured.hermesHome, boundAt: captured.boundAt, source: captured.source }
// Saving precedes every mutation. A storage failure leaves the live agent alone.
stoppedAgents.save(s)
await options.checkpoint?.(s, 'before')
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index acca5cea9..3820f01f0 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -117,10 +117,13 @@ export class StoppedAgentStore {
// A temporarily unbound observation of the SAME process cannot erase a known conversation.
// A replacement process must earn its own binding; never carry history across PID reuse.
if (!session.sessionId && previous?.sessionId && previous.engine === session.engine
+ && session.registeredAt === previous.registeredAt
+ && (session.codexHome ?? null) === (previous.codexHome ?? null)
+ && (!session.hermesHome || session.hermesHome === previous.hermesHome)
&& sameProcessIdentity(session.processIdentity, previous.processIdentity)
&& session.processIdentity!.executable === previous.processIdentity!.executable) {
session = { ...session, sessionId: previous.sessionId, transcriptPath: previous.transcriptPath,
- boundAt: previous.boundAt, source: previous.source }
+ hermesHome: previous.hermesHome, boundAt: previous.boundAt, source: previous.source }
}
// With optional readers absent, Stop can capture a path the live row has not learned.
// Hooks during its checkpoint and the final forget both save that pathless row. They
diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.md
index 9dd91c8fb..539c00694 100644
--- a/docs/research/2026-10-09-daemon-core-completion.md
+++ b/docs/research/2026-10-09-daemon-core-completion.md
@@ -14,6 +14,7 @@ This is the remaining completion scope as of October 9, after the six extraction
- [x] Kilo, Hermes, native identity, Muse/Pi repair, OpenCode control and native hook declarations are eager where session control requires them (#1095, #1097, #1104, #1106, #1110, #1111).
- [x] Launch preparation gathers dependencies before local writes and commits under current ownership (#1113).
- [x] Bounded repair pools and native headers hold incomplete evidence; Stop/Close preserve intent (#1114, merged as `138ae6766` at 13:59:26 UTC).
+- [x] Exact Cursor/Grok locations, Copilot/agy process claims and discovery retries retain incomplete evidence (#1118, merged as `902ab6038` at 15:01:46 UTC).
## Remaining blockers
diff --git a/docs/research/2026-10-09-hermes-pool-cost.json b/docs/research/2026-10-09-hermes-pool-cost.json
new file mode 100644
index 000000000..7534d77cc
--- /dev/null
+++ b/docs/research/2026-10-09-hermes-pool-cost.json
@@ -0,0 +1,908 @@
+{
+ "startedAt": "2026-10-09T15:56:57.231731+00:00",
+ "finishedAt": "2026-10-09T15:57:11.685131+00:00",
+ "method": "Three interleaved fresh processes per source/workload, ten lookups per process. Fixture setup and imports excluded from lookup CPU/latency. Peak RSS includes setup/import. Private homes and built-in SQLite; no daemon or vendor binary. Reference measurements, no numerical performance gate.",
+ "driver": "/** Identical private stores on former and current production; no host engine, process or daemon. */\nimport { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nconst sourceRoot = process.env.HERMES_COST_CLI!\nimport { performance } from 'node:perf_hooks'\nconst root = mkdtempSync(join(tmpdir(), 'hermes-pool-cost-'))\nconst workload = process.argv[2] ?? 'single'\nconst home = join(root, 'hermes'), cwd = join(root, 'work')\nfor (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR',\n 'CODEX_HOME', 'CURSOR_HOME', 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME', 'PI_HOME', 'MUSE_HOME', 'COMMANDCODE_HOME',\n 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'DEVIN_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {\n process.env[name] = join(root, name)\n}\nprocess.env.HERMES_HOME = home\nconst { DatabaseSync } = process.getBuiltinModule('node:sqlite') as {\n DatabaseSync: new (path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: unknown[]): void }; close(): void }\n}\ntry {\n mkdirSync(cwd)\n const count = (workload === 'single' || workload === 'rows') ? 1 : workload === 'limit' ? 66 : 33\n for (let i = 0; i < count; i++) {\n const folder = i ? join(home, 'profiles', `profile-${String(i).padStart(3, '0')}`) : home\n mkdirSync(folder, { recursive: true })\n const path = join(folder, 'state.db')\n if (workload === 'unavailable' && i === count - 1) { writeFileSync(path, 'unavailable store'); continue }\n const db = new DatabaseSync(path)\n db.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, started_at REAL, source TEXT)')\n if (i === 0) db.prepare(\"INSERT INTO sessions VALUES (?, ?, ?, 'cli')\").run('20261009_120000_abcd', cwd, 1791547200)\n if (workload === 'rows') {\n const insert = db.prepare(\"INSERT INTO sessions VALUES (?, ?, ?, 'cli')\")\n db.exec('BEGIN')\n for (let row = 0; row < 4096; row++) insert.run(`20261009_110000_${row.toString(16).padStart(4, '0')}`, `/elsewhere/${row}`, 0)\n db.exec('COMMIT')\n }\n db.close()\n }\n const { findLiveSession } = await import(pathToFileURL(join(sourceRoot, 'src/lib/sessionRepair.ts')).href)\n const latenciesMs: number[] = [], outcomes: Record<string, number> = {}\n const cpu = process.cpuUsage()\n for (let i = 0; i < 10; i++) {\n const at = performance.now()\n let outcome: string\n try { outcome = await findLiveSession('hermes', cwd, 1791547140000) ? 'exact' : 'absent' }\n catch (error) {\n if ((error as { code?: string }).code !== 'IDENTITY_UNAVAILABLE') throw error\n outcome = 'held'\n }\n latenciesMs.push(Number((performance.now() - at).toFixed(2)))\n outcomes[outcome] = (outcomes[outcome] ?? 0) + 1\n }\n const used = process.cpuUsage(cpu)\n console.log(JSON.stringify({ workload, stores: count, unrelatedRows: workload === 'rows' ? 4096 : 0, iterations: 10, outcomes, latenciesMs,\n cpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,\n node: process.version, platform: process.platform, arch: process.arch }))\n ;(await import(pathToFileURL(join(sourceRoot, 'src/lib/sqliteBuiltin.ts')).href)).closeSqliteHandles()\n} finally { rmSync(root, { recursive: true, force: true }) }\n",
+ "samples": [
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 0,
+ "wallSeconds": 0.464,
+ "workload": "single",
+ "stores": 1,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 1.11,
+ 0.18,
+ 0.17,
+ 0.15,
+ 0.21,
+ 0.16,
+ 0.21,
+ 0.17,
+ 0.2,
+ 0.28
+ ],
+ "cpuMs": 3.1,
+ "peakRssMiB": 106.3125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 0,
+ "wallSeconds": 0.447,
+ "workload": "single",
+ "stores": 1,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 2.84,
+ 1.23,
+ 1.04,
+ 0.93,
+ 0.94,
+ 1.05,
+ 1.03,
+ 0.86,
+ 1.07,
+ 1.04
+ ],
+ "cpuMs": 12.74,
+ "peakRssMiB": 102.69921875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 0,
+ "wallSeconds": 0.443,
+ "workload": "profiles",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 11.63,
+ 2.88,
+ 2.51,
+ 2.49,
+ 2.85,
+ 2.58,
+ 2.51,
+ 2.7,
+ 2.61,
+ 2.67
+ ],
+ "cpuMs": 36.661,
+ "peakRssMiB": 101.0234375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 0,
+ "wallSeconds": 0.652,
+ "workload": "profiles",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 43.04,
+ 25.83,
+ 24.02,
+ 23.15,
+ 21.56,
+ 23.93,
+ 23.78,
+ 20.89,
+ 20.99,
+ 21.91
+ ],
+ "cpuMs": 287.768,
+ "peakRssMiB": 109.0546875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 0,
+ "wallSeconds": 0.373,
+ "workload": "rows",
+ "stores": 1,
+ "unrelatedRows": 4096,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 1.36,
+ 0.39,
+ 0.37,
+ 0.34,
+ 0.35,
+ 0.33,
+ 0.47,
+ 0.36,
+ 0.39,
+ 0.47
+ ],
+ "cpuMs": 5.096,
+ "peakRssMiB": 94.27734375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 0,
+ "wallSeconds": 0.456,
+ "workload": "rows",
+ "stores": 1,
+ "unrelatedRows": 4096,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 9.34,
+ 8.05,
+ 9.14,
+ 9.06,
+ 7.36,
+ 7.38,
+ 7.35,
+ 7.54,
+ 7.09,
+ 6.4
+ ],
+ "cpuMs": 106.642,
+ "peakRssMiB": 110.66796875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 0,
+ "wallSeconds": 0.448,
+ "workload": "unavailable",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 12.44,
+ 3.16,
+ 2.97,
+ 2.79,
+ 2.61,
+ 2.52,
+ 2.5,
+ 2.51,
+ 2.61,
+ 2.72
+ ],
+ "cpuMs": 37.966,
+ "peakRssMiB": 102.375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 0,
+ "wallSeconds": 0.64,
+ "workload": "unavailable",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 38.67,
+ 21.02,
+ 24.78,
+ 27.42,
+ 25.52,
+ 25.55,
+ 23.22,
+ 20.12,
+ 19.41,
+ 20.06
+ ],
+ "cpuMs": 284.996,
+ "peakRssMiB": 109.6015625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 0,
+ "wallSeconds": 0.501,
+ "workload": "limit",
+ "stores": 66,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 21.76,
+ 5.17,
+ 4.95,
+ 4.98,
+ 5.12,
+ 5.64,
+ 5.48,
+ 5.46,
+ 4.97,
+ 4.88
+ ],
+ "cpuMs": 70.756,
+ "peakRssMiB": 103.96875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 0,
+ "wallSeconds": 0.447,
+ "workload": "limit",
+ "stores": 66,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 1.99,
+ 0.55,
+ 0.53,
+ 0.46,
+ 0.42,
+ 0.37,
+ 0.41,
+ 0.43,
+ 0.56,
+ 0.83
+ ],
+ "cpuMs": 7.981,
+ "peakRssMiB": 98.92578125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 1,
+ "wallSeconds": 0.372,
+ "workload": "single",
+ "stores": 1,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 2.7,
+ 1.17,
+ 1.11,
+ 1.03,
+ 1.03,
+ 1.01,
+ 0.96,
+ 0.89,
+ 1.06,
+ 0.9
+ ],
+ "cpuMs": 12.481,
+ "peakRssMiB": 96.23046875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 1,
+ "wallSeconds": 0.362,
+ "workload": "single",
+ "stores": 1,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 1.17,
+ 0.2,
+ 0.18,
+ 0.2,
+ 0.17,
+ 0.2,
+ 0.24,
+ 0.19,
+ 0.23,
+ 0.32
+ ],
+ "cpuMs": 3.369,
+ "peakRssMiB": 91.515625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 1,
+ "wallSeconds": 0.636,
+ "workload": "profiles",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 39.83,
+ 22.53,
+ 24.33,
+ 21.9,
+ 22.27,
+ 24.03,
+ 22.25,
+ 21.08,
+ 21.23,
+ 22.89
+ ],
+ "cpuMs": 279.571,
+ "peakRssMiB": 110.78515625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 1,
+ "wallSeconds": 0.467,
+ "workload": "profiles",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 11.91,
+ 2.86,
+ 2.71,
+ 2.58,
+ 2.68,
+ 2.77,
+ 2.67,
+ 2.47,
+ 2.44,
+ 2.35
+ ],
+ "cpuMs": 36.677,
+ "peakRssMiB": 101.04296875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 1,
+ "wallSeconds": 0.457,
+ "workload": "rows",
+ "stores": 1,
+ "unrelatedRows": 4096,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 9.42,
+ 8.1,
+ 9.15,
+ 7.84,
+ 6.85,
+ 7.14,
+ 7.29,
+ 7.23,
+ 7.23,
+ 6.18
+ ],
+ "cpuMs": 105.226,
+ "peakRssMiB": 110.25390625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 1,
+ "wallSeconds": 0.375,
+ "workload": "rows",
+ "stores": 1,
+ "unrelatedRows": 4096,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 1.39,
+ 0.39,
+ 0.35,
+ 0.33,
+ 0.33,
+ 0.33,
+ 0.4,
+ 0.34,
+ 0.39,
+ 0.46
+ ],
+ "cpuMs": 4.986,
+ "peakRssMiB": 94.52734375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 1,
+ "wallSeconds": 0.641,
+ "workload": "unavailable",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 40.19,
+ 24.77,
+ 21.9,
+ 23.4,
+ 19.3,
+ 22.05,
+ 22.73,
+ 19.89,
+ 19.85,
+ 21.11
+ ],
+ "cpuMs": 271.916,
+ "peakRssMiB": 107.26953125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 1,
+ "wallSeconds": 0.432,
+ "workload": "unavailable",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 11.71,
+ 2.88,
+ 2.58,
+ 2.69,
+ 2.89,
+ 2.72,
+ 2.58,
+ 2.57,
+ 2.45,
+ 2.46
+ ],
+ "cpuMs": 36.77,
+ "peakRssMiB": 102.02734375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 1,
+ "wallSeconds": 0.446,
+ "workload": "limit",
+ "stores": 66,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 1.94,
+ 0.52,
+ 0.64,
+ 0.57,
+ 0.48,
+ 0.43,
+ 0.41,
+ 0.44,
+ 0.98,
+ 0.47
+ ],
+ "cpuMs": 8.367,
+ "peakRssMiB": 96.1328125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 1,
+ "wallSeconds": 0.494,
+ "workload": "limit",
+ "stores": 66,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 21.84,
+ 5.03,
+ 4.84,
+ 4.71,
+ 5.31,
+ 5.29,
+ 4.54,
+ 4.5,
+ 4.57,
+ 4.53
+ ],
+ "cpuMs": 67.565,
+ "peakRssMiB": 105.9765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 2,
+ "wallSeconds": 0.372,
+ "workload": "single",
+ "stores": 1,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 1.14,
+ 0.19,
+ 0.19,
+ 0.16,
+ 0.17,
+ 0.14,
+ 0.23,
+ 0.17,
+ 0.23,
+ 0.27
+ ],
+ "cpuMs": 3.134,
+ "peakRssMiB": 93.75390625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 2,
+ "wallSeconds": 0.381,
+ "workload": "single",
+ "stores": 1,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 3.05,
+ 1.19,
+ 1.03,
+ 0.95,
+ 0.92,
+ 0.97,
+ 0.96,
+ 0.86,
+ 1.05,
+ 0.93
+ ],
+ "cpuMs": 12.613,
+ "peakRssMiB": 95.7265625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 2,
+ "wallSeconds": 0.424,
+ "workload": "profiles",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 11.73,
+ 2.87,
+ 2.43,
+ 2.36,
+ 2.59,
+ 2.7,
+ 2.55,
+ 2.54,
+ 2.59,
+ 2.61
+ ],
+ "cpuMs": 36.132,
+ "peakRssMiB": 97.12109375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 2,
+ "wallSeconds": 0.727,
+ "workload": "profiles",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 40.41,
+ 20.92,
+ 24.74,
+ 23.11,
+ 22.38,
+ 23.43,
+ 23.18,
+ 21.19,
+ 21.6,
+ 22.67
+ ],
+ "cpuMs": 281.852,
+ "peakRssMiB": 106.9375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 2,
+ "wallSeconds": 0.403,
+ "workload": "rows",
+ "stores": 1,
+ "unrelatedRows": 4096,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 1.6,
+ 0.49,
+ 0.5,
+ 0.38,
+ 0.37,
+ 0.4,
+ 0.47,
+ 0.4,
+ 0.47,
+ 0.49
+ ],
+ "cpuMs": 5.844,
+ "peakRssMiB": 96.73828125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 2,
+ "wallSeconds": 0.484,
+ "workload": "rows",
+ "stores": 1,
+ "unrelatedRows": 4096,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 9.65,
+ 8.4,
+ 11.29,
+ 8.72,
+ 7.01,
+ 7.5,
+ 7.39,
+ 8.4,
+ 7.75,
+ 6.31
+ ],
+ "cpuMs": 116.979,
+ "peakRssMiB": 111.65625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 2,
+ "wallSeconds": 0.49,
+ "workload": "unavailable",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 13.87,
+ 3.38,
+ 3.15,
+ 3.1,
+ 3.14,
+ 3.12,
+ 2.94,
+ 2.9,
+ 3.06,
+ 3.14
+ ],
+ "cpuMs": 43.141,
+ "peakRssMiB": 99.53125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 2,
+ "wallSeconds": 0.668,
+ "workload": "unavailable",
+ "stores": 33,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 39.88,
+ 21.44,
+ 23.15,
+ 24.31,
+ 20.62,
+ 22.64,
+ 22.23,
+ 21.54,
+ 20.34,
+ 20.57
+ ],
+ "cpuMs": 276.345,
+ "peakRssMiB": 109.7421875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "former",
+ "commit": "167001ed24abe415f8f411803a6b45d1161dbe1c",
+ "repeat": 2,
+ "wallSeconds": 0.507,
+ "workload": "limit",
+ "stores": 66,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 21.88,
+ 5.05,
+ 5.12,
+ 4.66,
+ 4.73,
+ 4.72,
+ 5.33,
+ 4.54,
+ 4.62,
+ 4.47
+ ],
+ "cpuMs": 67.357,
+ "peakRssMiB": 104.84765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "source": "current",
+ "commit": "09fb5818936e9caa9968d7c86630d9637259970d",
+ "repeat": 2,
+ "wallSeconds": 0.438,
+ "workload": "limit",
+ "stores": 66,
+ "unrelatedRows": 0,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 1.85,
+ 0.49,
+ 0.86,
+ 0.53,
+ 0.48,
+ 0.43,
+ 0.42,
+ 0.41,
+ 0.56,
+ 0.83
+ ],
+ "cpuMs": 8.332,
+ "peakRssMiB": 96.48046875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ }
+ ]
+}
diff --git a/docs/research/2026-10-09-hermes-store-pools.md b/docs/research/2026-10-09-hermes-store-pools.md
new file mode 100644
index 000000000..28522b32d
--- /dev/null
+++ b/docs/research/2026-10-09-hermes-store-pools.md
@@ -0,0 +1,42 @@
+# Fresh, complete Hermes store evidence
+
+Hermes repair used a 30-second profile cache and converted both failed reads and multiple rows in one database into no match. A newly created or unreadable competing profile could therefore make an ambiguous conversation appear unique. Hook admission read a fresh listing but accepted the first default or profile result before proving the remaining stores readable. These violate the daemon separation requirement that unavailable identity evidence preserve the current conversation and pending intent.
+
+The former-code golden was recorded in `bc6540795` before production changes. It covers 16 observations through native source declarations, home listing and live repair, with Linux, UTC, fixed time, private homes and built-in SQLite. Host process probes and optional engine loading are forbidden. Re-recording after integrating main `902ab6038` passed without changing the artifact. Proven empty and ambiguous repair pools retain the former result; unsafe incomplete evidence has separate regression assertions.
+
+## Control evidence
+
+`engines/kit/storePool.ts` streams at most 64 profile entries and includes default, populated, unwritten and known custom homes. It captures directory and native database/WAL/rollback-journal metadata, verifies read-only bounded queries, and rechecks all positive and negative claims before returning. Directory aliases count once; every alias path remains part of the proof. File symlinks and multiple hard links hold because their real journals may live beside another name. A changed, unreadable, nonregular or oversized pool raises the eager typed identity hold. Metadata is checked without a later native await; a single returned record's store is checked last. Lookup never initializes a home or database.
+
+Each poll has a shared two-second work budget. SQLite gets the remaining CLI deadline and at most 250 ms of synchronous busy wait. Cached native handles now honor each caller's requested busy timeout. Native input is capped at 64 MiB across all database/WAL/journal files. Schema checks require an ordinary table and stored control columns; hook point lookups require the id to lead the primary index. Repair reads at most 8,193 rows, holds above 8,192 across the complete pool, and filters without an unbounded SQL scan/sort. Original text type, byte length and NUL absence are checked before returning bounded fields. Filesystem calls and synchronous SQLite execution are not cancellable; this is bounded work and change detection, not a hard wall-clock or atomic multi-file snapshot guarantee. Oversized stores stay held with the specific limit reason. Contention or a changed pool retries from fresh evidence.
+
+Repair queries every store and retains all matching interactive rows, including multiple rows inside one store. Proven delegated rows cannot bind; malformed source evidence holds. Only a complete unique result can bind, and a known process home constrains that result. Hook admission verifies the complete pool before accepting or rejecting its source; missing rows, a record from the wrong known home, and conflicting homes remain pending with their reason. Stop capture passes and preserves the proven home. Existing core admission ordering, process fences, Stop tombstones and retry ownership remain in force. Optional history listing caches are outside this control path; the separate optional reader's registry promotion still needs its own authority audit in the completion checklist.
+
+## Validation plan
+
+Run typecheck, architecture, core/services and harnessd per-file coverage, affected native/SQLite/hook/repair tests and unchanged identity goldens. Run serial resume coverage alone. The private bundled Hermes lane runs with its optional module absent and stalled, checking readiness, unreadable later profiles, conflicting records, child rejection and automatic recovery. Mutation checks first require a green baseline and then assertion failures for disconnected declarations/callers, incomplete evidence, ambiguity, deadlines and stale results. Compare CPU, latency and RSS on identical private stores against main. Independent exact-head review and automatic CI precede the authorized merge. No release.
+
+Implementation began after the baseline was verified at 15:12 UTC on October 9. The first focused pass completed at 15:18 UTC: 149 tests, typecheck, architecture and unchanged goldens passed. Later validation, matched cost, review, waiting and merge are recorded with the PR. This item does not complete the entire native-identity group or the overall daemon checklist.
+
+Independent review of `0f0cbbdd6` identified five blockers: file-level aliases could hide a live WAL; output limits did not bound synchronous query work; SQLite text `substr` could normalize NUL-containing source/id values; known custom homes were omitted; repair did not distinguish delegated sources. Each has a real private database or caller regression. The follow-up focus passed 330 tests and unchanged goldens; its initial typecheck correctly failed on the Stop capture result union and was corrected. The first mutation run stopped on a quoting error in a mutant rather than an assertion failure; that run is not passing mutation evidence.
+
+The second review confirmed those corrections and found that Stop still discarded the captured profile twice: while merging its snapshot and when final forget saved the old unbound row. Stop now carries the profile into checkpoint/save and fences changing home authority. The stopped store preserves captured history only for the same registration/process and compatible homes, including the real final-forget path. Composed tests use the actual capture, Stop service, stopped store and forget implementation against private SQLite; process termination and terminal operations are stubs. The first serial pass completed 371 assertions and typecheck, but correctly failed coverage at 99.78% branches because the new nullable transcript normalization lacked an explicit unwritten-resume case. That case was added before rerunning the gate. The shared SQLite handle cache's lifetime under repeated profile churn remains part of the later native-reader resource audit.
+
+
+## Matched runtime cost
+
+The [raw comparison](2026-10-09-hermes-pool-cost.json) records three interleaved fresh processes per source and workload, ten lookups each, on Node 22.23.2, macOS x64. Former main is `167001ed24abe415f8f411803a6b45d1161dbe1c`; the implementation is `09fb5818936e9caa9968d7c86630d9637259970d`. All stores and homes are private. The embedded driver reproduces the fixtures, including the 4,096 unrelated-row case. Fixture setup and imports are excluded from lookup latency and CPU; peak RSS includes them. Measurements ran without concurrent validation from 15:56:57 to 15:57:11 UTC. These are reference measurements, not a numerical performance gate or Linux measurements.
+
+| Workload | Median lookup, former → current (ms) | Median CPU per 10 lookups (ms) | Median process peak RSS (MiB) | Current result |
+| --- | --- | --- | --- | --- |
+| One store, one matching row | 0.20 → 1.03 | 3.13 → 12.61 | 93.75 → 96.23 | Exact |
+| 33 stores, one matching row | 2.61 → 22.78 | 36.66 → 281.85 | 101.02 → 109.05 | Exact |
+| One store, 4,096 unrelated rows | 0.39 → 7.52 | 5.10 → 106.64 | 94.53 → 110.67 | Exact |
+| 33 stores, last unreadable | 2.88 → 22.14 | 37.97 → 276.35 | 102.03 → 109.60 | Held |
+| 66 stores, over the profile limit | 4.97 → 0.51 | 67.56 → 8.33 | 104.85 → 96.48 | Held |
+
+Fresh positive and negative metadata proof and schema validation cost more than cached incomplete discovery. Bounded prefix reads also cost more than the former filtering query for a large store. Healthy results stayed exact in all 30 lookups per workload; both unavailable workloads returned held in all 30 current lookups, where former code returned an unsafe exact result. The largest observed current lookup was 43.04 ms. The measurements do not establish long-term handle-cache behavior or a hard elapsed-time bound; those limitations remain explicit above.
+
+Final local acceptance on the implementation head passed typecheck, architecture and 356 affected assertions, core/services (1,942 tests) and harnessd (265 tests plus one existing skip) at their per-file 100% gates, serial resume (372 tests) at 100%, four private bundled missing/stalled-module lanes, and 57 private tmux lifecycle cases. Fifteen installed-vendor smoke rows were excluded and remain unverified. All 27 deliberately broken control variants produced assertion failures after a green baseline. The independent reviewer approved that exact head against the stated main with no remaining blockers; CI, final documentation review and merge are recorded in the PR.
+
+The first complete Linux CI run found an omitted local golden: `otherAdmission` still required the unsafe first-home answer when default and profile stores claimed the same id. Its recorded artifact remains unchanged. The assertion now verifies that former answer explicitly and requires the intended ambiguous-source hold. The unreadable-store case also verifies both its former hold and the new specific native-query reason. Every healthy observation stays unchanged. The initial local correction caught this second diagnostic difference before push. These are documented safety/diagnostic corrections, not a re-recording of the healthy baseline or passing results for the failed runs. No production code changed for these corrections.