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.

fix(daemon): a Hermes session reads the home it actually lives in

0xdiego25d4eeec74c2a4
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 56b342136..7ce9c8d8d 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -780,25 +780,52 @@ async function herdrFallbackRuntime(engine) {
*/
async function hermesTopLevelSession(dbPath, sessionId) {
if (!/^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/.test(String(sessionId || ''))) return false
+ // EVERY home on this machine, this one first. `hermes -p <name>` keeps its sessions in
+ // `~/.hermes/profiles/<name>/state.db`, and the block in a profile's config.yaml may still name the
+ // DEFAULT home (Hermes copies the config when it creates a profile, and older installs baked the
+ // default path into it) — so a profile session looked unknown here and was dropped, silently, on
+ // every registration the daemon was not up for (openharness#191). The extra stores are asked only
+ // when this one has no row, which on a single-home machine is never.
+ const homes = hermesHomes(dbPath)
for (let attempt = 0; attempt < 4; attempt++) {
if (attempt > 0) await sleep(75)
- const raw = await execFileText('sqlite3', [
- '-json', '-cmd', '.timeout 500', '-cmd', 'PRAGMA query_only=1', `file:${dbPath}?mode=ro`,
- `SELECT source FROM sessions WHERE id = '${sessionId}';`,
- ], 1000)
- if (raw === null) return false
- try {
- const rows = JSON.parse(raw.trim() || '[]')
- if (!Array.isArray(rows) || rows.length === 0) continue
- const source = typeof rows[0]?.source === 'string' ? rows[0].source : ''
- return source === '' || source === 'cli'
- } catch {
- return false
+ let sawStore = false
+ for (const db of homes) {
+ const raw = await execFileText('sqlite3', [
+ '-json', '-cmd', '.timeout 500', '-cmd', 'PRAGMA query_only=1', `file:${db}?mode=ro`,
+ `SELECT source FROM sessions WHERE id = '${sessionId}';`,
+ ], 1000)
+ if (raw === null) continue // unreadable store — another home may still hold the row
+ sawStore = true
+ try {
+ const rows = JSON.parse(raw.trim() || '[]')
+ if (!Array.isArray(rows) || rows.length === 0) continue
+ const source = typeof rows[0]?.source === 'string' ? rows[0].source : ''
+ return (source === '' || source === 'cli') ? db : false
+ } catch {
+ return false
+ }
}
+ if (!sawStore) return false
}
return false
}
+/** `dbPath` and every sibling profile store, deduped, the given one first. */
+function hermesHomes(dbPath) {
+ const home = dirname(dbPath)
+ const roots = [home]
+ // A profile store sits at <default home>/profiles/<name>/state.db, so the default home is two
+ // levels up from one and the profiles folder is beside the other. Both spellings are cheap to try.
+ const base = basename(dirname(home)) === 'profiles' ? dirname(dirname(home)) : home
+ if (base !== home) roots.push(base)
+ const out = roots.map((root) => join(root, 'state.db'))
+ let names = []
+ try { names = readdirSync(join(base, 'profiles')) } catch { return [...new Set(out)] }
+ for (const name of names.slice(0, 64)) out.push(join(base, 'profiles', name, 'state.db'))
+ return [...new Set(out)]
+}
+
function bootTimeSec() {
return Math.round(Date.now() / 1000 - uptime())
}
@@ -1238,7 +1265,14 @@ async function fallbackRegister(input, engine, tmuxPane) {
if (observations.some((observation) => observation.identity.pid !== process.identity.pid
|| observation.identity.startMarker !== process.identity.startMarker)) return
const observedRuntimes = observations.map((observation) => observation.runtime)
- if (engine === 'hermes' && !await hermesTopLevelSession(p.hermesDb, sessionId)) return
+ // The store that turned out to hold it — recorded below, so the daemon's mirror reads this agent's
+ // OWN history when it comes back up rather than the default home's.
+ let hermesHome = null
+ if (engine === 'hermes') {
+ const db = await hermesTopLevelSession(p.hermesDb, sessionId)
+ if (!db) return
+ hermesHome = dirname(db)
+ }
await withRegistryLock(p.registryFile, () => {
if (remainingBudget(600) < 50) return
@@ -1274,6 +1308,9 @@ async function fallbackRegister(input, engine, tmuxPane) {
grid: existing?.grid ?? null,
...(existing && Object.hasOwn(existing, 'gridLaunch') ? { gridLaunch: existing.gridLaunch ?? null } : {}),
codexHome: typeof existing?.codexHome === 'string' && existing.codexHome ? existing.codexHome : null,
+ // …and the Hermes home this session's store turned out to be in — see hermesTopLevelSession.
+ // Fill-only, exactly as the daemon's own registry treats it.
+ hermesHome: hermesHome || (typeof existing?.hermesHome === 'string' && existing.hermesHome ? existing.hermesHome : null),
...(existing?.bypassPermission === true ? { bypassPermission: true } : {}),
}
const entry = {
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 9a207c203..e3a1b701c 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -82,6 +82,7 @@ import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/c
import { hermesMessagesToEvents, windowHermesMessages } from './engines/hermes/normalizer.js'
import { devinMessagesToEvents, windowDevinMessages } from './engines/devin/normalizer.js'
import { readHermesMessages } from './engines/hermes/reader.js'
+import { hermesDbForSession } from './lib/hermesHome.js'
import { readDevinMessages } from './engines/devin/reader.js'
import { readOpencodeMessages } from './engines/opencode/reader.js'
import { readKiloMessages } from './engines/kilo/reader.js'
@@ -114,8 +115,8 @@ const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')
// Kilo keeps history the same way opencode does, in its own store.
const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')
const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')
-// Hermes history likewise comes from a SQLite store, not a per-session file.
-const HERMES_DB = join(env.HERMES_HOME, 'state.db')
+// Hermes history likewise comes from a SQLite store, not a per-session file — one per HOME, so the
+// path is the session's own (`hermesDbForSession`) rather than this machine's default.
/** Answers the device `project_recent` RPC — set by cli.ts to the CommanderMirror's `recent`. */
export type RecentProvider = (sessionId: string, n: number) => Array<{ kind: string; text: string; recap?: string }>
@@ -1632,7 +1633,7 @@ export class BackendSocket {
const rawLimit = payload.limit
const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined
const before = typeof payload.before === 'string' ? payload.before : undefined
- const messages = await readHermesMessages(HERMES_DB, sessionId)
+ const messages = await readHermesMessages(await hermesDbForSession(s), sessionId)
const timestamp = new Date(s.updatedAt).toISOString()
if (!limit) {
reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: hermesMessagesToEvents(messages), timestamp, engine: s.engine })
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e02b02bf5..53c57cb6e 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -202,6 +202,7 @@ import { CopilotNormalizer, copilotHistoryTurnOpen, lastCopilotTurnText } from '
import { copilotSessionForPid, findCopilotTranscript } from './engines/copilot/session.js'
import { PiNormalizer, lastPiTurnText } from './engines/pi/normalizer.js'
import { HermesReader, readHermesMessages } from './engines/hermes/reader.js'
+import { hermesDbForSession } from './lib/hermesHome.js'
import { DevinReader, readDevinMessages } from './engines/devin/reader.js'
import { lastHermesTurnText } from './engines/hermes/normalizer.js'
import { lastDevinTurnText } from './engines/devin/normalizer.js'
@@ -291,8 +292,9 @@ let deviceLinkRef: DeviceLink | null = null
const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')
// Kilo's SQLite store — same shape, its own file and its own reader (see engines/kilo/).
const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')
-// Hermes keeps every surface's history in one SQLite store — polled per session by HermesReader.
-const HERMES_DB = join(env.HERMES_HOME, 'state.db')
+// Hermes keeps every surface's history in one SQLite store PER HOME — polled per session by
+// HermesReader, against the home that session lives in (`hermesDbForSession`; `hermes -p <name>` has
+// its own). Reading one fixed store is what left profile agents' activity empty (openharness#191).
// Devin likewise keeps all history in one SQLite store (WAL) — polled per session by DevinReader.
const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')
/** How many agents' histories are read at once — the first reconcile pass after a boot asks for every
@@ -2111,7 +2113,7 @@ async function runForeground(session: AuthSession): Promise<void> {
} else if (session.engine === 'hermes') {
// Hermes has no transcript file — poll its SQLite store, like opencode.
const reader = new HermesReader({
- dbPath: HERMES_DB,
+ dbPath: await hermesDbForSession(session),
sessionId: session.sessionId,
onEvents: (events) => emitSessionEvents(session.sessionId, events),
onFatal: (err) => console.warn(`[hermes] ${sid(session.sessionId)} ${err.message}`),
@@ -2436,7 +2438,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (!s) return null
if (s.engine === 'opencode') return lastOpencodeTurnText(await readOpencodeMessages(OPENCODE_DB, sessionId))
if (s.engine === 'kilo') return lastKiloTurnText(await readKiloMessages(KILO_DB, sessionId))
- if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(HERMES_DB, sessionId))
+ if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(await hermesDbForSession(s), sessionId))
if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(DEVIN_DB, sessionId))
if (!s.transcriptPath) return null
const lines = await tailFile(s.transcriptPath, Infinity)
@@ -2863,6 +2865,7 @@ async function runForeground(session: AuthSession): Promise<void> {
let sessionId = observed.resumeSessionId
let transcriptPath: string | undefined
+ let hermesHome: string | undefined
let source = 'terminal-resume'
if (sessionId) {
if (isRecentlyDeleted(sessionId)) return
@@ -2905,6 +2908,9 @@ async function runForeground(session: AuthSession): Promise<void> {
if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return
sessionId = found.sessionId
transcriptPath = found.transcriptPath
+ // Which Hermes home the repair found it in, so the row starts life reading the right store
+ // rather than looking it up again on its first poll.
+ hermesHome = found.hermesHome
source = 'process-repair'
}
@@ -2913,6 +2919,7 @@ async function runForeground(session: AuthSession): Promise<void> {
engine: observed.engine,
sessionId,
transcriptPath,
+ ...(hermesHome ? { hermesHome } : {}),
cwd: observed.cwd,
source,
runtimes: observed.runtimes,
@@ -3011,6 +3018,9 @@ async function runForeground(session: AuthSession): Promise<void> {
// under learns it from the process, before the hook path validates a transcript against it.
// Fill-only — a profile the row already knows is never re-derived.
if (observed.codexHome && !current.codexHome) registry.setCodexHome(current.agentId, observed.codexHome)
+ // …and a Hermes home the same way, when the process names one. A row that learns it here never
+ // has to look its session up store by store (openharness#191).
+ if (observed.hermesHome && !current.hermesHome) registry.setHermesHome(current.agentId, observed.hermesHome)
// And the DSH: a row minted by discovery (or written before the field existed) learns it from
// the process's own `HARNESS_DSH`, and gets its viewer and verdict watch from here on.
if (observed.dsh && !current.dsh) registry.setDsh(current.agentId, observed.dsh)
diff --git a/cli/src/engines/hermes/home.spec.ts b/cli/src/engines/hermes/home.spec.ts
new file mode 100644
index 000000000..72de91090
--- /dev/null
+++ b/cli/src/engines/hermes/home.spec.ts
@@ -0,0 +1,98 @@
+/**
+ * A machine with more than one Hermes home.
+ *
+ * `hermes -p <name>` keeps its sessions in `~/.hermes/profiles/<name>/state.db`, and the daemon used to
+ * read `<HERMES_HOME>/state.db` everywhere — so a fleet of profile agents streamed their terminals and
+ * then sat on "No activity yet" forever (openharness#191). These pin the two answers that fix it: which
+ * homes exist, and which one holds a given session.
+ */
+
+import { describe, expect, it, beforeEach } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+import {
+ findHermesHomeForSession,
+ forgetHermesHomes,
+ hermesConfigHomes,
+ hermesDbPath,
+ hermesHomeFromEnv,
+ listHermesHomes,
+} from './home.js'
+
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+const DEFAULT_SESSION = '20260727_162325_e25264'
+const PROFILE_SESSION = '20260921_152236_a1b2c3'
+
+/** A home with a `sessions` table holding exactly the ids given. */
+function makeHome(root: string, sessions: string[], { config = true, db = true } = {}): string {
+ mkdirSync(root, { recursive: true })
+ if (config) writeFileSync(join(root, 'config.yaml'), 'model: nous/hermes-4\n')
+ if (!db) return root
+ execFileSync('sqlite3', [
+ hermesDbPath(root),
+ 'CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, cwd TEXT);'
+ + sessions.map((id) => `INSERT INTO sessions VALUES ('${id}','cli','/tmp/x');`).join(''),
+ ])
+ return root
+}
+
+d('hermes homes', () => {
+ let root: string
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'hm-home-'))
+ forgetHermesHomes()
+ return () => rmSync(root, { recursive: true, force: true })
+ })
+
+ it('lists the default home and every profile that has a store, default first', async () => {
+ makeHome(root, [DEFAULT_SESSION])
+ makeHome(join(root, 'profiles', 'demo'), [PROFILE_SESSION])
+ // A profile whose first session has never run: a config, no store. Nothing to read, so not a home.
+ makeHome(join(root, 'profiles', 'fresh'), [], { db: false })
+
+ expect(await listHermesHomes(root)).toEqual([root, join(root, 'profiles', 'demo')])
+ // …but it IS a home to install hooks into: that is what the block in its config is for.
+ expect(hermesConfigHomes(root)).toEqual([
+ root, join(root, 'profiles', 'demo'), join(root, 'profiles', 'fresh'),
+ ])
+ })
+
+ it('a machine with no profiles folder answers with its one home', async () => {
+ makeHome(root, [DEFAULT_SESSION])
+ expect(await listHermesHomes(root)).toEqual([root])
+ expect(hermesConfigHomes(root)).toEqual([root])
+ })
+
+ it('finds the home whose store holds the session', async () => {
+ makeHome(root, [DEFAULT_SESSION])
+ const demo = makeHome(join(root, 'profiles', 'demo'), [PROFILE_SESSION])
+ const homes = await listHermesHomes(root)
+
+ expect(await findHermesHomeForSession(DEFAULT_SESSION, homes)).toBe(root)
+ // The one the old code could not see: its row is in the profile's store, not the default one.
+ expect(await findHermesHomeForSession(PROFILE_SESSION, homes)).toBe(demo)
+ // A session no store has yet — the caller falls back to the default rather than guessing.
+ expect(await findHermesHomeForSession('20260101_000000_abcdef', homes)).toBeNull()
+ // Not a Hermes id at all: refused without opening anything.
+ expect(await findHermesHomeForSession('../../etc/passwd', homes)).toBeNull()
+ })
+
+ it('reads a home off a process environment, and only a real one', () => {
+ expect(hermesHomeFromEnv('hermes', { HERMES_HOME: '/home/u/.hermes/profiles/demo' }, '/home/u/.hermes'))
+ .toBe('/home/u/.hermes/profiles/demo')
+ // The default home is "no profile" — the row stays null, as `codexHome` does.
+ expect(hermesHomeFromEnv('hermes', { HERMES_HOME: '/home/u/.hermes/' }, '/home/u/.hermes')).toBeNull()
+ expect(hermesHomeFromEnv('hermes', {}, '/home/u/.hermes')).toBeNull()
+ // Junk, and another engine's process, say nothing.
+ expect(hermesHomeFromEnv('hermes', { HERMES_HOME: 'relative/path' }, '/home/u/.hermes')).toBeNull()
+ expect(hermesHomeFromEnv('hermes', { HERMES_HOME: '/bad\u0000path' }, '/home/u/.hermes')).toBeNull()
+ expect(hermesHomeFromEnv('codex', { HERMES_HOME: '/home/u/.hermes/profiles/demo' }, '/home/u/.hermes')).toBeNull()
+ })
+})
diff --git a/cli/src/engines/hermes/home.ts b/cli/src/engines/hermes/home.ts
new file mode 100644
index 000000000..0304080c5
--- /dev/null
+++ b/cli/src/engines/hermes/home.ts
@@ -0,0 +1,141 @@
+/**
+ * WHICH HERMES HOME A SESSION LIVES IN.
+ *
+ * Hermes keeps history in ONE SQLite store per home — and a machine has more than one home. `hermes -p
+ * <name>` runs against `~/.hermes/profiles/<name>`, with its own `config.yaml`, its own `auth.json` and
+ * its own `state.db`. The daemon used to read `<HERMES_HOME>/state.db` everywhere, so a fleet of profile
+ * agents streamed their terminals perfectly and then sat on "No activity yet" forever: the mirror polled
+ * a database their sessions were not in, so no turn ever opened, nothing was ever recapped, and
+ * `agent_recent` answered zero for the life of the agent (openharness#191).
+ *
+ * ⚠️ **THE SESSION ID IS THE ONLY EVIDENCE THAT NEEDS NO ASSUMPTION.** The obvious fix is to read
+ * `HERMES_HOME` off the live process, the way `codexHomeProbe` reads `CODEX_HOME` — and that is done
+ * below, because it is free when it works. But whether Hermes exports it for a `-p` session is the
+ * engine's business and changes between versions, and a pane the daemon did not create may be gone by
+ * the time anyone asks. A session id is unique and its row exists in exactly one store, so "which home
+ * holds this session" is answerable by looking, at the cost of one indexed lookup per home, once per
+ * agent — the answer is then filled onto the registry row and never asked again (see
+ * `RegisteredSession.hermesHome`).
+ *
+ * Nothing here writes. Discovering a home does not create one, and a home with no `state.db` is not a
+ * home yet — it is a profile whose first session has not started.
+ */
+
+import { readdirSync, realpathSync, statSync } from 'node:fs'
+import { readdir, stat } from 'node:fs/promises'
+import { isAbsolute, join } from 'node:path'
+import { env } from '../../config/env.js'
+import { sqliteReadAll } from '../../lib/sqliteRead.js'
+import type { AgentEngine } from '../types.js'
+
+/** `YYYYMMDD_HHMMSS_<hex>` — the same shape `reader.ts` guards its queries with. */
+const SESSION_ID_RE = /^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/
+/** How long a homes listing is reused. A profile is created by hand, minutes apart; this is a `readdir`. */
+const HOMES_TTL_MS = 30_000
+/** A person with hundreds of profile folders has a different problem; this keeps the scan bounded. */
+const MAX_PROFILES = 64
+
+export function hermesDbPath(home: string): string {
+ return join(home, 'state.db')
+}
+
+function canonical(path: string): string {
+ try { return realpathSync(path) } catch { return path }
+}
+
+/** Same home, spelled differently (a symlinked `~`, a trailing slash). */
+export function sameHermesHome(a: string, b: string): boolean {
+ return canonical(a.replace(/\/+$/, '')) === canonical(b.replace(/\/+$/, ''))
+}
+
+let homesCache: { at: number; homes: string[] } | null = null
+
+/**
+ * Every home this machine has, the default first.
+ *
+ * A profile counts only once it has a `state.db`: before that there is nothing to read and nothing to
+ * match a session against, and listing it would cost a failed query on every lookup.
+ */
+export async function listHermesHomes(defaultHome = env.HERMES_HOME): Promise<string[]> {
+ const now = Date.now()
+ if (homesCache && now - homesCache.at < HOMES_TTL_MS) return homesCache.homes
+ const homes = [defaultHome]
+ try {
+ const entries = await readdir(join(defaultHome, 'profiles'), { withFileTypes: true })
+ for (const entry of entries.slice(0, MAX_PROFILES)) {
+ if (!entry.isDirectory()) continue
+ const home = join(defaultHome, 'profiles', entry.name)
+ try {
+ if ((await stat(hermesDbPath(home))).isFile()) homes.push(home)
+ } catch { /* a profile whose first session has not started */ }
+ }
+ } catch { /* no profiles folder — the single-home machine, which is most of them */ }
+ homesCache = { at: now, homes }
+ return homes
+}
+
+/**
+ * Every home that has a `config.yaml` — the homes the hook installer has something to write to.
+ *
+ * A different question from `listHermesHomes`, and deliberately a different predicate: a profile is
+ * ready to READ from once it has a `state.db` (a session has run in it) and ready to be HOOKED as soon
+ * as it has a config, which is at creation. Synchronous because every hook installer is.
+ */
+export function hermesConfigHomes(defaultHome = env.HERMES_HOME): string[] {
+ const homes = [defaultHome]
+ let entries: string[] = []
+ try { entries = readdirSync(join(defaultHome, 'profiles')) } catch { return homes }
+ for (const name of entries.slice(0, MAX_PROFILES)) {
+ const home = join(defaultHome, 'profiles', name)
+ try {
+ if (statSync(join(home, 'config.yaml')).isFile()) homes.push(home)
+ } catch { /* not a profile folder, or no config yet */ }
+ }
+ return homes
+}
+
+/** Forget the listing — for a test, and for an installer that has just made a profile. */
+export function forgetHermesHomes(): void {
+ homesCache = null
+}
+
+/**
+ * The home whose store holds `sessionId`, or null when no home does (yet).
+ *
+ * Read-only and indexed: `sessions.id` is the primary key, so this is a point lookup per home. The
+ * default home is asked first, which is the answer on every machine that has only one.
+ */
+export async function findHermesHomeForSession(
+ sessionId: string,
+ homes?: string[],
+): Promise<string | null> {
+ if (!SESSION_ID_RE.test(sessionId)) return null
+ for (const home of homes ?? await listHermesHomes()) {
+ const result = await sqliteReadAll(
+ hermesDbPath(home),
+ 'SELECT id FROM sessions WHERE id = ? LIMIT 1;',
+ [sessionId],
+ { maxBuffer: 1 << 16 },
+ )
+ if (result.ok && result.rows.length > 0) return home
+ }
+ return null
+}
+
+/**
+ * The home a live `hermes` process was launched under, read off its environment — the free answer,
+ * when the engine offers it. Contract copied from `codexHomeFromEnv`: a path when the process runs
+ * under a non-default home, `null` when it runs under this machine's default (or says nothing), and
+ * `undefined` from the probe when the process could not be read at all, which must never overwrite
+ * what the registry already knows.
+ */
+export function hermesHomeFromEnv(
+ engine: AgentEngine,
+ processEnv: Record<string, string>,
+ defaultHome = env.HERMES_HOME,
+): string | null {
+ if (engine !== 'hermes') return null
+ const home = processEnv.HERMES_HOME
+ if (!home || !isAbsolute(home) || home.length > 4096 || /[\x00-\x1f\x7f]/.test(home)) return null
+ return sameHermesHome(home, defaultHome) ? null : home
+}
diff --git a/cli/src/engines/hermes/homeProbe.ts b/cli/src/engines/hermes/homeProbe.ts
new file mode 100644
index 000000000..6ca48a127
--- /dev/null
+++ b/cli/src/engines/hermes/homeProbe.ts
@@ -0,0 +1,24 @@
+/**
+ * Which Hermes home a live `hermes` process was launched under, read off its environment.
+ *
+ * The free half of the answer `home.ts` documents: when the engine exports `HERMES_HOME` for a
+ * `hermes -p <name>` session, one cached `ps` names the home and the registry row is filled before any
+ * store is opened. When it does not, this says nothing (`null`) and the session-id lookup answers
+ * instead — which is why nothing here is load-bearing.
+ *
+ * Same three answers as `codexHomeProbe`: a path for a non-default home, `null` for the default or an
+ * engine that said nothing, and `undefined` when the process could not be read at all, which must
+ * never overwrite what the registry already knows.
+ */
+
+import type { AgentEngine } from '../types.js'
+import { readProcessEnv } from '../../lib/processEnv.js'
+import type { ProcessIdentity } from '../../lib/registry.js'
+import { hermesHomeFromEnv } from './home.js'
+
+export async function probeHermesHome(identity: ProcessIdentity, engine: AgentEngine): Promise<string | null | undefined> {
+ if (engine !== 'hermes') return null
+ const processEnv = await readProcessEnv(identity)
+ if (!processEnv) return undefined
+ return hermesHomeFromEnv(engine, processEnv)
+}
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index a44a87813..d196f67e5 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -10,6 +10,7 @@ import http from 'node:http'
import type { AddressInfo } from 'node:net'
import { readCodexRolloutMeta } from './engines/codex/rollout.js'
import { hermesSessionSource } from './engines/hermes/reader.js'
+import { hermesDbPath, listHermesHomes } from './engines/hermes/home.js'
import { isRecentlyDeleted } from './lib/deletedSessions.js'
import { registry, type RegisterInput, type RegisteredSession } from './lib/registry.js'
import { LOCAL_WEB_HTML } from './webui.js'
@@ -337,12 +338,23 @@ async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers
* exactly the behaviour before this guard existed.
*/
async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers): Promise<void> {
- const dbPath = join(env.HERMES_HOME, 'state.db')
+ // EVERY home, not just the default. A `hermes -p <name>` session's row lives in that profile's own
+ // store, so asking the default one answered `null` (unknown) six times and fell through — and, worse,
+ // the home found here is the one the whole row then reads its history from (openharness#191).
+ const homes = await listHermesHomes()
+ let hermesHome: string | undefined
for (let i = 0; i < HERMES_KIND_TRIES; i++) {
if (i > 0) await new Promise((resolve) => { const t = setTimeout(resolve, HERMES_KIND_WAIT_MS); t.unref?.() })
if (!registeredHookProcess(body, 'hermes')) return
if (isRecentlyDeleted(body.sessionId)) return
- const source = await hermesSessionSource(dbPath, body.sessionId ?? '')
+ let source: string | null = null
+ for (const home of homes) {
+ const answer = await hermesSessionSource(hermesDbPath(home), body.sessionId ?? '')
+ if (answer === null) continue // not in this store — try the next home
+ source = answer
+ if (home !== env.HERMES_HOME) hermesHome = home
+ break
+ }
if (source === null) continue
if (source !== '' && source !== 'cli') {
console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · hermes_subagent`)
@@ -350,9 +362,9 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers
}
break
}
- const result = registry.register(body)
+ const result = registry.register(hermesHome ? { ...body, hermesHome } : body)
if (!result) return
- console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=hermes · isNew=${result.isNew} · after a source check`)
+ console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=hermes · isNew=${result.isNew} · after a source check${hermesHome ? ` · home=${hermesHome}` : ''}`)
handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
}
diff --git a/cli/src/lib/hermesHome.spec.ts b/cli/src/lib/hermesHome.spec.ts
new file mode 100644
index 000000000..cb5d1b55a
--- /dev/null
+++ b/cli/src/lib/hermesHome.spec.ts
@@ -0,0 +1,121 @@
+/**
+ * The store a registered Hermes session reads from — found once, remembered on the row.
+ *
+ * The bug this closes: every Hermes read went to `<HERMES_HOME>/state.db`, so an agent started with
+ * `hermes -p <name>` mirrored nothing, recapped nothing, and answered `agent_recent` with zero events
+ * for as long as it lived (openharness#191).
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync } from 'child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import { join } from 'path'
+
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
+const d = hasSqlite ? describe : describe.skip
+
+const DEFAULT_SESSION = '20260727_162325_e25264'
+const PROFILE_SESSION = '20260921_152236_a1b2c3'
+
+let dataDir = ''
+let hermesHome = ''
+
+function store(root: string, sessions: string[]): string {
+ mkdirSync(root, { recursive: true })
+ execFileSync('sqlite3', [
+ join(root, 'state.db'),
+ 'CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL);'
+ + sessions.map((id) => `INSERT INTO sessions VALUES ('${id}','cli');`).join(''),
+ ])
+ writeFileSync(join(root, 'config.yaml'), 'model: nous/hermes-4\n')
+ return root
+}
+
+/** A hook arriving on a pane the daemon has not met: the process agent is opened first, as the hook
+ * server does, then the session binds to it. */
+function bindSession(
+ registry: Awaited<ReturnType<typeof load>>['registry'],
+ sessionId: string,
+ pane: string,
+ pid: number,
+) {
+ const processIdentity = { pid, executable: 'hermes', startMarker: `Mon Sep 21 15:22:${pid % 60} 2026` }
+ registry.openProcessAgent({ engine: 'hermes', tmuxPane: pane, cwd: '/tmp/work', processIdentity })
+ const result = registry.register({ engine: 'hermes', sessionId, cwd: '/tmp/work', tmuxPane: pane, processIdentity })
+ if (!result) throw new Error('registration refused')
+ return result.entry
+}
+
+async function load() {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ process.env.CLAUDE_PROJECTS_DIR = dataDir
+ process.env.HERMES_HOME = hermesHome
+ const home = await import('../engines/hermes/home.js')
+ home.forgetHermesHomes()
+ return { ...await import('./hermesHome.js'), ...await import('./registry.js') }
+}
+
+d('the Hermes store a session reads from', () => {
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-hm-data-'))
+ hermesHome = mkdtempSync(join(tmpdir(), 'adapter-hm-home-'))
+ })
+
+ afterEach(() => {
+ for (const dir of [dataDir, hermesHome]) rmSync(dir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.HERMES_HOME
+ })
+
+ it('reads a profile session from its own store and remembers the home on the row', async () => {
+ store(hermesHome, [DEFAULT_SESSION])
+ const demo = store(join(hermesHome, 'profiles', 'demo'), [PROFILE_SESSION])
+ const { hermesDbForSession, registry } = await load()
+
+ const entry = bindSession(registry, PROFILE_SESSION, '%7', 4242)
+ expect(entry.hermesHome ?? null).toBeNull() // nothing known yet — the row was just born
+
+ expect(await hermesDbForSession(entry)).toBe(join(demo, 'state.db'))
+ // Found once: the row now carries it, so the next poll opens no other store.
+ expect(registry.resolve(entry.agentId)?.hermesHome).toBe(demo)
+ // …and it survives a reload, which is where a field added to the type but not to the rehydrate
+ // list silently disappears.
+ const reloaded = await load()
+ reloaded.registry.load() // the daemon's own first act — the singleton does not read on import
+ expect(reloaded.registry.resolve(entry.agentId)?.hermesHome).toBe(demo)
+ })
+
+ it('a default-home session keeps reading the default store, and writes nothing to its row', async () => {
+ store(hermesHome, [DEFAULT_SESSION])
+ const { hermesDbForSession, registry } = await load()
+
+ const entry = bindSession(registry, DEFAULT_SESSION, '%8', 4243)
+
+ expect(await hermesDbForSession(entry)).toBe(join(hermesHome, 'state.db'))
+ expect(registry.resolve(entry.agentId)?.hermesHome ?? null).toBeNull()
+ })
+
+ it('a session no store has yet falls back to the default, and does not remember that', async () => {
+ store(hermesHome, [])
+ const { hermesDbForSession, registry } = await load()
+
+ const entry = bindSession(registry, PROFILE_SESSION, '%9', 4244)
+
+ expect(await hermesDbForSession(entry)).toBe(join(hermesHome, 'state.db'))
+ expect(registry.resolve(entry.agentId)?.hermesHome ?? null).toBeNull()
+ })
+
+ it('a home the row already knows is taken as-is, with no lookup', async () => {
+ store(hermesHome, [DEFAULT_SESSION, PROFILE_SESSION]) // the default store holds BOTH
+ const { hermesDbForSession } = await load()
+ // …so a lookup would answer the default home; the row's own answer must win.
+ expect(await hermesDbForSession({
+ agentId: 'a1', sessionId: PROFILE_SESSION, hermesHome: '/somewhere/else',
+ })).toBe('/somewhere/else/state.db')
+ })
+})
diff --git a/cli/src/lib/hermesHome.ts b/cli/src/lib/hermesHome.ts
new file mode 100644
index 000000000..d428b47b5
--- /dev/null
+++ b/cli/src/lib/hermesHome.ts
@@ -0,0 +1,52 @@
+/**
+ * The Hermes store a REGISTERED session reads from, found once and remembered.
+ *
+ * `engines/hermes/home.ts` answers "which home holds this session" by looking; this is the half that
+ * knows about the registry, so the answer is filled onto the row (`RegisteredSession.hermesHome`) and
+ * the next caller pays nothing. Kept out of the engine folder for the same reason the readers are:
+ * an engine module reads its own files and knows nothing about agents.
+ *
+ * Every Hermes-shaped read goes through here — the live mirror, `agent_recent`, the recap fallback —
+ * so a profile agent's history is read from ITS store rather than from the default one, which is what
+ * left those agents' activity cards empty forever (openharness#191).
+ */
+
+import { findHermesHomeForSession, hermesDbPath } from '../engines/hermes/home.js'
+import { env } from '../config/env.js'
+import { registry, type RegisteredSession } from './registry.js'
+
+/** In flight right now, so N pollers asking at once cost one scan. Keyed by session id. */
+const pending = new Map<string, Promise<string>>()
+
+/**
+ * The home for a session: what the row already knows, else whichever store holds it, else the default.
+ *
+ * Falling back to the default home is deliberate — it is what every caller did before this existed, so
+ * a machine with one home behaves exactly as it did, and a session whose row has not landed yet reads
+ * the same store it would have read anyway. Nothing is remembered in that case: the row lands a moment
+ * later and the next call finds it.
+ */
+export async function hermesHomeForSession(session: Pick<RegisteredSession, 'agentId' | 'sessionId' | 'hermesHome'>): Promise<string> {
+ if (session.hermesHome) return session.hermesHome
+ const sessionId = session.sessionId
+ if (!sessionId) return env.HERMES_HOME
+ const existing = pending.get(sessionId)
+ if (existing) return existing
+ const lookup = findHermesHomeForSession(sessionId)
+ .then((home) => {
+ if (!home) return env.HERMES_HOME
+ // Only a home other than the default is worth a row write: `hermesHome` null means "the default",
+ // and writing the default into every row would be noise on every single-home machine.
+ if (home !== env.HERMES_HOME && session.agentId) registry.setHermesHome(session.agentId, home)
+ return home
+ })
+ .catch(() => env.HERMES_HOME)
+ .finally(() => { pending.delete(sessionId) })
+ pending.set(sessionId, lookup)
+ return lookup
+}
+
+/** The store path for a session — what the readers actually take. */
+export async function hermesDbForSession(session: Pick<RegisteredSession, 'agentId' | 'sessionId' | 'hermesHome'>): Promise<string> {
+ return hermesDbPath(await hermesHomeForSession(session))
+}
diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.ts
index 1d7785f6d..717e7ee58 100644
--- a/cli/src/lib/hooks.spec.ts
+++ b/cli/src/lib/hooks.spec.ts
@@ -373,6 +373,66 @@ describe('Hermes hook installation', () => {
expect(readFileSync(file, 'utf8')).toBe(mine)
expect(existsSync(join(hermesHome, 'shell-hooks-allowlist.json'))).toBe(false)
})
+
+ // `hermes -p <name>` runs against ~/.hermes/profiles/<name> — its own config, its own store. Hermes
+ // COPIES config.yaml when it creates a profile, so the block in there is a frozen snapshot no
+ // installer revisited, carrying an old command and the DEFAULT home's path. The hook then looked the
+ // session up in a store it was not in, and a profile fleet's activity stayed empty (openharness#191).
+ describe('profiles', () => {
+ const profileConfig = (name: string): string => {
+ const dir = join(hermesHome, 'profiles', name)
+ mkdirSync(dir, { recursive: true })
+ const path = join(dir, 'config.yaml')
+ writeFileSync(path, USER_CONFIG)
+ return path
+ }
+
+ it('installs into every profile, each naming ITS OWN home', async () => {
+ const demo = profileConfig('demo')
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+
+ const out = readFileSync(demo, 'utf8')
+ expect(blockCount(out)).toBe(1)
+ expect(out).toContain(`--hermes-home '${join(hermesHome, 'profiles', 'demo')}'`)
+ expect(out).not.toContain(`--hermes-home '${hermesHome}'`)
+ // …and the default home still names itself, unchanged by any of this.
+ expect(readFileSync(file, 'utf8')).toContain(`--hermes-home '${hermesHome}'`)
+ // The allowlist is exact-match on (event, command), so the profile's own command needs its own.
+ const allow = JSON.parse(readFileSync(join(hermesHome, 'profiles', 'demo', 'shell-hooks-allowlist.json'), 'utf8')) as {
+ approvals: Array<{ event: string; command: string }>
+ }
+ const cmd = /- command: "(.*?)"/.exec(out)![1]
+ expect(allow.approvals.map((a) => a.event).sort()).toEqual(['on_session_start', 'pre_llm_call'])
+ for (const a of allow.approvals) expect(a.command).toBe(cmd)
+ })
+
+ it('replaces the stale block a profile was created with', async () => {
+ // What `hermes profile create` leaves behind: our own block, frozen at the version that was
+ // current when the ROOT config was last written — old port, old path, default home.
+ const stale = "\n# machine-adapter: session discovery (managed block — safe to delete)\nhooks:\n"
+ + " on_session_start:\n - command: \"node '/old/notify.mjs' --port 19918 --hermes-home '/home/u/.hermes' --engine hermes\"\n timeout: 10\n"
+ + '# machine-adapter: end\n'
+ const demo = profileConfig('demo')
+ writeFileSync(demo, `${USER_CONFIG}${stale}`)
+
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+
+ const out = readFileSync(demo, 'utf8')
+ expect(blockCount(out)).toBe(1)
+ expect(out).not.toContain('19918')
+ expect(out).toContain(`--hermes-home '${join(hermesHome, 'profiles', 'demo')}'`)
+ expect(out).toContain('model:\n default: minimax/minimax-m3') // the user's own config survives
+ })
+
+ it('a profile with no config of its own is not written to', async () => {
+ mkdirSync(join(hermesHome, 'profiles', 'fresh'), { recursive: true })
+ const { installHermesHooks } = await loadHooks()
+ installHermesHooks(18473)
+ expect(existsSync(join(hermesHome, 'profiles', 'fresh', 'config.yaml'))).toBe(false)
+ })
+ })
})
/**
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 0bde0f3e1..54d668cb2 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -6,11 +6,12 @@
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'fs'
-import { join, dirname } from 'path'
+import { basename, join, dirname } from 'path'
import { homedir } from 'os'
import { fileURLToPath } from 'url'
import { env } from '../config/env.js'
import { VERSION } from '../version.js'
+import { hermesConfigHomes } from '../engines/hermes/home.js'
import { managedNodePath } from './nodeRuntime.js'
const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
@@ -62,6 +63,10 @@ function command(
// Only ever non-default for 'codex': a per-agent CODEX_HOME profile gets its OWN hooks.json, and
// that file's baked --codex-home must match where it actually lives (see installCodexHooks).
codexHome: string = env.CODEX_HOME,
+ // Same rule for Hermes, and it was broken the same way: a `hermes -p <name>` profile has its own
+ // config.yaml, and the block in it carried the DEFAULT home — so the hook looked the session up in
+ // a store it was not in (openharness#191). See installHermesHooks.
+ hermesHome: string = env.HERMES_HOME,
): string {
return [
// Absolute, never the bare word `node`. This string is executed later by the ENGINE, in a shell
@@ -76,7 +81,7 @@ function command(
'--codex-home', shellQuote(codexHome),
'--grok-home', shellQuote(env.GROK_HOME),
'--cursor-home', shellQuote(env.CURSOR_HOME),
- '--hermes-home', shellQuote(env.HERMES_HOME),
+ '--hermes-home', shellQuote(hermesHome),
'--commandcode-home', shellQuote(env.COMMANDCODE_HOME),
'--devin-home', shellQuote(env.DEVIN_HOME),
'--agy-home', shellQuote(env.AGY_HOME),
@@ -553,7 +558,6 @@ export function installDevinHooks(port: number): void {
}
const HERMES_CONFIG_PATH = join(env.HERMES_HOME, 'config.yaml')
-const HERMES_ALLOWLIST_PATH = join(env.HERMES_HOME, 'shell-hooks-allowlist.json')
// The managed block is delimited by BEGIN/END so it can be replaced unambiguously. (An earlier version
// used a single marker line and a lookahead regex, which only replaced the comment and orphaned the old
// `hooks:` mapping — YAML then took the LAST duplicate key, so a stale block silently won.)
@@ -565,10 +569,11 @@ const HERMES_HOOK_EVENTS = ['on_session_start', 'pre_llm_call'] as const
/** Hermes gates every (event, command) pair behind ~/.hermes/shell-hooks-allowlist.json; an unapproved
* hook is SILENTLY skipped in non-TTY runs. Record ours so it fires without an interactive prompt. */
-function allowlistHermesHook(cmd: string): void {
+function allowlistHermesHook(cmd: string, home: string): void {
+ const allowlistPath = join(home, 'shell-hooks-allowlist.json')
let data: { approvals?: Array<{ event?: string; command?: string }> } = { approvals: [] }
try {
- const parsed = JSON.parse(readFileSync(HERMES_ALLOWLIST_PATH, 'utf-8')) as typeof data
+ const parsed = JSON.parse(readFileSync(allowlistPath, 'utf-8')) as typeof data
if (parsed && Array.isArray(parsed.approvals)) data = parsed
} catch { /* absent or unreadable → start from an empty skeleton */ }
const previous = data.approvals ?? []
@@ -590,7 +595,7 @@ function allowlistHermesHook(cmd: string): void {
changed = true
}
if (!changed) return
- writeJsonAtomic(HERMES_ALLOWLIST_PATH, { ...data, approvals })
+ writeJsonAtomic(allowlistPath, { ...data, approvals })
}
function hermesHooksBlock(cmd: string): string {
@@ -650,18 +655,31 @@ function stripMachineHermesBlocks(config: string): { cleaned: string; foreignHoo
* leave the file untouched and print what to add.
*/
export function installHermesHooks(port: number): void {
- const cmd = command(port, 'hermes')
+ // EVERY home, each with its OWN path baked into its block.
+ //
+ // ⚠️ A PROFILE'S CONFIG IS A COPY, AND NOTHING WAS MAINTAINING IT. `hermes profile create` copies
+ // `~/.hermes/config.yaml`, managed block and all — so a profile made after an install carried a
+ // frozen command (an older node path, an older port) that no installer ever revisited, and the
+ // `--hermes-home` in it named the DEFAULT home rather than the profile's own. The hook then looked
+ // its session up in a store the session was not in (openharness#191). Walking the profiles fixes
+ // both: the drift, and the home.
+ for (const home of hermesConfigHomes()) installHermesHooksIn(port, home)
+}
+
+function installHermesHooksIn(port: number, home: string): void {
+ const configPath = join(home, 'config.yaml')
+ const cmd = command(port, 'hermes', env.CODEX_HOME, home)
let config = ''
try {
- config = readFileSync(HERMES_CONFIG_PATH, 'utf-8')
+ config = readFileSync(configPath, 'utf-8')
} catch {
- console.log(`[hooks] no Hermes config at ${HERMES_CONFIG_PATH} — skipping (run hermes once first)`)
+ if (home === env.HERMES_HOME) console.log(`[hooks] no Hermes config at ${configPath} — skipping (run hermes once first)`)
return
}
const { cleaned, foreignHooks, removed } = stripMachineHermesBlocks(config)
if (foreignHooks) {
- console.error(`[hooks] ${HERMES_CONFIG_PATH} has its own \`hooks:\` block — leaving it untouched.`)
+ console.error(`[hooks] ${configPath} has its own \`hooks:\` block — leaving it untouched.`)
console.error('[hooks] add these entries under it manually to mirror Hermes sessions:')
for (const event of HERMES_HOOK_EVENTS) console.error(`[hooks] ${event}: [{ command: ${JSON.stringify(cmd)}, timeout: 10 }]`)
return
@@ -669,18 +687,18 @@ export function installHermesHooks(port: number): void {
const next = `${cleaned.replace(/\s*$/, '')}\n${hermesHooksBlock(cmd)}`
if (next === config) {
- allowlistHermesHook(cmd) // keep the allowlist in sync even when the block is current
- console.log('[hooks] Hermes session hooks already installed')
+ allowlistHermesHook(cmd, home) // keep the allowlist in sync even when the block is current
+ console.log(`[hooks] Hermes session hooks already installed${home === env.HERMES_HOME ? '' : ` (${basename(home)})`}`)
return
}
try {
- writeFileSync(HERMES_CONFIG_PATH, next)
- allowlistHermesHook(cmd)
+ writeFileSync(configPath, next)
+ allowlistHermesHook(cmd, home)
console.log(
removed > 1
- ? `[hooks] installed Hermes session hooks (collapsed ${removed} stale blocks) → ${HERMES_CONFIG_PATH}`
- : `[hooks] installed Hermes session hooks → ${HERMES_CONFIG_PATH}`,
+ ? `[hooks] installed Hermes session hooks (collapsed ${removed} stale blocks) → ${configPath}`
+ : `[hooks] installed Hermes session hooks → ${configPath}`,
)
console.log('[hooks] (takes effect on the next hermes session start)')
} catch (err) {
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 058ebcb2a..5800132e9 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -143,6 +143,20 @@ export interface RegisteredSession {
* to a different grid.
*/
codexHome?: string | null
+ /**
+ * The Hermes home this session's history lives in — `~/.hermes/profiles/<name>` for an agent started
+ * with `hermes -p <name>`, null for this machine's default home.
+ *
+ * Unlike `codexHome` this is not a launch choice the daemon makes: `hermes -p` is how a person starts
+ * one, and the daemon meets the pane afterwards. So it is FOUND rather than recorded — by the session
+ * id, in whichever store holds its row (`engines/hermes/home.ts`) — and then kept here so the lookup
+ * happens once per agent instead of once per poll. Fill-only, like `codexHome`.
+ *
+ * Everything Hermes-shaped reads it: the live mirror, `agent_recent`, the recap fallback, the hook's
+ * source check and the model/effort poll. Reading one fixed home instead is what left a profile
+ * fleet's activity cards empty forever while their terminals streamed perfectly (openharness#191).
+ */
+ hermesHome?: string | null
/**
* The domain-specific harness this agent was created as (`autonomous/copper`), or null for a plain
* engine. NOT a second engine: `engine` stays the base (`claude`, `codex`, …) and every normalizer,
@@ -231,6 +245,10 @@ export interface RegisterInput {
runtimeHints?: HookTerminalHint[]
callerPid?: number
hookEvent?: string
+ /** Hermes only: the home whose store holds this session, when it is not the machine's default one.
+ * Found by the hook gate (`awaitHermesKind`), which has to look the session up anyway, and by the
+ * hook script itself when the daemon was down. Fill-only — see RegisteredSession.hermesHome. */
+ hermesHome?: string
}
/** Display name for a session's "project" tab/tile. A user rename (persisted override) is
@@ -870,6 +888,7 @@ class Registry {
gateway: raw.gateway === 'ori' ? 'ori' : null,
grid: normalizedGridAssignment(raw.grid),
codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,
+ hermesHome: typeof raw?.hermesHome === 'string' && raw.hermesHome ? raw.hermesHome : null,
dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),
agent: normalizedAgentName((raw as { agent?: unknown }).agent),
...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),
@@ -975,6 +994,8 @@ class Registry {
/** Codex only: the CODEX_HOME the process was launched under, read off its environment. Fills a
* row that does not know its profile yet; never overwrites one that does (see `codexHome`). */
codexHome?: string | null
+ /** The Hermes home this session's store lives in, if it is not the default. Fill-only. */
+ hermesHome?: string | null
/** The DSH read off the process's `HARNESS_DSH`, if any. Fill-only, like `codexHome`. */
dsh?: string | null
}):
@@ -1031,6 +1052,7 @@ class Registry {
if (input.gateway !== undefined) existing.gateway = input.gateway
if (input.grid !== undefined) existing.grid = input.grid
if (input.codexHome && !existing.codexHome) existing.codexHome = input.codexHome
+ if (input.hermesHome && !existing.hermesHome) existing.hermesHome = input.hermesHome
if (input.dsh && !existing.dsh) existing.dsh = input.dsh
existing.updatedAt = Date.now()
this.index(existing)
@@ -1074,6 +1096,7 @@ class Registry {
gridLaunch: null,
gridWebSearch: null,
codexHome: input.codexHome ?? null,
+ hermesHome: input.hermesHome ?? null,
dsh: input.dsh ?? null,
// A discovered pane's named agent is only visible in its argv; nothing here reads it, so the
// row cannot relaunch it as one. Fill-only, like `dsh`.
@@ -1142,6 +1165,9 @@ class Registry {
gridLaunch: input.gridLaunchRecord?.override ?? null,
gridWebSearch: input.gridLaunchRecord?.webSearch ?? null,
codexHome: input.codexHome ?? null,
+ // A pane Harness opens starts in the default home; `hermes -p` is the person's own doing, and
+ // the row learns it from the session that lands in it. See RegisteredSession.hermesHome.
+ hermesHome: null,
dsh: input.dsh ?? null,
agent: normalizedAgentName(input.agent),
...(input.bypassPermission ? { bypassPermission: true } : {}),
@@ -1395,6 +1421,10 @@ class Registry {
// re-reads off the live process on every discovery) — a hook-triggered bind must carry it
// forward or the very first SessionStart hook would silently wipe the agent's chosen profile.
codexHome: existing?.codexHome ?? null,
+ // The home the gate looked this session up in, or whatever the row already knew. Carried
+ // forward like every field here: a bind REBUILDS the row, and a home dropped at the first hook
+ // would send the mirror back to the default store (openharness#191).
+ hermesHome: input.hermesHome ?? existing?.hermesHome ?? null,
dsh: existing?.dsh ?? null,
agent: existing?.agent ?? null,
...(existing?.bypassPermission ? { bypassPermission: true } : {}),
@@ -1686,6 +1716,18 @@ class Registry {
return true
}
+ /** Fill in the Hermes home a row did not know — found by looking for its session in each store, or
+ * read off the live process. Never overwrites: like `setCodexHome`, a session does not move between
+ * homes, and a later probe that could not read the process must not take the answer away. */
+ setHermesHome(agentId: string, hermesHome: string): boolean {
+ const session = this.agents.get(agentId)
+ if (!session || session.engine !== 'hermes' || session.hermesHome) return false
+ session.hermesHome = hermesHome
+ session.updatedAt = Date.now()
+ this.save()
+ return true
+ }
+
/** Fill in the DSH a row did not know (discovery read `HARNESS_DSH` off the live process). Never
* replaces one it already has — the harness is chosen once, at creation. */
setDsh(agentId: string, dsh: string): boolean {
diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.ts
index e3e64123f..d11b0a78e 100644
--- a/cli/src/lib/runtimeProfile.ts
+++ b/cli/src/lib/runtimeProfile.ts
@@ -616,7 +616,9 @@ export class RuntimeProfileManager {
private commandcodeCatalogCache: { key: string; expiresAt: number; entries: CommandcodeModelTarget[] } | null = null
/** profile id → the full `/model` argument (the profile carries the SHORT name the device labels by). */
private readonly commandcodeTargets = new Map<string, Map<string, CommandcodeModelTarget>>()
- private hermesCatalogCache: { key: string; expiresAt: number; entries: HermesModelTarget[] } | null = null
+ /** Per HOME, not one slot: a desk with a default-home agent and a profile agent would otherwise
+ * evict each other's catalog on every menu open (`hermes -p <name>` has its own providers). */
+ private hermesCatalogCache = new Map<string, { expiresAt: number; entries: HermesModelTarget[] }>()
/** profile id → the picker page + row a hermes model sits on. */
private readonly hermesTargets = new Map<string, Map<string, HermesModelTarget>>()
private cursorCatalogCache: { key: string; expiresAt: number; entries: CursorCatalogEntry[] } | null = null
@@ -666,7 +668,9 @@ export class RuntimeProfileManager {
// Both axes are scalars in config.yaml and neither is announced, so this poll is the only reader.
const before = this.selectedModel(session)
const state = this.state(session.sessionId)
- const parsed = parseHermesConfig(await readText(join(env.HERMES_HOME, 'config.yaml')))
+ // This agent's OWN home: `hermes -p <name>` keeps its model and effort in the profile's
+ // config.yaml, and reading the default one reported the wrong model on every profile agent.
+ const parsed = parseHermesConfig(await readText(join(session.hermesHome || env.HERMES_HOME, 'config.yaml')))
if (parsed.model) state.model = parsed.model.slice(parsed.model.lastIndexOf('/') + 1)
state.effort = parsed.effort ?? 'auto'
state.observedAt = Date.now()
@@ -1432,7 +1436,7 @@ export class RuntimeProfileManager {
* the chip names it truthfully; it just cannot be picked.
*/
private async hermesModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {
- const entries = await this.hermesCatalog()
+ const entries = await this.hermesCatalog(session.hermesHome || env.HERMES_HOME)
const state = this.states.get(session.sessionId)
const targets = new Map<string, HermesModelTarget>()
const output: RuntimeModelOption[] = []
@@ -1460,14 +1464,14 @@ export class RuntimeProfileManager {
return output
}
- private async hermesCatalog(): Promise<HermesModelTarget[]> {
- const key = env.HERMES_HOME
- if (this.hermesCatalogCache?.key === key && this.hermesCatalogCache.expiresAt > Date.now()) {
- return this.hermesCatalogCache.entries
- }
- const cache = await readJson(join(env.HERMES_HOME, 'provider_models_cache.json'))
+ private async hermesCatalog(home = env.HERMES_HOME): Promise<HermesModelTarget[]> {
+ // Keyed by home, and now actually asked per home: a profile has its own providers, so the cache
+ // key was already right and only the path it read was not.
+ const cached = this.hermesCatalogCache.get(home)
+ if (cached && cached.expiresAt > Date.now()) return cached.entries
+ const cache = await readJson(join(home, 'provider_models_cache.json'))
const entries = parseHermesModelsCache(cache)
- this.hermesCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }
+ this.hermesCatalogCache.set(home, { entries, expiresAt: Date.now() + CATALOG_TTL_MS })
return entries
}
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index ebb3a967f..236a5e438 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'fs'
+import { execFileSync } from 'child_process'
import { tmpdir } from 'os'
import { join } from 'path'
import { claudeContinuation } from './sessionRepair.js'
@@ -440,3 +441,66 @@ it.each(['bad pid', 'bad start', 'missing file', 'bad json', 'different pid', 'd
if (mode !== 'missing file') writeFileSync(join(home, 'sessions', '77.json'), mode === 'bad json' ? '{' : JSON.stringify(record))
expect(await claudeProcessSession(mode === 'bad pid' ? -1 : 77, CWD, mode === 'bad start' ? NaN : STARTED_AT)).toBeNull()
})
+
+/**
+ * Hermes keeps one store per HOME, and `hermes -p <name>` has its own. A repair that only asked
+ * `<HERMES_HOME>/state.db` could never rebind a profile agent after a restart — its row is in a
+ * database that store has never heard of (openharness#191).
+ */
+describe('hermes repair across profile homes', () => {
+ const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+ })()
+ const t = hasSqlite ? it : it.skip
+ const SID_DEFAULT = '20260727_162325_e25264'
+ const SID_PROFILE = '20260921_152236_a1b2c3'
+
+ /** A home whose store holds one session started in `cwd`. */
+ function hermesHome(root: string, sessionId: string | null, cwd = CWD): string {
+ mkdirSync(root, { recursive: true })
+ execFileSync('sqlite3', [join(root, 'state.db'),
+ 'CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, cwd TEXT, started_at REAL);'
+ + (sessionId ? `INSERT INTO sessions VALUES ('${sessionId}','cli','${cwd}',${Math.trunc(STARTED_AT / 1000) + 5});` : '')])
+ return root
+ }
+
+ async function loadWithHome(home: string) {
+ vi.resetModules()
+ process.env.CLAUDE_PROJECTS_DIR = home
+ process.env.HERMES_HOME = home
+ const homes = await import('../engines/hermes/home.js')
+ homes.forgetHermesHomes()
+ return import('./sessionRepair.js')
+ }
+
+ t('binds a profile session and says which home it came from', async () => {
+ const home = tempRoot()
+ hermesHome(home, null) // the default store: no session here
+ const demo = hermesHome(join(home, 'profiles', 'demo'), SID_PROFILE)
+ const { findLiveSession } = await loadWithHome(home)
+
+ expect(await findLiveSession('hermes', CWD, STARTED_AT, { bornOnly: true }))
+ .toMatchObject({ sessionId: SID_PROFILE, hermesHome: demo })
+ })
+
+ t('a default-home session still binds, and names the default home', async () => {
+ const home = tempRoot()
+ hermesHome(home, SID_DEFAULT)
+ hermesHome(join(home, 'profiles', 'demo'), null)
+ const { findLiveSession } = await loadWithHome(home)
+
+ expect(await findLiveSession('hermes', CWD, STARTED_AT, { bornOnly: true }))
+ .toMatchObject({ sessionId: SID_DEFAULT, hermesHome: home })
+ })
+
+ t('refuses when two homes both claim the directory', async () => {
+ // Same rule as two rows in one store: ambiguous is a refusal, not a coin toss — pointing an agent
+ // at another agent's history is the failure this whole file exists to prevent.
+ const home = tempRoot()
+ hermesHome(home, SID_DEFAULT)
+ hermesHome(join(home, 'profiles', 'demo'), SID_PROFILE)
+ const { findLiveSession } = await loadWithHome(home)
+
+ expect(await findLiveSession('hermes', CWD, STARTED_AT, { bornOnly: true })).toBeNull()
+ })
+})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index e2a09ffa0..b9ae503e4 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -22,6 +22,7 @@ import type { AgentEngine } from '../engines/types.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'
import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from '../engines/copilot/session.js'
+import { hermesDbPath, listHermesHomes } from '../engines/hermes/home.js'
import { sqlitePreflightMessage } from './sqliteAvailability.js'
import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'
@@ -43,6 +44,8 @@ export interface RepairedSession {
sessionId: string
/** File-backed engines only; the DB-backed ones are read by session id. */
transcriptPath?: string
+ /** Hermes only: which home's store the session was found in, when it was not the default one. */
+ hermesHome?: string
}
interface TranscriptFile { path: string; mtimeMs: number; birthMs: number }
@@ -318,14 +321,28 @@ export async function findLiveSession(
+ ' ORDER BY time_updated DESC LIMIT 2;',
[...dirs, Math.trunc(sinceMs), Math.trunc(sinceMs)],
)
- case 'hermes':
+ case 'hermes': {
// started_at is epoch SECONDS (fractional).
- return dbEngineSession(
- join(env.HERMES_HOME, 'state.db'),
- `SELECT id FROM sessions WHERE cwd IN (${dirList}) AND started_at >= ?`
- + ' ORDER BY started_at DESC LIMIT 2;',
- [...dirs, Math.trunc(sinceMs / 1000)],
- )
+ //
+ // EVERY home, not just the default: `hermes -p <name>` keeps its sessions in
+ // `~/.hermes/profiles/<name>/state.db`, and a repair that only asked the default store could
+ // 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 listHermesHomes()
+ 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
+ }
+ return found[0] ?? null
+ }
case 'devin':
// created_at is epoch SECONDS (integer).
return dbEngineSession(
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index 2317b35fd..5d864d360 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -8,6 +8,7 @@ import {
import { probeGatewayRuntime } from './gatewayRuntime.js'
import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'
import { probeCodexHome } from './codexHomeProbe.js'
+import { probeHermesHome } from '../engines/hermes/homeProbe.js'
import { probeDsh } from '../dsh/probe.js'
import type { TerminalBackend } from './terminalBackend.js'
import {
@@ -59,6 +60,14 @@ export interface DiscoveredTerminalAgent {
* process, and the registry keeps what it already knows. See `codexHomeProbe.ts`.
*/
codexHome?: string | null
+ /**
+ * Hermes only: the home the process runs under (`hermes -p <name>` → `~/.hermes/profiles/<name>`),
+ * when it is not this machine's default and the engine exports `HERMES_HOME`. Same three answers as
+ * `codexHome`. The registry also finds this by looking the session up in each store
+ * (`engines/hermes/home.ts`), which is the answer that needs no cooperation from the engine — this
+ * is the free one, from a read the discovery pass makes anyway.
+ */
+ hermesHome?: string | null
/**
* The domain-specific harness this process was launched as, read off its `HARNESS_DSH`. null = a
* plain engine; undefined = the probe could not read the process, and the registry keeps what it
@@ -261,6 +270,8 @@ export async function probeTerminalAgents(
agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)
// And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.
agent.codexHome = await probeCodexHome(agent.processIdentity, agent.engine)
+ // …and, for Hermes, the home — same cached read, and it beats looking the session up in every store.
+ agent.hermesHome = await probeHermesHome(agent.processIdentity, agent.engine)
// And the DSH it was created as — same read, so a pane the daemon did not create is labelled too.
agent.dsh = await probeDsh(agent.processIdentity)
}))