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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Find and resume external conversations from every local engine (#396)
Deeaae130411c9a
diff --git a/.github/assets/external-engines/README.md b/.github/assets/external-engines/README.mdnew file mode 100644index 000000000..94ce7fff4--- /dev/null+++ b/.github/assets/external-engines/README.md@@ -0,0 +1,7 @@+# External session take-over++`take-over-grok.png` is a Flutter widget rendering of `askTakeOver` with a synthetic busy Grok+conversation, title and machine name. It shows the engine-specific wording: resuming Grok waits+for the person's next message. No real session or account appears in the image.++The behavior is covered by `desktop/test/take_over_dialog_test.dart`.diff --git a/.github/assets/external-engines/take-over-grok.png b/.github/assets/external-engines/take-over-grok.pngnew file mode 100644index 000000000..f0ae40132Binary files /dev/null and b/.github/assets/external-engines/take-over-grok.png differdiff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 8396c7352..39be23e3f 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -2382,7 +2382,9 @@ export class BackendSocket {// conversation is created with applies to it.let resumeSessionId: string | null = nullif (payload.resumeSessionId !== undefined && payload.resumeSessionId !== null) {- if (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9-]{8,80}$/.test(payload.resumeSessionId)) {+ // Engines' ids: uuids, `ses_…` (OpenCode, Kilo), `20260927_101500_ab12cd` (Hermes), slugs+ // (Devin), Pi's custom ids with dots. One word, never a path.+ if (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{1,127}$/.test(payload.resumeSessionId)) {reply(type, requestId, { error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return}if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || dsh || prompt || agent) {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 0a0c448ea..7218a5e79 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -74,7 +74,7 @@ import { gridAvailable } from './lib/gridExec.js'import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'import { isTerminalEngine, type AgentEngine } from './engines/types.js'import { engineInstallRecipe } from './lib/engineInstall.js'-import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported } from './lib/engineLaunch.js'+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt } from './lib/engineLaunch.js'import { workspaceMissing } from './lib/workspaceCheck.js'import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'@@ -94,7 +94,9 @@ import { createRetainExitedSession } from './lib/retainExitedSession.js'import { repairClaudeCwd } from './lib/cwdRepair.js'import { stoppedAgents } from './lib/stoppedAgents.js'import { SessionSearchIndex, folderWords, type SearchSource } from './lib/sessionSearch/indexer.js'-import { ExternalSessions, OpenSessions, processAlive, sessionBusy, stopSessionOwner, type SessionOwner } from './lib/sessionSearch/external.js'+import { ExternalSessions, OpenSessions, processAlive, stopSessionOwner, type SessionOwner } from './lib/sessionSearch/external.js'+import { externalProviders } from './lib/sessionSearch/externals/index.js'+import { engineLabel } from './lib/agentNames.js'import { SessionSearchStore } from './lib/sessionSearch/store.js'import { SESSION_SEARCH_FILE, searchCommand } from './lib/sessionSearch/command.js'import { sweepWorktrees } from './lib/worktreeSweep.js'@@ -122,7 +124,7 @@ import { ApiConnections } from './lib/apiConnections.js'import { apiCommand, apiUsage } from './lib/apiCommand.js'import { prepareApiInstructions } from './lib/apiInstructions.js'import type { AgentDshContext } from './lib/agentFrame.js'-import { basename, dirname as parentDir } from 'node:path'+import { basename } from 'node:path'import {bypassPermissionActive,permissionModeFromArgv,@@ -2808,10 +2810,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Session search: every turn of every conversation on this machine, live and stopped, indexed from// its transcript and searched by `session_search` (lib/sessionSearch/). Nothing leaves the machine// but the hits for a query. A Node without `node:sqlite` has no index; the RPC then says so.- // Claude Code and Codex conversations on this machine that Harness did not start, found on disk- // so Cmd-P can find them and open one here; and which sessions a process has open right now.- const externalSessions = new ExternalSessions({ claudeProjectsDir: env.CLAUDE_PROJECTS_DIR, codexHome: env.CODEX_HOME })- const openSessions = new OpenSessions({ claudeHome: parentDir(env.CLAUDE_PROJECTS_DIR) })+ // Conversations on this machine that Harness did not start, found where each engine keeps them so+ // Cmd-P can find them and open one here; and which sessions a process has open right now. Harness's+ // own byproducts (recaps run in its data folder) are never among them.+ const externalEngines = externalProviders()+ const externalSessions = new ExternalSessions({ providers: externalEngines, excluded: [env.ADAPTER_DATA_DIR], log: (line) => console.warn(line) })+ const openSessions = new OpenSessions({ providers: externalEngines, log: (line) => console.warn(line) })const sessionSearch = (() => {try {const store = SessionSearchStore.open(join(env.ADAPTER_DATA_DIR, SESSION_SEARCH_FILE))@@ -2841,10 +2845,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {const known = store.ownedSessionIds()for (const s of own) if (s.sessionId) known.add(s.sessionId)for (const e of externalSessions.list()) {- if (known.has(e.sessionId)) continue+ // A conversation Harness holds under any of its ids is Harness's.+ if (known.has(e.sessionId) || e.aliases?.some((id) => known.has(id)) || (!e.transcriptPath && !e.readHistory)) continuesources.push({agentId: '', sessionId: e.sessionId, engine: e.engine, transcriptPath: e.transcriptPath,header: '', changedAt: e.mtime, external: { cwd: e.cwd, origin: e.origin, title: e.title },+ ...(e.readHistory ? { readHistory: e.readHistory } : {}),})}return sources@@ -4986,11 +4992,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {* conversation resumes here. Asked without it, the refusal says whether that process is mid-turn,* so the person can choose to wait for the turn to end or stop it now. An app's is never stopped.*/- const adoptableSession = async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null): Promise<{ ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean } | { ok: false; error: string; detail: string }> => {- if (registry.bySession(sessionId) || stoppedAgents.list().some((s) => s.sessionId === sessionId)) {+ const adoptableSession = async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null): Promise<{ ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean; launchArgs: readonly string[] } | { ok: false; error: string; detail: string }> => {+ const held = (id: string) => !!registry.bySession(id) || stoppedAgents.list().some((s) => s.sessionId === id)+ if (held(sessionId)) {return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }}const found = externalSessions.get(sessionId) ?? (await externalSessions.scan(), externalSessions.get(sessionId))+ if (found && [found.sessionId, ...found.aliases ?? []].some(held)) {+ return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }+ }if (!found) return { ok: false, error: 'SESSION_NOT_FOUND', detail: 'This conversation is no longer on this machine.' }if (found.engine !== engine) return { ok: false, error: 'INVALID_ENGINE', detail: `This is a ${found.engine} conversation.` }// The Codex app keeps a thread in a folder of its own, which people tidy away. Checked before@@ -4999,20 +5009,28 @@ async function runForeground(session: AuthSession | null): Promise<void> {return { ok: false, error: 'SESSION_FOLDER_GONE', detail: `The folder it ran in is gone: ${found.cwd}` }}const title = found.title || sessionSearch?.session(sessionId)?.title || ''+ const launchArgs = found.launchArgs ?? []const owner = await openSessions.owner(sessionId)- if (!owner) return { ok: true, cwd: found.cwd, title, owner: null, busy: false }- const engineName = engine === 'claude' ? 'Claude Code' : 'Codex'+ if (!owner) return { ok: true, cwd: found.cwd, title, owner: null, busy: false, launchArgs }+ const engineName = engineLabel(engine)+ // A process in one of Harness's own panes is an agent the daemon is still binding: never stopped.+ if (owner.harness) return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }+ // Started on it, as its arguments say, and perhaps moved on since — or in a pane nobody could check+ // was not Harness's own: not opened twice, never stopped.+ if (owner.fromArgs || owner.unverified) {+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It may be open in ${engineName} in a terminal. Close it there, then open it here.` }+ }if (!owner.tty) {- return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It is open in the ${engine === 'claude' ? 'Claude' : 'Codex'} app. Close it there, then open it here.` }+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It is open in ${engineName}'s app or an editor. Close it there, then open it here.` }}- const busy = await sessionBusy(owner)+ const busy = await openSessions.busy(owner)if (busy && (takeOver === null || takeOver === 'idle')) {return { ok: false, error: 'SESSION_BUSY_IN_TERMINAL', detail: `${engineName} is working on it in a terminal.` }}if (takeOver === null) {return { ok: false, error: 'SESSION_OPEN_IN_TERMINAL', detail: `It is open in ${engineName} in a terminal. Moving it here quits it there.` }}- return { ok: true, cwd: found.cwd, title, owner, busy }+ return { ok: true, cwd: found.cwd, title, owner, busy, launchArgs }}/**@@ -5025,19 +5043,37 @@ async function runForeground(session: AuthSession | null): Promise<void> {for (;;) {await new Promise<void>((resolve) => { const timer = setTimeout(resolve, 1_000); timer.unref?.() })if (registry.byAgent(agentId)?.launch?.state !== 'starting' || !processAlive(owner.pid)) return- if (await sessionBusy(owner)) continue+ // Moved on in that terminal (`/resume`, `/new`): its turn is another conversation's now, and it+ // is left alone. The pane still waits for it to quit, and then opens this one.+ if (await heldBy(sessionId, owner) !== 'same') {+ console.log(`[agent] take over ${sid(sessionId)} · pid ${owner.pid} moved on · left running`)+ return+ }+ if (await openSessions.busy(owner)) continueconst stopped = await stopSessionOwner(owner)console.log(`[agent] take over ${sid(sessionId)} · turn ended · pid ${owner.pid} ${stopped ? 'stopped' : 'did not stop'}`)return}}+ /**+ * Who holds [sessionId] now, against the [owner] seen when the person chose: `same` (that process,+ * still a terminal's, by hard evidence, not one of Harness's own), `free` (nobody), or `other`.+ * Asked again right before anything is stopped: the terminal may have moved to other work since.+ */+ const heldBy = async (sessionId: string, owner: SessionOwner): Promise<'same' | 'free' | 'other'> => {+ const now = await openSessions.owner(sessionId)+ if (!now) return 'free'+ return now.pid === owner.pid && !!now.tty && !now.fromArgs && !now.harness && !now.unverified ? 'same' : 'other'+ }+backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }// A conversation Harness did not start opens in its own folder, under its own title — taken over// from the terminal that has it, when asked to.let owner: SessionOwner | null = nulllet ownerBusy = false+ let resumeArgs: readonly string[] = []if (resumeSessionId) {const adopted = await adoptableSession(resumeSessionId, engine, takeOver ?? null)if (!adopted.ok) return adopted@@ -5045,6 +5081,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {name = name ?? (adopted.title || null)owner = adopted.ownerownerBusy = adopted.busy+ resumeArgs = adopted.launchArgs}try {if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }@@ -5184,23 +5221,29 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was// checked for a contract at the wire (AGENT_UNSUPPORTED), so this cannot throw.- const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : [])]+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : []), ...resumeArgs]// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).- // The terminal's process goes last, once nothing else here can refuse the launch: stopped now, or- // — to wait for its turn — left running for the pane to wait on. Stopped mid-turn, the resumed- // conversation is told to carry on.+ // Stopped mid-turn, the resumed conversation is told to carry on — by an engine that can open+ // with a message; any other resumes where it stopped and waits.const waitFor = owner && takeOver === 'wait' && ownerBusy ? owner : null- if (owner && !waitFor) {- if (!await stopSessionOwner(owner)) {+ const firstPrompt = prompt ?? (owner && !waitFor && ownerBusy && supportsFirstPrompt(engine) ? 'continue' : null)+ const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), ...(waitFor ? { waitForPid: { pid: waitFor.pid, name: engineLabel(engine) } } : {}), terminalHint: { machineName: terminalHintMachineName() } }+ const command = buildEngineCommandArgv(engine, launchOptions)+ const argv = buildEngineLaunchArgv(engine, launchOptions)+ // The terminal's process goes last, once nothing here can refuse or fail the launch — the command+ // is built — stopped now, or, to wait for its turn, left running for the pane to wait on.+ if (owner && !waitFor && resumeSessionId) {+ const held = await heldBy(resumeSessionId, owner)+ if (held === 'other') {+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It moved to another process just now. Close it there, then open it here.' }+ }+ // Quit in its terminal meanwhile: it is free, and nothing is stopped.+ if (held === 'same' && !await stopSessionOwner(owner)) {return { ok: false, error: 'SESSION_STOP_FAILED', detail: 'The terminal that has it did not quit. Close it there, then open it here.' }}- console.log(`[agent] take over ${sid(resumeSessionId ?? '')} · pid ${owner.pid} stopped${ownerBusy ? ' mid-turn' : ''}`)+ if (held === 'same') console.log(`[agent] take over ${sid(resumeSessionId)} · pid ${owner.pid} stopped${ownerBusy ? ' mid-turn' : ''}`)}- const firstPrompt = prompt ?? (owner && !waitFor && ownerBusy ? 'continue' : null)- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), ...(waitFor ? { waitForPid: { pid: waitFor.pid, name: engine === 'claude' ? 'Claude Code' : 'Codex' } } : {}), terminalHint: { machineName: terminalHintMachineName() } }- const command = buildEngineCommandArgv(engine, launchOptions)- const argv = buildEngineLaunchArgv(engine, launchOptions)// A tmux route is enough to stream its screen. Register it before looking for a process so both// loopback and relayed Desktop clients can attach while the login shell/installer is still busy.// `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary, so adiff --git a/cli/src/engines/devin/errorLog.spec.ts b/cli/src/engines/devin/errorLog.spec.tsindex 465f9dbe2..45566d111 100644--- a/cli/src/engines/devin/errorLog.spec.ts+++ b/cli/src/engines/devin/errorLog.spec.ts@@ -90,6 +90,37 @@ describe('devin error log', () => {expect(tail.poll()).toHaveLength(1)})+ it('looks back over only the tail of a long log, reading nothing before it', () => {+ const { home, log } = devinHome()+ // A failure far back in a long-lived session's log: beyond the look-back window, so never seen.+ appendFileSync(log, REAL_ERROR.replace('2026-07-28T06:38:22', '2026-07-28T09:00:00') + '\n')+ const filler = `${NOISE}\n`.repeat(Math.ceil((2 * 1024 * 1024) / NOISE.length))+ appendFileSync(log, filler)+ const tail = new DevinErrorTail(home, 'tested-crabapple')+ expect(tail.scanSince('2026-07-28T08:00:00.000000Z')).toEqual([])+ appendFileSync(log, REAL_ERROR.replace('2026-07-28T06:38:22', '2026-07-28T09:30:00') + '\n')+ expect(tail.scanSince('2026-07-28T08:00:00.000000Z')).toEqual([+ "Permission denied: We're currently facing high demand for this model. Please try again later.",+ ])+ // Older than the turn being healed: an earlier turn's failure.+ expect(tail.scanSince('2026-07-28T10:00:00.000000Z')).toEqual([])+ expect(tail.scanSince('not a time')).toEqual([])++ // poll() reads what was appended, however long the log already is.+ tail.seekToEnd()+ appendFileSync(log, NOISE + '\n' + REAL_ERROR + '\n')+ expect(tail.poll()).toHaveLength(1)+ })++ it('finds nothing to scan without a lock, or once the log is gone', () => {+ const { home, log } = devinHome()+ expect(new DevinErrorTail(home, 'no-such-session').scanSince('2026-07-28T00:00:00Z')).toEqual([])+ const tail = new DevinErrorTail(home, 'tested-crabapple')+ tail.seekToEnd()+ rmSync(log)+ expect(tail.scanSince('2026-07-28T00:00:00Z')).toEqual([])+ })+it('collapses Devin\'s doubled prefix and drops the trace id', () => {expect(cleanDevinErrorMessage('Permission denied: Permission denied: Too busy. (trace ID: abc123)')).toBe('Permission denied: Too busy.')diff --git a/cli/src/engines/devin/errorLog.ts b/cli/src/engines/devin/errorLog.tsindex 144d21647..0e2d32ac0 100644--- a/cli/src/engines/devin/errorLog.ts+++ b/cli/src/engines/devin/errorLog.ts@@ -15,7 +15,7 @@* `session_locks/<id>.lock` holds the owning PID and the log is `logs/devin_<stamp>_<pid>.log`.*/-import { readdirSync, readFileSync, statSync } from 'fs'+import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'fs'import { join } from 'path'/** The ACP translator line Devin logs when a turn dies. WARN-level, but terminal for the turn. */@@ -48,6 +48,21 @@ export function devinLogPathForSession(devinHome: string, sessionId: string): streturn newest?.path ?? null}+/**+ * Bytes [start, end) of a file, read in place: a long-lived session's log grows without bound, and+ * this runs on the event loop (once a second while a take-over waits for the turn to end).+ */+function readRange(path: string, start: number, end: number): string {+ const fd = openSync(path, 'r')+ try {+ const buffer = Buffer.alloc(Math.max(0, end - start))+ const read = readSync(fd, buffer, 0, buffer.length, start)+ return buffer.subarray(0, read).toString('utf8')+ } finally {+ closeSync(fd)+ }+}+/** Strip Devin's doubled prefixes and the trace id so the web/device message stays readable. */export function cleanDevinErrorMessage(raw: string): string {let text = raw.trim().replace(/\s*\(trace ID:\s*[0-9a-f]+\)\s*$/i, '')@@ -90,9 +105,9 @@ export class DevinErrorTail {let text: stringtry {- const buffer = readFileSync(this.path)// Bounded look-back: a long-lived session's log can be large and only the tail can be relevant.- text = buffer.subarray(Math.max(0, buffer.length - SCAN_BACK_BYTES)).toString('utf8')+ const size = statSync(this.path).size+ text = readRange(this.path, Math.max(0, size - SCAN_BACK_BYTES), size)} catch { return [] }const out: string[] = []@@ -120,8 +135,7 @@ export class DevinErrorTail {let chunk: stringtry {- const fd = readFileSync(this.path)- chunk = fd.subarray(this.offset, size).toString('utf8')+ chunk = readRange(this.path, this.offset, size)} catch { return [] }this.offset = sizediff --git a/cli/src/engines/hermes/home.spec.ts b/cli/src/engines/hermes/home.spec.tsindex 72de91090..ae547ab3a 100644--- a/cli/src/engines/hermes/home.spec.ts+++ b/cli/src/engines/hermes/home.spec.ts@@ -76,6 +76,10 @@ d('hermes homes', () => {const homes = await listHermesHomes(root)expect(await findHermesHomeForSession(DEFAULT_SESSION, homes)).toBe(root)+ // An editor's (ACP) session is a uuid: its home is found the same way.+ const acp = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'+ execFileSync('sqlite3', [hermesDbPath(demo), `INSERT INTO sessions VALUES ('${acp}','acp',NULL);`])+ expect(await findHermesHomeForSession(acp, homes)).toBe(demo)// 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.diff --git a/cli/src/engines/hermes/home.ts b/cli/src/engines/hermes/home.tsindex 0304080c5..8543adde4 100644--- a/cli/src/engines/hermes/home.ts+++ b/cli/src/engines/hermes/home.ts@@ -27,9 +27,10 @@ import { isAbsolute, join } from 'node:path'import { env } from '../../config/env.js'import { sqliteReadAll } from '../../lib/sqliteRead.js'import type { AgentEngine } from '../types.js'+import { HERMES_HISTORY_ID_RE } from './reader.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}$/+/** `YYYYMMDD_HHMMSS_<hex>`, or an editor's (ACP) uuid — the shapes `reader.ts` reads history for. */+const SESSION_ID_RE = HERMES_HISTORY_ID_RE/** 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. */diff --git a/cli/src/engines/hermes/reader.spec.ts b/cli/src/engines/hermes/reader.spec.tsindex df7d8bfc3..a6faa8973 100644--- a/cli/src/engines/hermes/reader.spec.ts+++ b/cli/src/engines/hermes/reader.spec.ts@@ -55,6 +55,16 @@ d('HermesReader (sqlite3 CLI)', () => {expect(await readHermesMessages(db, "x'; DROP TABLE messages;--")).toEqual([])})+ it("reads an editor's (ACP) session, whose id is a uuid", async () => {+ const acp = '3f2a9c1e-8b4d-4e6f-9a1b-2c3d4e5f6a7b'+ run(db, `INSERT INTO messages (id, session_id, role, content, timestamp) VALUES (1, '${acp}', 'user', 'hi', 1)`)+ run(db, `INSERT INTO messages (id, session_id, role, content, finish_reason, timestamp) VALUES (2, '${acp}', 'assistant', 'hello', 'stop', 2)`)+ expect((await readHermesMessages(db, acp)).map((r) => r.role)).toEqual(['user', 'assistant'])+ // Uuid-shaped with a tail is not an id: refused, rows or not.+ run(db, `INSERT INTO messages (id, session_id, role, content, timestamp) VALUES (3, '${acp}-0', 'user', 'x', 3)`)+ expect(await readHermesMessages(db, `${acp}-0`)).toEqual([])+ })+it('hydrates silently, then streams a new turn incrementally', async () => {insert(db, { id: 1, role: 'user', content: 'old' })insert(db, { id: 2, role: 'assistant', content: 'done', finishReason: 'stop' })diff --git a/cli/src/engines/hermes/reader.ts b/cli/src/engines/hermes/reader.tsindex 9a9ff4b13..a7f969098 100644--- a/cli/src/engines/hermes/reader.ts+++ b/cli/src/engines/hermes/reader.ts@@ -20,6 +20,14 @@ import {// `YYYYMMDD_HHMMSS_<hex>` — CLI/TUI use 6 hex chars, the gateway 8.const SESSION_ID_RE = /^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/+/**+ * Every id a Hermes store keeps a conversation under: the ones above, and an editor's. The ACP adapter+ * names its sessions with a uuid4 (`acp_adapter/session.py`; all six ACP rows on the machine measured+ * were uuids), so their history is readable too. `hermesSessionSource` keeps the narrower shape: it+ * decides whether a hook's session is a pane's own, and editors' sessions never are.+ */+export const HERMES_HISTORY_ID_RE =+ /^(?:[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/const POLL_MS = 1_000const MAX_BUFFER = 32 * 1024 * 1024@@ -43,7 +51,7 @@ export async function readHermesMessages(sessionId: string,afterId?: number | null,): Promise<HmMessage[]> {- if (!SESSION_ID_RE.test(sessionId)) return []+ if (!HERMES_HISTORY_ID_RE.test(sessionId)) return []const bounded = Number.isFinite(afterId as number) && (afterId as number) > 0const sql = `SELECT ${COLUMNS} FROM messages WHERE session_id = ?${bounded ? ' AND id > ?' : ''} ORDER BY id;`const params = bounded ? [sessionId, Math.trunc(afterId as number)] : [sessionId]diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex e080482da..843d03970 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -441,16 +441,15 @@ describe('buildEngineLaunchArgv', () => {.toEqual([engineBin('claude'), '--permission-mode', 'auto'])})- it('is a no-op when resumeSessionId is set but the engine has no known launch resume flag', () => {- expect(buildEngineCommandArgv('devin', { resumeSessionId: 'abc-123' })).toEqual([engineBin('devin')])+ it('resumes devin by its session slug (docs.devin.ai/cli, since 2026.4.17)', () => {+ expect(buildEngineCommandArgv('devin', { resumeSessionId: 'brisk-otter' })).toEqual([engineBin('devin'), '--resume', 'brisk-otter'])})it('has a launch resume flag for every engine RESUME_ARGS also covers, plus claude/codex', () => {for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'kilo', 'pi', 'hermes', 'commandcode',- 'muse', 'amp', 'grok', 'agy', 'copilot'] as const) {+ 'muse', 'amp', 'grok', 'agy', 'copilot', 'devin'] as const) {expect(LAUNCH_RESUME_FLAG[engine]?.length).toBeGreaterThan(0)}- expect(LAUNCH_RESUME_FLAG.devin).toBeUndefined()})})diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 72db30249..a344b107e 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -293,8 +293,8 @@ export interface LaunchCommandOptions {** A leading token that does NOT start with `-` is a SUBCOMMAND (`resume`, `threads continue`) and must* be the first argv after the binary, ahead of any other flag — `buildEngineCommandArgv` branches on- * this. `devin` has no known resume flag at all (not even for `RESUME_ARGS` parsing) and is- * deliberately omitted, so no resume is ever attempted for it.+ * this. `devin --resume <id>` is documented since Devin CLI 2026.4.17 (docs.devin.ai/cli, "Essential+ * commands"); it must run in the session's own folder, or Devin asks which folder to use.*/export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>> = {claude: ['--resume'],@@ -310,6 +310,7 @@ export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>grok: ['--resume'],agy: ['--conversation'],copilot: ['--resume'],+ devin: ['--resume'],}/**diff --git a/cli/src/lib/resumeCapability.spec.ts b/cli/src/lib/resumeCapability.spec.tsindex 438ebd298..6cd8896a7 100644--- a/cli/src/lib/resumeCapability.spec.ts+++ b/cli/src/lib/resumeCapability.spec.ts@@ -13,10 +13,9 @@ describe('what a paused harness can promise, per engine', () => {}})- it('names the shell and the one engine with no resume argv', () => {+ it('names the shell, and every agent engine resumes its conversation', () => {expect(resumeMode('terminal')).toBe('shell')- // devin is deliberately absent from LAUNCH_RESUME_FLAG — no confirmed flag exists.- expect(resumeMode('devin')).toBe('fresh')+ expect(resumeMode('devin')).toBe('conversation')expect(resumeMode('claude')).toBe('conversation')expect(resumeMode('opencode')).toBe('conversation')})@@ -25,8 +24,8 @@ describe('what a paused harness can promise, per engine', () => {expect(resumesConversation('claude', 'abc')).toBe(true)expect(resumesConversation('claude', '')).toBe(false)expect(resumesConversation('claude', null)).toBe(false)- // A recorded id cannot help an engine that has no way to reopen it.- expect(resumesConversation('devin', 'abc')).toBe(false)+ // A recorded id cannot help a shell, which has no conversation to reopen.+ expect(resumesConversation('devin', 'brisk-otter')).toBe(true)expect(resumesConversation('terminal', 'abc')).toBe(false)})diff --git a/cli/src/lib/resumeStoppedAgent.spec.ts b/cli/src/lib/resumeStoppedAgent.spec.tsindex 345ab2b4c..74d067bbf 100644--- a/cli/src/lib/resumeStoppedAgent.spec.ts+++ b/cli/src/lib/resumeStoppedAgent.spec.ts@@ -34,10 +34,10 @@ describe('Enter resumes stopped work', () => {})it.each([- // No id recorded to reopen, and an engine with no resume argv at all: both still come back —- // same pane, same folder — as a new conversation, launched without a resume id.+ // No id recorded to reopen: it still comes back — same pane, same folder — as a new+ // conversation, launched without a resume id. (Every agent engine can resume one now.){ ...saved, sessionId: '' },- { ...saved, engine: 'devin' as const },+ { ...saved, engine: 'devin' as const, sessionId: '' },])('resumes without a conversation rather than refusing the harness', async entry => {const deps = fixture()deps.saved.mockReturnValue(entry)@@ -198,11 +198,11 @@ describe('exact conversation readiness', () => {})it('says a resume with no conversation to reopen is a fresh one', async () => {- // devin hooks at launch like the rest, so it is confirmed the strict way — but it has no resume- // argv, so what came back is a new conversation and `resumed` says so rather than lying.+ // devin hooks at launch like the rest, so it is confirmed the strict way — but with no id recorded+ // there was nothing to reopen, so what came back is a new conversation and `resumed` says so.const deps = readiness('devin')- deps.set({ lastHookAt: 100, launch: { state: 'ready' } })- await expect(waitForResumedAgent({ ...saved, engine: 'devin' as const }, deps))+ deps.set({ lastHookAt: 100, launch: { state: 'ready' }, sessionId: '' })+ await expect(waitForResumedAgent({ ...saved, engine: 'devin' as const, sessionId: '' }, deps)).resolves.toMatchObject({ ok: true, resumed: false })})diff --git a/cli/src/lib/sessionSearch/external.spec.ts b/cli/src/lib/sessionSearch/external.spec.tsindex 00c346012..1a842106f 100644--- a/cli/src/lib/sessionSearch/external.spec.ts+++ b/cli/src/lib/sessionSearch/external.spec.ts@@ -1,165 +1,204 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'-import { ExternalSessions, OpenSessions, readClaudeHead, readCodexHead, sessionBusy, stopSessionOwner } from './external.js'+import { ExternalSessions, foregroundJob, OpenSessions, stopSessionOwner, TERMINAL_RESTORE, writeTty } from './external.js'+import type { ExternalEngine, ExternalProvider, ExternalSession, OwnerClaim, ProcessView } from './externals/types.js'const dirs: string[] = []afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })-function home(): string {- const dir = mkdtempSync(join(tmpdir(), 'external-sessions-'))- dirs.push(dir)- return dir-}-function write(path: string, lines: unknown[]): string {- mkdirSync(join(path, '..'), { recursive: true })- writeFileSync(path, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + '\n')- return path-}--const claudeLine = (sessionId: string, entrypoint: string, extra: Record<string, unknown> = {}) => ({- type: 'user', sessionId, cwd: '/work/dial', entrypoint, timestamp: '2026-09-20T10:00:00Z',- message: { role: 'user', content: 'fix the dial scroll' }, ...extra,-})-const codexMeta = (id: string, source: unknown, originator = 'codex-tui') => ({- timestamp: '2026-09-20T10:00:00Z', type: 'session_meta',- payload: { id, cwd: '/work/cohorts', originator, source, timestamp: '2026-09-20T10:00:00Z', base_instructions: 'x'.repeat(40_000) },-})-const A = '11111111-1111-4111-8111-111111111111'-const B = '22222222-2222-4222-8222-222222222222'-const C = '01a0c4ad-de5e-7000-8000-000000000001'-const D = '01a0c4ad-de5e-7000-8000-000000000002'--describe('what counts as a conversation a person started', () => {- it('reads Claude Code: a terminal or the Claude app, not a program or a sub-agent', async () => {- const dir = home()- const file = (name: string, lines: unknown[]) => write(join(dir, `${name}.jsonl`), lines)- // The first lines may carry no entrypoint: a title, a mode.- expect(await readClaudeHead(file('t', [{ type: 'permission-mode', permissionMode: 'auto' }, claudeLine(A, 'cli')])))- .toEqual({ sessionId: A, engine: 'claude', cwd: '/work/dial', origin: 'terminal' })- expect(await readClaudeHead(file('d', [claudeLine(A, 'claude-desktop')]))).toMatchObject({ origin: 'claude-app' })- expect(await readClaudeHead(file('s', [claudeLine(A, 'sdk-cli')]))).toBeNull()- expect(await readClaudeHead(file('x', [claudeLine(A, 'cli', { isSidechain: true })]))).toBeNull()- expect(await readClaudeHead(file('r', [claudeLine(A, 'cli', { cwd: 'relative/path' })]))).toBeNull()- expect(await readClaudeHead(file('e', [{ type: 'summary', summary: 'nothing else' }]))).toBeNull()- })- it('reads Codex: the terminal, the Codex app and the editors, not scripts or sub-agent threads', async () => {- const dir = home()- const file = (name: string, meta: unknown) => write(join(dir, `${name}.jsonl`), [meta, { type: 'event_msg', payload: {} }])- expect(await readCodexHead(file('cli', codexMeta(C, 'cli'))))- .toEqual({ sessionId: C, engine: 'codex', cwd: '/work/cohorts', origin: 'terminal' })- expect(await readCodexHead(file('app', codexMeta(C, 'vscode', 'Codex Desktop')))).toMatchObject({ origin: 'codex-app' })- expect(await readCodexHead(file('ide', codexMeta(C, 'vscode', 'codex_vscode')))).toMatchObject({ origin: 'editor' })- expect(await readCodexHead(file('exec', codexMeta(C, 'exec', 'codex_exec')))).toBeNull()- expect(await readCodexHead(file('sub', codexMeta(C, { subagent: { other: 'guardian' } })))).toBeNull()- })+const session = (sessionId: string, engine: ExternalEngine, mtime: number, extra: Partial<ExternalSession> = {}): ExternalSession => ({+ sessionId, engine, cwd: `/work/${sessionId}`, origin: 'terminal', title: '', mtime, transcriptPath: `/t/${sessionId}.jsonl`, ...extra,})describe('ExternalSessions', () => {- it("finds both engines' conversations, titles Codex's, skips sub-agents, and forgets deleted files", async () => {- const root = home()- const claude = join(root, '.claude', 'projects')- const codex = join(root, '.codex')- write(join(claude, '-work-dial', `${A}.jsonl`), [claudeLine(A, 'cli')])- write(join(claude, '-work-dial', `${B}.jsonl`), [claudeLine(B, 'sdk-cli')])- write(join(claude, '-work-dial', A, 'subagents', 'agent-1.jsonl'), [claudeLine(A, 'cli')])- write(join(codex, 'sessions', '2026', '09', '20', `rollout-2026-09-20T10-00-00-${C}.jsonl`), [codexMeta(C, 'cli')])- const archived = write(join(codex, 'archived_sessions', `rollout-2026-09-19T10-00-00-${D}.jsonl`), [codexMeta(D, 'vscode', 'Codex Desktop')])- write(join(codex, 'session_index.jsonl'), [- { id: C, thread_name: 'Old name', updated_at: '2026-09-20T10:00:00Z' },- { id: C, thread_name: 'Retention cohorts', updated_at: '2026-09-21T10:00:00Z' },- 'half a line',- ])- const sessions = new ExternalSessions({ claudeProjectsDir: claude, codexHome: codex })+ it("joins every engine's list, newest first, one entry per id, and keeps an engine's last list when it fails", async () => {+ let grokFails = false+ let cwdSeen: boolean | null = null+ const providers: ExternalProvider[] = [+ { engine: 'claude', scan: async (ctx) => { cwdSeen = ctx.excluded('/data/harness/x'); return [session('a', 'claude', 3), session('dup', 'claude', 1)] } },+ { engine: 'grok', scan: async () => { if (grokFails) throw new Error('store locked'); return [session('g', 'grok', 5), session('dup', 'grok', 2)] } },+ { engine: 'pi', scan: async () => { throw 'not an error object' } },+ ]+ const log: string[] = []+ const sessions = new ExternalSessions({ providers, excluded: ['/data/harness'], log: (line) => log.push(line) })+ expect(sessions.list()).toEqual([])const found = await sessions.scan()- expect(found.map((s) => [s.sessionId, s.engine, s.origin, s.title]).sort()).toEqual([- [C, 'codex', 'terminal', 'Retention cohorts'],- [D, 'codex', 'codex-app', ''],- [A, 'claude', 'terminal', ''],- ].sort())- expect(sessions.get(C)).toMatchObject({ cwd: '/work/cohorts', transcriptPath: expect.stringContaining(C) })-- rmSync(archived)+ expect(found.map((s) => s.sessionId)).toEqual(['g', 'a', 'dup'])+ expect(sessions.get('dup')?.engine).toBe('grok')+ expect(sessions.get('none')).toBeUndefined()+ expect(cwdSeen).toBe(true)+ expect(log).toEqual(['[search] pi sessions not read: not an error object'])++ grokFails = true+ expect((await sessions.scan()).map((s) => s.sessionId)).toEqual(['g', 'a', 'dup'])+ expect(log).toContain('[search] grok sessions not read: store locked')+ })++ it('finds a conversation by an older id it carried on from, never over another conversation', async () => {+ const sessions = new ExternalSessions({ providers: [+ { engine: 'hermes', scan: async () => [+ session('tip', 'hermes', 5, { aliases: ['root', 'taken'] }),+ session('taken', 'hermes', 1),+ ] },+ ] })await sessions.scan()- expect(sessions.get(D)).toBeUndefined()- expect(sessions.list()).toHaveLength(2)+ expect(sessions.get('root')?.sessionId).toBe('tip')+ expect(sessions.get('taken')?.sessionId).toBe('taken')})- it('shares one scan between callers, and finds nothing where nothing is', async () => {- const root = home()- const sessions = new ExternalSessions({ claudeProjectsDir: join(root, 'none'), codexHome: join(root, 'none') })+ it('shares one scan between callers, and finds nothing with no engines', async () => {+ const sessions = new ExternalSessions({ providers: [] })const [a, b] = [sessions.scan(), sessions.scan()]expect(a).toBe(b)expect(await a).toEqual([])})})-describe('OpenSessions', () => {- const rollout = (id: string) => `/h/.codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-${id}.jsonl`+const quiet: ProcessView = { list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }- it('knows Claude sessions from their live process records, Codex ones from open rollouts, and which are in a terminal', async () => {- const root = home()- write(join(root, 'sessions', '101.json'), [{ pid: 101, sessionId: A }])- write(join(root, 'sessions', '102.json'), [{ pid: 102, sessionId: B }])- write(join(root, 'sessions', '103.json'), ['{ being written'])+describe('OpenSessions', () => {+ function open(providers: ExternalProvider[], extra: Partial<ConstructorParameters<typeof OpenSessions>[0]> = {}) {let now = 1_000- let reads = 0- const open = new OpenSessions({- claudeHome: root,- alive: (pid) => pid === 101,- openRollouts: async () => { reads++; return [{ pid: 201, path: rollout(C) }] },- ttys: async (pids) => new Map(pids.map((pid) => [pid, pid === 101 ? '/dev/ttys003' : null])),+ let looks = 0+ const sessions = new OpenSessions({+ providers,+ view: () => { looks++; return quiet },+ ttys: async (pids) => new Map(pids.map((pid) => [pid, pid === 7 ? null : pid === 9 ? '/dev/ttys009' : `/dev/ttys00${pid}`])),+ harnessTtys: async () => new Set(['/dev/ttys009']),now: () => now,maxAgeMs: 5_000,+ ...extra,})- expect(open.known().size).toBe(0)- const ids = await open.fresh()- expect([...ids].sort()).toEqual([[A, 'terminal'], [C, 'app']].sort())- expect(reads).toBe(1)- now += 1_000- await open.fresh()- expect(reads).toBe(1)- now += 10_000- await open.fresh()- expect(reads).toBe(2)- expect(open.known().get(C)).toBe('app')- // Who has one is looked at now, not taken from the last answer.- expect(await open.owner(A)).toEqual({ pid: 101, engine: 'claude', tty: '/dev/ttys003', record: join(root, 'sessions', '101.json') })- expect(reads).toBe(3)- expect(await open.owner(B)).toBeNull()+ return { sessions, tick: (ms: number) => { now += ms }, looks: () => looks }+ }++ it("says where each open session is: a terminal, an app, or one of Harness's own panes", async () => {+ const claims: OwnerClaim[] = [+ { sessionId: 'term', pid: 1, record: '/r/term' },+ { sessionId: 'notty', pid: 7, record: '/r/notty' },+ { sessionId: 'leader', pid: 2, record: '/r/leader', app: true },+ { sessionId: 'mine', pid: 9, record: '/r/mine' },+ ]+ const { sessions } = open([+ { engine: 'grok', scan: async () => [], owners: async () => claims },+ { engine: 'pi', scan: async () => [] },+ ])+ expect(sessions.known().size).toBe(0)+ expect(Object.fromEntries(await sessions.fresh())).toEqual({ term: 'terminal', notty: 'app', leader: 'app', mine: 'harness' })+ expect(await sessions.owner('term')).toEqual({ pid: 1, engine: 'grok', tty: '/dev/ttys001', record: '/r/term' })+ expect(await sessions.owner('leader')).toMatchObject({ tty: null })+ expect(await sessions.owner('mine')).toMatchObject({ harness: true })+ expect(await sessions.owner('none')).toBeNull()+ })++ it("calls one only its arguments name 'maybe', and lets harder evidence of the same session win", async () => {+ const { sessions } = open([+ { engine: 'opencode', scan: async () => [], owners: async () => [+ { sessionId: 'guess', pid: 1, record: '/r/1', fromArgs: true },+ { sessionId: 'both', pid: 2, record: '/r/argv', fromArgs: true },+ { sessionId: 'both', pid: 3, record: '/r/lock' },+ { sessionId: 'lockfirst', pid: 4, record: '/r/lock' },+ { sessionId: 'lockfirst', pid: 5, record: '/r/argv', fromArgs: true },+ { sessionId: 'twice', pid: 6, record: '/r/a' },+ { sessionId: 'twice', pid: 1, record: '/r/b' },+ ] },+ ])+ expect(Object.fromEntries(await sessions.fresh())).toMatchObject({ guess: 'maybe', both: 'terminal', lockfirst: 'terminal', twice: 'terminal' })+ expect(await sessions.owner('guess')).toMatchObject({ pid: 1, fromArgs: true })+ expect((await sessions.owner('both'))?.pid).toBe(3)+ expect((await sessions.owner('lockfirst'))?.pid).toBe(4)+ expect((await sessions.owner('twice'))?.pid).toBe(6)+ })++ it('reuses an answer for a while, looks again after, and looks now when asked who owns one', async () => {+ const { sessions, tick, looks } = open([{ engine: 'claude', scan: async () => [], owners: async () => [{ sessionId: 'a', pid: 1, record: '/r' }] }])+ await sessions.fresh()+ tick(1_000)+ await sessions.fresh()+ expect(looks()).toBe(1)+ expect(sessions.known().get('a')).toBe('terminal')+ tick(10_000)+ sessions.known()+ await sessions.fresh()+ expect(looks()).toBe(2)+ await sessions.owner('a')+ expect(looks()).toBe(3)+ // While a look is under way, a second caller shares it rather than starting another.+ const [x, y] = [sessions.owner('a'), sessions.owner('a')]+ await Promise.all([x, y])+ expect(looks()).toBe(4)})-})-describe('sessionBusy', () => {- it("reads Claude Code's record, and where the last Codex turn in the rollout stands", async () => {- const dir = home()- const claude = (status: string) => ({ engine: 'claude' as const, record: write(join(dir, `${status}.json`), [{ pid: 1, sessionId: A, status }]) })- expect(await sessionBusy(claude('idle'))).toBe(false)- expect(await sessionBusy(claude('busy'))).toBe(true)- expect(await sessionBusy({ engine: 'claude', record: join(dir, 'gone.json') })).toBe(false)-- const event = (type: string) => ({ type: 'event_msg', payload: { type } })- const codex = (name: string, lines: unknown[]) => ({ engine: 'codex' as const, record: write(join(dir, `${name}.jsonl`), [codexMeta(C, 'cli'), ...lines]) })- // What was said can name the events; only the events count.- const talk = { type: 'response_item', payload: { type: 'message', content: [{ text: 'then "task_complete" arrives' }] } }- expect(await sessionBusy(codex('ended', [event('task_started'), talk, event('task_complete'), talk]))).toBe(false)- expect(await sessionBusy(codex('aborted', [event('task_started'), event('turn_aborted')]))).toBe(false)- expect(await sessionBusy(codex('working', [event('task_complete'), event('task_started'), talk]))).toBe(true)- expect(await sessionBusy(codex('unsaid', []))).toBe(true)+ it("carries on when one engine cannot say, and asks nothing more when none has anything open", async () => {+ const log: string[] = []+ let asked = 0+ const { sessions } = open([+ { engine: 'codex', scan: async () => [], owners: async () => { throw new Error('lsof failed') } },+ { engine: 'devin', scan: async () => [], owners: async () => { throw 'odd' } },+ { engine: 'grok', scan: async () => [], owners: async () => [] },+ ], { log: (line) => log.push(line), ttys: async () => { asked++; return new Map() } })+ expect((await sessions.fresh()).size).toBe(0)+ expect(asked).toBe(0)+ expect(log).toEqual(['[search] codex owners not read: lsof failed', '[search] devin owners not read: odd'])+ })++ it("calls a terminal's session 'maybe' when Harness's own panes could not be listed", async () => {+ const { sessions } = open([{ engine: 'claude', scan: async () => [], owners: async () => [{ sessionId: 'a', pid: 1, record: '/r' }] }], {+ harnessTtys: async () => null,+ })+ expect((await sessions.fresh()).get('a')).toBe('maybe')+ expect(await sessions.owner('a')).toMatchObject({ tty: '/dev/ttys001', unverified: true })+ })++ it('reads no terminal and no Harness pane when those lookups fail', async () => {+ const { sessions } = open([{ engine: 'claude', scan: async () => [], owners: async () => [{ sessionId: 'a', pid: 1, record: '/r' }] }], {+ ttys: async () => { throw new Error('ps failed') },+ harnessTtys: async () => { throw new Error('tmux failed') },+ })+ expect(await sessions.owner('a')).toEqual({ pid: 1, engine: 'claude', tty: null, record: '/r' })+ })++ it("asks the owner's engine whether it is mid-turn, and counts not knowing as busy", async () => {+ const { sessions } = open([+ { engine: 'claude', scan: async () => [], busy: async (owner) => owner.pid === 1 },+ { engine: 'grok', scan: async () => [], busy: async () => null },+ { engine: 'codex', scan: async () => [], busy: async () => { throw new Error('unreadable') } },+ { engine: 'pi', scan: async () => [] },+ ])+ expect(await sessions.busy({ engine: 'claude', pid: 1, record: '' })).toBe(true)+ expect(await sessions.busy({ engine: 'claude', pid: 2, record: '' })).toBe(false)+ expect(await sessions.busy({ engine: 'grok', pid: 1, record: '' })).toBe(true)+ expect(await sessions.busy({ engine: 'codex', pid: 1, record: '' })).toBe(true)+ expect(await sessions.busy({ engine: 'pi', pid: 1, record: '' })).toBe(true)+ expect(await sessions.busy({ engine: 'muse', pid: 1, record: '' })).toBe(true)+ })++ it('looks at the real machine by default, and finds nothing open for engines with no owners', async () => {+ const sessions = new OpenSessions({ providers: [{ engine: 'pi', scan: async () => [], owners: async (view) => {+ const me = (await view.list()).find((row) => row.pid === process.pid)+ return me ? [{ sessionId: 'me', pid: me.pid, record: '' }] : []+ } }] })+ const owner = await sessions.owner('me')+ expect(owner?.pid).toBe(process.pid)+ // The default clock and reuse window: a second ask within five seconds is the same answer.+ expect(sessions.known().get('me')).toBeDefined()+ expect(await sessions.fresh()).toBe(await sessions.fresh())})})describe('stopSessionOwner', () => {- it('asks it to quit, makes it after five seconds, and gives the terminal its cursor back', async () => {+ it('asks it to quit, makes it after five seconds, and gives the terminal back', async () => {const signals: string[] = []const written: string[] = []let living = truelet slept = 0const opts = {alive: () => living,+ job: async () => null,kill: (_pid: number, signal: NodeJS.Signals) => { signals.push(signal); if (signal === 'SIGTERM' && slept === 0) return; living = false },sleep: async (ms: number) => { slept += ms },writeTty: async (tty: string, text: string) => { written.push(`${tty} ${JSON.stringify(text)}`) },@@ -167,12 +206,55 @@ describe('stopSessionOwner', () => {expect(await stopSessionOwner({ pid: 7, tty: '/dev/ttys009' }, opts)).toBe(true)expect(signals).toEqual(['SIGTERM', 'SIGKILL'])expect(slept).toBe(5_000)- expect(written).toEqual(['/dev/ttys009 "\\u001b[?25h"'])+ expect(written).toEqual([`/dev/ttys009 ${JSON.stringify(TERMINAL_RESTORE)}`])// One that quits when asked is not made to; one that will not quit at all is reported.signals.length = 0; living = true; slept = 1expect(await stopSessionOwner({ pid: 7, tty: null }, opts)).toBe(true)expect(signals).toEqual(['SIGTERM'])- expect(await stopSessionOwner({ pid: 8, tty: null }, { ...opts, alive: () => true, kill: () => undefined })).toBe(false)+ expect(await stopSessionOwner({ pid: 8, tty: null }, { ...opts, alive: () => true, kill: () => { throw new Error('EPERM') } })).toBe(false)+ // A terminal that cannot be written to is left as it is.+ living = true; slept = 1+ expect(await stopSessionOwner({ pid: 7, tty: '/dev/gone' }, { ...opts, writeTty: async () => { throw new Error('ENOENT') } })).toBe(true)+ })++ it("signals the whole foreground job an engine leads, and only the engine otherwise", async () => {+ const targets: number[] = []+ let living = true+ const opts = { alive: () => living, sleep: async () => undefined, kill: (pid: number) => { targets.push(pid); living = false } }+ expect(await stopSessionOwner({ pid: 40, tty: null }, { ...opts, job: async () => 40 })).toBe(true)+ living = true+ expect(await stopSessionOwner({ pid: 41, tty: null }, { ...opts, job: async () => { throw new Error('ps failed') } })).toBe(true)+ expect(targets).toEqual([-40, 41])+ // Leading its group, and that group in front: the job. Anything else: none.+ const ps = (out: string | null) => async () => out+ expect(await foregroundJob(40, ps(' 40 40\n'))).toBe(40)+ expect(await foregroundJob(40, ps(' 12 40\n'))).toBeNull()+ expect(await foregroundJob(40, ps(' 40 -1\n'))).toBeNull()+ expect(await foregroundJob(40, ps(null))).toBeNull()+ // This process leads no foreground job of a terminal.+ expect(await foregroundJob(process.pid)).toBeNull()+ })++ it('stops a real process, and writes the terminal back to a real file', async () => {+ const { spawn } = await import('node:child_process')+ const child = spawn('sleep', ['30'], { stdio: 'ignore' })+ const exited = new Promise((resolve) => child.on('exit', resolve))+ const dir = mkdtempSync(join(tmpdir(), 'external-stop-'))+ dirs.push(dir)+ const tty = join(dir, 'tty')+ writeFileSync(tty, '')+ // The child is ours, so it lingers as a zombie until reaped: count it gone once it has exited.+ let done = false+ void exited.then(() => { done = true })+ expect(await stopSessionOwner({ pid: child.pid!, tty }, { alive: () => !done })).toBe(true)+ expect(readFileSync(tty, 'utf8')).toBe(TERMINAL_RESTORE)+ await expect(writeTty(join(dir, 'missing', 'tty'), 'x')).rejects.toThrow()+ })++ it("stops a process that is not this one's child, as a terminal's never is", async () => {+ const { execFileSync } = await import('node:child_process')+ const pid = Number(execFileSync('/bin/sh', ['-c', 'sleep 30 >/dev/null 2>&1 & echo $!']).toString().trim())+ expect(await stopSessionOwner({ pid, tty: null })).toBe(true)})})diff --git a/cli/src/lib/sessionSearch/external.ts b/cli/src/lib/sessionSearch/external.tsindex 3681f8a1d..c1a3d3c13 100644--- a/cli/src/lib/sessionSearch/external.ts+++ b/cli/src/lib/sessionSearch/external.ts@@ -1,58 +1,39 @@/**- * Conversations on this machine that Harness did not start: Claude Code and Codex sessions run in a- * terminal or in their own desktop apps. Found where each engine keeps them, so Cmd-P can find them- * and open one in Harness (`agent_create` with `resumeSessionId`).+ * Conversations on this machine that Harness did not start: sessions people ran in a terminal, an+ * editor or an engine's app. Found where each engine keeps them, so Cmd-P and the welcome page can+ * find them and open one in Harness (`agent_create` with `resumeSessionId`), taking it over from a+ * terminal that still has it.*- * Only what a person started, told apart by what each engine records at the top of the file:- * - Claude Code's `entrypoint`: `cli` (a terminal) or `claude-desktop` (the Claude app). `sdk-cli`- * is a program driving Claude — Harness's own summaries among them — and a sub-agent's file lives- * in a folder of its own.- * - Codex's `source`: `cli` (a terminal) or `vscode` (the Codex app, which says so in `originator`,- * and the editor extensions). `exec` is a script and a `subagent` source is another thread's helper.- *- * A file's first lines never change, so each file is read once, however often it is scanned.+ * Each engine is a provider (`externals/<engine>.ts`): how it lists its conversations, which process+ * has one open, and whether that process is mid-turn. This file joins them: one list, one look at+ * the machine's processes, and one way to stop a terminal's process.*/-import { execFile } from 'node:child_process'-import { open, readdir, readFile, stat } from 'node:fs/promises'-import { join } from 'node:path'--export type ExternalOrigin = 'terminal' | 'claude-app' | 'codex-app' | 'editor'-export type ExternalEngine = 'claude' | 'codex'--export interface ExternalSession {- sessionId: string- engine: ExternalEngine- transcriptPath: string- /** The folder it ran in, and so the folder it resumes in. */- cwd: string- origin: ExternalOrigin- /** Codex's thread name (`session_index.jsonl`); Claude's comes from the transcript as it is indexed. */- title: string- /** When the file last changed, epoch ms. */- mtime: number-}+import { open } from 'node:fs/promises'-type Head = Pick<ExternalSession, 'sessionId' | 'engine' | 'cwd' | 'origin'>+import { harnessTtys as readHarnessTtys, processAlive, processTtys, processView, run, scanMemo } from './externals/support.js'+import type { ExternalEngine, ExternalProvider, ExternalSession, OwnerClaim, ProcessView } from './externals/types.js'-/** How much of a file is read to classify it: a Claude file's first lines, a Codex file's first line. */-const CLAUDE_HEAD_BYTES = 256 * 1024-const CODEX_HEAD_BYTES = 1024 * 1024-const SESSION_ID = /^[A-Za-z0-9-]{8,80}$/+export type { ExternalEngine, ExternalOrigin, ExternalProvider, ExternalSession } from './externals/types.js'+export { processAlive } from './externals/support.js'export interface ExternalSessionsOptions {- claudeProjectsDir: string- codexHome: string+ providers: readonly ExternalProvider[]+ /** Folders whose sessions are Harness's own byproducts (its data folder): never offered. */+ excluded?: readonly string[]+ log?: (line: string) => void}export class ExternalSessions {- /** A verdict per file: its head, or null for a file that is not a person's conversation. */- private readonly heads = new Map<string, Head | null>()private found: ExternalSession[] = []private byId = new Map<string, ExternalSession>()+ private readonly lastGood = new Map<ExternalEngine, ExternalSession[]>()private scanning: Promise<ExternalSession[]> | null = null+ private readonly memo- constructor(private readonly opts: ExternalSessionsOptions) {}+ constructor(private readonly opts: ExternalSessionsOptions) {+ this.memo = scanMemo({ excluded: opts.excluded ?? [] })+ }/** What the last scan found, newest first. */list(): readonly ExternalSession[] { return this.found }@@ -66,126 +47,40 @@ export class ExternalSessions {}private async scanOnce(): Promise<ExternalSession[]> {- const found: ExternalSession[] = []- const seen = new Set<string>()- const consider = async (path: string, read: (path: string) => Promise<Head | null>, title = (_id: string) => '') => {- seen.add(path)- const file = await stat(path).catch(() => null)- if (!file?.isFile()) return- let head = this.heads.get(path)- if (head === undefined) {- head = await read(path).catch(() => null)- this.heads.set(path, head)- }- if (head) found.push({ ...head, transcriptPath: path, title: title(head.sessionId), mtime: Math.floor(file.mtimeMs) })- // A first scan reads a thousand files: let the daemon breathe between them.- if (seen.size % 64 === 0) await new Promise<void>((resolve) => setImmediate(resolve))- }-- for (const project of await entries(this.opts.claudeProjectsDir)) {- if (!project.isDirectory()) continue- const folder = join(this.opts.claudeProjectsDir, project.name)- // Only the project's own files: a sub-agent's are in a folder beneath it.- for (const file of await entries(folder)) {- if (file.isFile() && file.name.endsWith('.jsonl')) await consider(join(folder, file.name), readClaudeHead)+ const ctx = this.memo.context()+ const all: ExternalSession[] = []+ for (const provider of this.opts.providers) {+ try {+ const sessions = await provider.scan(ctx)+ this.lastGood.set(provider.engine, sessions)+ all.push(...sessions)+ } catch (error) {+ // One engine's store failing (locked, mid-migration) keeps what it said last time.+ this.opts.log?.(`[search] ${provider.engine} sessions not read: ${error instanceof Error ? error.message : error}`)+ all.push(...this.lastGood.get(provider.engine) ?? [])}}-- const titles = await codexTitles(join(this.opts.codexHome, 'session_index.jsonl'))- for (const path of [- ...await rollouts(join(this.opts.codexHome, 'sessions')),- ...await rollouts(join(this.opts.codexHome, 'archived_sessions')),- ]) await consider(path, readCodexHead, (id) => titles.get(id) ?? '')-- for (const path of [...this.heads.keys()]) if (!seen.has(path)) this.heads.delete(path)- found.sort((a, b) => b.mtime - a.mtime)- this.found = found- this.byId = new Map(found.map((session) => [session.sessionId, session]))- return found- }-}--async function entries(dir: string) {- return readdir(dir, { withFileTypes: true }).catch(() => [])-}--/** Every rollout file under a Codex sessions folder (`YYYY/MM/DD/rollout-*.jsonl`), at any depth. */-async function rollouts(dir: string): Promise<string[]> {- const out: string[] = []- const walk = async (at: string, depth: number): Promise<void> => {- for (const entry of await entries(at)) {- const path = join(at, entry.name)- if (entry.isDirectory() && depth < 4) await walk(path, depth + 1)- else if (entry.isFile() && entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) out.push(path)+ this.memo.prune()+ all.sort((a, b) => b.mtime - a.mtime)+ // One id, one conversation: the newest record of it wins.+ const byId = new Map<string, ExternalSession>()+ for (const session of all) if (!byId.has(session.sessionId)) byId.set(session.sessionId, session)+ this.found = [...byId.values()]+ // An older id of a conversation that carried on under a new one finds the conversation.+ for (const session of this.found) {+ for (const alias of session.aliases ?? []) if (!byId.has(alias)) byId.set(alias, session)}+ this.byId = byId+ return this.found}- await walk(dir, 0)- return out}-async function readHead(path: string, bytes: number): Promise<string> {- const handle = await open(path, 'r')- try {- const buffer = Buffer.alloc(bytes)- const { bytesRead } = await handle.read(buffer, 0, bytes, 0)- return buffer.subarray(0, bytesRead).toString('utf8')- } finally {- await handle.close()- }-}--/** A Claude Code transcript's session, folder and entrypoint, from the first line that has them. */-export async function readClaudeHead(path: string): Promise<Head | null> {- const text = await readHead(path, CLAUDE_HEAD_BYTES)- for (const line of text.split('\n')) {- if (!line.includes('"entrypoint"')) continue- let record: { sessionId?: unknown; cwd?: unknown; entrypoint?: unknown; isSidechain?: unknown }- try { record = JSON.parse(line) } catch { continue }- if (record.isSidechain === true) return null- const origin = record.entrypoint === 'cli' ? 'terminal' : record.entrypoint === 'claude-desktop' ? 'claude-app' : null- if (!origin) return null- if (typeof record.sessionId !== 'string' || !SESSION_ID.test(record.sessionId)) return null- if (typeof record.cwd !== 'string' || !record.cwd.startsWith('/')) return null- return { sessionId: record.sessionId, engine: 'claude', cwd: record.cwd, origin }- }- return null-}--/** A Codex rollout's session, folder and source, from its first line (`session_meta`). */-export async function readCodexHead(path: string): Promise<Head | null> {- const text = await readHead(path, CODEX_HEAD_BYTES)- const newline = text.indexOf('\n')- if (newline < 0) return null- let record: { type?: unknown; payload?: { id?: unknown; cwd?: unknown; source?: unknown; originator?: unknown } }- try { record = JSON.parse(text.slice(0, newline)) } catch { return null }- const meta = record.payload- if (record.type !== 'session_meta' || !meta) return null- const origin = meta.source === 'cli' ? 'terminal'- : meta.source === 'vscode' ? (meta.originator === 'Codex Desktop' ? 'codex-app' : 'editor')- : null- if (!origin) return null- if (typeof meta.id !== 'string' || !SESSION_ID.test(meta.id)) return null- if (typeof meta.cwd !== 'string' || !meta.cwd.startsWith('/')) return null- return { sessionId: meta.id, engine: 'codex', cwd: meta.cwd, origin }-}--/** Codex's thread names: `session_index.jsonl`, one `{id, thread_name}` a line, the last one winning. */-async function codexTitles(path: string): Promise<Map<string, string>> {- const titles = new Map<string, string>()- const text = await readFile(path, 'utf8').catch(() => '')- for (const line of text.split('\n')) {- try {- const record = JSON.parse(line) as { id?: unknown; thread_name?: unknown }- if (typeof record.id === 'string' && typeof record.thread_name === 'string' && record.thread_name.trim()) {- titles.set(record.id, record.thread_name.trim())- }- } catch { /* a line being written */ }- }- return titles-}--/** Where an open session is: a terminal, which Harness can take it over from, or an app, which it cannot. */-export type OpenIn = 'terminal' | 'app'+/**+ * Where an open session is: a terminal, which Harness can take it over from; an app, which it cannot;+ * one of Harness's own panes, whose agent the daemon is still binding; or `maybe` a terminal, whose+ * process was started on it and may have moved on since (`OwnerClaim.fromArgs`).+ */+export type OpenIn = 'terminal' | 'app' | 'harness' | 'maybe'/** The process that has a session open. */export interface SessionOwner {@@ -193,22 +88,28 @@ export interface SessionOwner {engine: ExternalEngine/** The terminal it runs in (`/dev/ttys003`), or null for an app: an app is never stopped from here. */tty: string | null- /** What says whether it is mid-turn: Claude Code's `sessions/<pid>.json`, or Codex's rollout. */+ /** What says whether it is mid-turn: a record, a transcript, a database. */record: string+ /** It runs in one of Harness's own panes: an agent of Harness's, never an outside conversation. */+ harness?: boolean+ /** Only its arguments name the session: it may have moved on, and is never stopped from here. */+ fromArgs?: boolean+ /** Harness's own panes could not be listed, so this one may be Harness's: never stopped from here. */+ unverified?: boolean}export interface OpenSessionsOptions {- /** `~/.claude`: running Claude Code processes each keep `sessions/<pid>.json` there. */- claudeHome: string+ providers: readonly ExternalProvider[]/** How long an answer is reused. */maxAgeMs?: number- /** Whether a process is running; tests replace it. */- alive?: (pid: number) => boolean- /** The Codex rollouts open in a running process, and the process; tests replace it. */- openRollouts?: () => Promise<Array<{ pid: number; path: string }>>+ /** A fresh look at the machine's processes; tests replace it. */+ view?: () => ProcessView/** The terminal each process runs in, or null; tests replace it. */ttys?: (pids: number[]) => Promise<Map<number, string | null>>+ /** The terminals of Harness's own panes, or null when they could not be listed; tests replace it. */+ harnessTtys?: () => Promise<Set<string> | null>now?: () => number+ log?: (line: string) => void}type OpenAnswer = { at: number; owners: Map<string, SessionOwner>; open: Map<string, OpenIn> }@@ -218,10 +119,8 @@ type OpenAnswer = { at: number; owners: Map<string, SessionOwner>; open: Map<str* beside a terminal that still has it: both would write the same conversation. One open in a* terminal can be taken over instead (`owner`, `stopSessionOwner`).*- * Claude Code says so itself — each running process keeps `~/.claude/sessions/<pid>.json` naming its- * session. Codex keeps no such record, but holds its rollout file open while it runs, so the- * operating system says which are (`lsof`). A process with a terminal is one a person runs there;- * the engines' apps have none.+ * Only exact evidence counts: a process's own record, a lock it holds, a file it has open, the id in+ * its arguments. A guess from a folder is never enough to stop a process.*/export class OpenSessions {private answer: OpenAnswer | null = null@@ -247,11 +146,21 @@ export class OpenSessions {return (await this.current()).owners.get(sessionId) ?? null}+ /** Whether [owner] is mid-turn. An engine whose store cannot say counts as busy: the answer only+ * decides whether to ask before stopping it. */+ async busy(owner: Pick<SessionOwner, 'engine' | 'pid' | 'record'>): Promise<boolean> {+ const provider = this.opts.providers.find((candidate) => candidate.engine === owner.engine)+ const said = await provider?.busy?.(owner).catch(() => null)+ return said ?? true+ }+private current(): Promise<OpenAnswer> {const now = (this.opts.now ?? Date.now)()if (this.answer && now - this.answer.at <= (this.opts.maxAgeMs ?? 5_000)) return Promise.resolve(this.answer)this.asking ??= this.read().then((owners) => {- const open = new Map([...owners].map(([id, owner]): [string, OpenIn] => [id, owner.tty ? 'terminal' : 'app']))+ const open = new Map([...owners].map(([id, owner]): [string, OpenIn] => [+ id, owner.harness ? 'harness' : !owner.tty ? 'app' : owner.fromArgs || owner.unverified ? 'maybe' : 'terminal',+ ]))this.answer = { at: (this.opts.now ?? Date.now)(), owners, open }return this.answer}).finally(() => { this.asking = null })@@ -259,89 +168,72 @@ export class OpenSessions {}private async read(): Promise<Map<string, SessionOwner>> {- const owners = new Map<string, SessionOwner>()- const alive = this.opts.alive ?? processAlive- const dir = join(this.opts.claudeHome, 'sessions')- for (const file of await entries(dir)) {- if (!file.isFile() || !file.name.endsWith('.json')) continue- const path = join(dir, file.name)+ const view = (this.opts.view ?? (() => processView()))()+ const claims: Array<OwnerClaim & { engine: ExternalEngine }> = []+ for (const provider of this.opts.providers) {+ if (!provider.owners) continuetry {- const record = JSON.parse(await readFile(path, 'utf8')) as { pid?: unknown; sessionId?: unknown }- if (typeof record.pid === 'number' && typeof record.sessionId === 'string' && alive(record.pid)) {- owners.set(record.sessionId, { pid: record.pid, engine: 'claude', tty: null, record: path })- }- } catch { /* one being written, or gone */ }- }- for (const { pid, path } of await (this.opts.openRollouts ?? openCodexRollouts)().catch(() => [])) {- const id = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(path)?.[1]- if (id) owners.set(id, { pid, engine: 'codex', tty: null, record: path })+ for (const claim of await provider.owners(view)) claims.push({ ...claim, engine: provider.engine })+ } catch (error) {+ this.opts.log?.(`[search] ${provider.engine} owners not read: ${error instanceof Error ? error.message : error}`)+ }}- if (owners.size) {- const ttys = await (this.opts.ttys ?? processTtys)([...new Set([...owners.values()].map((owner) => owner.pid))]).catch(() => new Map<number, string | null>())- for (const owner of owners.values()) owner.tty = ttys.get(owner.pid) ?? null+ const owners = new Map<string, SessionOwner>()+ if (!claims.length) return owners+ const [ttys, harness] = await Promise.all([+ (this.opts.ttys ?? ((pids) => processTtys(pids)))([...new Set(claims.map((claim) => claim.pid))]).catch(() => new Map<number, string | null>()),+ (this.opts.harnessTtys ?? (() => readHarnessTtys()))().catch(() => null),+ ])+ for (const claim of claims) {+ const tty = claim.app ? null : ttys.get(claim.pid) ?? null+ const owner: SessionOwner = {+ pid: claim.pid, engine: claim.engine, tty, record: claim.record,+ ...(tty && harness?.has(tty) ? { harness: true } : {}),+ ...(tty && !harness ? { unverified: true } : {}),+ ...(claim.fromArgs ? { fromArgs: true } : {}),+ }+ // Hard evidence outranks a process's arguments for the same session.+ const known = owners.get(claim.sessionId)+ if (!known || (known.fromArgs && !owner.fromArgs)) owners.set(claim.sessionId, owner)}return owners}}-/**- * Whether [owner] is in the middle of a turn. Claude Code's record says `idle` between turns. A Codex- * rollout marks a turn's start (`task_started`) and its end (`task_complete`, or `turn_aborted`), so- * the last of those near its end says. A file that cannot say counts as busy: the answer only- * decides whether to ask before stopping it.- */-export async function sessionBusy(owner: Pick<SessionOwner, 'engine' | 'record'>): Promise<boolean> {- if (owner.engine === 'claude') {- try {- return (JSON.parse(await readFile(owner.record, 'utf8')) as { status?: unknown }).status !== 'idle'- } catch {- return false // gone: the process ended with it- }- }- for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {- const lines = (await readTail(owner.record, bytes)).split('\n')- for (let i = lines.length - 1; i > 0; i--) {- const line = lines[i]- if (!line.includes('"event_msg"') || !TURN_MARK.test(line)) continue- try {- const kind = (JSON.parse(line) as { payload?: { type?: unknown } }).payload?.type- if (kind === 'task_started') return true- if (kind === 'task_complete' || kind === 'turn_aborted') return false- } catch { /* the line being written */ }- }- }- return true-}--const TURN_MARK = /"(task_started|task_complete|turn_aborted)"/--async function readTail(path: string, bytes: number): Promise<string> {- const handle = await open(path, 'r').catch(() => null)- if (!handle) return ''- try {- const { size } = await handle.stat()- const length = Math.min(size, bytes)- const buffer = Buffer.alloc(length)- await handle.read(buffer, 0, length, size - length)- return buffer.toString('utf8')- } finally {- await handle.close()- }-}-export interface StopOptions {alive?: (pid: number) => booleankill?: (pid: number, signal: NodeJS.Signals) => voidsleep?: (ms: number) => Promise<void>/** Writes to the owner's terminal; tests replace it. */writeTty?: (tty: string, text: string) => Promise<void>+ /** The foreground job [pid] leads, if it leads one; tests replace it. */+ job?: (pid: number) => Promise<number | null>}+/**+ * The foreground job an engine leads in its terminal: the process group it heads, when that group is+ * the one the terminal is showing. Its whole job is signalled then, so what it started for its screen+ * goes with it (Hermes's terminal UI runs a Node child its Python does not pass SIGTERM to). An+ * engine that does not lead its job (Codex's native binary under its Node launcher, anything run+ * without job control) is signalled alone: its group may hold the shell it runs in.+ */+export async function foregroundJob(pid: number, exec: typeof run = run): Promise<number | null> {+ const out = await exec('ps', ['-o', 'pgid=,tpgid=', '-p', String(pid)], 3_000)+ const [pgid, tpgid] = (out ?? '').trim().split(/\s+/).map(Number)+ return pgid === pid && tpgid === pid ? pid : null+}++/**+ * What a terminal gets back after its engine is stopped from outside: the main screen, no mouse+ * reporting, and a cursor. A TUI that quit cleanly already restored them, and then these change+ * nothing; Codex leaves its cursor hidden, and a TUI made to quit leaves whatever it had on.+ */+export const TERMINAL_RESTORE = '\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h'+/*** Stops the terminal process that has a session open, so Harness can resume it: asked to quit- * (SIGTERM, which both engines answer by saving and restoring the terminal), then made to after five- * seconds. Codex leaves its cursor hidden when told to quit rather than typing its way out, so the- * terminal gets it back. Whether the process is gone.+ * (SIGTERM, which the engines answer by saving and restoring the terminal), then made to after five+ * seconds, and the terminal put back. Whether the process is gone.*/export async function stopSessionOwner(owner: Pick<SessionOwner, 'pid' | 'tty'>, opts: StopOptions = {}): Promise<boolean> {const alive = opts.alive ?? processAlive@@ -354,54 +246,20 @@ export async function stopSessionOwner(owner: Pick<SessionOwner, 'pid' | 'tty'>,}return !alive(owner.pid)}+ const job = await (opts.job ?? foregroundJob)(owner.pid).catch(() => null)const signal = (name: NodeJS.Signals): void => {- try { kill(owner.pid, name) } catch { /* already gone */ }+ try { kill(job ? -job : owner.pid, name) } catch { /* already gone */ }}signal('SIGTERM')if (!await gone(5_000)) {signal('SIGKILL')if (!await gone(2_000)) return false}- if (owner.tty) await (opts.writeTty ?? writeTty)(owner.tty, '\x1b[?25h').catch(() => undefined)+ if (owner.tty) await (opts.writeTty ?? writeTty)(owner.tty, TERMINAL_RESTORE).catch(() => undefined)return true}-async function writeTty(tty: string, text: string): Promise<void> {+export async function writeTty(tty: string, content: string): Promise<void> {const handle = await open(tty, 'w')- try { await handle.write(text) } finally { await handle.close() }-}--export function processAlive(pid: number): boolean {- try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }-}--/** The rollout files Codex processes have open, and which process: `lsof` over processes named codex. */-function openCodexRollouts(): Promise<Array<{ pid: number; path: string }>> {- return new Promise((resolve) => {- execFile('lsof', ['-n', '-P', '-Fpn', '-c', 'codex', '-c', 'Codex'], { timeout: 3_000, maxBuffer: 8 * 1024 * 1024 }, (_error, stdout) => {- // lsof exits 1 when a name matches no process; what it printed is still the answer.- const found: Array<{ pid: number; path: string }> = []- let pid = 0- for (const line of String(stdout ?? '').split('\n')) {- if (line.startsWith('p')) pid = Number(line.slice(1)) || 0- else if (pid && line.startsWith('n') && line.includes('rollout-') && line.endsWith('.jsonl')) found.push({ pid, path: line.slice(1) })- }- resolve(found)- })- })-}--/** Each process's terminal (`ps -o tty`): `ttys003` on macOS, `pts/3` on Linux, `??` or `?` for none. */-function processTtys(pids: number[]): Promise<Map<number, string | null>> {- return new Promise((resolve) => {- execFile('ps', ['-o', 'pid=,tty=', '-p', pids.join(',')], { timeout: 3_000 }, (_error, stdout) => {- const ttys = new Map<number, string | null>()- for (const line of String(stdout ?? '').split('\n')) {- const [pid, tty] = line.trim().split(/\s+/)- if (!pid) continue- ttys.set(Number(pid), tty && !tty.startsWith('?') ? `/dev/${tty}` : null)- }- resolve(ttys)- })- })+ try { await handle.write(content) } finally { await handle.close() }}diff --git a/cli/src/lib/sessionSearch/externals/agy.spec.ts b/cli/src/lib/sessionSearch/externals/agy.spec.tsnew file mode 100644index 000000000..b3b8b8e67--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/agy.spec.ts@@ -0,0 +1,194 @@+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { agyHistoryFolders, agyLatestFolders, agyProvider } from './agy.js'+import { scanMemo } from './support.js'+import type { ExternalProvider, ProcessView, RunningProcess } from './types.js'++// Shapes follow agy 1.1.14 as the repo measured it (engines/agy/session.ts, hook/notify.mjs, the+// recorded transcript lib/__fixtures__/agy-session.jsonl) and agy's documented `last_conversations.json`.+// `history.jsonl`'s fields are from a third-party reader of it (agentgrep). Values are made up.+const ID = 'ae51057a-0000-4000-8000-000000000001'+const ID2 = 'be51057a-0000-4000-8000-000000000002'+const ID3 = 'ce51057a-0000-4000-8000-000000000003'+const T0 = Date.parse('2026-09-01T10:00:00.000Z')++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function temp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'agy-external-'))+ dirs.push(dir)+ return dir+}++const jsonl = (...lines: unknown[]) => `${lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n')}\n`+const step = (index: number, type: string) => ({ step_index: index, source: 'USER_EXPLICIT', type, status: 'DONE', created_at: '2026-09-01T10:00:00Z', content: 'words' })++function write(path: string, content: string, mtimeSeconds?: number): string {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, content)+ if (mtimeSeconds !== undefined) utimesSync(path, new Date(T0 + mtimeSeconds * 1000), new Date(T0 + mtimeSeconds * 1000))+ return path+}++const transcriptOf = (home: string, id: string) => join(home, 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl')++/** A top-level conversation: its transcript and its presence lock. */+function conversation(home: string, id: string, mtimeSeconds = 10, lock = true): string {+ const path = write(transcriptOf(home, id), jsonl(step(0, 'USER_INPUT'), step(1, 'PLANNER_RESPONSE')), mtimeSeconds)+ if (lock) write(join(home, 'presence', `${id}.lock`), '')+ return path+}++function scanner(provider: ExternalProvider, excluded: string[] = []) {+ const memo = scanMemo({ excluded })+ return async () => {+ const found = await provider.scan(memo.context())+ memo.prune()+ return found+ }+}++const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })++describe('agyHistoryFolders', () => {+ it("takes each conversation's workspace from its latest prompt that names both", async () => {+ const dir = temp()+ const path = write(join(dir, 'history.jsonl'), jsonl(+ { display: 'first', timestamp: T0, workspace: '/w/old', conversationId: ID },+ { display: 'no conversation', timestamp: T0, workspace: '/w/none' },+ { display: '/help', timestamp: T0, workspace: '/w/new', type: 'slash_command', conversationId: ID },+ { display: 'relative', timestamp: T0, workspace: 'w/rel', conversationId: ID2 },+ { display: 'no workspace', timestamp: T0, conversationId: ID3 },+ { display: 'empty id', timestamp: T0, workspace: '/w/x', conversationId: '' },+ '{"conversationId": torn',+ ))+ expect(await agyHistoryFolders(path)).toEqual(new Map([[ID, '/w/new']]))+ expect(await agyHistoryFolders(join(dir, 'missing.jsonl'))).toEqual(new Map())+ })+})++describe('agyLatestFolders', () => {+ it('turns the workspace → latest conversation map around, and places no conversation it names twice', async () => {+ const dir = temp()+ const path = write(join(dir, 'last.json'), JSON.stringify({ '/w/a': ID, '/w/b': ID2, '/w/c': ID2, 'rel/d': ID3, '/w/e': 7, '/w/f': '' }))+ expect(await agyLatestFolders(path)).toEqual(new Map([[ID, '/w/a']]))+ expect(await agyLatestFolders(write(join(dir, 'list.json'), '[1]'))).toEqual(new Map())+ expect(await agyLatestFolders(join(dir, 'missing.json'))).toEqual(new Map())+ })+})++describe('agyProvider', () => {+ it('lists each top-level conversation with a transcript, in the workspace its prompts name', async () => {+ const home = temp()+ const path = conversation(home, ID, 42)+ write(join(home, 'history.jsonl'), jsonl({ display: 'x', timestamp: T0, workspace: '/Users/me/Work/app', conversationId: ID }))+ expect(await scanner(agyProvider({ home }))()).toEqual([+ { sessionId: ID, engine: 'agy', cwd: '/Users/me/Work/app', origin: 'terminal', title: '', mtime: T0 + 42_000, transcriptPath: path },+ ])+ })++ it('places a conversation its prompts do not by the latest-conversation map, and the prompts win when both do', async () => {+ const home = temp()+ conversation(home, ID)+ conversation(home, ID2)+ write(join(home, 'history.jsonl'), jsonl({ display: 'x', timestamp: T0, workspace: '/w/from-history', conversationId: ID }))+ write(join(home, 'cache', 'last_conversations.json'), JSON.stringify({ '/w/from-cache': ID, '/w/latest': ID2 }))+ const found = await scanner(agyProvider({ home }))()+ expect(Object.fromEntries(found.map((s) => [s.sessionId, s.cwd]))).toEqual({ [ID]: '/w/from-history', [ID2]: '/w/latest' })+ })++ it('leaves out sub-agents (no lock), `-p` runs (no workspace), empty or missing transcripts, excluded folders and stray entries', async () => {+ const home = temp()+ conversation(home, ID, 10, false) // a sub-agent: no presence lock+ conversation(home, ID2) // `-p`: a lock, but no workspace anywhere+ write(transcriptOf(home, ID3), '') // nobody has spoken in it yet+ write(join(home, 'presence', `${ID3}.lock`), '')+ const noTranscript = 'de51057a-0000-4000-8000-000000000004'+ mkdirSync(join(home, 'brain', noTranscript), { recursive: true })+ write(join(home, 'presence', `${noTranscript}.lock`), '')+ const lockIsFolder = 'ee51057a-0000-4000-8000-000000000005'+ conversation(home, lockIsFolder, 10, false)+ mkdirSync(join(home, 'presence', `${lockIsFolder}.lock`), { recursive: true })+ const scratch = 'fe51057a-0000-4000-8000-000000000006'+ conversation(home, scratch)+ mkdirSync(join(home, 'brain', 'not-a-conversation'), { recursive: true })+ write(join(home, 'brain', 'aa51057a-0000-4000-8000-000000000007'), 'a file, not a folder')+ const kept = '0a51057a-0000-4000-8000-000000000008'+ conversation(home, kept)+ write(join(home, 'history.jsonl'), jsonl(...[ID, ID3, noTranscript, lockIsFolder, kept].map((id) => ({ display: 'x', timestamp: T0, workspace: `/w/${id}`, conversationId: id })),+ { display: 'x', timestamp: T0, workspace: '/data/harness/summary-scratch', conversationId: scratch }))+ const found = await scanner(agyProvider({ home }), ['/data/harness'])()+ expect(found.map((s) => s.sessionId)).toEqual([kept])+ })++ it('reads the history again only when it changed', async () => {+ const home = temp()+ conversation(home, ID)+ const history = write(join(home, 'history.jsonl'), jsonl({ display: 'x', timestamp: T0, workspace: '/w/aaa', conversationId: ID }), 100)+ const scan = scanner(agyProvider({ home }))+ expect((await scan())[0].cwd).toBe('/w/aaa')+ write(history, jsonl({ display: 'x', timestamp: T0, workspace: '/w/bbb', conversationId: ID }), 100)+ expect((await scan())[0].cwd).toBe('/w/aaa')+ write(history, jsonl({ display: 'x', timestamp: T0, workspace: '/w/bbb', conversationId: ID }), 200)+ expect((await scan())[0].cwd).toBe('/w/bbb')+ rmSync(history)+ expect(await scan()).toEqual([])+ })++ it('finds nothing in a home agy never wrote', async () => {+ expect(await scanner(agyProvider({ home: join(temp(), 'nothing') }))()).toEqual([])+ })++ it('names the process that holds a conversation\'s lock open, however the presence folder is reached, and never says whether it is mid-turn', async () => {+ // lsof reports a file by its real path (on macOS the temp folder itself is behind a link).+ const real = realpathSync(temp())+ mkdirSync(join(real, 'presence'), { recursive: true })+ const home = join(temp(), 'linked-home')+ symlinkSync(real, home)+ const asked: number[][] = []+ const provider = agyProvider({ home })+ const view: ProcessView = {+ list: async () => [+ row(91701, 'agy', 'agy'),+ row(91702, '/Users/me/.local/bin/agy', '/Users/me/.local/bin/agy --conversation ' + ID3),+ row(91703, '/Applications/Antigravity.app/Contents/Resources/bin/agy', '/Applications/Antigravity.app/Contents/Resources/bin/agy'),+ row(91704, 'node', 'node server.js'),+ ],+ openFiles: async (pids) => {+ asked.push([...pids])+ return new Map([+ [91701, [join(home, 'presence', `${ID}.lock`), join(home, 'brain', ID, 'x.jsonl'), '/dev/ttys003']],+ [91702, [join(real, 'presence', `${ID2}.lock`), join(real, 'presence', 'not-an-id.lock'), join(real, 'elsewhere', `${ID3}.lock`), join(real, 'presence', `${ID3}.pid`)]],+ ])+ },+ openFilesOf: async () => { throw new Error('not used') },+ alive: () => true,+ }+ const claims = await provider.owners!(view)+ expect(asked).toEqual([[91701, 91702]])+ expect(claims).toEqual([+ { sessionId: ID, pid: 91701, record: join(home, 'presence', `${ID}.lock`) },+ { sessionId: ID2, pid: 91702, record: join(real, 'presence', `${ID2}.lock`) },+ ])+ expect(await provider.busy!(claims[0])).toBeNull()+ })++ it('asks nothing when no agy is running, and names the lock as configured when the folder is missing', async () => {+ const home = join(temp(), 'no-presence')+ const provider = agyProvider({ home })+ let asked = 0+ const view = (rows: RunningProcess[]): ProcessView => ({+ list: async () => rows,+ openFiles: async () => { asked++; return new Map([[5, [join(home, 'presence', `${ID}.lock`)]]]) },+ openFilesOf: async () => new Map(),+ alive: () => true,+ })+ expect(await provider.owners!(view([row(1, 'zsh', '-zsh')]))).toEqual([])+ expect(asked).toBe(0)+ expect(await provider.owners!(view([row(5, 'agy', 'agy')]))).toEqual([{ sessionId: ID, pid: 5, record: join(home, 'presence', `${ID}.lock`) }])+ })+})diff --git a/cli/src/lib/sessionSearch/externals/agy.ts b/cli/src/lib/sessionSearch/externals/agy.tsnew file mode 100644index 000000000..88d1d9fe9--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/agy.ts@@ -0,0 +1,119 @@+/**+ * Antigravity (`agy`): `<home>/brain/<id>/.system_generated/logs/transcript_full.jsonl` is each+ * conversation's history, and `<home>/presence/<id>.lock` is made only for a top-level one (a+ * sub-agent gets a brain folder and no lock) and held open by the process that has it. A `-p` run+ * gets a lock too, but opens no workspace.+ *+ * The transcript names no folder. `history.jsonl`, agy's prompt recall, does: each line's+ * `conversationId` and `workspace`, the latest line winning. `cache/last_conversations.json` maps a+ * workspace to its latest conversation and answers for the rest. A conversation neither places is+ * left out: resumed anywhere else it would work in the wrong folder.+ *+ * The lock held open says exactly which process has a conversation. Nothing on disk says a turn is+ * running: the transcript never marks one's end, and a backgrounded step stays `RUNNING` for good.+ */++import { realpath, stat } from 'node:fs/promises'+import { basename, dirname, join } from 'node:path'++import { agyTranscriptPath } from '../../../engines/agy/session.js'+import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'+import { engineProcessMatch } from '../../tmux.js'+import { absoluteFolder, entries, fileStamp, parseLine, readJson, readText, record, text, UUID } from './support.js'+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, ScanContext } from './types.js'++/**+ * A process row carries no file identity, so the PATH walk behind a full ownership snapshot could+ * not change a match: one empty snapshot serves every row.+ */+const NO_FILE_OWNERS: AgentCommandOwnershipSnapshot = {+ cursorFileKeys: new Set(), grokFileKeys: new Set(), conflictingFileKeys: new Set(),+ agentCandidates: [], cursorAgentCandidates: [], grokCandidates: [],+}++/** Each conversation's workspace from `history.jsonl`: the latest line that names both wins. */+export async function agyHistoryFolders(path: string): Promise<Map<string, string>> {+ const folders = new Map<string, string>()+ for (const line of (await readText(path)).split('\n')) {+ if (!line.includes('"conversationId"')) continue+ const row = record(parseLine(line))+ const id = text(row?.conversationId)+ const cwd = absoluteFolder(row?.workspace)+ if (id && cwd) folders.set(id, cwd)+ }+ return folders+}++/**+ * Each conversation's workspace from `cache/last_conversations.json` (workspace → its latest+ * conversation). A conversation it names under two workspaces is placed by neither.+ */+export async function agyLatestFolders(path: string): Promise<Map<string, string>> {+ const folders = new Map<string, string>()+ const twice = new Set<string>()+ for (const [workspace, id] of Object.entries(record(await readJson(path)) ?? {})) {+ const cwd = absoluteFolder(workspace)+ if (!cwd || typeof id !== 'string' || !id) continue+ if (folders.has(id)) twice.add(id)+ folders.set(id, cwd)+ }+ for (const id of twice) folders.delete(id)+ return folders+}++/** A file's parsed value, read again only when it changed; [empty] when it is missing. */+async function memoFile<T>(ctx: ScanContext, path: string, read: (path: string) => Promise<T>, empty: T): Promise<T> {+ const stamp = await fileStamp(path)+ return stamp ? ctx.memo(`agy:${path}`, stamp.stamp, () => read(path)) : empty+}++async function isFile(path: string): Promise<boolean> {+ return (await stat(path).catch(() => null))?.isFile() ?? false+}++export interface AgyOptions { home: string }++export function agyProvider(options: AgyOptions): ExternalProvider {+ const presence = join(options.home, 'presence')+ return {+ engine: 'agy',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const history = await memoFile(ctx, join(options.home, 'history.jsonl'), agyHistoryFolders, new Map<string, string>())+ const latest = await memoFile(ctx, join(options.home, 'cache', 'last_conversations.json'), agyLatestFolders, new Map<string, string>())+ const found: ExternalSession[] = []+ for (const entry of await entries(join(options.home, 'brain'))) {+ if (!entry.isDirectory() || !UUID.test(entry.name)) continue+ const id = entry.name+ const transcriptPath = agyTranscriptPath(options.home, id)!+ const transcript = await stat(transcriptPath).catch(() => null)+ // A conversation nobody has spoken in yet has an empty transcript, or none.+ if (!transcript?.isFile() || !transcript.size || !await isFile(join(presence, `${id}.lock`))) continue+ await ctx.pace()+ const cwd = history.get(id) ?? latest.get(id)+ if (!cwd || ctx.excluded(cwd)) continue+ found.push({+ sessionId: id, engine: 'agy', cwd, origin: 'terminal',+ // Steps carry `created_at` to the second, set when a step begins; the file's time is when it was written.+ title: '', mtime: Math.floor(transcript.mtimeMs), transcriptPath,+ })+ }+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const pids = (await view.list()).filter((row) => engineProcessMatch(row, 'agy', NO_FILE_OWNERS).score).map((row) => row.pid)+ if (!pids.length) return []+ // lsof names a file by its real path: the presence folder may be reached through a link.+ const folders = new Set([presence, await realpath(presence).catch(() => presence)])+ const claims: OwnerClaim[] = []+ for (const [pid, files] of await view.openFiles(pids)) {+ for (const path of files) {+ const id = basename(path, '.lock')+ if (path.endsWith('.lock') && UUID.test(id) && folders.has(dirname(path))) claims.push({ sessionId: id, pid, record: path })+ }+ }+ return claims+ },+ // The transcript never marks a turn's end: the file cannot say one is running.+ busy: async () => null,+ }+}diff --git a/cli/src/lib/sessionSearch/externals/claude.spec.ts b/cli/src/lib/sessionSearch/externals/claude.spec.tsnew file mode 100644index 000000000..6f59c530d--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/claude.spec.ts@@ -0,0 +1,130 @@+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { claudeProvider, readClaudeHead } from './claude.js'+import { scanMemo } from './support.js'+import { type ProcessView, UNSETTLED } from './types.js'++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function home(): string {+ const dir = mkdtempSync(join(tmpdir(), 'externals-claude-'))+ dirs.push(dir)+ return dir+}+function write(path: string, lines: unknown[]): string {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + '\n')+ return path+}+const A = '11111111-1111-4111-8111-111111111111'+const B = '22222222-2222-4222-8222-222222222222'+const line = (sessionId: string, entrypoint: string, extra: Record<string, unknown> = {}) => ({+ type: 'user', sessionId, cwd: '/work/dial', entrypoint, timestamp: '2026-09-20T10:00:00Z',+ message: { role: 'user', content: 'fix the dial scroll' }, ...extra,+})+const view = (alive: (pid: number) => boolean): ProcessView => ({+ list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive,+})++describe('readClaudeHead', () => {+ it('reads a terminal or the Claude app, never a program, a sub-agent or a line it cannot trust', async () => {+ const dir = home()+ const file = (name: string, lines: unknown[]) => write(join(dir, `${name}.jsonl`), lines)+ // The first lines may carry no entrypoint: a mode, a title, a line being written.+ expect(await readClaudeHead(file('t', [{ type: 'permission-mode' }, '{"entrypoint": half', line(A, 'cli')])))+ .toEqual({ sessionId: A, cwd: '/work/dial', origin: 'terminal' })+ expect(await readClaudeHead(file('d', [line(A, 'claude-desktop')]))).toMatchObject({ origin: 'claude-app' })+ expect(await readClaudeHead(file('s', [line(A, 'sdk-cli')]))).toBeNull()+ expect(await readClaudeHead(file('x', [line(A, 'cli', { isSidechain: true })]))).toBeNull()+ expect(await readClaudeHead(file('r', [line(A, 'cli', { cwd: 'relative/path' })]))).toBeNull()+ expect(await readClaudeHead(file('i', [line('short', 'cli')]))).toBeNull()+ // No line says yet: Claude may still be writing it, so it is not judged — unless the file is too+ // long for that.+ expect(await readClaudeHead(file('n', ['["entrypoint"]']))).toBe(UNSETTLED)+ expect(await readClaudeHead(file('e', [{ type: 'summary', summary: 'nothing else' }]))).toBe(UNSETTLED)+ // Past every window without one: not a conversation, for good.+ expect(await readClaudeHead(file('big', [{ type: 'summary', summary: 'x'.repeat(3000) }]), [1024, 2048])).toBeNull()+ // A first prompt with a pasted image runs past the first window: the next, wider one reads it.+ const pasted = line(A, 'cli', { message: { role: 'user', content: [{ type: 'image', source: { data: 'i'.repeat(300 * 1024) } }] } })+ expect(await readClaudeHead(file('pasted', [{ type: 'permission-mode' }, pasted]))).toEqual({ sessionId: A, cwd: '/work/dial', origin: 'terminal' })+ })+})++describe('claudeProvider', () => {+ it("finds a project's own conversations, not a sub-agent's, and not Harness's own byproducts", async () => {+ const root = home()+ const projects = join(root, 'projects')+ write(join(projects, '-work-dial', `${A}.jsonl`), [line(A, 'cli')])+ write(join(projects, '-work-dial', `${B}.jsonl`), [line(B, 'cli', { cwd: '/data/harness/summary-scratch' })])+ write(join(projects, '-work-dial', 'notes.txt'), ['not a transcript'])+ write(join(projects, '-work-dial', A, 'subagents', 'agent-1.jsonl'), [line(A, 'cli')])+ writeFileSync(join(projects, 'stray-file'), '')+ mkdirSync(join(projects, '-work-dial', 'odd.jsonl'))+ symlinkSync(join(root, 'nowhere.jsonl'), join(projects, '-work-dial', 'broken.jsonl'))+ const provider = claudeProvider({ projectsDir: projects, home: root })+ const memo = scanMemo({ excluded: ['/data/harness'] })+ const found = await provider.scan(memo.context())+ expect(found).toEqual([expect.objectContaining({+ sessionId: A, engine: 'claude', cwd: '/work/dial', origin: 'terminal', title: '',+ transcriptPath: join(projects, '-work-dial', `${A}.jsonl`),+ })])+ expect(found[0].mtime).toBeGreaterThan(0)+ // Nothing where nothing is.+ expect(await claudeProvider({ projectsDir: join(root, 'none'), home: root }).scan(memo.context())).toEqual([])+ })++ it('finds a conversation it first saw half-written once Claude has written its first lines', async () => {+ const root = home()+ const projects = join(root, 'projects')+ const path = write(join(projects, '-work-dial', `${B}.jsonl`), [{ type: 'permission-mode' }])+ const provider = claudeProvider({ projectsDir: projects, home: root })+ const memo = scanMemo()+ expect(await provider.scan(memo.context())).toEqual([])+ write(path, [{ type: 'permission-mode' }, line(B, 'cli')])+ expect((await provider.scan(memo.context())).map((s) => s.sessionId)).toEqual([B])+ })++ it('knows its owners from their live process records, and whether they are between turns', async () => {+ const root = home()+ const started = Date.parse('2026-09-27T10:00:00Z')+ write(join(root, 'sessions', '101.json'), [{ pid: 101, sessionId: A, status: 'busy', startedAt: started + 400 }])+ write(join(root, 'sessions', '102.json'), [{ pid: 102, sessionId: B, status: 'idle' }])+ // A crashed Claude's record, its pid now a shell's, and one now a later Claude's.+ write(join(root, 'sessions', '107.json'), [{ pid: 107, sessionId: 'reused-by-a-shell', startedAt: started }])+ write(join(root, 'sessions', '108.json'), [{ pid: 108, sessionId: 'reused-by-claude', startedAt: started }])+ // Alive, but gone from the process list by the time it was read.+ write(join(root, 'sessions', '109.json'), [{ pid: 109, sessionId: 'unlisted' }])+ write(join(root, 'sessions', '103.json'), [{ pid: 103, sessionId: B }])+ write(join(root, 'sessions', '104.json'), ['{ being written'])+ write(join(root, 'sessions', '105.json'), [{ pid: '105', sessionId: B }])+ write(join(root, 'sessions', '106.json'), [{ pid: 106 }])+ write(join(root, 'sessions', 'notes.txt'), ['x'])+ mkdirSync(join(root, 'sessions', 'dir.json'))+ const provider = claudeProvider({ projectsDir: join(root, 'projects'), home: root })+ const running = [+ { pid: 101, ppid: 1, executable: 'claude', args: 'claude --resume x', started },+ { pid: 102, ppid: 1, executable: 'claude', args: 'claude' },+ { pid: 106, ppid: 1, executable: 'claude', args: 'claude', started },+ { pid: 107, ppid: 1, executable: '-zsh', args: '-zsh', started: started + 60_000 },+ { pid: 108, ppid: 1, executable: 'claude', args: 'claude', started: started + 60_000 },+ ]+ const claims = await provider.owners!({ ...view((pid) => [101, 102, 106, 107, 108, 109].includes(pid)), list: async () => running })+ expect(claims.sort((a, b) => a.pid - b.pid)).toEqual([+ { sessionId: A, pid: 101, record: join(root, 'sessions', '101.json') },+ { sessionId: B, pid: 102, record: join(root, 'sessions', '102.json') },+ ])+ expect(await provider.busy!({ pid: 101, record: join(root, 'sessions', '101.json') })).toBe(true)+ expect(await provider.busy!({ pid: 102, record: join(root, 'sessions', '102.json') })).toBe(false)+ // No records at all: nothing is open, and no process is looked at.+ let looked = false+ expect(await claudeProvider({ projectsDir: join(root, 'projects'), home: join(root, 'none') })+ .owners!({ ...view(() => true), list: async () => { looked = true; return [] } })).toEqual([])+ expect(looked).toBe(false)+ // The record gone is the process gone: not mid-turn.+ expect(await provider.busy!({ pid: 9, record: join(root, 'sessions', 'gone.json') })).toBe(false)+ })+})diff --git a/cli/src/lib/sessionSearch/externals/claude.ts b/cli/src/lib/sessionSearch/externals/claude.tsnew file mode 100644index 000000000..56d87c85c--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/claude.ts@@ -0,0 +1,107 @@+/**+ * Claude Code: `~/.claude/projects/<folder>/<id>.jsonl`. A transcript's first lines say who wrote it:+ * `entrypoint` `cli` (a terminal) or `claude-desktop` (the Claude app). `sdk-cli` is a program driving+ * Claude (Harness's own summaries among them), and a sub-agent's file lives in a folder of its own.+ *+ * A running Claude Code keeps `~/.claude/sessions/<pid>.json` naming its session and saying `idle`+ * between turns: the owner and its state, exactly.+ */++import { join } from 'node:path'++import { agentCommandOwnershipSnapshot } from '../../engineBin.js'+import { engineProcessMatch } from '../../tmux.js'+import { absoluteFolder, entries, fileStamp, readHead, readJson, record, text } from './support.js'+import { type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'++/**+ * How much of a transcript is read to classify it, a window at a time. The line that says who wrote it+ * is usually the first prompt, which can carry a pasted image: a few hundred kilobytes, or megabytes.+ */+const HEAD_BYTES = [256 * 1024, 4 * 1024 * 1024, 32 * 1024 * 1024]+const SESSION_ID = /^[A-Za-z0-9-]{8,80}$/+/** `ps` gives a start to the second; Claude stamps its record a moment after it starts. */+const START_SLACK_MS = 2_000++export interface ClaudeHead { sessionId: string; cwd: string; origin: ExternalOrigin }++/**+ * A transcript's session, folder and entrypoint, from the first line that has them. UNSETTLED when no+ * such line is there yet in a file shorter than what is read: Claude may still be writing it.+ */+export async function readClaudeHead(path: string, windows: readonly number[] = HEAD_BYTES): Promise<ClaudeHead | null | typeof UNSETTLED> {+ for (const bytes of windows) {+ const head = await readHead(path, bytes)+ const whole = Buffer.byteLength(head) < bytes+ // A window that ends mid-file ends mid-line: that line is read whole by the next, wider one.+ const lines = head.split('\n')+ if (!whole) lines.pop()+ for (const line of lines) {+ if (!line.includes('"entrypoint"')) continue+ let row: Record<string, unknown> | null+ try { row = record(JSON.parse(line)) } catch { continue }+ if (!row) continue+ if (row.isSidechain === true) return null+ const origin: ExternalOrigin | null = row.entrypoint === 'cli' ? 'terminal' : row.entrypoint === 'claude-desktop' ? 'claude-app' : null+ const cwd = absoluteFolder(row.cwd)+ if (!origin || !SESSION_ID.test(text(row.sessionId)) || !cwd) return null+ return { sessionId: text(row.sessionId), cwd, origin }+ }+ // The whole file, and no line says yet: Claude may still be writing it.+ if (whole) return UNSETTLED+ }+ return null+}++export function claudeProvider(options: { projectsDir: string; home: string }): ExternalProvider {+ return {+ engine: 'claude',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const found: ExternalSession[] = []+ for (const project of await entries(options.projectsDir)) {+ if (!project.isDirectory()) continue+ const folder = join(options.projectsDir, project.name)+ // Only the project's own files: a sub-agent's are in a folder beneath it.+ for (const file of await entries(folder)) {+ if (!file.name.endsWith('.jsonl')) continue+ const path = join(folder, file.name)+ // A file, or a link to one; not a folder, not a broken link.+ const stamp = await fileStamp(path)+ if (!stamp) continue+ // A transcript's first lines never change: its head is read once, however it grows.+ const head = await ctx.head(`claude:${path}`, stamp.stamp, () => readClaudeHead(path))+ await ctx.pace()+ if (!head || ctx.excluded(head.cwd)) continue+ found.push({ ...head, engine: 'claude', title: '', mtime: stamp.mtime, transcriptPath: path })+ }+ }+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const dir = join(options.home, 'sessions')+ const claims: OwnerClaim[] = []+ const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith('.json'))+ if (!records.length) return claims+ const processes = new Map((await view.list()).map((process): [number, RunningProcess] => [process.pid, process]))+ const ownership = agentCommandOwnershipSnapshot()+ for (const file of records) {+ const path = join(dir, file.name)+ const row = record(await readJson(path))+ const pid = row?.pid+ if (typeof pid !== 'number' || !text(row?.sessionId) || !view.alive(pid)) continue+ // A record outlives a crash, and its pid can be handed to anything after — a shell in another+ // tab. Only a Claude process already running when the record says Claude started still has it.+ const process = processes.get(pid)+ if (!process || engineProcessMatch(process, 'claude', ownership).score <= 0) continue+ if (process.started !== undefined && typeof row?.startedAt === 'number' && process.started > row.startedAt + START_SLACK_MS) continue+ claims.push({ sessionId: text(row?.sessionId), pid, record: path })+ }+ return claims+ },+ async busy(owner): Promise<boolean> {+ const row = record(await readJson(owner.record))+ // No record: the process ended with it, so it is not mid-turn.+ return row ? row.status !== 'idle' : false+ },+ }+}diff --git a/cli/src/lib/sessionSearch/externals/codex.spec.ts b/cli/src/lib/sessionSearch/externals/codex.spec.tsnew file mode 100644index 000000000..257fe55d7--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/codex.spec.ts@@ -0,0 +1,160 @@+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { codexProvider, codexServer, codexTitles, codexTurnOpen, readCodexHead, rollouts } from './codex.js'+import { scanMemo } from './support.js'+import { type ProcessView, UNSETTLED } from './types.js'++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function home(): string {+ const dir = mkdtempSync(join(tmpdir(), 'externals-codex-'))+ dirs.push(dir)+ return dir+}+function write(path: string, lines: unknown[]): string {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + '\n')+ return path+}+const C = '01a0c4ad-de5e-7000-8000-000000000001'+const D = '01a0c4ad-de5e-7000-8000-000000000002'+const meta = (id: string, source: unknown, originator = 'codex-tui', cwd: unknown = '/work/cohorts') => ({+ timestamp: '2026-09-20T10:00:00Z', type: 'session_meta',+ payload: { id, cwd, originator, source, base_instructions: 'x'.repeat(40_000) },+})+const event = (type: string) => ({ type: 'event_msg', payload: { type } })+const rolloutName = (id: string) => `rollout-2026-09-20T10-00-00-${id}.jsonl`++describe('readCodexHead', () => {+ it('reads the terminal, the Codex app and the editors, not scripts, sub-agents or a broken head', async () => {+ const dir = home()+ const file = (name: string, first: unknown) => write(join(dir, `${name}.jsonl`), [first, event('x')])+ // `meta` carries 40 KB of instructions: past the first window, found by the second.+ expect(await readCodexHead(file('cli', meta(C, 'cli')))).toEqual({ sessionId: C, cwd: '/work/cohorts', origin: 'terminal' })+ const short = { ...meta(C, 'cli'), payload: { ...meta(C, 'cli').payload, base_instructions: 'x' } }+ expect(await readCodexHead(file('short', short))).toMatchObject({ sessionId: C })+ expect(await readCodexHead(file('app', meta(C, 'vscode', 'Codex Desktop')))).toMatchObject({ origin: 'codex-app' })+ expect(await readCodexHead(file('ide', meta(C, 'vscode', 'codex_vscode')))).toMatchObject({ origin: 'editor' })+ expect(await readCodexHead(file('exec', meta(C, 'exec', 'codex_exec')))).toBeNull()+ expect(await readCodexHead(file('sub', meta(C, { subagent: { other: 'guardian' } })))).toBeNull()+ expect(await readCodexHead(file('cwd', meta(C, 'cli', 'codex-tui', 'relative')))).toBeNull()+ expect(await readCodexHead(file('id', meta('x', 'cli')))).toBeNull()+ expect(await readCodexHead(file('type', { type: 'other', payload: {} }))).toBeNull()+ expect(await readCodexHead(file('nopayload', { type: 'session_meta' }))).toBeNull()+ expect(await readCodexHead(file('garbage', 'not json'))).toBeNull()+ // No newline yet: the first line is still being written, and is not judged until it is done —+ // unless it is longer than any first line.+ const partial = join(dir, 'partial.jsonl')+ writeFileSync(partial, JSON.stringify(meta(C, 'cli')))+ expect(await readCodexHead(partial)).toBe(UNSETTLED)+ const endless = join(dir, 'endless.jsonl')+ writeFileSync(endless, 'x'.repeat(1024 * 1024 + 10))+ expect(await readCodexHead(endless)).toBeNull()+ })+})++describe('the rest of a Codex home', () => {+ it('reads thread names, the last one winning, and reads them again only when the file changes', async () => {+ const dir = home()+ const path = write(join(dir, 'session_index.jsonl'), [+ { id: C, thread_name: 'Old name' },+ { id: C, thread_name: 'Retention cohorts' },+ { id: D, thread_name: ' ' },+ { thread_name: 'no id' },+ 'half a line',+ ])+ const memo = scanMemo()+ expect(await codexTitles(path, memo.context())).toEqual(new Map([[C, 'Retention cohorts']]))+ expect(await codexTitles(join(dir, 'none.jsonl'), memo.context())).toEqual(new Map())+ })++ it('finds rollouts at any date depth, not beyond, and nothing else', async () => {+ const dir = home()+ write(join(dir, '2026', '09', '20', rolloutName(C)), [meta(C, 'cli')])+ write(join(dir, '2026', '09', '20', 'notes.jsonl'), ['x'])+ write(join(dir, 'a', 'b', 'c', 'd', 'e', rolloutName(D)), [meta(D, 'cli')])+ expect(await rollouts(dir)).toEqual([join(dir, '2026', '09', '20', rolloutName(C))])+ })++ it("says a turn is running until its task_complete or turn_aborted, whatever was said", async () => {+ const dir = home()+ const talk = { type: 'response_item', payload: { type: 'message', content: [{ text: 'then "task_complete" arrives' }] } }+ const file = (name: string, lines: unknown[]) => write(join(dir, `${name}.jsonl`), [meta(C, 'cli'), ...lines])+ expect(await codexTurnOpen(file('ended', [event('task_started'), talk, event('task_complete'), talk]))).toBe(false)+ expect(await codexTurnOpen(file('aborted', [event('task_started'), event('turn_aborted')]))).toBe(false)+ expect(await codexTurnOpen(file('working', [event('task_complete'), event('task_started'), talk]))).toBe(true)+ expect(await codexTurnOpen(file('other', [event('task_started'), { type: 'event_msg', payload: { type: 'task_complete_ish' } }]))).toBe(true)+ expect(await codexTurnOpen(file('unsaid', []))).toBe(true)+ // An agent that talks about the events is not one.+ const quoted = { type: 'event_msg', payload: { type: 'agent_message', phase: 'task_started' } }+ expect(await codexTurnOpen(file('quoted', [event('task_complete'), quoted]))).toBe(false)+ expect(await codexTurnOpen(join(dir, 'gone.jsonl'))).toBe(true)+ // Too far back to be read: busy, the safe answer.+ expect(await codexTurnOpen(file('long', [event('task_complete'), { type: 'response_item', payload: { big: 'x'.repeat(5 * 1024 * 1024) } }]))).toBe(true)+ })+})++describe('codexProvider', () => {+ it('lists sessions and archived ones with their names, skips what is not a person’s or is Harness’s own', async () => {+ const root = home()+ const live = write(join(root, 'sessions', '2026', '09', '20', rolloutName(C)), [meta(C, 'cli')])+ write(join(root, 'archived_sessions', rolloutName(D)), [meta(D, 'vscode', 'Codex Desktop')])+ write(join(root, 'sessions', '2026', '09', '21', rolloutName('01a0c4ad-de5e-7000-8000-000000000003')), [meta('01a0c4ad-de5e-7000-8000-000000000003', 'exec')])+ write(join(root, 'sessions', '2026', '09', '22', rolloutName('01a0c4ad-de5e-7000-8000-000000000004')), [meta('01a0c4ad-de5e-7000-8000-000000000004', 'cli', 'codex-tui', '/data/harness/recap')])+ mkdirSync(join(root, 'sessions', '2026', '09', '23', rolloutName('01a0c4ad-de5e-7000-8000-000000000005')), { recursive: true })+ symlinkSync(join(root, 'nowhere.jsonl'), join(root, 'archived_sessions', rolloutName('01a0c4ad-de5e-7000-8000-000000000006')))+ write(join(root, 'session_index.jsonl'), [{ id: C, thread_name: 'Retention cohorts' }])+ utimesSync(live, new Date('2026-09-25T00:00:00Z'), new Date('2026-09-25T00:00:00Z'))+ const provider = codexProvider({ home: root })+ const found = await provider.scan(scanMemo({ excluded: ['/data/harness'] }).context())+ expect(found.map((s) => [s.sessionId, s.origin, s.title]).sort()).toEqual([+ [C, 'terminal', 'Retention cohorts'],+ [D, 'codex-app', ''],+ ].sort())+ expect(found.find((s) => s.sessionId === C)).toMatchObject({ engine: 'codex', transcriptPath: live, mtime: Date.parse('2026-09-25T00:00:00Z') })+ })++ it('knows its owners from the rollouts Codex processes hold open, and asks their rollout about the turn', async () => {+ const root = home()+ const path = write(join(root, rolloutName(C)), [meta(C, 'cli'), event('task_started')])+ const served = join(root, rolloutName(D))+ const view: ProcessView = {+ list: async () => [+ { pid: 201, ppid: 1, executable: 'codex', args: '/opt/codex/bin/codex resume x' },+ { pid: 203, ppid: 1, executable: 'codex', args: '/opt/codex/bin/codex app-server --listen stdio' },+ ],+ openFiles: async () => new Map(), alive: () => true,+ openFilesOf: async (commands) => {+ expect(commands).toEqual(['codex', 'Codex'])+ return new Map([[201, [path, '/dev/ttys003', '/tmp/rollout-notes.txt']], [202, ['/x/rollout-2026-not-an-id.jsonl']], [203, [served]]])+ },+ }+ const provider = codexProvider({ home: root })+ // A server holding a thread is never stopped from here, even when a terminal started it.+ expect(await provider.owners!(view)).toEqual([+ { sessionId: C, pid: 201, record: path },+ { sessionId: D, pid: 203, record: served, app: true },+ ])+ expect(await provider.busy!({ pid: 201, record: path })).toBe(true)+ // Nothing held open: no process is looked at.+ let listed = false+ expect(await provider.owners!({ ...view, openFilesOf: async () => new Map(), list: async () => { listed = true; return [] } })).toEqual([])+ expect(listed).toBe(false)+ })++ it("tells Codex's servers from a person's Codex", () => {+ const row = (executable: string, args: string) => ({ pid: 1, ppid: 0, executable, args })+ expect(codexServer(undefined)).toBe(false)+ expect(codexServer(row('codex', 'codex'))).toBe(false)+ expect(codexServer(row('codex', 'codex -m o3 --yolo'))).toBe(false)+ expect(codexServer(row('codex', 'codex resume 01a0'))).toBe(false)+ expect(codexServer(row('codex', 'codex "run the mcp tests"'))).toBe(false)+ for (const sub of ['app-server', 'mcp-server', 'mcp', 'proto']) expect(codexServer(row('codex', `codex --verbose ${sub}`))).toBe(true)+ expect(codexServer(row('/opt/bin/codex-acp', '/opt/bin/codex-acp'))).toBe(true)+ expect(codexServer(row('node', 'node /opt/lib/codex-acp --stdio'))).toBe(true)+ })+})diff --git a/cli/src/lib/sessionSearch/externals/codex.ts b/cli/src/lib/sessionSearch/externals/codex.tsnew file mode 100644index 000000000..e57c22508--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/codex.ts@@ -0,0 +1,150 @@+/**+ * Codex: every local session is a rollout under `~/.codex/sessions/YYYY/MM/DD/` (or+ * `archived_sessions/`). Its first line (`session_meta`) says who wrote it: `source` `cli` (a+ * terminal) or `vscode` (the Codex app, whose `originator` is "Codex Desktop", and the editor+ * extensions). `exec` is a script and a `subagent` source is another thread's helper. Thread names+ * are in `session_index.jsonl`.+ *+ * Codex keeps no process record, but holds its rollout open while it runs, so `lsof` names the+ * owner; the rollout's last turn event says whether a turn is running.+ */++import { join } from 'node:path'++import { absoluteFolder, entries, fileStamp, firstLine, parseLine, readHead, readTail, readText, record, text } from './support.js'+import { argvTokens } from '../../tmux.js'+import { type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'++/** How much of a rollout is read for its first line: a little first; `session_meta` can carry long+ * base instructions, so up to a megabyte when it has to. */+const HEAD_BYTES = [16 * 1024, 1024 * 1024]+const SESSION_ID = /^[A-Za-z0-9-]{8,80}$/+const ROLLOUT_ID = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i++export interface CodexHead { sessionId: string; cwd: string; origin: ExternalOrigin }++/**+ * A rollout's session, folder and source, from its first line. UNSETTLED while that line has no end+ * yet in a file shorter than what is read: Codex is still writing it.+ */+export async function readCodexHead(path: string): Promise<CodexHead | null | typeof UNSETTLED> {+ let line: string | null = null+ for (const bytes of HEAD_BYTES) {+ line = await firstLine(path, bytes)+ if (line !== null) break+ // The whole file was read and it has no line yet: Codex is still writing it.+ if (Buffer.byteLength(await readHead(path, bytes)) < bytes) return UNSETTLED+ }+ if (line === null) return null+ const row = record(parseLine(line))+ const meta = record(row?.payload)+ if (row?.type !== 'session_meta' || !meta) return null+ const origin: ExternalOrigin | null = meta.source === 'cli' ? 'terminal'+ : meta.source === 'vscode' ? (meta.originator === 'Codex Desktop' ? 'codex-app' : 'editor')+ : null+ const cwd = absoluteFolder(meta.cwd)+ if (!origin || !SESSION_ID.test(text(meta.id)) || !cwd) return null+ return { sessionId: text(meta.id), cwd, origin }+}++/** Thread names: `session_index.jsonl`, one `{id, thread_name}` a line, the last one winning. */+export async function codexTitles(path: string, ctx: ScanContext): Promise<Map<string, string>> {+ const stamp = await fileStamp(path)+ if (!stamp) return new Map()+ return ctx.memo(`codex:titles:${path}`, stamp.stamp, async () => {+ const titles = new Map<string, string>()+ for (const line of (await readText(path)).split('\n')) {+ const row = record(parseLine(line))+ const name = text(row?.thread_name).trim()+ if (text(row?.id) && name) titles.set(text(row?.id), name)+ }+ return titles+ })+}++/** Every rollout file under a sessions folder (`YYYY/MM/DD/rollout-*.jsonl`), at any depth up to 4. */+export async function rollouts(dir: string): Promise<string[]> {+ const out: string[] = []+ const walk = async (at: string, depth: number): Promise<void> => {+ for (const entry of await entries(at)) {+ const path = join(at, entry.name)+ if (entry.isDirectory() && depth < 4) await walk(path, depth + 1)+ // A file or a link to one; the scan's stat drops a broken link.+ else if (!entry.isDirectory() && entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) out.push(path)+ }+ }+ await walk(dir, 0)+ return out+}++const TURN_MARK = /"(task_started|task_complete|turn_aborted)"/++const SERVER_COMMANDS = new Set(['app-server', 'mcp-server', 'mcp', 'proto'])++/** Whether a Codex process serves other clients rather than a person's terminal. */+export function codexServer(row: RunningProcess | undefined): boolean {+ if (!row) return false+ if (/codex-acp$/.test(row.executable) || /(?:^|\/)codex-acp(?:\s|$)/.test(row.args)) return true+ // The subcommand: the first argument that is not an option.+ const subcommand = argvTokens(row.args).slice(1).find((token) => !token.startsWith('-'))+ return !!subcommand && SERVER_COMMANDS.has(subcommand)+}++/**+ * Whether a rollout's last turn is still running: the last `task_started`, `task_complete` or+ * `turn_aborted` event near its end says. What was said can name the events; only events count.+ * A file that cannot say counts as busy.+ */+export async function codexTurnOpen(path: string): Promise<boolean> {+ for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {+ const lines = (await readTail(path, bytes)).split('\n')+ for (let i = lines.length - 1; i > 0; i--) {+ const line = lines[i]+ if (!line.includes('"event_msg"') || !TURN_MARK.test(line)) continue+ const kind = record(record(parseLine(line))?.payload)?.type+ if (kind === 'task_started') return true+ if (kind === 'task_complete' || kind === 'turn_aborted') return false+ }+ }+ return true+}++export function codexProvider(options: { home: string }): ExternalProvider {+ return {+ engine: 'codex',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const titles = await codexTitles(join(options.home, 'session_index.jsonl'), ctx)+ const found: ExternalSession[] = []+ for (const path of [+ ...await rollouts(join(options.home, 'sessions')),+ ...await rollouts(join(options.home, 'archived_sessions')),+ ]) {+ const stamp = await fileStamp(path)+ if (!stamp) continue+ // A rollout's first line never changes: read once, however the file grows.+ const head = await ctx.head(`codex:${path}`, stamp.stamp, () => readCodexHead(path))+ await ctx.pace()+ if (!head || ctx.excluded(head.cwd)) continue+ found.push({ ...head, engine: 'codex', title: titles.get(head.sessionId) ?? '', mtime: stamp.mtime, transcriptPath: path })+ }+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const claims: OwnerClaim[] = []+ const held = await view.openFilesOf(['codex', 'Codex'])+ if (!held.size) return claims+ const processes = new Map((await view.list()).map((row): [number, RunningProcess] => [row.pid, row]))+ for (const [pid, files] of held) {+ // A server Codex runs for other clients (the app, an editor, MCP) holds their threads: never+ // stopped from here, even when a terminal started it.+ const app = codexServer(processes.get(pid))+ for (const path of files) {+ const id = ROLLOUT_ID.exec(path)?.[1]+ if (id && path.includes('rollout-')) claims.push({ sessionId: id, pid, record: path, ...(app ? { app: true } : {}) })+ }+ }+ return claims+ },+ busy: (owner) => codexTurnOpen(owner.record),+ }+}diff --git a/cli/src/lib/sessionSearch/externals/commandcode.spec.ts b/cli/src/lib/sessionSearch/externals/commandcode.spec.tsnew file mode 100644index 000000000..421264a14--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/commandcode.spec.ts@@ -0,0 +1,226 @@+import { appendFileSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { commandCodeActivity, commandcodeProvider, readCommandCodeHead, readCommandCodeMeta } from './commandcode.js'+import { scanMemo } from './support.js'+import { type ExternalProvider, type ProcessView, type RunningProcess, UNSETTLED } from './types.js'++// Shapes follow command-code 1.66.0's own writer and the repo's recorded Command Code session+// (engines/commandcode/normalizer.spec.ts); every value here is made up.+const ID = '34e1385f-c18a-4f54-bf12-f8f57e151a3d'+const ID2 = '5d2c9b1e-0000-4000-8000-000000000002'+const T0 = Date.parse('2026-09-01T10:00:00.000Z')++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function temp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'commandcode-external-'))+ dirs.push(dir)+ return dir+}++const at = (seconds: number) => new Date(T0 + seconds * 1000).toISOString()+const header = (id: string, cwd: string, extra: Record<string, unknown> = {}) =>+ JSON.stringify({ type: 'session', version: 3, id, timestamp: at(0), cwd, ...extra })+const message = (role: string, seconds: number, source = role === 'user' ? 'user' : 'model') =>+ JSON.stringify({ type: 'message', id: `m${seconds}`, parentId: null, timestamp: at(seconds), message: { role, content: [{ type: 'text', text: 'words' }], meta: { source } } })+const jsonl = (...lines: string[]) => `${lines.join('\n')}\n`++function write(path: string, content: string, mtimeSeconds?: number): string {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, content)+ if (mtimeSeconds !== undefined) utimesSync(path, new Date(T0 + mtimeSeconds * 1000), new Date(T0 + mtimeSeconds * 1000))+ return path+}++/** A transcript where Command Code puts it; the slug is not derived here, since it is never read. */+function transcript(home: string, slug: string, id: string, lines: string[], mtimeSeconds?: number): string {+ return write(join(home, 'projects', slug, `${id}.jsonl`), jsonl(...lines), mtimeSeconds)+}++function scanner(provider: ExternalProvider, excluded: string[] = []) {+ const memo = scanMemo({ excluded })+ return async () => {+ const found = await provider.scan(memo.context())+ memo.prune()+ return found+ }+}++const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })+const view = (rows: RunningProcess[]): ProcessView => ({+ list: async () => rows, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,+})++describe('readCommandCodeHead', () => {+ const head = async (content: string, id = ID) => readCommandCodeHead(write(join(temp(), `${id}.jsonl`), content), id)++ it("reads the folder from Command Code's v3 header, when it names the file's own id", async () => {+ expect(await head(jsonl(header(ID, '/work/app'), message('user', 1)))).toEqual({ sessionId: ID, cwd: '/work/app' })+ expect(await head(`\n \n${jsonl(header(ID, '/work/app'))}`)).toEqual({ sessionId: ID, cwd: '/work/app' })+ // A fork (`/fork`, `--fork`) is a session of its own that names its parent.+ expect(await head(jsonl(header(ID, '/w', { parentSession: '/elsewhere/parent.jsonl' })))).toEqual({ sessionId: ID, cwd: '/w' })+ // A later format keeps the header's shape: its sessions are still listed.+ expect(await head(jsonl(header(ID, '/w', { version: 4 })))).toEqual({ sessionId: ID, cwd: '/w' })+ })++ it('refuses a v3 header that names another id, no time or a relative folder', async () => {+ expect(await head(jsonl(header(ID2, '/w')))).toBeNull()+ expect(await head(jsonl(header(ID, '/w', { timestamp: 5 })))).toBeNull()+ expect(await head(jsonl(header(ID, 'relative')))).toBeNull()+ })++ it('cannot judge yet a file from before v3 (Command Code rewrites it when it opens it) or a first line that is no header', async () => {+ expect(await head(jsonl(JSON.stringify({ sessionId: ID, role: 'user', content: 'x', metadata: { version: 2, entrypoint: 'interactive' } })))).toBe(UNSETTLED)+ expect(await head(jsonl(header(ID, '/w', { version: 2 })))).toBe(UNSETTLED)+ expect(await head(jsonl(header(ID, '/w', { version: '3' })))).toBe(UNSETTLED)+ expect(await head(jsonl(message('user', 1)))).toBe(UNSETTLED)+ expect(await head(jsonl('{torn'))).toBe(UNSETTLED)+ })++ it('says "not yet" while the header is being written, and "never" when no line fits the bound', async () => {+ expect(await head(header(ID, '/w'))).toBe(UNSETTLED)+ expect(await head('\n\n')).toBe(UNSETTLED)+ expect(await head('x'.repeat(256 * 1024 + 1))).toBeNull()+ // A header larger than the first read is read whole on a second.+ expect(await head(jsonl(header(ID, '/w', { extra: 'y'.repeat(40_000) }), message('user', 1)))).toEqual({ sessionId: ID, cwd: '/w' })+ })+})++describe('readCommandCodeMeta', () => {+ it('reads the title, and whether a headless run made the session', async () => {+ const dir = temp()+ expect(await readCommandCodeMeta(write(join(dir, 'a.meta.json'), JSON.stringify({ title: ' Fix the build ', model: 'm', userRenamed: true }))))+ .toEqual({ title: 'Fix the build', headless: false })+ expect(await readCommandCodeMeta(write(join(dir, 'b.meta.json'), JSON.stringify({ entrypoint: 'print' })))).toEqual({ title: '', headless: true })+ expect(await readCommandCodeMeta(write(join(dir, 'c.meta.json'), JSON.stringify({ entrypoint: 'interactive', title: 7 })))).toEqual({ title: '', headless: false })+ expect(await readCommandCodeMeta(write(join(dir, 'd.meta.json'), '{"title": "torn'))).toEqual({ title: '', headless: false })+ expect(await readCommandCodeMeta(join(dir, 'missing.meta.json'))).toEqual({ title: '', headless: false })+ })+})++describe('commandCodeActivity', () => {+ it("is Command Code's own time: its newest entry's, never the header's", async () => {+ const dir = temp()+ expect(await commandCodeActivity(write(join(dir, 'a.jsonl'), jsonl(+ header(ID, '/w', { timestamp: at(999) }), message('user', 10), message('assistant', 30),+ JSON.stringify({ type: 'session_info', id: 'i', parentId: null, timestamp: at(20), name: 'n' }),+ JSON.stringify({ type: 'label', timestamp: 'never' }), '{torn',+ )))).toBe(T0 + 30_000)+ expect(await commandCodeActivity(write(join(dir, 'b.jsonl'), jsonl(header(ID, '/w'))))).toBeNull()+ expect(await commandCodeActivity(join(dir, 'gone.jsonl'))).toBeNull()+ })++ it('reads only the end of a long transcript', async () => {+ const dir = temp()+ const long = JSON.stringify({ type: 'message', id: 'big', timestamp: at(5), message: { role: 'user', content: 'x'.repeat(70_000) } })+ expect(await commandCodeActivity(write(join(dir, 'a.jsonl'), jsonl(header(ID, '/w'), long, message('assistant', 6))))).toBe(T0 + 6_000)+ })+})++describe('commandcodeProvider', () => {+ it('lists each transcript under its header, titled from its meta file, beside the sidecars that are not transcripts', async () => {+ const home = temp()+ const path = transcript(home, 'users-me-work-app', ID, [header(ID, '/Users/me/Work/App'), message('user', 1), message('assistant', 2)])+ const folder = join(home, 'projects', 'users-me-work-app')+ write(join(folder, `${ID}.meta.json`), JSON.stringify({ title: 'Ship it' }))+ write(join(folder, `${ID}.prompts.jsonl`), jsonl(JSON.stringify({ prompt: 'x', cwd: '/Users/me/Work/App' })))+ write(join(folder, `${ID}.checkpoints.jsonl`), jsonl(JSON.stringify({ cwd: '/Users/me/Work/App' })))+ write(join(folder, `${ID}.share.json`), '{}')+ write(join(folder, `${ID}.v2.bak`), 'old')+ write(join(folder, 'notes.jsonl'), jsonl(header('notes', '/w')))+ expect(await scanner(commandcodeProvider({ home }))()).toEqual([+ { sessionId: ID, engine: 'commandcode', cwd: '/Users/me/Work/App', origin: 'terminal', title: 'Ship it', mtime: T0 + 2_000, transcriptPath: path },+ ])+ })++ it('leaves out headless runs, excluded folders, files from before the v3 format, and what is not a transcript file', async () => {+ const home = temp()+ transcript(home, 'a', ID, [header(ID, '/w/headless'), message('user', 1)])+ write(join(home, 'projects', 'a', `${ID}.meta.json`), JSON.stringify({ entrypoint: 'print' }))+ transcript(home, 'b', ID2, [header(ID2, '/data/harness/summary-scratch'), message('user', 1)])+ transcript(home, 'c', 'aaaaaaaa-0000-4000-8000-000000000003', [JSON.stringify({ sessionId: 'x', role: 'user', content: 'x', metadata: { version: 2 } })])+ write(join(home, 'projects', 'stray.jsonl'), jsonl(header(ID, '/w')))+ mkdirSync(join(home, 'projects', 'd', 'bbbbbbbb-0000-4000-8000-000000000004.jsonl'), { recursive: true })+ symlinkSync(join(home, 'nowhere.jsonl'), join(home, 'projects', 'd', 'cccccccc-0000-4000-8000-000000000005.jsonl'))+ const kept = transcript(home, 'e', 'dddddddd-0000-4000-8000-000000000006', [header('dddddddd-0000-4000-8000-000000000006', '/w/kept'), message('user', 1)])+ const found = await scanner(commandcodeProvider({ home }), ['/data/harness'])()+ expect(found.map((s) => [s.transcriptPath, s.title])).toEqual([[kept, '']])+ })++ it('titles a session with a torn meta file by nothing, dates one with no entry time by its file, and follows a linked project folder', async () => {+ const home = temp()+ const elsewhere = temp()+ write(join(elsewhere, `${ID}.jsonl`), jsonl(header(ID, '/w/linked'), JSON.stringify({ type: 'message', timestamp: 'later', message: { role: 'user', content: 'x' } })), 700)+ write(join(elsewhere, `${ID}.meta.json`), '{"title": "to')+ mkdirSync(join(home, 'projects'), { recursive: true })+ symlinkSync(elsewhere, join(home, 'projects', 'w-linked'))+ expect(await scanner(commandcodeProvider({ home }))()).toMatchObject([{ sessionId: ID, cwd: '/w/linked', title: '', mtime: T0 + 700_000 }])+ })++ it('lists a transcript whose header was still being written once it is whole', async () => {+ const home = temp()+ const path = write(join(home, 'projects', 'w', `${ID}.jsonl`), header(ID, '/w'))+ const scan = scanner(commandcodeProvider({ home }))+ expect(await scan()).toEqual([])+ appendFileSync(path, `\n${message('user', 1)}\n`)+ expect((await scan()).map((s) => s.sessionId)).toEqual([ID])+ })++ it('lists a file from before v3 once Command Code rewrites it in place with a header', async () => {+ const home = temp()+ const legacy = JSON.stringify({ sessionId: ID, role: 'user', content: 'x', timestamp: at(1), metadata: { version: 2, entrypoint: 'interactive' } })+ const path = transcript(home, 'w', ID, [legacy], 100)+ const scan = scanner(commandcodeProvider({ home }))+ expect(await scan()).toEqual([])+ // Unchanged: not read again, and still not listed.+ expect(await scan()).toEqual([])+ // Migrated as Command Code does it: a new file renamed over the old one.+ write(`${path}.tmp`, jsonl(header(ID, '/w/migrated'), message('user', 1)), 200)+ renameSync(`${path}.tmp`, path)+ expect((await scan()).map((s) => [s.sessionId, s.cwd])).toEqual([[ID, '/w/migrated']])+ })++ it('reads a meta file again only when it changed, and the header never again', async () => {+ const home = temp()+ const path = transcript(home, 'w', ID, [header(ID, '/w'), message('user', 1)], 100)+ const metaPath = write(join(home, 'projects', 'w', `${ID}.meta.json`), JSON.stringify({ title: 'First' }), 100)+ const scan = scanner(commandcodeProvider({ home }))+ expect((await scan())[0]).toMatchObject({ title: 'First', mtime: T0 + 1_000 })+ write(metaPath, JSON.stringify({ title: 'Firsx' }), 100)+ expect((await scan())[0].title).toBe('First')+ write(metaPath, JSON.stringify({ title: 'Renamed' }), 200)+ expect((await scan())[0].title).toBe('Renamed')+ // Headless learned late (the meta file is written after the transcript's header): dropped then.+ write(metaPath, JSON.stringify({ entrypoint: 'print' }), 300)+ expect(await scan()).toEqual([])+ rmSync(metaPath)+ write(path, jsonl(header(ID, '/w/elsewhere'), message('user', 1), message('assistant', 9)), 400)+ expect((await scan())[0]).toMatchObject({ cwd: '/w', title: '', mtime: T0 + 9_000 })+ })++ it('says which process has a session open from a resume in its arguments, and never whether it is mid-turn', async () => {+ const home = temp()+ const path = transcript(home, 'w', ID, [header(ID, '/w'), message('user', 1)])+ const provider = commandcodeProvider({ home })+ await scanner(provider)()+ const claims = await provider.owners!(view([+ // A process that kept its arguments (the recorded macOS row in tmux.spec.ts has these).+ row(4242, '⌘ Greeting', `cmd -r ${ID}`),+ row(4243, 'node', `node /opt/lib/node_modules/command-code/dist/index.mjs --resume ${ID2}`),+ // Renamed, as 1.66.0 does at start: nothing left to read.+ row(4244, 'command-code', 'command-code'),+ row(4247, '⌘ Greeting', '⌘ Greeting'),+ row(4245, '⌘ Other', 'cmd -r "Fix the build"'),+ row(4246, 'python3', `python3 tool.py --resume ${ID}`),+ ]))+ expect(claims).toEqual([+ { sessionId: ID, pid: 4242, record: path, fromArgs: true },+ { sessionId: ID2, pid: 4243, record: '', fromArgs: true },+ ])+ expect(await provider.busy!(claims[0])).toBeNull()+ })+})diff --git a/cli/src/lib/sessionSearch/externals/commandcode.ts b/cli/src/lib/sessionSearch/externals/commandcode.tsnew file mode 100644index 000000000..c1776e4f5--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/commandcode.ts@@ -0,0 +1,148 @@+/**+ * Command Code: `<home>/projects/<slug>/<id>.jsonl`, one file per session, written once its first+ * turn commits. The slug is lossy (case-folded, punctuation collapsed, camelCase split), so the+ * folder comes from the header alone: `{type:'session', version:3, id, timestamp, cwd}`, Pi's+ * envelope. Beside the transcript sit `<id>.meta.json` (its title, and `entrypoint: 'print'` for a+ * headless `cmd -p` run, which Command Code keeps out of its own picker and so is left out here),+ * `.prompts.jsonl`, `.checkpoints.jsonl`, `.share.json` and `.v2.bak`. A file from before the v3+ * format has no header and so no folder: it is left out until Command Code opens and rewrites it,+ * and read again then.+ * Read from command-code 1.66.0.+ *+ * Command Code holds no file open and writes no process record. Only an argv that names the session+ * (`--resume <id>`) says which process has it, and Command Code renames its process at start+ * (`command-code` in 1.66.0, `⌘ <title>` before), which replaces the arguments `ps` shows: a build or+ * launcher that leaves them is the only one found. Nothing on disk says a turn is running: a turn is+ * written when it commits, so a running one is not in the file yet.+ */++import { join } from 'node:path'++import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'+import { engineProcessMatch, resumeSessionId } from '../../tmux.js'+import { absoluteFolder, entries, fileStamp, parseLine, readHead, readJson, readTail, record, text } from './support.js'+import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'++/** A header is a few hundred bytes: this much is read first, and never more than the bound. */+const FIRST_BYTES = 16 * 1024+const HEAD_BYTES = 256 * 1024+const TAIL_BYTES = 64 * 1024+/** A transcript's name. Its sidecars end `.jsonl` too, so the whole name is matched. */+const TRANSCRIPT = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i++/**+ * A process row carries no file identity, so the PATH walk behind a full ownership snapshot could+ * not change a match: one empty snapshot serves every row.+ */+const NO_FILE_OWNERS: AgentCommandOwnershipSnapshot = {+ cursorFileKeys: new Set(), grokFileKeys: new Set(), conflictingFileKeys: new Set(),+ agentCandidates: [], cursorAgentCandidates: [], grokCandidates: [],+}++export interface CommandCodeHead { sessionId: string; cwd: string }++/**+ * A transcript's folder, from its first line: Command Code's v3 header, naming the same id as the+ * file (Command Code resumes by the file's name). Any later format keeps the header's shape. A file+ * from before v3 cannot be judged yet: Command Code rewrites it in place, with a header, when it+ * next opens it.+ */+export async function readCommandCodeHead(path: string, fileId: string): Promise<CommandCodeHead | null | typeof UNSETTLED> {+ let line: string | undefined+ for (const bytes of [FIRST_BYTES, HEAD_BYTES]) {+ const head = await readHead(path, bytes)+ line = head.split('\n').slice(0, -1).find((piece) => piece.trim())+ if (line !== undefined) break+ // The whole file, and no line in it yet: its header is still being written.+ if (Buffer.byteLength(head) < bytes) return UNSETTLED+ }+ if (line === undefined) return null+ const row = record(parseLine(line))+ const version = row?.version+ if (row?.type !== 'session' || typeof version !== 'number' || version < 3) return UNSETTLED+ const cwd = absoluteFolder(row.cwd)+ return typeof row.timestamp === 'string' && row.id === fileId && cwd ? { sessionId: fileId, cwd } : null+}++export interface CommandCodeMeta { title: string; headless: boolean }++/** A session's title and whether a headless run made it, from `<id>.meta.json`; none when it is missing or torn. */+export async function readCommandCodeMeta(path: string): Promise<CommandCodeMeta> {+ const meta = record(await readJson(path))+ return { title: text(meta?.title).trim(), headless: meta?.entrypoint === 'print' }+}++/** When the conversation last moved, as Command Code measures it: its newest entry's time. */+export async function commandCodeActivity(path: string): Promise<number | null> {+ const tail = await readTail(path, TAIL_BYTES)+ const lines = tail.split('\n')+ let latest: number | null = null+ // The first piece is part of a line when the read began mid-file; the header's time is its birth.+ for (const line of Buffer.byteLength(tail) < TAIL_BYTES ? lines : lines.slice(1)) {+ const row = record(parseLine(line))+ const at = row && row.type !== 'session' ? Date.parse(text(row.timestamp)) : NaN+ if (at > 0 && (latest === null || at > latest)) latest = at+ }+ return latest+}++/** Every file named like a transcript, one folder a project. Command Code reads linked folders too. */+async function transcripts(dir: string): Promise<Array<{ path: string; id: string }>> {+ const out: Array<{ path: string; id: string }> = []+ for (const project of await entries(dir)) {+ if (!project.isDirectory() && !project.isSymbolicLink()) continue+ const folder = join(dir, project.name)+ for (const file of await entries(folder)) {+ const id = TRANSCRIPT.exec(file.name)?.[1]+ if (id) out.push({ path: join(folder, file.name), id })+ }+ }+ return out+}++export interface CommandcodeOptions { home: string }++export function commandcodeProvider(options: CommandcodeOptions): ExternalProvider {+ /** Each id's transcript, from the last scan: what an owner's record points at. */+ let known = new Map<string, string>()+ return {+ engine: 'commandcode',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const found: ExternalSession[] = []+ for (const { path, id } of await transcripts(join(options.home, 'projects'))) {+ const stamp = await fileStamp(path)+ if (!stamp) continue+ // A v3 header never changes: read once, however the transcript grows.+ const head = await ctx.head(`commandcode:${path}`, stamp.stamp, () => readCommandCodeHead(path, id))+ await ctx.pace()+ if (!head || ctx.excluded(head.cwd)) continue+ const metaPath = path.replace(/\.jsonl$/, '.meta.json')+ const metaStamp = await fileStamp(metaPath)+ const meta = metaStamp+ ? await ctx.memo(`commandcode:meta:${metaPath}`, metaStamp.stamp, () => readCommandCodeMeta(metaPath))+ : { title: '', headless: false }+ if (meta.headless) continue+ const moved = await ctx.memo(`commandcode:time:${path}`, stamp.stamp, () => commandCodeActivity(path))+ found.push({+ sessionId: head.sessionId, engine: 'commandcode', cwd: head.cwd, origin: 'terminal',+ title: meta.title, mtime: moved ?? stamp.mtime, transcriptPath: path,+ })+ }+ known = new Map(found.map((session) => [session.sessionId, session.transcriptPath!]))+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const claims: OwnerClaim[] = []+ for (const row of await view.list()) {+ if (!engineProcessMatch(row, 'commandcode', NO_FILE_OWNERS).score) continue+ // `--resume <id>`, `-r <id>` or `--session <id>`: a title, a path or a prefix names no session exactly.+ const sessionId = resumeSessionId('commandcode', row.args)+ // Only the arguments say so, and a /resume inside moves on: never stopped on this.+ if (sessionId) claims.push({ sessionId, pid: row.pid, record: known.get(sessionId) ?? '', fromArgs: true })+ }+ return claims+ },+ // A turn reaches the file only once it commits: the file cannot say one is running.+ busy: async () => null,+ }+}diff --git a/cli/src/lib/sessionSearch/externals/copilot.spec.ts b/cli/src/lib/sessionSearch/externals/copilot.spec.tsnew file mode 100644index 000000000..e1a0b5517--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/copilot.spec.ts@@ -0,0 +1,416 @@+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { copilotMovedAt, copilotOrigin, copilotProvider, copilotTurnOpen, readCopilotSession, workspaceYaml } from './copilot.js'+import { scanMemo } from './support.js'+import type { ProcessView, RunningProcess, ScanContext } from './types.js'++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })++function home(): string {+ const dir = mkdtempSync(join(tmpdir(), 'copilot-external-'))+ dirs.push(dir)+ return dir+}++const ID = '10980e65-1a47-45ff-b666-90b8705efe20'+const ID2 = 'ef3f7502-a87c-41fd-b9b1-e1cbc9bcb643'+const ID3 = '5b0c6f7e-2d1a-4c3b-9e8f-7a6b5c4d3e2f'++function event(type: string, data: Record<string, unknown> = {}, extra: Record<string, unknown> = {}, timestamp = '2026-09-19T09:12:40.000Z'): string {+ return JSON.stringify({ type, data, id: 'e', timestamp, parentId: null, ...extra })+}++const start = (id: string, data: Record<string, unknown> = {}) =>+ event('session.start', { sessionId: id, version: 1, producer: 'copilot-agent', context: { cwd: '/work/start' }, ...data })+const ask = (extra: Record<string, unknown> = {}, data: Record<string, unknown> = {}, at = '2026-09-19T09:12:41.000Z') =>+ event('user.message', { content: 'hello', ...data }, extra, at)+const answer = (at = '2026-09-19T09:12:44.137Z', extra: Record<string, unknown> = {}) => event('assistant.message', { content: 'hi' }, extra, at)+const turnStart = (extra: Record<string, unknown> = {}) => event('assistant.turn_start', { turnId: '1' }, extra)+const turnEnd = (extra: Record<string, unknown> = {}, at = '2026-09-19T09:12:44.200Z') => event('assistant.turn_end', { turnId: '1' }, extra, at)+const shutdown = () => event('session.shutdown', { shutdownType: 'routine' }, {}, '2026-09-20T01:53:00.000Z')++interface Fixture { events?: string[] | string | null; workspace?: string | null }++function session(root: string, id: string, fixture: Fixture = {}): string {+ const dir = join(root, 'session-state', id)+ mkdirSync(dir, { recursive: true })+ const events = fixture.events === undefined ? [start(id), ask(), turnStart(), answer(), turnEnd(), shutdown()] : fixture.events+ if (events !== null) writeFileSync(join(dir, 'events.jsonl'), typeof events === 'string' ? events : `${events.join('\n')}\n`)+ const workspace = fixture.workspace === undefined+ ? `id: ${id}\ncwd: /work/app\nclient_name: vscode-agent-host\nname: Greeting reply\nuser_named: false\nsummary_count: 0\n`+ : fixture.workspace+ if (workspace !== null) writeFileSync(join(dir, 'workspace.yaml'), workspace)+ return dir+}++function counted(excluded: string[] = []) {+ const memo = scanMemo({ excluded })+ let reads = 0+ let paces = 0+ const context = (): ScanContext => {+ const inner = memo.context()+ return {+ ...inner,+ memo: (key, fingerprint, read) => inner.memo(key, fingerprint, () => { reads++; return read() }),+ pace: async () => { paces++; await inner.pace() },+ }+ }+ return { context, reads: () => reads, paces: () => paces }+}++function view(rows: RunningProcess[], alive: (pid: number) => boolean = () => true): ProcessView & { listed: () => number } {+ let listed = 0+ return {+ list: async () => { listed++; return rows },+ openFiles: async () => new Map(),+ openFilesOf: async () => new Map(),+ alive,+ listed: () => listed,+ }+}++const NATIVE = '/opt/homebrew/lib/node_modules/@github/copilot/node_modules/@github/copilot-darwin-arm64/copilot'+const cli = (pid: number, args = 'copilot'): RunningProcess => ({ pid, ppid: pid - 1, executable: NATIVE, args })++describe('copilotProvider.scan', () => {+ it('offers a session with the folder it is in now, its name, its program, and its last message\'s time', async () => {+ const root = home()+ session(root, ID)+ expect(await copilotProvider({ home: root }).scan(counted().context())).toEqual([{+ sessionId: ID, engine: 'copilot', cwd: '/work/app', origin: 'editor', title: 'Greeting reply',+ // The end of the last turn, not the shutdown written when VS Code quit hours later.+ mtime: Date.parse('2026-09-19T09:12:44.200Z'),+ transcriptPath: join(root, 'session-state', ID, 'events.jsonl'),+ }])+ })++ it('tells a terminal from an editor by `client_name`, and leaves out automation', async () => {+ expect(copilotOrigin('')).toBe('terminal')+ expect(copilotOrigin('copilot-cli')).toBe('terminal')+ for (const client of ['vscode-agent-host', 'GitHub Copilot Language Server', 'github/acp', 'microsoft/visualstudio-chat', 'JetBrains.IntelliJ', 'Google.Antigravity']) {+ expect(copilotOrigin(client)).toBe('editor')+ }+ for (const client of ['sdk', 'github/copilot-cloud-agent', 'github/coverage-agent', 'github/copilot-code-review', 'github/copilot-code-review/verification', 'github/code-scanning', 'github/code-scanning/semantic-query']) {+ expect(copilotOrigin(client)).toBeNull()+ }+ const root = home()+ session(root, ID, { workspace: `cwd: /work/app\nname: Terminal one\n` })+ session(root, ID2, { workspace: `cwd: /work/app\nclient_name: github/copilot-cloud-agent\n` })+ const found = await copilotProvider({ home: root }).scan(counted().context())+ expect(found.map((s) => [s.sessionId, s.origin])).toEqual([[ID, 'terminal']])+ expect(await readCopilotSession(join(root, 'session-state', ID2), ID2)).toEqual({ kind: 'skip', reason: 'automation' })+ })++ it('leaves out cloud tasks, detached rem-agent runs, and streams that are not this session\'s', async () => {+ const root = home()+ session(root, ID, { workspace: 'cwd: /work/app\nmc_task_id: task-1\n' })+ session(root, ID2, { events: [start(ID2, { detachedFromSpawningParentSessionId: ID }), ask()] })+ session(root, ID3, { events: [start(ID), ask()] })+ expect(await copilotProvider({ home: root }).scan(counted().context())).toEqual([])+ expect(await readCopilotSession(join(root, 'session-state', ID), ID)).toEqual({ kind: 'skip', reason: 'cloud-task' })+ expect(await readCopilotSession(join(root, 'session-state', ID2), ID2)).toEqual({ kind: 'skip', reason: 'detached' })+ expect(await readCopilotSession(join(root, 'session-state', ID3), ID3)).toEqual({ kind: 'skip', reason: 'mismatch' })+ })++ it('does not offer a stream that does not open with `session.start`', async () => {+ const root = home()+ session(root, ID, { events: [ask(), start(ID)] })+ session(root, ID3, { events: [event('session.start', {}), ask()].map((line) => line.replace('"data":{}', '"data":"x"')) })+ const blank = '66666666-6666-4666-8666-666666666666'+ session(root, blank, { events: ['', start(blank), ask()] })+ expect(await copilotProvider({ home: root }).scan(counted().context())).toEqual([])+ for (const id of [ID, ID3, blank]) expect(await readCopilotSession(join(root, 'session-state', id), id)).toEqual({ kind: 'skip', reason: 'unreadable' })+ })++ it('reads a session again next scan while its first line is half-written', async () => {+ const root = home()+ const dir = session(root, ID, { events: start(ID).slice(0, 40) })+ await expect(readCopilotSession(dir, ID)).rejects.toThrow('not written yet')+ const provider = copilotProvider({ home: root })+ const scan = counted()+ expect(await provider.scan(scan.context())).toEqual([])+ expect(await provider.scan(scan.context())).toEqual([])+ expect(scan.reads()).toBe(2)+ writeFileSync(join(dir, 'events.jsonl'), `${[start(ID), ask()].join('\n')}\n`)+ expect((await provider.scan(scan.context())).map((s) => s.sessionId)).toEqual([ID])+ })++ it('offers a session only once a person asked something: not a sub-agent, a skill, another agent or autopilot', async () => {+ const root = home()+ const noise = [+ ask({ agentId: 'sub-1' }), ask({ ephemeral: true }), ask({}, { source: 'skill-pdf' }), ask({}, { source: 'agent-7' }),+ ask({}, { isAutopilotContinuation: true }), event('user.message', 'not data' as unknown as Record<string, unknown>),+ event('system.message', { content: 'user.message' }), '{"type":"user.message",',+ ]+ session(root, ID, { events: [start(ID), ...noise, answer()] })+ session(root, ID2, { events: [start(ID2), ...noise, ask({}, { source: 'user' }), answer()] })+ session(root, ID3, { events: [start(ID3)] })+ // A prompt stays found when a sub-agent's prompt follows it in the same read.+ const later = '55555555-5555-4555-8555-555555555555'+ session(root, later, { events: [start(later), ask(), ask({ agentId: 'sub-1' }), answer()] })+ const found = await copilotProvider({ home: root }).scan(counted().context())+ expect(found.map((s) => s.sessionId).sort()).toEqual([later, ID2].sort())+ expect(await readCopilotSession(join(root, 'session-state', ID), ID)).toEqual({ kind: 'skip', reason: 'empty' })+ // A stream that went away between the listing and the read.+ expect(await readCopilotSession(join(root, 'session-state', 'gone'), 'gone')).toEqual({ kind: 'skip', reason: 'unreadable' })+ })++ it('follows a `/cwd` change, and falls back to the folder the session began in', async () => {+ const root = home()+ session(root, ID, { workspace: 'cwd: /work/moved\n' })+ session(root, ID2, { workspace: null })+ session(root, ID3, { workspace: 'cwd: relative/path\n' })+ const found = await copilotProvider({ home: root }).scan(counted().context())+ expect(Object.fromEntries(found.map((s) => [s.sessionId, [s.cwd, s.origin, s.title]]))).toEqual({+ [ID]: ['/work/moved', 'terminal', ''], [ID2]: ['/work/start', 'terminal', ''], [ID3]: ['/work/start', 'terminal', ''],+ })+ const nowhere = '44444444-4444-4444-8444-444444444444'+ session(root, nowhere, { events: [start(nowhere, { context: {} }), ask()], workspace: '' })+ expect(await readCopilotSession(join(root, 'session-state', nowhere), nowhere)).toEqual({ kind: 'skip', reason: 'no-folder' })+ })++ it('reads a quoted, escaped or wrapped folder and name exactly', async () => {+ const root = home()+ session(root, ID, { workspace: `cwd: '/work/it''s: here'\nname: "Fix \\"quotes\\" \\u00e9"\n` })+ session(root, ID2, { workspace: `cwd: /Users/x/Library/Application Support/Autonomous Workshop/runs/wish-20260827-173926\n /workspace one\nname: >-\n a folded\n name\n` })+ const found = await copilotProvider({ home: root }).scan(counted().context())+ expect(Object.fromEntries(found.map((s) => [s.sessionId, [s.cwd, s.title]]))).toEqual({+ [ID]: ["/work/it's: here", 'Fix "quotes" é'],+ [ID2]: ['/Users/x/Library/Application Support/Autonomous Workshop/runs/wish-20260827-173926 /workspace one', 'a folded name'],+ })+ })++ it('skips what is not a session folder, and folders Harness keeps its own sessions in', async () => {+ const root = home()+ session(root, ID)+ session(root, ID2, { events: null })+ mkdirSync(join(root, 'session-state', 'not-a-uuid'))+ writeFileSync(join(root, 'session-state', ID3), 'a file')+ expect((await copilotProvider({ home: root }).scan(counted().context())).map((s) => s.sessionId)).toEqual([ID])+ expect(await copilotProvider({ home: root }).scan(counted(['/work']).context())).toEqual([])+ expect(await copilotProvider({ home: join(root, 'missing') }).scan(counted().context())).toEqual([])+ })++ it('reads a session again only when its stream or workspace changed', async () => {+ const root = home()+ const dir = session(root, ID)+ const provider = copilotProvider({ home: root })+ const scan = counted()+ await provider.scan(scan.context())+ await provider.scan(scan.context())+ expect([scan.reads(), scan.paces()]).toEqual([1, 2])+ writeFileSync(join(dir, 'workspace.yaml'), 'cwd: /work/app\nname: Renamed\n')+ expect((await provider.scan(scan.context()))[0].title).toBe('Renamed')+ expect(scan.reads()).toBe(2)+ })+})++describe('when a Copilot conversation last moved', () => {+ it('is its last prompt, answer or turn end, else the stream\'s own time', async () => {+ const root = home()+ const a = session(root, ID, { events: [start(ID), ask(), turnEnd({}, '2026-09-19T10:00:00.000Z'), event('hook.start', {}, {}, '2026-09-19T11:00:00.000Z')] })+ expect(await copilotMovedAt(join(a, 'events.jsonl'))).toBe(Date.parse('2026-09-19T10:00:00.000Z'))+ const b = session(root, ID2, { events: [start(ID2), ask({}, {}, 'not a time'), shutdown()] })+ utimesSync(join(b, 'events.jsonl'), 1_700_000_000, 1_700_000_000)+ const found = await copilotProvider({ home: root }).scan(counted().context())+ expect(found.find((s) => s.sessionId === ID2)?.mtime).toBe(1_700_000_000_000)+ })++ it('reads further back past one long last line, and gives up past four megabytes', async () => {+ const root = home()+ const long = event('tool.execution_complete', { result: { content: 'x'.repeat(300 * 1024) } })+ const a = session(root, ID, { events: [start(ID), ask(), answer(), long] })+ expect(await copilotMovedAt(join(a, 'events.jsonl'))).toBe(Date.parse('2026-09-19T09:12:44.137Z'))+ const huge = event('tool.execution_complete', { result: { content: 'x'.repeat(5 * 1024 * 1024) } })+ const b = session(root, ID2, { events: [start(ID2), ask(), huge] })+ expect(await copilotMovedAt(join(b, 'events.jsonl'))).toBeNull()+ expect(await copilotMovedAt(join(root, 'missing.jsonl'))).toBeNull()+ })+})++describe('copilotProvider.owners', () => {+ const lock = (root: string, id: string, pid: number | string, at: number) => {+ const path = join(root, 'session-state', id, `inuse.${pid}.lock`)+ writeFileSync(path, '')+ utimesSync(path, at, at)+ }++ it('claims the session a live Copilot holds a lock on', async () => {+ const root = home()+ session(root, ID)+ lock(root, ID, 4242, 1_700_000_000)+ expect(await copilotProvider({ home: root }).owners!(view([cli(4242)]))).toEqual([+ { sessionId: ID, pid: 4242, record: join(root, 'session-state', ID, 'events.jsonl') },+ ])+ })++ it('reads nothing of the machine when no session is locked', async () => {+ const root = home()+ session(root, ID)+ lock(root, ID, 'x', 1_700_000_000)+ lock(root, ID, 0, 1_700_000_000)+ mkdirSync(join(root, 'session-state', ID, 'inuse.77.lock'))+ writeFileSync(join(root, 'session-state', 'inuse.5.lock'), '')+ mkdirSync(join(root, 'session-state', 'not-a-uuid'))+ writeFileSync(join(root, 'session-state', 'not-a-uuid', 'inuse.6.lock'), '')+ const processes = view([cli(4242)])+ expect(await copilotProvider({ home: root }).owners!(processes)).toEqual([])+ expect(await copilotProvider({ home: join(root, 'missing') }).owners!(processes)).toEqual([])+ expect(processes.listed()).toBe(0)+ })++ it('takes a pid\'s newest lock as the session it is in: `/resume` inside Copilot keeps the old one', async () => {+ const root = home()+ for (const id of [ID, ID2, ID3]) session(root, id)+ lock(root, ID, 4242, 1_700_000_000)+ lock(root, ID2, 4242, 1_700_000_100)+ lock(root, ID3, 5151, 1_700_000_000)+ lock(root, ID, 5151, 1_700_000_000)+ lock(root, ID, 6161, 1_700_000_200)+ lock(root, ID2, 6161, 1_700_000_000)+ const claims = await copilotProvider({ home: root }).owners!(view([cli(4242), cli(5151), cli(6161)]))+ // Two locks written in the same instant: the later id, for an answer that does not change.+ expect(claims.map((claim) => [claim.pid, claim.sessionId]).sort()).toEqual([[4242, ID2], [5151, ID3], [6161, ID]])+ })++ it('ignores a lock a crash left behind: a dead pid, one gone from the list, or one another program now has', async () => {+ const root = home()+ for (const id of [ID, ID2, ID3]) session(root, id)+ lock(root, ID, 11, 1_700_000_000)+ lock(root, ID2, 12, 1_700_000_000)+ lock(root, ID3, 13, 1_700_000_000)+ const rows: RunningProcess[] = [cli(11), { pid: 13, ppid: 1, executable: '/usr/bin/python3', args: '' }]+ expect(await copilotProvider({ home: root }).owners!(view(rows, (pid) => pid !== 11))).toEqual([])+ })++ it('ignores a lock older than the process that now has its pid, allowing the second `ps` truncates', async () => {+ const root = home()+ const ids = [ID, ID2, ID3, '77777777-7777-4777-8777-777777777777']+ for (const id of ids) session(root, id)+ ids.forEach((id, index) => lock(root, id, 31 + index, 1_700_000_000))+ const rows = [+ { ...cli(31), started: 1_700_000_005_000 },+ { ...cli(32), started: 1_700_000_000_500 },+ { ...cli(33), started: 1_699_999_940_000 },+ { ...cli(34), started: 1_700_000_001_001 },+ ]+ const claims = await copilotProvider({ home: root }).owners!(view(rows))+ expect(claims.map((claim) => claim.pid).sort()).toEqual([32, 33])+ })++ it('never offers to stop an editor\'s runtime or a Copilot serving other programs', async () => {+ const root = home()+ for (const id of [ID, ID2, ID3]) session(root, id)+ lock(root, ID, 21, 1_700_000_000)+ lock(root, ID2, 22, 1_700_000_000)+ lock(root, ID3, 23, 1_700_000_000)+ const rows: RunningProcess[] = [+ { pid: 21, ppid: 1, executable: '/Users/x/Library/Caches/copilot/sdk/runtime/1.0.15-darwin-arm64/prebuilds/darwin-arm64/copilot-runtime', args: 'copilot-runtime --headless --no-auto-update --stdio' },+ cli(22, `${NATIVE} --headless --stdio`),+ cli(23, `${NATIVE} --resume=${ID3}`),+ ]+ const claims = await copilotProvider({ home: root }).owners!(view(rows))+ expect(claims.map((claim) => [claim.pid, claim.app ?? false]).sort()).toEqual([[21, true], [22, true], [23, false]])+ })+})++describe('copilotProvider.busy', () => {+ const busy = (path: string) => copilotProvider({ home: '/nowhere' }).busy!({ pid: 1, record: path })++ it('is mid-turn when a prompt or a round started after the last round ended', async () => {+ const root = home()+ const open = session(root, ID, { events: [start(ID), ask(), turnStart(), answer(), turnEnd(), ask(), turnStart()] })+ expect(await busy(join(open, 'events.jsonl'))).toBe(true)+ const closed = session(root, ID2, { events: [start(ID2), ask(), turnStart(), answer(), turnEnd()] })+ expect(await busy(join(closed, 'events.jsonl'))).toBe(false)+ })++ it('is not mid-turn after Esc or a shutdown', async () => {+ const root = home()+ const aborted = session(root, ID, { events: [start(ID), ask(), turnStart(), event('abort', { reason: 'user' })] })+ expect(await copilotTurnOpen(join(aborted, 'events.jsonl'))).toBe(false)+ const down = session(root, ID2, { events: [start(ID2), ask(), turnStart(), shutdown()] })+ expect(await copilotTurnOpen(join(down, 'events.jsonl'))).toBe(false)+ })++ it('leaves a sub-agent\'s rounds out: they end inside the parent\'s turn', async () => {+ const root = home()+ const dir = session(root, ID, { events: [start(ID), ask(), turnStart(), turnStart({ agentId: 'sub' }), turnEnd({ agentId: 'sub' })] })+ expect(await copilotTurnOpen(join(dir, 'events.jsonl'))).toBe(true)+ })++ it('reads further back past one long last line, and cannot say with no turn event at all', async () => {+ const root = home()+ const long = event('tool.execution_complete', { result: { content: 'x'.repeat(300 * 1024) } })+ const a = session(root, ID, { events: [start(ID), ask(), turnStart(), long] })+ expect(await copilotTurnOpen(join(a, 'events.jsonl'))).toBe(true)+ const b = session(root, ID2, { events: [start(ID2), event('hook.start', {})] })+ expect(await copilotTurnOpen(join(b, 'events.jsonl'))).toBeNull()+ const huge = event('tool.execution_complete', { result: { content: 'x'.repeat(5 * 1024 * 1024) } })+ const c = session(root, ID3, { events: [start(ID3), ask(), huge] })+ expect(await copilotTurnOpen(join(c, 'events.jsonl'))).toBeNull()+ expect(await copilotTurnOpen(join(root, 'missing.jsonl'))).toBeNull()+ })+})++describe('workspaceYaml', () => {+ const value = (yaml: string, key = 'v') => workspaceYaml(yaml).get(key)++ it('reads the flat keys libyaml writes, whatever the line ending', () => {+ const parsed = workspaceYaml('\ufeffid: abc\r\ncwd: /work/app\r\nuser_named: false\r\nsummary_count: 0\r\n')+ expect(Object.fromEntries(parsed)).toEqual({ id: 'abc', cwd: '/work/app', user_named: 'false', summary_count: '0' })+ expect(workspaceYaml('')).toEqual(new Map())+ })++ it('reads plain values: comments, nulls, and lines folded into one', () => {+ expect(value('v: C# is fine # but this is a comment')).toBe('C# is fine')+ expect(value('v: a long\n folded\n\n value\nnext: x')).toBe('a long folded\nvalue')+ for (const none of ['v: ~', 'v: null', 'v: Null', 'v: NULL', 'v:', 'v: # only a comment']) expect(value(none)).toBeNull()+ })++ it('reads single quotes: a doubled quote is one, and lines fold', () => {+ expect(value("v: 'it''s: #here'")).toBe("it's: #here")+ expect(value("v: ' padded '")).toBe(' padded ')+ expect(value("v: 'one\n two \n\n\n three'")).toBe('one two\n\nthree')+ expect(value("v: 'unterminated")).toBeNull()+ expect(value("v: 'ends here\n '")).toBe('ends here ')+ })++ it('reads double quotes: every escape, escaped line breaks, and folded ones', () => {+ expect(value('v: "tab\\there \\"q\\" back\\\\slash \\/ \\x41 \\u00e9 \\U0001F600"')).toBe('tab\there "q" back\\slash / A é 😀')+ expect(value('v: "\\0\\a\\b\\v\\f\\r\\e\\ \\N\\_\\L\\P\\\t|"')).toBe('\0\x07\b\v\f\r\x1b \x85\xa0\u2028\u2029\t|')+ expect(value('v: "joined \\\n here"')).toBe('joined here')+ expect(value('v: "a\n \\ b"')).toBe('a b')+ expect(value('v: "one\n two\n\n three"')).toBe('one two\nthree')+ expect(value('v: "trailing "')).toBe('trailing ')+ })++ it('refuses a double-quoted value it cannot read', () => {+ for (const bad of ['v: "\\q"', 'v: "\\x4"', 'v: "\\xZZ"', 'v: "\\U00110000"', 'v: "ends in \\', 'v: "unterminated']) {+ expect(value(bad)).toBeNull()+ }+ })++ it('reads block values: literal and folded, each chomping, and an explicit indent', () => {+ expect(value('v: |-\n one\n two\nnext: x')).toBe('one\ntwo')+ expect(value('v: |\n one\n two\n')).toBe('one\ntwo\n')+ expect(value('v: |+\n one\n\n\nnext: x')).toBe('one\n\n\n')+ expect(value('v: |2-\n indented\n kept')).toBe(' indented\nkept')+ expect(value('v: |-2\n a')).toBe('a')+ expect(value('v: | # a comment\n a')).toBe('a\n')+ expect(value('v: >-\n one\n two\n\n three\n more\n four')).toBe('one two\nthree\n more\nfour')+ expect(value('v: >\n\n after a blank\n')).toBe('\nafter a blank\n')+ expect(value('v: |\n\nnext: x')).toBe('')+ expect(value('v: |x\n a')).toBeNull()+ })++ it('reads a map or a list as nothing, and ignores what is not a key', () => {+ const parsed = workspaceYaml('# comment\n---\nnested:\n a: 1\n b: 2\nlist:\n - x\nkey:value\n stray\nname: kept\n')+ expect(Object.fromEntries(parsed)).toEqual({ nested: null, list: null, name: 'kept' })+ })+})diff --git a/cli/src/lib/sessionSearch/externals/copilot.ts b/cli/src/lib/sessionSearch/externals/copilot.tsnew file mode 100644index 000000000..2b7279ae6--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/copilot.ts@@ -0,0 +1,348 @@+/**+ * GitHub Copilot CLI: one folder per conversation, `<COPILOT_HOME>/session-state/<id>/`, holding its+ * event stream (`events.jsonl`, whose first line is `session.start`) and `workspace.yaml` (its folder+ * as it is now, its name, and `client_name`: which program held it). The VS Code agent host and+ * other editors keep their sessions in the same store; cloud tasks (`mc_task_id`), a rem-agent run+ * detached from its parent, and programs driving the SDK are not a person's conversations.+ * Sub-agents live inside their parent's stream (`agentId`), never in a folder of their own.+ *+ * A process with a session open holds `inuse.<pid>.lock` in its folder, and an in-process `/resume`+ * takes a second lock without dropping the first: a pid's newest lock is the session it is in. The+ * pid is the runtime itself: the native `copilot` (the npm loader's child), or the SDK's+ * `copilot-runtime` that an editor starts, which is never stopped from here.+ */++import { readFile, stat } from 'node:fs/promises'+import { basename, join } from 'node:path'++import { copilotHistoryTurnOpen } from '../../../engines/copilot/normalizer.js'+import { agentCommandOwnershipSnapshot } from '../../engineBin.js'+import { argvTokens, engineProcessMatch } from '../../tmux.js'+import { forEachLine } from '../transcript.js'+import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readTail, record, text, UUID } from './support.js'+import type { ExternalOrigin, ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'++export interface CopilotOptions { home: string }++export type CopilotSkip = 'unreadable' | 'mismatch' | 'detached' | 'cloud-task' | 'automation' | 'no-folder' | 'empty'++/** What one session folder holds: a conversation to offer, or why it is not one. */+export type CopilotRead =+ | { kind: 'session'; cwd: string; origin: ExternalOrigin; title: string; movedAt: number | null }+ | { kind: 'skip'; reason: CopilotSkip }++const TAIL_BYTES = [256 * 1024, 4 * 1024 * 1024]+const LOCK = /^inuse\.(\d+)\.lock$/+/** `ps` gives a process's start to the second, truncated: a lock this much older can still be its own. */+const START_SLACK_MS = 1000++/** Clients that are an editor's agent (`client_name`, as the runtime's own telemetry groups them). */+const EDITOR_CLIENT = /^(?:vscode-agent-host|GitHub Copilot Language Server|github\/acp|microsoft\/.+|JetBrains\..+|Google\..+)$/+/** Clients that are GitHub's automation, or a program on the SDK that named nothing (`sdk`). */+const AUTOMATION_CLIENT = /^(?:sdk|github\/(?:copilot-cloud-agent|coverage-agent|copilot-code-review(?:\/.*)?|code-scanning(?:\/.*)?))$/+/** Event types that are the conversation moving. */+const MOVES = new Set(['user.message', 'assistant.message', 'assistant.turn_end', 'abort'])+/** Event types that open or close a turn: a tail with none of them cannot say whether one runs. */+const TURN_MARKS = new Set(['user.message', 'assistant.turn_start', 'assistant.turn_end', 'abort', 'session.shutdown'])+/** Flags that make a Copilot a server for other programs rather than a person's terminal. */+const SERVER_FLAGS = new Set(['--headless', '--server', '--stdio', '--acp'])++const skip = (reason: CopilotSkip): CopilotRead => ({ kind: 'skip', reason })++// ---- workspace.yaml -------------------------------------------------------------------------------++/** A double-quoted scalar's one-character escapes. */+const ESCAPES: Record<string, string> = {+ '0': String.fromCharCode(0), a: String.fromCharCode(7), b: '\b', t: '\t', '\t': '\t', n: '\n', v: '\v', f: '\f',+ r: '\r', e: String.fromCharCode(0x1b), ' ': ' ', '"': '"', '/': '/', '\\': '\\', N: String.fromCharCode(0x85),+ _: String.fromCharCode(0xa0), L: String.fromCharCode(0x2028), P: String.fromCharCode(0x2029),+}++/**+ * A flow scalar's text: plain (to the end of [source]), or quoted from its opening quote to its+ * closing one. Lines fold as YAML folds them: a line break between two lines is a space, each blank+ * line between them a newline, and the white space around a break is not content. In single quotes+ * `''` is a quote; in double quotes a backslash escapes, and an escaped line break joins two lines.+ */+function flow(source: string, quote: '' | "'" | '"'): string | null {+ let out = ''+ let space = ''+ let breaks = 0+ for (let i = quote ? 1 : 0; i < source.length; i++) {+ const char = source[i]+ if (char === ' ' || char === '\t') { space += char; continue }+ if (char === '\n') { breaks++; space = ''; continue }+ // Text follows: whatever separated it from the text before is folded now.+ out += breaks ? (breaks === 1 ? ' ' : '\n'.repeat(breaks - 1)) : space+ breaks = 0+ space = ''+ if (char === quote) {+ if (quote === "'" && source[i + 1] === "'") { out += "'"; i++; continue }+ return out+ }+ if (quote !== '"' || char !== '\\') { out += char; continue }+ const next = source[++i]+ if (next === '\n') {+ while (source[i + 1] === ' ' || source[i + 1] === '\t') i+++ continue+ }+ const width = next === 'x' ? 2 : next === 'u' ? 4 : next === 'U' ? 8 : 0+ const hex = source.slice(i + 1, i + 1 + width)+ if (width && hex.length === width && /^[0-9a-fA-F]+$/.test(hex) && parseInt(hex, 16) <= 0x10ffff) {+ out += String.fromCodePoint(parseInt(hex, 16))+ i += width+ } else if (!width && Object.hasOwn(ESCAPES, next)) {+ out += ESCAPES[next]+ } else {+ return null+ }+ }+ return quote ? null : out+}++/** A block scalar: `|` keeps its line breaks, `>` folds them; `-` strips the final ones, `+` keeps them all. */+function block(header: string, lines: readonly string[]): string | null {+ const shape = /^([|>])(?:([1-9])?([+-])?|([+-])([1-9]))[ \t]*(?:#.*)?$/.exec(header)+ if (!shape) return null+ const chomp = shape[3] ?? shape[4] ?? ''+ const indent = Number(shape[2] ?? shape[5] ?? 0) || (lines.find((line) => line.trim())?.search(/[^ ]/) ?? 0)+ const body = lines.map((line) => line.slice(indent))+ let end = body.length+ while (end > 0 && !body[end - 1].trim()) end--+ if (!end) return ''+ let text = ''+ if (shape[1] === '|') {+ text = body.slice(0, end).join('\n')+ } else {+ // Folded: a break between two lines is a space, but not around a blank or a more-indented line.+ let blank = 0+ let started = false+ let wasIndented = false+ for (const line of body.slice(0, end)) {+ if (!line) { blank++; continue }+ const indented = /^[ \t]/.test(line)+ if (!started) text += '\n'.repeat(blank)+ else text += indented || wasIndented ? '\n'.repeat(blank + 1) : blank ? '\n'.repeat(blank) : ' '+ text += line+ blank = 0+ started = true+ wasIndented = indented+ }+ }+ if (chomp === '-') return text+ return text + '\n'.repeat(chomp === '+' ? body.length - end + 1 : 1)+}++/** One value: the text after `key:`, and the lines that continue it. Null for none, and for a map+ * or a list, which Harness never needs from this file. */+function scalar(first: string, more: readonly string[]): string | null {+ if (!first) return null+ if (first.startsWith('"') || first.startsWith("'")) return flow([first, ...more].join('\n'), first[0] as "'" | '"')+ if (first.startsWith('|') || first.startsWith('>')) return block(first, more)+ // A plain value ends at a comment.+ const value = flow([first, ...more].map((line) => line.replace(/(?:^|[ \t])#.*$/, '')).join('\n'), '')+ return /^(?:~|null|Null|NULL)?$/.test(value!) ? null : value+}++/**+ * The top-level scalars of `workspace.yaml`. Copilot's runtime writes it with libyaml (serde_yaml),+ * which quotes a value only when it must (single quotes, else double) and writes one with line breaks as a+ * literal block (`|-`).+ */+export function workspaceYaml(source: string): Map<string, string | null> {+ const lines = (source.charCodeAt(0) === 0xfeff ? source.slice(1) : source).split(/\r?\n/)+ if (lines[lines.length - 1] === '') lines.pop()+ const values = new Map<string, string | null>()+ for (let i = 0; i < lines.length;) {+ const key = /^([A-Za-z_][\w.-]*):(?:[ \t]+(.*))?$/.exec(lines[i++])+ if (!key) continue+ const more: string[] = []+ while (i < lines.length && (!lines[i] || /^[ \t]/.test(lines[i]))) more.push(lines[i++])+ values.set(key[1], scalar((key[2] ?? '').trim(), more))+ }+ return values+}++// ---- the stream ----------------------------------------------------------------------------------++/** Where a session was held, from its `client_name`; null for automation, which is never offered. */+export function copilotOrigin(client: string): ExternalOrigin | null {+ if (AUTOMATION_CLIENT.test(client)) return null+ return EDITOR_CLIENT.test(client) ? 'editor' : 'terminal'+}++/** A prompt a person wrote: the main agent's, not a skill's injection, another agent's or autopilot's. */+function personPrompt(line: string): boolean {+ const row = record(parseLine(line))+ const data = record(row?.data)+ if (row?.type !== 'user.message' || !data || 'agentId' in row || row.ephemeral === true) return false+ return !/^(?:skill-|agent-)/.test(text(data.source)) && data.isAutopilotContinuation !== true+}++/**+ * The stream's first record (`session.start`), and whether a person asked anything: one pass from the+ * start, which stops at the first prompt. Null when the stream cannot be read. Throws while its first+ * line is still being written, so a scan's memo keeps nothing and the next scan reads it again.+ */+async function streamHead(path: string): Promise<{ start: Record<string, unknown> | null; prompted: boolean } | null> {+ let start: Record<string, unknown> | null = null+ let prompted = false+ let first = true+ let end: number+ try {+ ({ end } = await forEachLine(path, 0, ({ text: line, offset }) => {+ if (!offset) start = record(parseLine(line))+ // Several lines can follow in the chunk that held the prompt: one prompt is enough.+ else if (personPrompt(line)) prompted = true+ }, {+ // Past `session.start`, only a line that can be a prompt is read whole.+ skip: (head) => {+ const skipped = !first && !head.includes('"user.message"')+ first = false+ return skipped+ },+ shouldStop: () => prompted,+ }))+ } catch {+ return null+ }+ // Not one whole line yet.+ if (!end) throw new Error('session.start is not written yet')+ return { start, prompted }+}++/** The first answer [pick] gives, reading lines back from the end of [path]. */+async function fromEnd<T>(path: string, pick: (line: string) => T | null): Promise<T | null> {+ const size = (await stat(path).catch(() => null))?.size ?? 0+ for (const bytes of TAIL_BYTES) {+ const lines = (await readTail(path, bytes)).split('\n')+ // A window that starts mid-file starts mid-line.+ for (let i = lines.length - 1; i >= (size > bytes ? 1 : 0); i--) {+ const found = pick(lines[i])+ if (found !== null) return found+ }+ if (size <= bytes) break+ }+ return null+}++/** When the conversation last moved: its last prompt, answer or turn end. */+export function copilotMovedAt(path: string): Promise<number | null> {+ return fromEnd(path, (line) => {+ const row = record(parseLine(line))+ return MOVES.has(text(row?.type)) ? epochMs(row?.timestamp) : null+ })+}++/**+ * Whether the main agent is mid-turn, by `copilotHistoryTurnOpen` over the end of the stream. A+ * sub-agent's rounds (`agentId`) run inside the parent's turn and are left out. Null when the end of+ * the stream holds no turn event at all.+ */+export async function copilotTurnOpen(path: string): Promise<boolean | null> {+ const size = (await stat(path).catch(() => null))?.size ?? 0+ for (const bytes of TAIL_BYTES) {+ const lines = (await readTail(path, bytes)).split('\n').filter((line) => {+ // A window that starts mid-file starts mid-line, and half a line is not JSON.+ const row = record(parseLine(line))+ return !!row && !('agentId' in row) && TURN_MARKS.has(text(row.type))+ })+ if (lines.length) return copilotHistoryTurnOpen(lines)+ if (size <= bytes) break+ }+ return null+}++/**+ * One session folder, read: the conversation a person had there, or why it is not one. Throws while+ * its first line is half-written.+ */+export async function readCopilotSession(dir: string, sessionId: string): Promise<CopilotRead> {+ const events = join(dir, 'events.jsonl')+ const head = await streamHead(events)+ const data = record(head?.start?.data)+ if (!head || head.start?.type !== 'session.start' || !data) return skip('unreadable')+ if (text(data.sessionId) && data.sessionId !== sessionId) return skip('mismatch')+ if (text(data.detachedFromSpawningParentSessionId)) return skip('detached')+ const workspace = workspaceYaml(await readFile(join(dir, 'workspace.yaml'), 'utf8').catch(() => ''))+ if (workspace.get('mc_task_id')) return skip('cloud-task')+ const origin = copilotOrigin(workspace.get('client_name') ?? '')+ if (!origin) return skip('automation')+ // `workspace.yaml` follows a `/cwd` change, and a resume restores that folder; `session.start` has+ // the folder it began in.+ const cwd = absoluteFolder(workspace.get('cwd')) ?? absoluteFolder(record(data.context)?.cwd)+ if (!cwd) return skip('no-folder')+ if (!head.prompted) return skip('empty')+ return { kind: 'session', cwd, origin, title: (workspace.get('name') ?? '').trim(), movedAt: await copilotMovedAt(events) }+}++// ---- processes -----------------------------------------------------------------------------------++/** What [row] is: the CLI, an editor's SDK runtime (or a CLI serving one), or not Copilot at all. */+function copilotProcess(row: RunningProcess, ownership: ReturnType<typeof agentCommandOwnershipSnapshot>): 'cli' | 'server' | null {+ const tokens = argvTokens(row.args)+ const runtime = [row.executable, tokens[0] ?? ''].some((path) => /^copilot-runtime(?:\.exe)?$/i.test(basename(path)))+ if (!runtime && engineProcessMatch(row, 'copilot', ownership).score <= 0) return null+ return runtime || tokens.some((token) => SERVER_FLAGS.has(token)) ? 'server' : 'cli'+}++export function copilotProvider(options: CopilotOptions): ExternalProvider {+ const root = join(options.home, 'session-state')+ return {+ engine: 'copilot',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const found: ExternalSession[] = []+ for (const entry of await entries(root)) {+ if (!entry.isDirectory() || !UUID.test(entry.name)) continue+ const dir = join(root, entry.name)+ const events = join(dir, 'events.jsonl')+ const stamp = await fileStamp(events)+ if (!stamp) continue+ const workspace = await fileStamp(join(dir, 'workspace.yaml'))+ const read = await ctx.memo(`copilot:${dir}`, `${stamp.stamp}|${workspace?.stamp ?? '-'}`, () => readCopilotSession(dir, entry.name))+ .catch(() => null)+ await ctx.pace()+ // Half-written: nothing was remembered, and the next scan reads it again.+ if (read?.kind !== 'session' || ctx.excluded(read.cwd)) continue+ found.push({+ sessionId: entry.name, engine: 'copilot', cwd: read.cwd, origin: read.origin, title: read.title,+ mtime: read.movedAt ?? stamp.mtime, transcriptPath: events,+ })+ }+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ // Each pid's newest lock: the session it is in now.+ const newest = new Map<number, { sessionId: string; at: number }>()+ for (const entry of await entries(root)) {+ if (!entry.isDirectory() || !UUID.test(entry.name)) continue+ for (const file of await entries(join(root, entry.name))) {+ const pid = Number(LOCK.exec(file.name)?.[1] ?? 0)+ const stamp = pid > 0 ? await fileStamp(join(root, entry.name, file.name)) : null+ if (!stamp) continue+ const held = newest.get(pid)+ if (!held || stamp.mtime > held.at || (stamp.mtime === held.at && entry.name > held.sessionId)) {+ newest.set(pid, { sessionId: entry.name, at: stamp.mtime })+ }+ }+ }+ if (!newest.size) return []+ const rows = new Map((await view.list()).map((row) => [row.pid, row]))+ const ownership = agentCommandOwnershipSnapshot()+ const claims: OwnerClaim[] = []+ for (const [pid, held] of newest) {+ const row = rows.get(pid)+ // A crash leaves its lock behind, and the pid can be reused: only a live Copilot counts.+ const kind = row && view.alive(pid) ? copilotProcess(row, ownership) : null+ // A lock older than the process that has its pid was left by an earlier one.+ if (!kind || (row!.started !== undefined && held.at + START_SLACK_MS < row!.started)) continue+ claims.push({+ sessionId: held.sessionId, pid, record: join(root, held.sessionId, 'events.jsonl'),+ ...(kind === 'server' ? { app: true } : {}),+ })+ }+ return claims+ },+ busy: (owner) => copilotTurnOpen(owner.record),+ }+}diff --git a/cli/src/lib/sessionSearch/externals/cursor.spec.ts b/cli/src/lib/sessionSearch/externals/cursor.spec.tsnew file mode 100644index 000000000..c4e45af4c--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/cursor.spec.ts@@ -0,0 +1,471 @@+import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { builtinSqlite } from '../../sqliteRead.js'+import { cursorBucket, cursorProvider, cursorSlug, cursorTurnOpen, readChat, type CursorDatabase } from './cursor.js'+import { scanMemo } from './support.js'+import type { ProcessView, RunningProcess, ScanContext } from './types.js'++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })++/** A temporary folder, by its real path: Cursor hashes the physical folder. */+function temp(prefix = 'cursor-external-'): string {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), prefix)))+ dirs.push(dir)+ return dir+}++const ID = '6c3b2a1d-0e9f-4a8b-9c7d-6e5f4a3b2c1d'+const ID2 = '7d4c3b2e-1f0a-4b9c-8d7e-6f5a4b3c2d1e'+const ID3 = '8e5d4c3f-2a1b-4c0d-9e8f-7a6b5c4d3e2f'+const CWD = '/work/app'++interface ChatFixture { meta?: unknown; store?: boolean; bucket?: string }++function chat(config: string, cwd: string, id: string, fixture: ChatFixture = {}): string {+ const dir = join(config, 'chats', fixture.bucket ?? cursorBucket(cwd), id)+ mkdirSync(dir, { recursive: true })+ if (fixture.store !== false) writeFileSync(join(dir, 'store.db'), '')+ const meta = fixture.meta === undefined+ ? { schemaVersion: 1, createdAtMs: 1_790_000_000_000, hasConversation: true, title: ' Fix the build ', updatedAtMs: 1_790_000_100_000, cwd }+ : fixture.meta+ if (meta !== null) writeFileSync(join(dir, 'meta.json'), typeof meta === 'string' ? meta : JSON.stringify(meta))+ return dir+}++const USER = JSON.stringify({ role: 'user', message: { content: [{ type: 'text', text: '<user_query>hi</user_query>' }] } })+const ASSISTANT = JSON.stringify({ role: 'assistant', message: { content: [{ type: 'text', text: 'hello' }] } })+const ENDED = JSON.stringify({ type: 'turn_ended', status: 'success' })++function transcript(data: string, project: string, id: string, lines: string[] = [USER, ASSISTANT, ENDED], flat = false): string {+ const dir = flat ? join(data, 'projects', project, 'agent-transcripts') : join(data, 'projects', project, 'agent-transcripts', id)+ mkdirSync(dir, { recursive: true })+ const path = join(dir, `${id}.jsonl`)+ writeFileSync(path, `${lines.join('\n')}\n`)+ return path+}++function counted(excluded: string[] = []) {+ const memo = scanMemo({ excluded })+ let reads = 0+ let paces = 0+ const context = (): ScanContext => {+ const inner = memo.context()+ return {+ ...inner,+ memo: (key, fingerprint, read) => inner.memo(key, fingerprint, () => { reads++; return read() }),+ pace: async () => { paces++; await inner.pace() },+ }+ }+ return { context, reads: () => reads, paces: () => paces }+}++/** A chat store whose `meta` row is [value], as Cursor's agent-kv writes it. */+function fakeDatabase(value: unknown, opened: Array<string | URL> = []): CursorDatabase {+ return class {+ constructor(path: string | URL) { opened.push(path) }+ prepare() { return { get: () => value === undefined ? undefined : { value } } }+ close() { /* nothing held */ }+ } as unknown as CursorDatabase+}++const hex = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('hex')++function roots() {+ const config = temp()+ const data = temp()+ return { config, data, provider: (database: CursorDatabase | null = null) => cursorProvider({ configDir: config, dataDir: data, database }) }+}++describe('cursor naming', () => {+ it('slugs a folder the way Cursor files its transcripts, and buckets it by md5', () => {+ expect(cursorSlug('/Users/me/code/my-app')).toBe('Users-me-code-my-app')+ expect(cursorSlug('/a/b-c')).toBe(cursorSlug('/a/b/c'))+ expect(cursorSlug('/Users/me/.config/my app/')).toBe('Users-me-config-my-app')+ expect(cursorBucket('/work/app/')).toBe(cursorBucket('/work/app'))+ expect(cursorBucket('/work/app')).toMatch(/^[0-9a-f]{32}$/)+ })+})++describe('cursorProvider.scan', () => {+ it('offers a chat with its folder, title and transcript, from a config folder and a data folder apart', async () => {+ const { config, data, provider } = roots()+ chat(config, CWD, ID)+ const path = transcript(data, 'work-app', ID)+ expect(await provider().scan(counted().context())).toEqual([{+ sessionId: ID, engine: 'cursor', cwd: CWD, origin: 'terminal', title: 'Fix the build', mtime: 1_790_000_100_000, transcriptPath: path,+ }])+ })++ it('reads Cursor\'s default name as no title', async () => {+ const { config, provider } = roots()+ chat(config, CWD, ID, { meta: { createdAtMs: 1, hasConversation: true, title: 'New Agent', cwd: CWD } })+ expect((await provider().scan(counted().context()))[0]).toMatchObject({ title: '', transcriptPath: null })+ })++ it('leaves out sub-agents, empty chats, chats with no store, and chats it cannot read', async () => {+ const { config, provider } = roots()+ const ctx = counted().context()+ const sub = chat(config, CWD, ID, { meta: { createdAtMs: 1, hasConversation: true, isSubagent: true, cwd: CWD } })+ const empty = chat(config, CWD, ID2, { meta: { createdAtMs: 1, hasConversation: false, cwd: CWD } })+ const storeless = chat(config, CWD, ID3, { store: false })+ const bad = chat(config, '/work/other', ID, { meta: '{"createdAtMs":' })+ const undated = chat(config, '/work/other', ID2, { meta: { hasConversation: true, cwd: '/work/other' } })+ expect(await provider().scan(ctx)).toEqual([])+ expect(await readChat(ctx, sub, () => null)).toEqual({ kind: 'skip', reason: 'subagent' })+ expect(await readChat(ctx, empty, () => null)).toEqual({ kind: 'skip', reason: 'empty' })+ expect(await readChat(ctx, storeless, () => null)).toEqual({ kind: 'skip', reason: 'no-store' })+ expect(await readChat(ctx, bad, () => null)).toEqual({ kind: 'skip', reason: 'unreadable' })+ // Half-written: remembered by nothing, so read again.+ const again = counted()+ await readChat(again.context(), bad, () => null)+ await readChat(again.context(), bad, () => null)+ expect(again.reads()).toBe(2)+ writeFileSync(join(bad, 'meta.json'), JSON.stringify({ createdAtMs: 1, hasConversation: true, cwd: '/work/other' }))+ expect((await readChat(again.context(), bad, () => null)).kind).toBe('chat')+ expect(await readChat(ctx, undated, () => null)).toEqual({ kind: 'skip', reason: 'unreadable' })+ })++ it('gives every chat of a bucket the folder one of them names, and trusts a folder only when its md5 is the bucket', async () => {+ const { config, provider } = roots()+ chat(config, CWD, ID, { meta: { createdAtMs: 1, hasConversation: true, updatedAtMs: 5 } })+ chat(config, CWD, ID2, { meta: { createdAtMs: 1, hasConversation: true, updatedAtMs: 6, cwd: '/work/elsewhere' } })+ chat(config, CWD, ID3, { meta: { createdAtMs: 1, hasConversation: true, updatedAtMs: 7, cwd: `${CWD}/` } })+ const found = await provider().scan(counted().context())+ expect(found.map((s) => [s.sessionId, s.cwd])).toEqual([ID, ID2, ID3].map((id) => [id, CWD]))+ // A bucket whose only folder is wrong is not placed.+ const lone = roots()+ chat(lone.config, CWD, ID, { meta: { createdAtMs: 1, hasConversation: true, cwd: '/work/elsewhere' } })+ expect(await lone.provider().scan(counted().context())).toEqual([])+ })++ it('finds the folder of chats that never recorded it, from the project their transcript is filed under', async () => {+ const { config, data, provider } = roots()+ const base = temp('cursor-folder-')+ // `a-b` has the same slug as `a-b/_`, but not the md5 the bucket needs.+ const folder = join(base, 'a-b', '_')+ mkdirSync(folder, { recursive: true })+ writeFileSync(join(base, 'a-b', 'a file'), '')+ const meta = { createdAtMs: 1, hasConversation: true, updatedAtMs: 9 }+ chat(config, folder, ID, { meta })+ chat(config, folder, ID2, { meta })+ transcript(data, cursorSlug(folder), ID2)+ const scan = counted()+ const found = await provider().scan(scan.context())+ expect(found.map((s) => [s.sessionId, s.cwd])).toEqual([[ID, folder], [ID2, folder]])+ expect(found[1].transcriptPath).toBe(join(data, 'projects', cursorSlug(folder), 'agent-transcripts', ID2, `${ID2}.jsonl`))+ // The walk is remembered while the bucket's chats are the same ones.+ const reads = scan.reads()+ await provider().scan(scan.context())+ expect(scan.reads()).toBe(reads)+ })++ it('does not place chats whose folder is gone or cannot be reached', async () => {+ const { config, data, provider } = roots()+ const meta = { createdAtMs: 1, hasConversation: true }+ // Gone: two chats filed under one project, which is walked once.+ chat(config, '/nowhere/app-x', ID, { meta })+ chat(config, '/nowhere/app-x', ID2, { meta })+ transcript(data, cursorSlug('/nowhere/app-x'), ID)+ transcript(data, cursorSlug('/nowhere/app-x'), ID2)+ // No transcript at all.+ chat(config, '/nowhere/else', ID3, { meta })+ expect(await provider().scan(counted().context())).toEqual([])+ })++ it('stops walking after a bounded number of folders', async () => {+ const { config, data, provider } = roots()+ const base = temp('cursor-deep-')+ // Folders named `_` add nothing to a slug: every one of them looks like the way on.+ mkdirSync(join(base, ...Array.from({ length: 300 }, () => '_')), { recursive: true })+ const target = join(base, 'missing')+ chat(config, target, ID, { meta: { createdAtMs: 1, hasConversation: true } })+ transcript(data, cursorSlug(target), ID)+ expect(await provider().scan(counted().context())).toEqual([])+ })++ it('dates a chat by its store when `meta.json` does not say, the WAL included', async () => {+ const { config, provider } = roots()+ const dir = chat(config, CWD, ID, { meta: { createdAtMs: 1, hasConversation: true, cwd: CWD, updatedAtMs: 0 } })+ utimesSync(join(dir, 'store.db'), 1_700_000_000, 1_700_000_000)+ expect((await provider().scan(counted().context()))[0].mtime).toBe(1_700_000_000_000)+ writeFileSync(join(dir, 'store.db-wal'), 'wal')+ utimesSync(join(dir, 'store.db-wal'), 1_700_000_500, 1_700_000_500)+ expect((await provider().scan(counted().context()))[0].mtime).toBe(1_700_000_500_000)+ })++ it('finds a transcript filed under another project (a `--workspace` run), and the flat layout of older builds', async () => {+ const { config, data, provider } = roots()+ chat(config, CWD, ID)+ chat(config, CWD, ID2)+ chat(config, CWD, ID3)+ const moved = transcript(data, 'somewhere-else', ID)+ const flat = transcript(data, 'older', ID2, undefined, true)+ // A second flat copy elsewhere does not replace the first one found, and a text transcript is not one.+ transcript(data, 'zz-older', ID2, undefined, true)+ mkdirSync(join(data, 'projects', 'text', 'agent-transcripts', ID3), { recursive: true })+ writeFileSync(join(data, 'projects', 'text', 'agent-transcripts', ID3, `${ID3}.txt`), 'user: hi')+ writeFileSync(join(data, 'projects', 'text', 'agent-transcripts', `${ID3}.txt`), 'user: hi')+ mkdirSync(join(data, 'projects', 'mcp-only', 'mcps'), { recursive: true })+ mkdirSync(join(data, 'projects', 'text', 'agent-transcripts', 'not-a-uuid'), { recursive: true })+ writeFileSync(join(data, 'projects', '.agent-data-cleanup-2026-09-27'), '')+ const found = await provider().scan(counted().context())+ const byId = Object.fromEntries(found.map((s) => [s.sessionId, s.transcriptPath]))+ expect(byId[ID]).toBe(moved)+ expect([flat, join(data, 'projects', 'zz-older', 'agent-transcripts', `${ID2}.jsonl`)]).toContain(byId[ID2])+ expect(byId[ID3]).toBeNull()+ })++ it('skips what is not a chat folder, and folders Harness keeps its own sessions in', async () => {+ const { config, provider } = roots()+ chat(config, CWD, ID)+ mkdirSync(join(config, 'chats', 'not-a-bucket', ID), { recursive: true })+ writeFileSync(join(config, 'chats', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), '')+ mkdirSync(join(config, 'chats', cursorBucket(CWD), 'not-a-uuid'))+ writeFileSync(join(config, 'chats', cursorBucket(CWD), 'prompt_history.json'), '[]')+ mkdirSync(join(config, 'chats', cursorBucket('/work/empty')), { recursive: true })+ expect((await provider().scan(counted().context())).map((s) => s.sessionId)).toEqual([ID])+ expect(await provider().scan(counted(['/work']).context())).toEqual([])+ expect(await cursorProvider({ configDir: join(config, 'missing'), dataDir: config }).scan(counted().context())).toEqual([])+ })++ it('reads a chat again only when one of its files changed', async () => {+ const { config, provider } = roots()+ const dir = chat(config, CWD, ID)+ const scan = counted()+ const cursor = provider()+ await cursor.scan(scan.context())+ await cursor.scan(scan.context())+ expect([scan.reads(), scan.paces()]).toEqual([1, 2])+ writeFileSync(join(dir, 'meta.json'), JSON.stringify({ createdAtMs: 1, hasConversation: true, title: 'Renamed', cwd: CWD }))+ expect((await cursor.scan(scan.context()))[0].title).toBe('Renamed')+ expect(scan.reads()).toBe(2)+ })+})++describe('a chat with no meta.json, read from its store', () => {+ it('reads its title, whether it is empty or a sub-agent\'s, and checks the store is this chat\'s', async () => {+ const cases: Array<[unknown, string]> = [+ [hex({ agentId: ID, name: 'Refactor', latestRootBlobId: 'ab'.repeat(32) }), 'Refactor'],+ [hex({ name: 'New Agent', latestRootBlobId: 'ab' }), ''],+ [hex({ agentId: ID, latestRootBlobId: '' }), 'empty'],+ [hex({ agentId: ID, latestRootBlobId: 'ab', subagentInfo: { parentAgentId: ID2 } }), 'subagent'],+ [hex({ agentId: ID2, latestRootBlobId: 'ab' }), 'unreadable'],+ [hex(['not', 'an', 'object']), 'unreadable'],+ ['zz', 'unreadable'],+ ['abc', 'unreadable'],+ ['', 'unreadable'],+ [42, 'unreadable'],+ [undefined, 'unreadable'],+ ['ab'.repeat(64 * 1024 + 1), 'unreadable'],+ ]+ for (const [value, expected] of cases) {+ const { config } = roots()+ const dir = chat(config, CWD, ID, { meta: null })+ const read = await readChat(counted().context(), dir, () => fakeDatabase(value))+ expect(read.kind === 'chat' ? read.chat.meta.title : read.reason).toBe(expected)+ }+ })++ it('opens a store its Cursor closed immutable, so nothing is written beside it', async () => {+ const Database = builtinSqlite() as unknown as new (path: string, options: { readOnly: boolean }) => { exec(sql: string): void; close(): void }+ const { config, provider } = roots()+ const dir = chat(config, CWD, ID, { meta: null })+ rmSync(join(dir, 'store.db'))+ const writer = new Database(join(dir, 'store.db'), { readOnly: false })+ writer.exec(`PRAGMA journal_mode=WAL; CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT); INSERT INTO meta VALUES ('0', '${hex({ agentId: ID, name: 'Stored', latestRootBlobId: 'ab' })}')`)+ writer.close()+ expect(readdirSync(dir).sort()).toEqual(['store.db'])+ // The chat has no folder of its own; a sibling names the bucket's.+ chat(config, CWD, ID2)+ // No `database` given: the provider uses this Node's own SQLite.+ const found = await cursorProvider({ configDir: config, dataDir: temp() }).scan(counted().context())+ expect(found.map((s) => [s.sessionId, s.title])).toEqual([[ID, 'Stored'], [ID2, 'Fix the build']])+ expect(readdirSync(dir).sort()).toEqual(['store.db'])+ void provider+ })++ it('reads a store its Cursor still has open through the WAL, where the latest metadata is', async () => {+ const Database = builtinSqlite() as unknown as new (path: string, options: { readOnly: boolean }) => { exec(sql: string): void; close(): void }+ const { config } = roots()+ const dir = chat(config, CWD, ID, { meta: null })+ rmSync(join(dir, 'store.db'))+ const writer = new Database(join(dir, 'store.db'), { readOnly: false })+ try {+ writer.exec(`PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT); INSERT INTO meta VALUES ('0', '${hex({ agentId: ID, name: 'Old', latestRootBlobId: 'ab' })}')`)+ writer.exec(`UPDATE meta SET value = '${hex({ agentId: ID, name: 'Latest', latestRootBlobId: 'ab' })}' WHERE key = '0'`)+ expect(existsSync(join(dir, 'store.db-wal')) && existsSync(join(dir, 'store.db-shm'))).toBe(true)+ const read = await readChat(counted().context(), dir, () => builtinSqlite() as unknown as CursorDatabase)+ expect(read.kind === 'chat' && read.chat.meta.title).toBe('Latest')+ } finally {+ writer.close()+ }+ })++ it('tries again next scan when a store cannot be opened, and reads nothing with no SQLite', async () => {+ const { config } = roots()+ const dir = chat(config, CWD, ID, { meta: null })+ let opens = 0+ const Broken = class { constructor() { opens++; throw new Error('database is locked') } } as unknown as CursorDatabase+ const scan = counted()+ expect(await readChat(scan.context(), dir, () => Broken)).toEqual({ kind: 'skip', reason: 'unreadable' })+ expect(await readChat(scan.context(), dir, () => Broken)).toEqual({ kind: 'skip', reason: 'unreadable' })+ expect(opens).toBe(2)+ expect(await readChat(counted().context(), dir, () => null)).toEqual({ kind: 'skip', reason: 'unreadable' })+ })++ it('opens the store in place while its WAL files are there, and as an immutable URL when they are not', async () => {+ const { config } = roots()+ const dir = chat(config, CWD, ID, { meta: null })+ const opened: Array<string | URL> = []+ const value = hex({ agentId: ID, latestRootBlobId: 'ab' })+ await readChat(counted().context(), dir, () => fakeDatabase(value, opened))+ writeFileSync(join(dir, 'store.db-wal'), '')+ writeFileSync(join(dir, 'store.db-shm'), '')+ await readChat(counted().context(), dir, () => fakeDatabase(value, opened))+ expect(opened.map(String)).toEqual([`file://${join(dir, 'store.db')}?immutable=1`, join(dir, 'store.db')])+ })+})++describe('cursorProvider.owners', () => {+ const NODE = '/Users/x/.local/share/cursor-agent/versions/2026.09.26/node'+ const cursorRow = (pid: number, args = '', ppid = 1): RunningProcess => ({+ pid, ppid, executable: NODE, args: `cursor-agent --use-system-ca /Users/x/.local/share/cursor-agent/versions/2026.09.26/index.js ${args}`.trim(),+ })++ /** No [files]: `lsof` said nothing at all. */+ function view(rows: RunningProcess[], files?: Record<number, string[]>, alive: (pid: number) => boolean = () => true) {+ const asked: number[][] = []+ const processes: ProcessView = {+ list: async () => rows,+ openFiles: async (pids) => { asked.push([...pids]); return new Map(files ? pids.map((pid) => [pid, files[pid] ?? []]) : []) },+ openFilesOf: async () => new Map(),+ alive,+ }+ return { processes, asked }+ }++ it('claims the chat whose store a running Cursor holds open', async () => {+ const { config, provider } = roots()+ const dir = chat(config, CWD, ID)+ const store = join(dir, 'store.db')+ const { processes } = view([cursorRow(70)], { 70: [store, `${store}-wal`, `${store}-shm`, '/dev/ttys003'] })+ expect(await provider().owners!(processes)).toEqual([{ sessionId: ID, pid: 70, record: store }])+ })++ it('reads the files of Cursor processes only, and nothing when none runs', async () => {+ const { provider } = roots()+ const { processes, asked } = view([{ pid: 5, ppid: 1, executable: '/usr/bin/python3', args: 'python3 cursor-agent.py' }, cursorRow(71)], undefined, (pid) => pid !== 71)+ expect(await provider().owners!(processes)).toEqual([])+ expect(asked).toEqual([])+ })++ it('knows a chat store by where it is, whichever spelling of the config folder `lsof` prints', async () => {+ const { config, provider } = roots()+ const bucket = cursorBucket(CWD)+ const worker = `/Users/x/Library/Application Support/Cursor/User/globalStorage/anysphere.cursor-agent-worker/worker-data/w/chats/${bucket}/${ID2}/store.db`+ const { processes } = view([cursorRow(72)], {+ 72: [+ join(config, 'chats', bucket, ID, 'store.db'),+ worker,+ join(config, 'chats', bucket, ID3, 'store.db-journal'),+ join(config, 'chats', bucket, 'not-a-uuid', 'store.db'),+ join(config, 'chats', 'not-a-bucket', ID3, 'store.db'),+ ],+ })+ expect(await provider().owners!(processes)).toEqual([{ sessionId: ID, pid: 72, record: join(config, 'chats', bucket, ID, 'store.db') }])+ })++ it('falls back to the chat its `--resume` names when no store is open', async () => {+ const { config, provider } = roots()+ const dir = chat(config, CWD, ID)+ writeFileSync(join(config, 'chats', 'README'), '')+ mkdirSync(join(config, 'chats', 'not-a-bucket', ID2), { recursive: true })+ writeFileSync(join(config, 'chats', 'not-a-bucket', ID2, 'store.db'), '')+ const { processes } = view([+ cursorRow(73, `--resume ${ID}`), cursorRow(74, `--resume=${ID2}`), cursorRow(75, '--resume 0123456789abcdef'), cursorRow(76),+ ])+ // Arguments only say where a process started: a guess, never stopped on.+ expect(await provider().owners!(processes)).toEqual([+ { sessionId: ID, pid: 73, record: join(dir, 'store.db'), fromArgs: true },+ { sessionId: ID2, pid: 74, record: '', fromArgs: true },+ ])+ // A Cursor that has not made its config folder yet.+ const bare = cursorProvider({ configDir: join(config, 'missing'), dataDir: config, database: null })+ expect(await bare.owners!(view([cursorRow(73, `--resume ${ID}`)]).processes)).toEqual([{ sessionId: ID, pid: 73, record: '', fromArgs: true }])+ })++ it('never offers to stop a chat in Cursor\'s own tmux server', async () => {+ const { config, provider } = roots()+ const store = join(chat(config, CWD, ID), 'store.db')+ const rows: RunningProcess[] = [+ { pid: 10, ppid: 1, executable: 'tmux', args: 'tmux -u -L cursor-agent -f /dev/null new-session -d' },+ { pid: 11, ppid: 10, executable: '/bin/bash', args: 'bash -l' },+ cursorRow(80, '', 11),+ { pid: 12, ppid: 1, executable: '/opt/homebrew/bin/tmux', args: '/opt/homebrew/bin/tmux -Lcursor-agent-2 attach' },+ cursorRow(81, `--resume ${ID}`, 12),+ { pid: 13, ppid: 1, executable: 'tmux', args: 'tmux -L harness new-session' },+ cursorRow(82, `--resume ${ID}`, 13),+ { pid: 14, ppid: 1, executable: '/bin/zsh', args: 'tmux -L' },+ cursorRow(83, `--resume ${ID}`, 14),+ ]+ const { processes } = view(rows, { 80: [store] })+ const claims = await provider().owners!(processes)+ expect(claims.map((claim) => [claim.pid, claim.app ?? false])).toEqual([[80, true], [81, true], [82, false], [83, false]])+ })++ it('looks only a few parents up for that tmux server', async () => {+ const { config, provider } = roots()+ chat(config, CWD, ID)+ const rows: RunningProcess[] = [+ { pid: 20, ppid: 1, executable: 'tmux', args: 'tmux -L cursor-agent' },+ ...[21, 22, 23, 24].map((pid) => ({ pid, ppid: pid - 1, executable: '/bin/sh', args: '' })),+ cursorRow(90, `--resume ${ID}`, 24),+ ]+ const claims = await provider().owners!(view(rows).processes)+ expect(claims.map((claim) => claim.app ?? false)).toEqual([false])+ })+})++describe('cursorProvider.busy', () => {+ it('reads the transcript of the chat whose store the owner holds', async () => {+ const { config, data, provider } = roots()+ const open = chat(config, CWD, ID)+ transcript(data, 'work-app', ID, [USER, ASSISTANT, ENDED, USER, ASSISTANT])+ const closed = chat(config, CWD, ID2, { meta: { createdAtMs: 1, hasConversation: true } })+ transcript(data, 'somewhere-else', ID2)+ const cursor = provider()+ expect(await cursor.busy!({ pid: 1, record: join(open, 'store.db') })).toBe(true)+ // No folder in its `meta.json`: its transcript is found by id.+ expect(await cursor.busy!({ pid: 1, record: join(closed, 'store.db') })).toBe(false)+ })++ it('cannot say without a store or a transcript', async () => {+ const { config, provider } = roots()+ const dir = chat(config, CWD, ID)+ expect(await provider().busy!({ pid: 1, record: '' })).toBeNull()+ expect(await provider().busy!({ pid: 1, record: join(dir, 'store.db') })).toBeNull()+ })+})++describe('cursorTurnOpen', () => {+ it('is open when a prompt follows the last `turn_ended`, and cannot say from answers alone', async () => {+ const { data } = roots()+ expect(await cursorTurnOpen(transcript(data, 'p', ID, [USER, ASSISTANT, ENDED]))).toBe(false)+ expect(await cursorTurnOpen(transcript(data, 'p', ID2, [USER, ENDED, USER]))).toBe(true)+ expect(await cursorTurnOpen(transcript(data, 'p', ID3, [ASSISTANT, 'not json']))).toBeNull()+ expect(await cursorTurnOpen(join(data, 'missing.jsonl'))).toBeNull()+ })++ it('reads further back past one long last line', async () => {+ const { data } = roots()+ const long = JSON.stringify({ role: 'assistant', message: { content: [{ type: 'text', text: 'x'.repeat(300 * 1024) }] } })+ expect(await cursorTurnOpen(transcript(data, 'p', ID, [USER, long]))).toBe(true)+ const huge = JSON.stringify({ role: 'assistant', message: { content: [{ type: 'text', text: 'x'.repeat(5 * 1024 * 1024) }] } })+ expect(await cursorTurnOpen(transcript(data, 'p', ID2, [USER, huge]))).toBeNull()+ })+})diff --git a/cli/src/lib/sessionSearch/externals/cursor.ts b/cli/src/lib/sessionSearch/externals/cursor.tsnew file mode 100644index 000000000..8d445bc4a--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/cursor.ts@@ -0,0 +1,349 @@+/**+ * Cursor (`cursor-agent`, also `agent`): a chat is `<configDir>/chats/<md5(folder)>/<id>/`, holding its+ * `store.db` (SQLite, WAL) and `meta.json`, which says its title, when it last moved, the folder it+ * ran in, and whether it is a sub-agent's or still empty. What was said is a separate transcript+ * under the data folder: `<dataDir>/projects/<slug(folder)>/agent-transcripts/<id>/<id>.jsonl`.+ *+ * `--resume` looks for a chat only in the bucket of the folder it runs in, so a chat is offered with+ * a folder only when that folder's md5 is its bucket's name. Every chat in a bucket shares its folder,+ * so one chat that names it names it for all. The slug is lossy (`/a/b-c` and `/a/b/c` are both+ * `a-b-c`) and is never read as a folder; it only guides a walk whose every answer the md5 checks.+ *+ * No `store.db` means no chat Cursor can resume (the IDE's transcripts, a worker's runs elsewhere).+ * A `--print` run cannot be told from a person's chat: both are listed.+ *+ * A running Cursor holds its chat's `store.db` open for the life of the chat, so `lsof` names the+ * owner; `--resume <id>` in its arguments is the fallback. A chat inside Cursor's own tmux server+ * (`tmux -L cursor-agent`, its "persistent sessions") is stopped with `agent persist stop`, never by+ * a signal from here.+ */++import { createHash } from 'node:crypto'+import { readFile, realpath, stat } from 'node:fs/promises'+import { basename, dirname, join, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'++import { agentCommandOwnershipSnapshot } from '../../engineBin.js'+import { builtinSqlite } from '../../sqliteRead.js'+import { argvTokens, engineProcessMatch, resumeSessionId } from '../../tmux.js'+import { absoluteFolder, entries, fileStamp, parseLine, readJson, readTail, record, text, UUID } from './support.js'+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'++/** The read-only SQLite a chat store is read with; `node:sqlite`'s `DatabaseSync` in production. */+export interface CursorDatabase {+ new (path: string | URL, options: { readOnly: boolean }): { prepare(sql: string): { get(): unknown }; close(): void }+}++export interface CursorOptions {+ configDir: string+ dataDir: string+ /** How a chat with no `meta.json` has its store read; null when this Node has no SQLite. Tests set it. */+ database?: CursorDatabase | null+}++/** A chat's own account of itself, from `meta.json` or, when that is missing, its store. */+export interface CursorMeta {+ title: string+ /** When the chat last moved (`updatedAtMs`); null when it does not say. */+ updatedAt: number | null+ hasConversation: boolean+ isSubagent: boolean+ cwd: string | null+}++export type CursorSkip = 'no-store' | 'unreadable' | 'subagent' | 'empty'++const BUCKET = /^[0-9a-f]{32}$/+/** Cursor's name for a chat nobody named. */+const DEFAULT_TITLE = 'New Agent'+const META_MAX_BYTES = 64 * 1024+const TAIL_BYTES = [256 * 1024, 4 * 1024 * 1024]+/** How many folders a walk for a lost folder may list before it gives up. */+const WALK_READS = 256++/** Cursor's project name for a folder: every run of other characters becomes one `-`, trimmed. */+export function cursorSlug(folder: string): string {+ return folder.replace(/[^a-zA-Z0-9]/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '')+}++/** A folder's bucket name: the md5 of its resolved path. */+export function cursorBucket(folder: string): string {+ return createHash('md5').update(resolve(folder)).digest('hex')+}++function cursorTitle(value: unknown): string {+ const title = text(value).trim()+ return title === DEFAULT_TITLE ? '' : title+}++/** `meta.json` as Cursor itself reads it: without a numeric `createdAtMs` it is not one. */+export function parseCursorMeta(value: unknown): CursorMeta | null {+ const row = record(value)+ if (!row || typeof row.createdAtMs !== 'number' || !Number.isFinite(row.createdAtMs)) return null+ const updated = row.updatedAtMs+ return {+ title: cursorTitle(row.title),+ updatedAt: typeof updated === 'number' && Number.isFinite(updated) && updated > 0 ? Math.floor(updated) : null,+ hasConversation: row.hasConversation === true,+ isSubagent: row.isSubagent === true,+ cwd: absoluteFolder(row.cwd),+ }+}++/**+ * A chat store's own metadata (`meta` row `0`, hex-encoded JSON), for a chat whose `meta.json` is+ * missing. Opening a WAL database creates its `-wal` and `-shm` files when they are not there, so a+ * store without them (its Cursor closed it cleanly, and the main file holds everything) is opened+ * immutable: nothing is written beside it. A store that cannot be opened throws; the next scan tries+ * again.+ */+export async function readStoreMeta(storePath: string, Database: CursorDatabase | null): Promise<CursorMeta | null> {+ if (!Database) return null+ const [wal, shm] = await Promise.all([fileStamp(`${storePath}-wal`), fileStamp(`${storePath}-shm`)])+ const url = pathToFileURL(storePath)+ url.search = 'immutable=1'+ const db = new Database(wal && shm ? storePath : url, { readOnly: true })+ let value: unknown+ try {+ value = record(db.prepare("SELECT value FROM meta WHERE key = '0' LIMIT 1").get())?.value+ } finally {+ db.close()+ }+ const hex = text(value)+ if (!hex || hex.length > META_MAX_BYTES * 2 || !/^(?:[0-9a-f]{2})+$/i.test(hex)) return null+ const meta = record(parseLine(Buffer.from(hex, 'hex').toString('utf8')))+ if (!meta || (text(meta.agentId) && meta.agentId !== basename(dirname(storePath)))) return null+ return {+ title: cursorTitle(meta.name),+ updatedAt: null,+ hasConversation: text(meta.latestRootBlobId).length > 0,+ isSubagent: meta.subagentInfo !== undefined && meta.subagentInfo !== null,+ cwd: null,+ }+}++/** The first answer [pick] gives, reading lines back from the end of [path]. */+async function fromEnd<T>(path: string, pick: (line: string) => T | null): Promise<T | null> {+ const size = (await stat(path).catch(() => null))?.size ?? 0+ for (const bytes of TAIL_BYTES) {+ const lines = (await readTail(path, bytes)).split('\n')+ // A window that starts mid-file starts mid-line.+ for (let i = lines.length - 1; i >= (size > bytes ? 1 : 0); i--) {+ const found = pick(lines[i])+ if (found !== null) return found+ }+ if (size <= bytes) break+ }+ return null+}++/**+ * Whether a chat's last turn is still running: a prompt after the last `turn_ended`. Cursor writes the+ * transcript at each checkpoint of the chat, so it trails the chat: a turn that just ended can read+ * as running (the safe way: Harness asks before stopping it), and a prompt just sent can read as+ * idle until its first checkpoint. Null when the end of the transcript says neither.+ */+export function cursorTurnOpen(path: string): Promise<boolean | null> {+ return fromEnd(path, (line) => {+ const row = record(parseLine(line))+ if (row?.type === 'turn_ended') return false+ return row?.role === 'user' ? true : null+ })+}++/** A transcript, and the project (the slug of a folder) it is filed under. */+interface Transcript { path: string; project: string }++/** Transcripts by chat id, for chats whose own folder's project holds none: every project, listed once. */+async function transcriptIndex(dataDir: string): Promise<Map<string, Transcript>> {+ const projects = join(dataDir, 'projects')+ const found = new Map<string, Transcript>()+ for (const project of await entries(projects)) {+ if (!project.isDirectory()) continue+ const dir = join(projects, project.name, 'agent-transcripts')+ for (const entry of await entries(dir)) {+ const flat = entry.name.replace(/\.jsonl$/, '')+ if (entry.isDirectory() && UUID.test(entry.name)) {+ found.set(entry.name, { path: join(dir, entry.name, `${entry.name}.jsonl`), project: project.name })+ } else if (entry.isFile() && flat !== entry.name && UUID.test(flat) && !found.has(flat)) {+ // The layout older builds wrote: `agent-transcripts/<id>.jsonl`.+ found.set(flat, { path: join(dir, entry.name), project: project.name })+ }+ }+ }+ return found+}++/** A chat's transcript: where its folder puts it, else wherever a project holds one by its id. */+async function transcriptOf(+ dataDir: string, sessionId: string, cwd: string | null, index: () => Promise<Map<string, Transcript>>,+): Promise<Transcript | null> {+ if (cwd) {+ const project = cursorSlug(cwd)+ const path = join(dataDir, 'projects', project, 'agent-transcripts', sessionId, `${sessionId}.jsonl`)+ if (await fileStamp(path)) return { path, project }+ }+ const elsewhere = (await index()).get(sessionId)+ return elsewhere && await fileStamp(elsewhere.path) ? elsewhere : null+}++/**+ * The folder whose bucket is [bucket] and whose slug is [slug], walked down to from `/` through real+ * folders whose slugs lead to it. The md5 decides: a slug alone never names a folder.+ */+async function walkToFolder(slug: string, bucket: string): Promise<string | null> {+ let reads = WALK_READS+ const walk = async (dir: string): Promise<string | null> => {+ const own = cursorSlug(dir)+ if (own === slug && cursorBucket(dir) === bucket) return dir+ if (own && own !== slug && !slug.startsWith(`${own}-`)) return null+ if (reads-- <= 0) return null+ for (const entry of await entries(dir)) {+ if (!entry.isDirectory()) continue+ const found = await walk(join(dir, entry.name))+ if (found) return found+ }+ return null+ }+ return walk('/')+}++interface Chat {+ sessionId: string+ meta: CursorMeta+ /** When it last moved: `updatedAtMs`, else the store's last write. */+ movedAt: number+}++type ChatRead = { kind: 'chat'; chat: Chat } | { kind: 'skip'; reason: CursorSkip }++/** One chat folder, classified. Its metadata is read again only when one of its files changed. */+export async function readChat(ctx: ScanContext, chatDir: string, Database: () => CursorDatabase | null): Promise<ChatRead> {+ const store = join(chatDir, 'store.db')+ const [db, wal, meta] = await Promise.all([fileStamp(store), fileStamp(`${store}-wal`), fileStamp(join(chatDir, 'meta.json'))])+ if (!db) return { kind: 'skip', reason: 'no-store' }+ let read: CursorMeta | null+ try {+ read = await ctx.memo(`cursor:${chatDir}`, `${meta?.stamp ?? '-'}|${db.stamp}|${wal?.stamp ?? '-'}`, async () => {+ // A `meta.json` Cursor is still writing is not JSON yet, and throws: nothing is remembered, and+ // the next scan reads it again. One that is not a sidecar is read past, as Cursor reads past it.+ const source = await readFile(join(chatDir, 'meta.json'), 'utf8').catch(() => null)+ return (source === null ? null : parseCursorMeta(JSON.parse(source))) ?? readStoreMeta(store, Database())+ })+ } catch {+ // Half-written, or a store that could not be opened: read again next scan.+ read = null+ }+ if (!read) return { kind: 'skip', reason: 'unreadable' }+ if (read.isSubagent) return { kind: 'skip', reason: 'subagent' }+ if (!read.hasConversation) return { kind: 'skip', reason: 'empty' }+ return { kind: 'chat', chat: { sessionId: basename(chatDir), meta: read, movedAt: read.updatedAt ?? Math.max(db.mtime, wal?.mtime ?? 0) } }+}++/** Whether [row] runs inside Cursor's own tmux server (`tmux -L cursor-agent`), a few parents up. */+function persistent(row: RunningProcess, byPid: ReadonlyMap<number, RunningProcess>): boolean {+ let parent = byPid.get(row.ppid)+ for (let depth = 0; parent && depth < 4; depth++) {+ const tokens = argvTokens(parent.args)+ const tmux = basename(parent.executable) === 'tmux' || basename(tokens[0] ?? '') === 'tmux'+ if (tmux && tokens.some((token, i) => /^-Lcursor/.test(token) || (token === '-L' && /^cursor/.test(tokens[i + 1] ?? '')))) return true+ parent = byPid.get(parent.ppid)+ }+ return false+}++export function cursorProvider(options: CursorOptions): ExternalProvider {+ const chatsRoot = join(options.configDir, 'chats')+ let database: CursorDatabase | null | undefined = options.database+ const Database = (): CursorDatabase | null => (database === undefined ? (database = builtinSqlite() as unknown as CursorDatabase | null) : database)++ /** The store of chat [sessionId], in whichever bucket holds it. */+ async function storeOf(sessionId: string): Promise<string | null> {+ for (const bucket of await entries(chatsRoot)) {+ const path = join(chatsRoot, bucket.name, sessionId, 'store.db')+ if (bucket.isDirectory() && BUCKET.test(bucket.name) && await fileStamp(path)) return path+ }+ return null+ }++ return {+ engine: 'cursor',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ let listed: Promise<Map<string, Transcript>> | null = null+ const index = () => (listed ??= transcriptIndex(options.dataDir))+ const found: ExternalSession[] = []+ for (const bucket of await entries(chatsRoot)) {+ if (!bucket.isDirectory() || !BUCKET.test(bucket.name)) continue+ const bucketDir = join(chatsRoot, bucket.name)+ const chats: Chat[] = []+ for (const entry of await entries(bucketDir)) {+ if (!entry.isDirectory() || !UUID.test(entry.name)) continue+ const read = await readChat(ctx, join(bucketDir, entry.name), Database)+ await ctx.pace()+ if (read.kind === 'chat') chats.push(read.chat)+ }+ if (!chats.length) continue+ // A chat that names a folder whose md5 is the bucket names it for every chat there.+ const named = chats.map((chat) => chat.meta.cwd).find((cwd) => cwd && cursorBucket(cwd) === bucket.name)+ const cwd = named ? resolve(named) : await ctx.memo(`cursor:folder:${bucketDir}`, chats.map((chat) => chat.sessionId).sort().join(','), async () => {+ // None does (chats older than their `cwd`): the project a transcript is filed under guides a walk.+ const tried = new Set<string>()+ for (const chat of chats) {+ const project = (await transcriptOf(options.dataDir, chat.sessionId, null, index))?.project+ if (!project || tried.has(project)) continue+ tried.add(project)+ const folder = await walkToFolder(project, bucket.name)+ if (folder) return folder+ }+ return null+ })+ if (!cwd || ctx.excluded(cwd)) continue+ for (const chat of chats) {+ found.push({+ sessionId: chat.sessionId, engine: 'cursor', cwd, origin: 'terminal', title: chat.meta.title, mtime: chat.movedAt,+ transcriptPath: (await transcriptOf(options.dataDir, chat.sessionId, cwd, index))?.path ?? null,+ })+ }+ }+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const rows = await view.list()+ const ownership = agentCommandOwnershipSnapshot()+ const cursor = rows.filter((row) => engineProcessMatch(row, 'cursor', ownership).score > 0 && view.alive(row.pid))+ if (!cursor.length) return []+ const byPid = new Map(rows.map((row) => [row.pid, row]))+ const roots = new Set([chatsRoot, join(await realpath(options.configDir).catch(() => options.configDir), 'chats')])+ const files = await view.openFiles(cursor.map((row) => row.pid))+ const claims: OwnerClaim[] = []+ for (const row of cursor) {+ const app = persistent(row, byPid) ? { app: true } : {}+ const held = new Set<string>()+ for (const path of files.get(row.pid) ?? []) {+ const store = path.replace(/-(?:wal|shm)$/, '')+ const chatDir = dirname(store)+ const sessionId = basename(chatDir)+ if (basename(store) !== 'store.db' || !UUID.test(sessionId) || !BUCKET.test(basename(dirname(chatDir)))) continue+ if (!roots.has(dirname(dirname(chatDir))) || held.has(sessionId)) continue+ held.add(sessionId)+ claims.push({ sessionId, pid: row.pid, record: store, ...app })+ }+ if (held.size) continue+ // No chat store open (yet, or `lsof` could not say): the chat its arguments name.+ const resumed = resumeSessionId('cursor', row.args)+ // A guess: an in-app `/resume` leaves the arguments naming the first chat. Never stopped on it.+ if (resumed && UUID.test(resumed)) claims.push({ sessionId: resumed, pid: row.pid, record: await storeOf(resumed) ?? '', fromArgs: true, ...app })+ }+ return claims+ },+ async busy(owner): Promise<boolean | null> {+ if (!owner.record) return null+ const chatDir = dirname(owner.record)+ const meta = parseCursorMeta(await readJson(join(chatDir, 'meta.json')))+ const cwd = meta?.cwd && cursorBucket(meta.cwd) === basename(dirname(chatDir)) ? meta.cwd : null+ const transcript = await transcriptOf(options.dataDir, basename(chatDir), cwd, () => transcriptIndex(options.dataDir))+ return transcript ? cursorTurnOpen(transcript.path) : null+ },+ }+}+diff --git a/cli/src/lib/sessionSearch/externals/devin.spec.ts b/cli/src/lib/sessionSearch/externals/devin.spec.tsnew file mode 100644index 000000000..c2f56d193--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/devin.spec.ts@@ -0,0 +1,342 @@+/**+ * Devin discovery against fixture stores. Devin is not installed here, so the schema is the one other+ * readers of `sessions.db` publish from real stores (devin 3000.11.x: `sessions` and `message_nodes`+ * with `UNIQUE(session_id, node_id)`), plus the older shape Harness's own reader was written against+ * (3000.2.17). WAL mode, read through both of Harness's SQLite paths. No real conversation text.+ */++import { chmodSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++import { builtinSqlite, closeSqliteHandles, overrideBuiltinSqlite } from '../../sqliteRead.js'+import { devinListSql, devinProvider, devinTurnOpen, lockPid } from './devin.js'+import { LIST_LIMIT, ownerRecord, readSql, type SqlRead } from './opencode.js'+import { scanMemo } from './support.js'+import type { ProcessView, RunningProcess, ScanContext } from './types.js'++const Database = builtinSqlite()!+type Db = InstanceType<typeof Database>++const dirs: string[] = []+function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ext-devin-'))+ dirs.push(dir)+ return dir+}+afterEach(() => {+ closeSqliteHandles()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++/** devin 3000.11.x, as published by readers of real stores (agent-sessions' fixtures; pond#315). */+const SCHEMA = `+CREATE TABLE sessions (+ id TEXT PRIMARY KEY, working_directory TEXT NOT NULL, backend_type TEXT NOT NULL, model TEXT NOT NULL,+ agent_mode TEXT NOT NULL, created_at INTEGER NOT NULL, last_activity_at INTEGER NOT NULL, title TEXT,+ main_chain_id INTEGER, hidden INTEGER NOT NULL DEFAULT 0, workspace_dirs TEXT, metadata TEXT);+CREATE TABLE message_nodes (+ row_id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, node_id INTEGER NOT NULL, parent_node_id INTEGER,+ chat_message TEXT NOT NULL, created_at INTEGER NOT NULL, metadata TEXT, UNIQUE(session_id, node_id));+CREATE TABLE tool_call_state (session_id TEXT, tool_call_id TEXT, tool_call_json TEXT, tool_call_update_json TEXT);+CREATE TABLE subagent_heads (session_id TEXT, agent_id TEXT, chain_node_id INTEGER);`++const S0 = 1_786_004_275 // integer epoch seconds, as Devin writes them+const AGENT_ERROR = (at: string) => `${at} WARN chisel_core::translator: ACP: agent error (Internal):`+ + ' Permission denied: We are currently facing high demand for this model. Please try again later. (trace ID: 0123abcd)'++interface SessionRow { cwd?: string; title?: string | null; hidden?: number; created?: number; active?: number }++class Store {+ readonly db: Db+ private nodeId = 0+ constructor(readonly home: string, schema = SCHEMA) {+ mkdirSync(home, { recursive: true })+ this.db = new Database(join(home, 'sessions.db'), { readOnly: false })+ this.db.exec('PRAGMA journal_mode = WAL')+ this.db.exec(schema)+ }++ get path(): string { return join(this.home, 'sessions.db') }++ session(id: string, row: SessionRow = {}): this {+ this.db.prepare(+ 'INSERT INTO sessions (id, working_directory, backend_type, model, agent_mode, created_at, last_activity_at, title, hidden)'+ + " VALUES (?, ?, 'windsurf', 'swe-1-7', 'normal', ?, ?, ?, ?)",+ ).all(id, row.cwd ?? `/work/${id}`, row.created ?? S0, row.active ?? S0, row.title === undefined ? null : row.title, row.hidden ?? 0)+ return this+ }++ node(sessionId: string, message: Record<string, unknown> | string): this {+ const json = typeof message === 'string' ? message : JSON.stringify(message)+ this.db.prepare('INSERT INTO message_nodes (session_id, node_id, chat_message, created_at) VALUES (?, ?, ?, ?)')+ .all(sessionId, this.nodeId++, json, S0)+ return this+ }++ /** The system prompt, a person's ask, and a finished answer, persisted the way Devin repeats them. */+ turn(sessionId: string): this {+ const system = { message_id: `${sessionId}-sys`, role: 'system', content: 'You are Devin' }+ const user = { message_id: `${sessionId}-u`, role: 'user', content: 'please fix the tests', metadata: { created_at: '2026-09-20T10:00:00Z' } }+ return this.node(sessionId, system).node(sessionId, user).node(sessionId, system).node(sessionId, user)+ .node(sessionId, { message_id: `${sessionId}-a`, role: 'assistant', content: 'Fixed.', metadata: { finish_reason: 'stop' } })+ }++ close(): void { this.db.close() }+}++function context(excluded: string[] = []): ScanContext {+ return scanMemo({ excluded }).context()+}++const READERS: Array<[string, typeof Database | null]> = [['node:sqlite', Database], ['the sqlite3 CLI', null]]++describe.each(READERS)('Devin discovery read through %s', (_name, reader) => {+ beforeAll(() => { overrideBuiltinSqlite(reader) })+ afterAll(() => { overrideBuiltinSqlite(Database) })++ it('lists the conversations a person can resume, and says why each other one is left out', async () => {+ const home = tempDir()+ const store = new Store(home)+ store.session('brisk-otter', { cwd: '/work/app', title: ' Fix the CI ', created: S0, active: S0 + 100 }).turn('brisk-otter')+ store.session('timeless-heron', { active: 0, created: 0 }).turn('timeless-heron')+ store.session('quiet-heron', { active: 0, created: S0 + 7 }).node('quiet-heron', { message_id: 'x', role: 'tool', content: '{}' })+ store.session('hidden-otter', { hidden: 1 }).turn('hidden-otter')+ store.session('silent-crane').node('silent-crane', { message_id: 's', role: 'system', content: 'You are Devin' })+ store.session('bare-lynx')+ store.session('mangled-wren').node('mangled-wren', '{not json')+ store.session('lost-finch', { cwd: 'relative/dir' }).turn('lost-finch')+ store.session('empty-dir', { cwd: '' }).turn('empty-dir')+ store.session('recap-crane', { cwd: join(home, 'harness-data', 'summary-scratch') }).turn('recap-crane')+ store.session('Not_A_Slug').turn('Not_A_Slug')++ const provider = devinProvider({ home })+ const found = await provider.scan(context([join(home, 'harness-data')]))+ expect(found.map((s) => s.sessionId).sort()).toEqual(['brisk-otter', 'quiet-heron', 'timeless-heron'])+ expect(provider.lastScan()).toEqual({ found: 3, hidden: 1, empty: 3, noFolder: 2, excluded: 1, badId: 1 })+ expect(found.find((s) => s.sessionId === 'timeless-heron')!.mtime).toBe(0)+ const brisk = found.find((s) => s.sessionId === 'brisk-otter')!+ expect(brisk).toMatchObject({ engine: 'devin', cwd: '/work/app', origin: 'terminal', title: 'Fix the CI', mtime: (S0 + 100) * 1000, transcriptPath: null })+ expect(brisk.launchArgs).toBeUndefined()+ // No activity stamp: the start is the time.+ expect(found.find((s) => s.sessionId === 'quiet-heron')).toMatchObject({ title: '', mtime: (S0 + 7) * 1000 })+ // The repeated rows are one conversation: one ask, one answer.+ expect((await brisk.readHistory!()).filter((e) => e.type === 'user_message')).toHaveLength(1)+ store.close()+ })++ it('reads a store once until its files change', async () => {+ const home = tempDir()+ const store = new Store(home)+ store.session('brisk-otter').turn('brisk-otter')+ const read = vi.fn(readSql)+ const provider = devinProvider({ home, read })+ const memo = scanMemo({ excluded: [] })+ expect(await provider.scan(memo.context())).toHaveLength(1)+ memo.prune()+ expect(await provider.scan(memo.context())).toHaveLength(1)+ expect(read).toHaveBeenCalledTimes(2)+ store.session('blue-agustinia').turn('blue-agustinia')+ expect(await provider.scan(memo.context())).toHaveLength(2)+ expect(read).toHaveBeenCalledTimes(4)+ store.close()+ })++ it('reads an older schema by the columns it has', async () => {+ const dir = tempDir()+ // The store Harness's reader was written against: no title, no hidden flag, no activity stamp.+ const old = new Store(join(dir, 'old'), 'CREATE TABLE sessions (id TEXT PRIMARY KEY, working_directory TEXT, created_at INTEGER);'+ + 'CREATE TABLE message_nodes (row_id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, node_id INTEGER NOT NULL,'+ + ' parent_node_id INTEGER, chat_message TEXT NOT NULL, created_at INTEGER NOT NULL, metadata TEXT);')+ old.db.exec(`INSERT INTO sessions VALUES ('tested-crabapple', '/work/old', ${S0})`)+ old.node('tested-crabapple', { message_id: 'm', role: 'user', content: 'hi' })+ const provider = devinProvider({ home: old.home })+ expect(await provider.scan(context())).toMatchObject([{ sessionId: 'tested-crabapple', cwd: '/work/old', title: '', mtime: S0 * 1000 }])++ const bare = new Store(join(dir, 'bare'), "CREATE TABLE sessions (id TEXT PRIMARY KEY, working_directory TEXT); INSERT INTO sessions VALUES ('lone-heron', '/w');")+ const bareProvider = devinProvider({ home: bare.home })+ expect(await bareProvider.scan(context())).toEqual([])+ expect(bareProvider.lastScan()).toEqual({ found: 0, empty: 1 })++ const other = new Store(join(dir, 'other'), 'CREATE TABLE sessions (id TEXT PRIMARY KEY);')+ const otherProvider = devinProvider({ home: other.home })+ expect(await otherProvider.scan(context())).toEqual([])+ expect(otherProvider.lastScan()).toEqual({ found: 0 })++ const alien = new Store(join(dir, 'alien'), 'CREATE TABLE things (id TEXT);')+ expect(await devinProvider({ home: alien.home }).scan(context())).toEqual([])+ old.close(); bare.close(); other.close(); alien.close()+ })++ it('lists the newest 500', async () => {+ const home = tempDir()+ const store = new Store(home)+ store.db.exec('BEGIN')+ for (let n = 0; n < LIST_LIMIT + 1; n++) {+ store.session(`many-${n}`, { active: S0 + n }).node(`many-${n}`, { message_id: `m${n}`, role: 'user', content: 'x' })+ }+ store.db.exec('COMMIT')+ const provider = devinProvider({ home })+ const found = await provider.scan(context())+ expect(found).toHaveLength(LIST_LIMIT)+ expect(found.some((s) => s.sessionId === 'many-0')).toBe(false)+ expect(provider.lastScan()).toEqual({ found: LIST_LIMIT, older: 1 })+ store.close()+ })++ it('says from the tail whether a turn is running, and that a turn died when the log says so', async () => {+ const home = tempDir()+ const store = new Store(home)+ const provider = devinProvider({ home })+ const busy = (id: string) => provider.busy!({ pid: 4242, record: ownerRecord(store.path, id) })+ const asked = (id: string, at: string) => store.session(id).node(id, { message_id: `${id}-sys`, role: 'system', content: 'sys' })+ .node(id, { message_id: `${id}-u`, role: 'user', content: 'go', metadata: { created_at: at } })++ store.session('fresh-start')+ expect(await busy('fresh-start')).toBe(false)+ asked('asking-heron', '2026-09-20T10:00:00.000000Z')+ expect(await busy('asking-heron')).toBe(true)+ store.session('done-heron').turn('done-heron')+ expect(await busy('done-heron')).toBe(false)+ store.session('calling-heron').node('calling-heron', { message_id: 'c', role: 'assistant', content: '', metadata: { finish_reason: 'tool_calls' } })+ expect(await busy('calling-heron')).toBe(true)+ store.session('pending-heron').node('pending-heron', { message_id: 'p', role: 'assistant', tool_calls: [{ id: 't1', name: 'exec', arguments: '{}' }] })+ expect(await busy('pending-heron')).toBe(true)+ store.session('nocalls-heron').node('nocalls-heron', { message_id: 'n', role: 'assistant', tool_calls: [] })+ expect(await busy('nocalls-heron')).toBe(false)+ store.session('tool-heron').node('tool-heron', { message_id: 't', role: 'tool', content: '{}' })+ expect(await busy('tool-heron')).toBe(true)+ store.session('odd-heron').node('odd-heron', { message_id: 'o', role: 'developer', content: '' })+ expect(await busy('odd-heron')).toBeNull()++ // The turn died on a provider error after its ask: Devin wrote no row, only its log line.+ asked('failed-heron', '2026-09-20T10:00:00.000000Z')+ mkdirSync(join(home, 'session_locks'))+ mkdirSync(join(home, 'logs'))+ writeFileSync(join(home, 'session_locks', 'failed-heron.lock'), '4242')+ writeFileSync(join(home, 'logs', 'devin_20260920-100000_4242.log'), `${AGENT_ERROR('2026-09-20T10:00:01.000000Z')}\n`)+ expect(await busy('failed-heron')).toBe(false)+ // A failure older than the ask is an earlier turn's.+ asked('retried-heron', '2026-09-20T11:00:00.000000Z')+ writeFileSync(join(home, 'session_locks', 'retried-heron.lock'), '4242')+ expect(await busy('retried-heron')).toBe(true)++ expect(await provider.busy!({ pid: 1, record: 'no-record' })).toBeNull()+ expect(await provider.busy!({ pid: 1, record: ownerRecord(join(home, 'gone.db'), 'x-y') })).toBeNull()+ store.close()+ })+})++describe('a Devin store that cannot be read', () => {+ it('finds nothing with no store or no reader, and throws on one it cannot read', async () => {+ const home = tempDir()+ const read = vi.fn(readSql)+ expect(await devinProvider({ home, read }).scan(context())).toEqual([])+ expect(read).not.toHaveBeenCalled()+ const store = new Store(home)+ store.session('brisk-otter').turn('brisk-otter')+ const none = devinProvider({ home, read, available: () => false })+ expect(await none.scan(context())).toEqual([])+ expect(none.lastScan()).toEqual({})+ expect(read).not.toHaveBeenCalled()+ expect(await devinProvider({ home, read: async () => ({ ok: false, reason: 'missing' }) }).scan(context())).toEqual([])+ let calls = 0+ const vanishing: SqlRead = async (db, sql, params) => (++calls === 1 ? readSql(db, sql, params) : { ok: false, reason: 'missing' })+ expect(await devinProvider({ home, read: vanishing }).scan(context())).toEqual([])+ await expect(devinProvider({ home, read: async () => ({ ok: false, reason: 'transient' }) }).scan(context()))+ .rejects.toThrow('sessions.db not readable: locked')+ store.close()++ const garbage = tempDir()+ writeFileSync(join(garbage, 'sessions.db'), 'definitely not sqlite '.repeat(100))+ await expect(devinProvider({ home: garbage }).scan(context())).rejects.toThrow(/^sessions\.db not readable: /)+ })+})++describe('Devin owners', () => {+ const DEVIN = '/Users/me/.local/share/devin/cli/_versions/2026.9.1/bin/devin'+ const devin = (pid: number, rest = ''): RunningProcess => ({ pid, ppid: 1, executable: 'devin', args: `${DEVIN}${rest ? ` ${rest}` : ''}` })+ const view = (rows: RunningProcess[], dead: number[] = []): ProcessView => ({+ list: async () => rows,+ openFiles: async () => new Map(),+ openFilesOf: async () => new Map(),+ alive: (pid) => !dead.includes(pid),+ })++ it('claims a session from a live Devin holding its lock, or resumed with its id', async () => {+ const home = tempDir()+ const locks = join(home, 'session_locks')+ mkdirSync(locks, { recursive: true })+ writeFileSync(join(locks, 'brisk-otter.lock'), '101\n')+ writeFileSync(join(locks, 'json-otter.lock'), '{"pid": 102, "started": 1}')+ writeFileSync(join(locks, 'stale-otter.lock'), '103') // crashed: the pid is gone+ writeFileSync(join(locks, 'reused-otter.lock'), '104') // the pid now belongs to something else+ writeFileSync(join(locks, 'vanished-otter.lock'), '105') // not in the process list at all+ writeFileSync(join(locks, 'garbage-otter.lock'), 'held')+ writeFileSync(join(locks, 'Not_A_Slug.lock'), '101')+ writeFileSync(join(locks, 'notes.txt'), '101')+ mkdirSync(join(locks, 'folder-otter.lock'))+ writeFileSync(join(locks, 'sealed-otter.lock'), '101')+ chmodSync(join(locks, 'sealed-otter.lock'), 0o000) // unreadable: no pid to trust+ writeFileSync(join(locks, 'editor-otter.lock'), '106')+ const claims = await devinProvider({ home }).owners!(view([+ devin(101), devin(102), devin(103),+ { pid: 104, ppid: 1, executable: 'vim', args: 'vim notes' },+ devin(106, 'acp'),+ devin(107, '-r argv-otter'),+ devin(108, '--resume=brisk-otter'),+ devin(109, '-r solo'), // not a Devin id: ids are hyphenated word slugs+ { pid: 110, ppid: 1, executable: 'node', args: '/Users/me/.hermes/node/bin/node x.js -r decoy-otter' },+ ], [103]))+ const db = join(home, 'sessions.db')+ expect(claims).toEqual([+ { sessionId: 'brisk-otter', pid: 101, record: ownerRecord(db, 'brisk-otter') },+ { sessionId: 'editor-otter', pid: 106, record: ownerRecord(db, 'editor-otter'), app: true },+ { sessionId: 'json-otter', pid: 102, record: ownerRecord(db, 'json-otter') },+ // No lock says so: the id it was started on, which it may have left since.+ { sessionId: 'argv-otter', pid: 107, record: ownerRecord(db, 'argv-otter'), fromArgs: true },+ ])+ })++ it('refuses a lock written before the process now under its pid began', async () => {+ const home = tempDir()+ const locks = join(home, 'session_locks')+ mkdirSync(locks, { recursive: true })+ const now = Date.now()+ // Left by a Devin that crashed an hour ago; its pid now belongs to another Devin.+ writeFileSync(join(locks, 'crashed-otter.lock'), '201')+ utimesSync(join(locks, 'crashed-otter.lock'), (now - 3_600_000) / 1000, (now - 3_600_000) / 1000)+ // Written by the Devin running now: after its start (ps reports whole seconds, so allow one).+ writeFileSync(join(locks, 'current-otter.lock'), '202')+ utimesSync(join(locks, 'current-otter.lock'), (now - 1_000) / 1000, (now - 1_000) / 1000)+ const claims = await devinProvider({ home }).owners!(view([+ { ...devin(201), started: now - 60_000 },+ { ...devin(202), started: now },+ ]))+ expect(claims.map((c) => [c.sessionId, c.pid])).toEqual([['current-otter', 202]])+ })++ it('finds no lock folder on a machine Devin never ran on', async () => {+ expect(await devinProvider({ home: join(tempDir(), 'none') }).owners!(view([devin(1)]))).toEqual([])+ })+})++describe('Devin pieces', () => {+ it('reads a lock\'s pid', () => {+ expect(lockPid('4242\n')).toBe(4242)+ expect(lockPid('{"pid": 7}')).toBe(7)+ expect(lockPid('{"pid": "7"}')).toBeNull()+ expect(lockPid('0')).toBeNull()+ expect(lockPid('{"pid": 1.5}')).toBeNull()+ expect(lockPid('')).toBeNull()+ })++ it('reads a tail', () => {+ expect(devinTurnOpen([])).toBe(false)+ expect(devinTurnOpen([{ role: 'assistant', calls: 'not json' }])).toBe(false)+ expect(devinTurnOpen([{ role: 'assistant', calls: null, finish: 'stop' }])).toBe(false)+ expect(devinListSql(new Set(['id']), new Set())).toBeNull()+ })+})diff --git a/cli/src/lib/sessionSearch/externals/devin.ts b/cli/src/lib/sessionSearch/externals/devin.tsnew file mode 100644index 000000000..1f125057f--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/devin.ts@@ -0,0 +1,196 @@+/**+ * Devin CLI: one SQLite store, `<DEVIN_HOME>/sessions.db` (WAL; `~/.local/share/devin/cli` on macOS+ * too). `sessions` holds one row a conversation (id, `working_directory`, `title`, `created_at` and+ * `last_activity_at` in integer epoch seconds, `hidden` for compaction helpers and deleted ones);+ * `message_nodes` holds what was said, as JSON, re-persisted on every inference. Columns are read from+ * the store first: Devin migrates its schema (refinery) and versions differ. Not measured on this+ * machine (Devin is not installed): the schema is the one other readers of the store publish, and+ * the one Harness's own reader was written against (3000.2.17).+ *+ * A running Devin holds `session_locks/<id>.lock` with its pid, the one per-session ownership file+ * among the database engines. A lock outlives a crash, so it counts only while that pid is alive and+ * is Devin. `devin -r <id>` names the session a process started on in its arguments (`fromArgs`).+ */++import { open } from 'node:fs/promises'+import { join } from 'node:path'++import { DevinErrorTail } from '../../../engines/devin/errorLog.js'+import { devinMessagesToEvents } from '../../../engines/devin/normalizer.js'+import { isDevinSessionId, readDevinMessages } from '../../../engines/devin/reader.js'+import { hasSqliteReader } from '../../sqliteAvailability.js'+import type { SqliteRow } from '../../sqliteRead.js'+import { resumeSessionId } from '../../tmux.js'+import {+ LIST_LIMIT, argvSubcommand, engineProcess, ownerRecord, parseOwnerRecord, readSql, rowsOf, splitCounts, storeStamp,+ tableColumns, tally, type Counting, type SqlRead, type Tally,+} from './opencode.js'+import { absoluteFolder, entries, epochMs, parseLine, record, text } from './support.js'+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'++export interface DevinOptions {+ home: string+ /** How a statement is run; tests replace it. */+ read?: SqlRead+ /** Whether this machine can read SQLite at all; tests replace it. */+ available?: () => boolean+}++/** An editor's agent server: never stopped from here. */+const SERVERS = new Set(['acp'])+const VALUE_FLAGS = new Set(['-p', '--prompt', '-r', '--resume', '-m', '--model'])++/**+ * One statement: the newest conversations that are neither hidden nor empty (nothing but the system+ * prompt), and how many rows each rule kept out (a row with a null id is a count).+ */+export function devinListSql(sessions: ReadonlySet<string>, nodes: ReadonlySet<string>): string | null {+ if (!sessions.has('id') || !sessions.has('working_directory')) return null+ const col = (name: string): string => (sessions.has(name) ? `s.${name}` : 'NULL')+ const said = nodes.has('session_id') && nodes.has('chat_message')+ ? 'EXISTS (SELECT 1 FROM message_nodes m WHERE m.session_id = s.id'+ + " AND CASE WHEN json_valid(m.chat_message) THEN json_extract(m.chat_message, '$.role') END <> 'system')"+ : '0'+ const skip = `CASE${sessions.has('hidden') ? " WHEN COALESCE(s.hidden, 0) <> 0 THEN 'hidden'" : ''}`+ + ` WHEN NOT ${said} THEN 'empty' ELSE '' END`+ return 'SELECT * FROM (SELECT s.id AS id, s.working_directory AS cwd, '+ + `${col('title')} AS title, ${col('last_activity_at')} AS active, ${col('created_at')} AS created, '' AS skip, NULL AS n `+ + `FROM sessions s WHERE ${skip} = '' `+ + `ORDER BY coalesce(${col('last_activity_at')}, ${col('created_at')}, 0) DESC LIMIT ${LIST_LIMIT}) `+ + `UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, ${skip} AS skip, count(*) AS n FROM sessions s GROUP BY skip`+}++interface Listed { rows: SqliteRow[]; counts: Tally }++async function listSessions(read: SqlRead, dbPath: string): Promise<Listed | null> {+ const columns = await tableColumns(read, dbPath, ['sessions', 'message_nodes'])+ if (!columns) return null+ const sql = devinListSql(columns.get('sessions') ?? new Set(), columns.get('message_nodes') ?? new Set())+ if (!sql) return { rows: [], counts: {} }+ const rows = await rowsOf(read, dbPath, sql)+ return rows && splitCounts(rows)+}++/** The pid a session lock names: a bare number, or `{"pid": n}`. */+export function lockPid(content: string): number | null {+ const trimmed = content.trim()+ const value = /^\d+$/.test(trimmed) ? Number(trimmed) : record(parseLine(trimmed))?.pid+ return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null+}++/** How much earlier than its process's start (`ps`, whole seconds) a lock may seem to be written. */+const LOCK_SLACK_MS = 2_000++/** A lock's pid and when it was written; null when it cannot be read. */+async function readLock(path: string): Promise<{ pid: number | null; written: number } | null> {+ const handle = await open(path, 'r').catch(() => null)+ if (!handle) return null+ try {+ const [info, content] = await Promise.all([handle.stat(), handle.readFile('utf8')])+ return { pid: lockPid(content), written: info.mtimeMs }+ } finally {+ await handle.close()+ }+}++/** The last thing said, the system prompt aside (row order: Devin appends the chain it just persisted). */+const TAIL_SQL = "SELECT json_extract(chat_message, '$.role') AS role, json_extract(chat_message, '$.metadata.finish_reason') AS finish,"+ + " json_extract(chat_message, '$.tool_calls') AS calls, json_extract(chat_message, '$.metadata.created_at') AS at"+ + " FROM message_nodes WHERE session_id = ? AND json_extract(chat_message, '$.role') <> 'system' ORDER BY row_id DESC LIMIT 1"++/**+ * Whether the tail says a turn runs: a person's message or a tool's result waits for the model; an+ * assistant message runs on while it stopped to call tools, or named tools no result answered yet.+ */+export function devinTurnOpen(rows: readonly SqliteRow[]): boolean | null {+ const tail = rows[0]+ if (!tail) return false+ if (tail.role === 'user' || tail.role === 'tool') return true+ if (tail.role !== 'assistant') return null+ const calls = typeof tail.calls === 'string' ? parseLine(tail.calls) : null+ return tail.finish === 'tool_calls' || (Array.isArray(calls) && calls.length > 0)+}++export function devinProvider(options: DevinOptions): ExternalProvider & Counting {+ const { home } = options+ const dbPath = join(home, 'sessions.db')+ const read = options.read ?? readSql+ const available = options.available ?? hasSqliteReader+ let counts: Tally = {}+ return {+ engine: 'devin',+ lastScan: () => counts,+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ counts = {}+ if (!available()) return []+ const stamp = await storeStamp(dbPath)+ if (!stamp) return []+ const listed = await ctx.memo(`devin:${dbPath}`, stamp, () => listSessions(read, dbPath))+ await ctx.pace()+ if (!listed) return []+ counts = { ...listed.counts }+ const found: ExternalSession[] = []+ for (const row of listed.rows) {+ const sessionId = text(row.id)+ const cwd = absoluteFolder(row.cwd)+ if (!isDevinSessionId(sessionId)) { tally(counts, 'badId'); continue }+ // Resumed anywhere else, Devin stops to ask which folder: only its own will do.+ if (!cwd) { tally(counts, 'noFolder'); continue }+ if (ctx.excluded(cwd)) { tally(counts, 'excluded'); continue }+ found.push({+ sessionId, engine: 'devin', cwd, origin: 'terminal', title: text(row.title).trim(),+ mtime: Math.max(epochMs(row.active) ?? 0, epochMs(row.created) ?? 0),+ transcriptPath: null,+ readHistory: async () => devinMessagesToEvents(await readDevinMessages(dbPath, sessionId)),+ })+ }+ counts.found = found.length+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const processes = await view.list()+ const byPid = new Map(processes.map((row) => [row.pid, row]))+ const isDevin = engineProcess('devin')+ const claims = new Map<string, OwnerClaim>()+ const add = (sessionId: string, row: RunningProcess, fromArgs: boolean): void => {+ if (claims.has(sessionId)) return+ claims.set(sessionId, {+ sessionId, pid: row.pid, record: ownerRecord(dbPath, sessionId),+ ...(SERVERS.has(argvSubcommand(row.args, VALUE_FLAGS)) ? { app: true } : {}),+ ...(fromArgs ? { fromArgs: true } : {}),+ })+ }+ const locks = join(home, 'session_locks')+ for (const file of (await entries(locks)).sort((a, b) => a.name.localeCompare(b.name))) {+ if (!file.isFile() || !file.name.endsWith('.lock')) continue+ const sessionId = file.name.slice(0, -'.lock'.length)+ if (!isDevinSessionId(sessionId)) continue+ const lock = await readLock(join(locks, file.name))+ if (lock?.pid == null) continue+ // A lock outlives a crash, and its pid can be handed to anything after, another Devin among+ // them: one written before the process under its pid began was that earlier process's.+ const row = byPid.get(lock.pid)+ if (!row || !view.alive(lock.pid) || !isDevin(row)) continue+ if (row.started !== undefined && lock.written < row.started - LOCK_SLACK_MS) continue+ add(sessionId, row, false)+ }+ // The id a process was started on, where no lock says more: it may have moved on since.+ for (const row of processes) {+ if (!isDevin(row)) continue+ const sessionId = resumeSessionId('devin', row.args)+ if (sessionId) add(sessionId, row, true)+ }+ return [...claims.values()]+ },+ async busy(owner): Promise<boolean | null> {+ const at = parseOwnerRecord(owner.record)+ if (!at) return null+ const result = await read(at.dbPath, TAIL_SQL, [at.sessionId])+ if (!result.ok) return null+ const open = devinTurnOpen(result.rows)+ if (!open) return open+ // A turn that died on a provider error writes no row: the owner's log says so after the tail.+ return new DevinErrorTail(home, at.sessionId).scanSince(text(result.rows[0].at)).length === 0+ },+ }+}diff --git a/cli/src/lib/sessionSearch/externals/grok.spec.ts b/cli/src/lib/sessionSearch/externals/grok.spec.tsnew file mode 100644index 000000000..2add5aa41--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/grok.spec.ts@@ -0,0 +1,414 @@+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { grokMovedAt, grokProvider, grokTurnOpen, readGrokSession } from './grok.js'+import { scanMemo } from './support.js'+import type { ProcessView, RunningProcess, ScanContext } from './types.js'++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })++function home(): string {+ const dir = mkdtempSync(join(tmpdir(), 'grok-external-'))+ dirs.push(dir)+ return dir+}++const ID = '01a0438c-0e05-73b1-98f9-978079f9e0a5'+const ID2 = '01a045b0-7db7-7e90-9348-5495a0dd4604'+const ID3 = '9159b98b-4050-4788-a7f7-e4bc235513aa'++/** One `updates.jsonl` line as Grok writes it. */+function line(kind: string, at: { s?: number; ms?: number } = {}, extra: Record<string, unknown> = {}): string {+ return JSON.stringify({+ ...(at.s !== undefined ? { timestamp: at.s } : {}),+ method: 'session/update',+ params: {+ sessionId: ID,+ update: { sessionUpdate: kind, ...extra },+ _meta: at.ms !== undefined ? { eventId: 'e', agentTimestampMs: at.ms } : { eventId: 'e' },+ },+ })+}++const PROMPT = line('user_message_chunk', { s: 1_787_839_648, ms: 1_787_839_648_590 }, { content: { type: 'text', text: 'hello' } })+const ANSWER = line('agent_message_chunk', { s: 1_787_839_700, ms: 1_787_839_700_123 }, { content: { type: 'text', text: 'hi' } })+const DONE = line('turn_completed', { s: 1_787_839_701, ms: 1_787_839_701_000 }, { stop_reason: 'end_turn' })+const HOOK = (event: string) => line('hook_execution', { s: 1_787_900_000, ms: 1_787_900_000_000 }, { event_name: event, runs: [] })++interface SessionFixture {+ group?: string+ summary?: unknown+ context?: unknown+ updates?: string[] | string | null+}++function session(root: string, id: string, fixture: SessionFixture = {}): string {+ const dir = join(root, 'sessions', fixture.group ?? encodeURIComponent('/work/app'), id)+ mkdirSync(dir, { recursive: true })+ const summary = fixture.summary === undefined+ ? { info: { id, cwd: '/work/app' }, generated_title: ' Fix the build ', last_active_at: '2026-08-28T13:11:02.565632Z' }+ : fixture.summary+ const context = fixture.context === undefined ? { audience: 'primary', is_non_interactive: false, working_directory: '/work/app' } : fixture.context+ if (summary !== null) writeFileSync(join(dir, 'summary.json'), typeof summary === 'string' ? summary : JSON.stringify(summary))+ if (context !== null) writeFileSync(join(dir, 'prompt_context.json'), typeof context === 'string' ? context : JSON.stringify(context))+ const updates = fixture.updates === undefined ? [HOOK('session_start'), PROMPT, ANSWER, DONE, HOOK('session_end'), HOOK('stop')] : fixture.updates+ if (updates !== null) writeFileSync(join(dir, 'updates.jsonl'), typeof updates === 'string' ? updates : `${updates.join('\n')}\n`)+ return dir+}++/** A scan context that counts how often a memo's reader actually ran. */+function counted(excluded: string[] = []) {+ const memo = scanMemo({ excluded, paceEvery: 1 })+ let reads = 0+ let paces = 0+ const context = (): ScanContext => {+ const inner = memo.context()+ return {+ ...inner,+ memo: (key, fingerprint, read) => inner.memo(key, fingerprint, () => { reads++; return read() }),+ pace: async () => { paces++; await inner.pace() },+ }+ }+ return { context, reads: () => reads, paces: () => paces, prune: () => memo.prune() }+}++function view(rows: RunningProcess[], alive: (pid: number) => boolean = () => true): ProcessView & { listed: () => number } {+ let listed = 0+ return {+ list: async () => { listed++; return rows },+ openFiles: async () => new Map(),+ openFilesOf: async () => new Map(),+ alive,+ listed: () => listed,+ }+}++const grokRow = (pid: number, args = 'grok'): RunningProcess => ({ pid, ppid: 1, executable: '/Users/x/.grok/downloads/grok-1.0.34-macos-aarch64', args })++describe('grokProvider.scan', () => {+ it('offers a person\'s session: its folder, title, stream, and when the conversation last moved', async () => {+ const root = home()+ session(root, ID)+ const found = await grokProvider({ home: root }).scan(counted().context())+ expect(found).toEqual([{+ sessionId: ID, engine: 'grok', cwd: '/work/app', origin: 'terminal', title: 'Fix the build',+ // The last turn's end, not the exit hooks Grok appends hours later.+ mtime: 1_787_839_701_000,+ transcriptPath: join(root, 'sessions', encodeURIComponent('/work/app'), ID, 'updates.jsonl'),+ }])+ })++ it('leaves out headless runs, sub-agents and their forks, hidden and empty sessions', async () => {+ const root = home()+ session(root, ID, { context: { audience: 'primary', is_non_interactive: true } })+ session(root, ID2, { context: { audience: 'subagent', is_non_interactive: false } })+ session(root, ID3, { summary: { info: { id: ID3, cwd: '/work/app' }, session_kind: 'subagent_fork' } })+ const hidden = '11111111-1111-4111-8111-111111111111'+ session(root, hidden, { summary: { info: { id: hidden, cwd: '/work/app' }, hidden: true } })+ const empty = '22222222-2222-4222-8222-222222222222'+ session(root, empty, { updates: [HOOK('session_start'), HOOK('session_end')] })+ expect(await grokProvider({ home: root }).scan(counted().context())).toEqual([])+ expect(await readGrokSession(join(root, 'sessions', encodeURIComponent('/work/app'), ID), ID)).toEqual({ kind: 'skip', reason: 'headless' })+ expect(await readGrokSession(join(root, 'sessions', encodeURIComponent('/work/app'), ID2), ID2)).toEqual({ kind: 'skip', reason: 'subagent' })+ expect(await readGrokSession(join(root, 'sessions', encodeURIComponent('/work/app'), ID3), ID3)).toEqual({ kind: 'skip', reason: 'subagent' })+ expect(await readGrokSession(join(root, 'sessions', encodeURIComponent('/work/app'), hidden), hidden)).toEqual({ kind: 'skip', reason: 'hidden' })+ expect(await readGrokSession(join(root, 'sessions', encodeURIComponent('/work/app'), empty), empty)).toEqual({ kind: 'skip', reason: 'empty' })+ })++ it('keeps a /fork peer: a primary session with a parent', async () => {+ const root = home()+ session(root, ID, { summary: { info: { id: ID, cwd: '/work/app' }, parent_session_id: ID2, session_kind: 'fork' } })+ expect((await grokProvider({ home: root }).scan(counted().context())).map((s) => s.sessionId)).toEqual([ID])+ })++ it('does not offer a session it cannot classify or place', async () => {+ const root = home()+ const group = join(root, 'sessions', encodeURIComponent('/work/app'))+ session(root, ID, { summary: null })+ session(root, ID2, { context: '{"audience":' })+ session(root, ID3, { summary: { info: { id: ID2, cwd: '/work/app' } } })+ const relative = '33333333-3333-4333-8333-333333333333'+ session(root, relative, { summary: { info: { id: relative, cwd: 'work/app' } }, context: { audience: 'primary' } })+ expect(await grokProvider({ home: root }).scan(counted().context())).toEqual([])+ expect(await readGrokSession(join(group, ID), ID)).toEqual({ kind: 'skip', reason: 'unreadable' })+ // Half-written: not a verdict to remember.+ await expect(readGrokSession(join(group, ID2), ID2)).rejects.toThrow()+ expect(await readGrokSession(join(group, ID3), ID3)).toEqual({ kind: 'skip', reason: 'mismatch' })+ expect(await readGrokSession(join(group, relative), relative)).toEqual({ kind: 'skip', reason: 'no-folder' })+ })++ it('reads a session again next scan while its summary is half-written', async () => {+ const root = home()+ const dir = session(root, ID, { summary: '{"info":{"id":' })+ const provider = grokProvider({ home: root })+ const scan = counted()+ expect(await provider.scan(scan.context())).toEqual([])+ expect(await provider.scan(scan.context())).toEqual([])+ expect(scan.reads()).toBe(2)+ writeFileSync(join(dir, 'summary.json'), JSON.stringify({ info: { id: ID, cwd: '/work/app' } }))+ expect((await provider.scan(scan.context())).map((s) => s.sessionId)).toEqual([ID])+ })++ it('takes the folder from the prompt context when the summary has none, and needs no title', async () => {+ const root = home()+ session(root, ID, { summary: { last_active_at: 'not a time' }, context: { audience: 'primary', working_directory: '/work/other' } })+ const [found] = await grokProvider({ home: root }).scan(counted().context())+ expect(found).toMatchObject({ cwd: '/work/other', title: '' })+ })++ it('reads a session in a hashed group (its path in `.cwd`) by its own summary', async () => {+ const root = home()+ const long = `/work/${'deep/'.repeat(60)}app`+ const dir = session(root, ID, { group: 'work-deep-app-1a2b3c', summary: { info: { id: ID, cwd: long } } })+ writeFileSync(join(dir, '..', '.cwd'), long)+ expect((await grokProvider({ home: root }).scan(counted().context()))[0].cwd).toBe(long)+ })++ it('skips what is not a session folder', async () => {+ const root = home()+ session(root, ID)+ mkdirSync(join(root, 'sessions', 'group', 'not-a-uuid'), { recursive: true })+ writeFileSync(join(root, 'sessions', 'session_search.sqlite'), '')+ writeFileSync(join(root, 'sessions', encodeURIComponent('/work/app'), 'prompt_history.jsonl'), '{}\n')+ writeFileSync(join(root, 'sessions', encodeURIComponent('/work/app'), ID2), 'a file, not a folder')+ session(root, ID3, { updates: null })+ expect((await grokProvider({ home: root }).scan(counted().context())).map((s) => s.sessionId)).toEqual([ID])+ expect(await grokProvider({ home: join(root, 'missing') }).scan(counted().context())).toEqual([])+ })++ it('leaves out folders Harness keeps its own sessions in', async () => {+ const root = home()+ session(root, ID)+ expect(await grokProvider({ home: root }).scan(counted(['/work']).context())).toEqual([])+ })++ it('reads a session again only when one of its files changed', async () => {+ const root = home()+ const dir = session(root, ID)+ const provider = grokProvider({ home: root })+ const scan = counted()+ await provider.scan(scan.context())+ await provider.scan(scan.context())+ expect(scan.reads()).toBe(1)+ expect(scan.paces()).toBe(2)+ writeFileSync(join(dir, 'summary.json'), JSON.stringify({ info: { id: ID, cwd: '/work/app' }, generated_title: 'Renamed' }))+ expect((await provider.scan(scan.context()))[0].title).toBe('Renamed')+ expect(scan.reads()).toBe(2)+ rmSync(join(dir, 'prompt_context.json'))+ expect(await provider.scan(scan.context())).toEqual([])+ expect(scan.reads()).toBe(3)+ })+})++describe('when a Grok conversation last moved', () => {+ it('reads milliseconds from `_meta`, else the line\'s seconds, and skips lines that are not the conversation', async () => {+ const root = home()+ const dir = session(root, ID, { updates: [PROMPT, line('tool_call', { s: 1_787_839_800 }), line('current_mode_update', { s: 1_787_839_900 })] })+ expect(await grokMovedAt(join(dir, 'updates.jsonl'))).toBe(1_787_839_800_000)+ })++ it('falls back to the summary\'s last activity, then to the file', async () => {+ const root = home()+ const undated = line('agent_message_chunk')+ const a = session(root, ID, { updates: [line('user_message_chunk'), undated, 'not json', ''] })+ expect(await readGrokSession(a, ID)).toMatchObject({ movedAt: Date.parse('2026-08-28T13:11:02.565632Z') })+ const b = session(root, ID2, { summary: { info: { id: ID2, cwd: '/work/app' } }, updates: [line('user_message_chunk')] })+ utimesSync(join(b, 'updates.jsonl'), 1_700_000_000, 1_700_000_000)+ const found = await grokProvider({ home: root }).scan(counted().context())+ expect(found.find((s) => s.sessionId === ID2)?.mtime).toBe(1_700_000_000_000)+ })++ it('reads further back when the end of the stream is one long line, and gives up past four megabytes', async () => {+ const root = home()+ const big = HOOK('stop').replace('"runs":[]', `"runs":["${'x'.repeat(300 * 1024)}"]`)+ const a = session(root, ID, { updates: [PROMPT, ANSWER, big] })+ expect(await grokMovedAt(join(a, 'updates.jsonl'))).toBe(1_787_839_700_123)+ const huge = HOOK('stop').replace('"runs":[]', `"runs":["${'x'.repeat(5 * 1024 * 1024)}"]`)+ const b = session(root, ID2, { updates: [PROMPT, huge] })+ expect(await grokMovedAt(join(b, 'updates.jsonl'))).toBeNull()+ expect(await grokMovedAt(join(root, 'missing.jsonl'))).toBeNull()+ })++ it('finds a prompt past a long first line, and never in the text of another line', async () => {+ const root = home()+ const setup = HOOK('session_start').replace('"runs":[]', `"runs":["${'y'.repeat(4096)}"]`)+ const quoted = line('agent_message_chunk', { s: 1 }, { content: { type: 'text', text: '"sessionUpdate":"user_message_chunk"' } })+ const a = session(root, ID, { updates: [setup, PROMPT] })+ expect(await readGrokSession(a, ID)).toMatchObject({ kind: 'session' })+ const b = session(root, ID2, { updates: [quoted] })+ expect(await readGrokSession(b, ID2)).toEqual({ kind: 'skip', reason: 'empty' })+ const c = session(root, ID3, { updates: null })+ expect(await readGrokSession(c, ID3)).toEqual({ kind: 'skip', reason: 'empty' })+ })+})++describe('grokProvider.owners', () => {+ const stream = (root: string, cwd = '/work/app', id = ID) => join(root, 'sessions', encodeURIComponent(cwd), id, 'updates.jsonl')++ it('claims each live Grok in `active_sessions.json`, with the stream that says whether it is mid-turn', async () => {+ const root = home()+ session(root, ID)+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([{ session_id: ID, pid: 41, cwd: '/work/app', opened_at: '2026-09-27T10:00:00Z' }]))+ const claims = await grokProvider({ home: root }).owners!(view([grokRow(41)]))+ expect(claims).toEqual([{ sessionId: ID, pid: 41, record: stream(root) }])+ })++ it('reads nothing of the machine when no session is open, and starts over from a corrupt list', async () => {+ const root = home()+ const processes = view([grokRow(41)])+ expect(await grokProvider({ home: root }).owners!(processes)).toEqual([])+ writeFileSync(join(root, 'active_sessions.json'), '[{"session_id":')+ expect(await grokProvider({ home: root }).owners!(processes)).toEqual([])+ writeFileSync(join(root, 'active_sessions.json'), '{"session_id":"x"}')+ expect(await grokProvider({ home: root }).owners!(processes)).toEqual([])+ writeFileSync(join(root, 'active_sessions.json'), '[]')+ expect(await grokProvider({ home: root }).owners!(processes)).toEqual([])+ expect(processes.listed()).toBe(0)+ })++ it('ignores entries a crash left behind: a dead pid, a pid now another program\'s, or Cursor\'s `agent`', async () => {+ const root = home()+ session(root, ID)+ const entries = [41, 42, 43, 44, 45, 46].map((pid) => ({ session_id: ID, pid, cwd: '/work/app' }))+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify(entries))+ const rows: RunningProcess[] = [+ grokRow(41),+ { pid: 42, ppid: 1, executable: '/usr/bin/python3', args: 'python3 worker.py grok' },+ { pid: 43, ppid: 1, executable: '/Users/x/.local/share/cursor-agent/versions/2026.09.26/node', args: 'agent --use-system-ca /Users/x/.local/share/cursor-agent/versions/2026.09.26/index.js' },+ grokRow(45),+ // A process whose arguments cannot be read.+ { pid: 46, ppid: 1, executable: '/bin/zsh', args: '' },+ ]+ const claims = await grokProvider({ home: root }).owners!(view(rows, (pid) => pid !== 41))+ expect(claims).toEqual([{ sessionId: ID, pid: 45, record: stream(root) }])+ })++ it('takes a terminal Grok\'s newest entry as its session, and every session a shared backend holds', async () => {+ const root = home()+ for (const id of [ID, ID2, ID3]) session(root, id)+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([+ // A crashed Grok's entry, its pid now another terminal Grok's with an entry of its own.+ { session_id: ID, pid: 70, cwd: '/work/app', opened_at: '2026-09-20T10:00:00Z' },+ { session_id: ID2, pid: 70, cwd: '/work/app', opened_at: '2026-09-27T10:00:00Z' },+ // Written in the same instant, or without a time: the later entry.+ { session_id: ID, pid: 71, cwd: '/work/app' },+ { session_id: ID3, pid: 71, cwd: '/work/app' },+ { session_id: ID, pid: 72, cwd: '/work/app', opened_at: '2026-09-27T10:00:00Z' },+ { session_id: ID3, pid: 72, cwd: '/work/app', opened_at: '2026-09-20T10:00:00Z' },+ // The newest listed first.+ { session_id: ID3, pid: 73, cwd: '/work/app', opened_at: 1_790_500_000 },+ { session_id: ID2, pid: 73, cwd: '/work/app', opened_at: 1_790_000_000 },+ ]))+ const rows = [grokRow(70), grokRow(71), grokRow(72, 'grok agent leader'), grokRow(73)]+ const claims = await grokProvider({ home: root }).owners!(view(rows))+ expect(claims.map((claim) => [claim.pid, claim.sessionId, claim.app ?? false])).toEqual([+ [70, ID2, false], [71, ID3, false], [72, ID, true], [72, ID3, true], [73, ID3, false],+ ])+ })++ it('ignores an entry opened before the process that now has its pid, allowing the second `ps` truncates', async () => {+ const root = home()+ for (const id of [ID, ID2, ID3]) session(root, id)+ const opened = '2023-11-14T22:13:20Z' // 1_700_000_000 s+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([+ { session_id: ID, pid: 80, cwd: '/work/app', opened_at: opened },+ { session_id: ID, pid: 81, cwd: '/work/app', opened_at: opened },+ { session_id: ID, pid: 82, cwd: '/work/app' },+ // A crashed Grok's entry beside the current one of the Grok that now has its pid.+ { session_id: ID, pid: 83, cwd: '/work/app', opened_at: opened },+ { session_id: ID2, pid: 83, cwd: '/work/app', opened_at: '2023-11-14T22:14:00Z' },+ { session_id: ID, pid: 84, cwd: '/work/app', opened_at: opened },+ { session_id: ID3, pid: 84, cwd: '/work/app', opened_at: '2023-11-14T22:14:00Z' },+ ]))+ const rows = [+ { ...grokRow(80), started: 1_700_000_005_000 },+ { ...grokRow(81), started: 1_700_000_000_500 },+ // No time on the entry: kept.+ { ...grokRow(82), started: 1_700_000_005_000 },+ { ...grokRow(83), started: 1_700_000_030_000 },+ { ...grokRow(84, 'grok agent leader'), started: 1_700_000_030_000 },+ ]+ const claims = await grokProvider({ home: root }).owners!(view(rows))+ expect(claims.map((claim) => [claim.pid, claim.sessionId])).toEqual([[81, ID], [82, ID], [83, ID2], [84, ID3]])+ })++ it('knows a Grok that runs as `agent`, the name it shares with Cursor', async () => {+ const root = home()+ session(root, ID)+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([{ session_id: ID, pid: 50, cwd: '/work/app' }]))+ const claims = await grokProvider({ home: root }).owners!(view([{ pid: 50, ppid: 1, executable: '/Users/x/.grok/bin/agent', args: 'agent' }]))+ expect(claims.map((claim) => claim.pid)).toEqual([50])+ })++ it('never offers to stop a shared backend (the leader, a server, a relay, an editor\'s stdio agent) or a leader\'s client', async () => {+ const root = home()+ session(root, ID)+ const pids = [60, 61, 62, 63, 64, 65]+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify(pids.map((pid) => ({ session_id: ID, pid, cwd: '/work/app' }))))+ const rows = [+ grokRow(60, '/Users/x/.grok/downloads/grok-1.0.34-macos-aarch64 agent leader'),+ grokRow(61, 'grok agent -m grok-4.6 serve --bind 127.0.0.1:0'),+ grokRow(62, 'grok agent headless'),+ grokRow(63, 'grok agent stdio'),+ grokRow(64, 'grok --resume 01a0438c-0e05-73b1-98f9-978079f9e0a5'),+ grokRow(65, 'grok --leader'),+ ]+ const claims = await grokProvider({ home: root }).owners!(view(rows))+ expect(claims.map((claim) => [claim.pid, claim.app ?? false])).toEqual([[60, true], [61, true], [62, true], [63, true], [64, false], [65, true]])+ })++ it('skips entries that are not a session and a pid', async () => {+ const root = home()+ session(root, ID)+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([+ null, 'x', { session_id: 'not-a-uuid', pid: 41 }, { session_id: ID, pid: '41' }, { session_id: ID, pid: 4.5 },+ { session_id: ID, pid: 0 }, { session_id: ID, pid: -3 }, { session_id: ID },+ ]))+ expect(await grokProvider({ home: root }).owners!(view([grokRow(41)]))).toEqual([])+ })++ it('finds the stream by id when the session is not where its folder puts it, and says nothing when it is gone', async () => {+ const root = home()+ session(root, ID, { group: 'work-deep-app-1a2b3c' })+ writeFileSync(join(root, 'sessions', 'session_search.sqlite'), '')+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([+ { session_id: ID, pid: 41, cwd: '/work/app' }, { session_id: ID2, pid: 42 },+ ]))+ const provider = grokProvider({ home: root })+ const claims = await provider.owners!(view([grokRow(41), grokRow(42)]))+ expect(claims).toEqual([+ { sessionId: ID, pid: 41, record: join(root, 'sessions', 'work-deep-app-1a2b3c', ID, 'updates.jsonl') },+ { sessionId: ID2, pid: 42, record: '' },+ ])+ expect(await provider.busy!({ pid: 42, record: '' })).toBeNull()+ })+})++describe('grokProvider.busy', () => {+ it('is mid-turn when a prompt came after the last `turn_completed`', async () => {+ const root = home()+ const provider = grokProvider({ home: root })+ const open = session(root, ID, { updates: [PROMPT, ANSWER, DONE, PROMPT, line('tool_call', { s: 1 })] })+ expect(await provider.busy!({ pid: 1, record: join(open, 'updates.jsonl') })).toBe(true)+ const cancelled = line('turn_completed', { s: 2 }, { stop_reason: 'cancelled' })+ const closed = session(root, ID2, { updates: [PROMPT, cancelled, HOOK('stop')] })+ expect(await provider.busy!({ pid: 1, record: join(closed, 'updates.jsonl') })).toBe(false)+ })++ it('is not mid-turn once the process wrote its `session_end`', async () => {+ const root = home()+ const dir = session(root, ID, { updates: [PROMPT, HOOK('session_end'), HOOK('stop')] })+ expect(await grokTurnOpen(join(dir, 'updates.jsonl'))).toBe(false)+ })++ it('cannot say from a stream with no turn in it, or no stream', async () => {+ const root = home()+ const dir = session(root, ID, { updates: [HOOK('session_start'), line('current_mode_update', { s: 1 })] })+ expect(await grokTurnOpen(join(dir, 'updates.jsonl'))).toBeNull()+ expect(await grokTurnOpen(join(root, 'missing.jsonl'))).toBeNull()+ })+})diff --git a/cli/src/lib/sessionSearch/externals/grok.ts b/cli/src/lib/sessionSearch/externals/grok.tsnew file mode 100644index 000000000..1768530fc--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/grok.ts@@ -0,0 +1,252 @@+/**+ * Grok: one folder per conversation, `<GROK_HOME>/sessions/<group>/<id>/`, where the group is the+ * folder it ran in (URL-encoded, or a slug and hash with the path in `.cwd` when that is too long).+ * `summary.json` names its folder and title, `prompt_context.json` says who it was written for (a+ * headless run says `is_non_interactive`, a sub-agent's `audience` is `subagent`), and `updates.jsonl`+ * is the conversation itself.+ *+ * A running Grok lists what it has open in `<GROK_HOME>/active_sessions.json` (`session_id`, `pid`,+ * `cwd`, `opened_at`), which can outlive a crash. A shared backend (`grok agent leader`, `serve`,+ * `headless`, `stdio`) holds the sessions of every client connected to it: never stopped from here.+ *+ * When a conversation last moved is its own last line's time, not the file's: Grok appends its exit+ * hooks (`session_end`) when the process quits, hours after the last word.+ */++import { readFile, stat } from 'node:fs/promises'+import { basename, join } from 'node:path'++import { agentCommandOwnershipSnapshot } from '../../engineBin.js'+import { argvTokens, engineProcessMatch } from '../../tmux.js'+import { forEachLine } from '../transcript.js'+import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readJson, readTail, record, text, UUID } from './support.js'+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'++export interface GrokOptions { home: string }++export type GrokSkip = 'unreadable' | 'headless' | 'subagent' | 'hidden' | 'mismatch' | 'no-folder' | 'empty'++/** What one session folder holds: a conversation to offer, or why it is not one. */+export type GrokRead =+ | { kind: 'session'; cwd: string; title: string; movedAt: number | null }+ | { kind: 'skip'; reason: GrokSkip }++const PROMPT = /"sessionUpdate"\s*:\s*"user_message_chunk"/++/** The kinds that are the conversation itself; hooks, mode changes and retries are not. */+const MOVES = new Set([+ 'user_message_chunk', 'agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'tool_call_update',+ 'turn_completed', 'plan', 'subagent_spawned', 'subagent_finished',+])++/** How much of the end of `updates.jsonl` is read, and then how much more when that was one long line. */+const TAIL_BYTES = [256 * 1024, 4 * 1024 * 1024]++/** `ps` gives a process's start to the second, truncated: an entry this much older can still be its own. */+const START_SLACK_MS = 1000++/** A Grok process that serves other clients rather than one person's terminal. */+const SHARED_MODES = new Set(['leader', 'serve', 'headless', 'stdio'])++const skip = (reason: GrokSkip): GrokRead => ({ kind: 'skip', reason })++/**+ * A JSON file's value; undefined when there is none. One Grok is still writing is not JSON yet and+ * throws, so a scan's memo keeps nothing of it and the next scan reads it again.+ */+async function jsonFile(path: string): Promise<unknown> {+ const source = await readFile(path, 'utf8').catch(() => null)+ return source === null ? undefined : JSON.parse(source)+}++/** One `updates.jsonl` line: its kind, and when it was written (`_meta.agentTimestampMs`, else the+ * line's `timestamp` in seconds). */+function update(line: string): { kind: string; at: number | null; event: string } | null {+ const row = record(parseLine(line))+ const params = record(row?.params)+ const change = record(params?.update)+ const kind = text(change?.sessionUpdate)+ if (!kind) return null+ return { kind, at: epochMs(record(params?._meta)?.agentTimestampMs) ?? epochMs(row?.timestamp), event: text(change?.event_name) }+}++/**+ * The first answer [pick] gives, reading lines back from the end of [path]. A window that starts+ * mid-file starts mid-line, so its first line is never read.+ */+async function fromEnd<T>(path: string, pick: (line: string) => T | null): Promise<T | null> {+ const size = (await stat(path).catch(() => null))?.size ?? 0+ for (const bytes of TAIL_BYTES) {+ const lines = (await readTail(path, bytes)).split('\n')+ for (let i = lines.length - 1; i >= (size > bytes ? 1 : 0); i--) {+ const found = pick(lines[i])+ if (found !== null) return found+ }+ if (size <= bytes) break+ }+ return null+}++/** Whether a person said anything: a `user_message_chunk` anywhere in the stream. */+async function prompted(path: string): Promise<boolean> {+ let found = false+ try {+ await forEachLine(path, 0, () => { found = true }, { skip: (head) => !PROMPT.test(head), shouldStop: () => found })+ } catch {+ return false+ }+ return found+}++/** When the conversation last moved: the time of its last conversation line. */+export function grokMovedAt(path: string): Promise<number | null> {+ return fromEnd(path, (line) => {+ const row = update(line)+ return row && MOVES.has(row.kind) ? row.at : null+ })+}++/**+ * Whether a session's last turn is still running: a prompt after the last `turn_completed`. A+ * `session_end` hook means the process that wrote it quit. Null when the end of the stream says+ * neither.+ */+export function grokTurnOpen(path: string): Promise<boolean | null> {+ return fromEnd(path, (line) => {+ const row = update(line)+ if (row?.kind === 'user_message_chunk') return true+ if (row?.kind === 'turn_completed') return false+ if (row?.kind === 'hook_execution' && row.event === 'session_end') return false+ return null+ })+}++/**+ * One session folder, read: the conversation a person had there, or why it is not one. Throws while+ * its `summary.json` or `prompt_context.json` is half-written.+ */+export async function readGrokSession(dir: string, sessionId: string): Promise<GrokRead> {+ const summary = record(await jsonFile(join(dir, 'summary.json')))+ const context = record(await jsonFile(join(dir, 'prompt_context.json')))+ // Without both, a session cannot be told apart from a headless run or a sub-agent: not offered.+ if (!summary || !context) return skip('unreadable')+ if (context.is_non_interactive === true) return skip('headless')+ // A `/fork` peer is `primary` with a parent: a conversation of its own, and kept.+ if (context.audience === 'subagent' || text(summary.session_kind).startsWith('subagent')) return skip('subagent')+ if (summary.hidden === true) return skip('hidden')+ const info = record(summary.info)+ if (text(info?.id) && info?.id !== sessionId) return skip('mismatch')+ const cwd = absoluteFolder(info?.cwd) ?? absoluteFolder(context.working_directory)+ if (!cwd) return skip('no-folder')+ const updates = join(dir, 'updates.jsonl')+ if (!await prompted(updates)) return skip('empty')+ return {+ kind: 'session',+ cwd,+ title: text(summary.generated_title).trim(),+ movedAt: await grokMovedAt(updates) ?? epochMs(summary.last_active_at),+ }+}++/** The stream of session [sessionId], wherever its group is: first where [cwd] puts it, then by id. */+async function streamOf(home: string, sessionId: string, cwd: string): Promise<string | null> {+ const root = join(home, 'sessions')+ const direct = cwd ? join(root, encodeURIComponent(cwd), sessionId, 'updates.jsonl') : null+ if (direct && await fileStamp(direct)) return direct+ for (const group of await entries(root)) {+ if (!group.isDirectory()) continue+ const path = join(root, group.name, sessionId, 'updates.jsonl')+ if (await fileStamp(path)) return path+ }+ return null+}++/**+ * Whether [row] is a Grok. `agent` is also Cursor's name, and Cursor's `agent` is a node process+ * carrying its package's path, so an `agent` that is not Cursor's is Grok's.+ */+function isGrok(row: RunningProcess, ownership: ReturnType<typeof agentCommandOwnershipSnapshot>): boolean {+ if (engineProcessMatch(row, 'grok', ownership).score > 0) return true+ const named = [basename(row.executable), basename(argvTokens(row.args)[0] ?? '')].some((name) => name.toLowerCase() === 'agent')+ return named && engineProcessMatch(row, 'cursor', ownership).score === 0+}++/**+ * Whether [row] is a Grok backend shared by other clients (`grok agent [options] leader`), or a client+ * of one (`--leader`), whose session lives on in the leader when the client is stopped.+ */+function shared(row: RunningProcess): boolean {+ const tokens = argvTokens(row.args).slice(1)+ const agent = tokens.indexOf('agent')+ return tokens.includes('--leader') || (agent >= 0 && tokens.slice(agent + 1).some((token) => SHARED_MODES.has(token)))+}++export function grokProvider(options: GrokOptions): ExternalProvider {+ return {+ engine: 'grok',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const root = join(options.home, 'sessions')+ const found: ExternalSession[] = []+ for (const group of await entries(root)) {+ if (!group.isDirectory()) continue+ const folder = join(root, group.name)+ for (const entry of await entries(folder)) {+ if (!entry.isDirectory() || !UUID.test(entry.name)) continue+ const dir = join(folder, entry.name)+ const updates = join(dir, 'updates.jsonl')+ const stamp = await fileStamp(updates)+ if (!stamp) continue+ const [summary, context] = await Promise.all([+ fileStamp(join(dir, 'summary.json')), fileStamp(join(dir, 'prompt_context.json')),+ ])+ const fingerprint = `${stamp.stamp}|${summary?.stamp ?? '-'}|${context?.stamp ?? '-'}`+ const read = await ctx.memo(`grok:${dir}`, fingerprint, () => readGrokSession(dir, entry.name)).catch(() => null)+ await ctx.pace()+ // Half-written: nothing was remembered, and the next scan reads it again.+ if (read?.kind !== 'session' || ctx.excluded(read.cwd)) continue+ found.push({+ sessionId: entry.name, engine: 'grok', cwd: read.cwd, origin: 'terminal', title: read.title,+ mtime: read.movedAt ?? stamp.mtime, transcriptPath: updates,+ })+ }+ }+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const listed = await readJson(join(options.home, 'active_sessions.json'))+ // Grok itself starts over from an empty list when this file is corrupt.+ if (!Array.isArray(listed) || !listed.length) return []+ const byPid = new Map<number, Array<{ sessionId: string; cwd: string; at: number }>>()+ for (const item of listed) {+ const entry = record(item)+ const sessionId = text(entry?.session_id)+ const pid = entry?.pid+ if (!UUID.test(sessionId) || typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) continue+ byPid.set(pid, [...byPid.get(pid) ?? [], { sessionId, cwd: text(entry?.cwd), at: epochMs(entry?.opened_at) ?? 0 }])+ }+ const rows = new Map((await view.list()).map((row) => [row.pid, row]))+ const ownership = agentCommandOwnershipSnapshot()+ const claims: OwnerClaim[] = []+ for (const [pid, held] of byPid) {+ const row = rows.get(pid)+ // An entry outlives a crash, and its pid can be reused: only a live Grok counts.+ if (!row || !view.alive(pid) || !isGrok(row, ownership)) continue+ // An entry opened before the process that has its pid started was an earlier process's. An+ // entry that does not say when it was opened is kept.+ const current = held.filter((entry) => !entry.at || row.started === undefined || entry.at + START_SLACK_MS >= row.started)+ if (!current.length) continue+ const app = shared(row)+ // A terminal's Grok has one session open: an older entry under its pid is a crashed Grok's.+ const open = app ? current : [current.reduce((newest, entry) => (entry.at >= newest.at ? entry : newest))]+ for (const entry of open) {+ const stream = await streamOf(options.home, entry.sessionId, entry.cwd)+ claims.push({ sessionId: entry.sessionId, pid, record: stream ?? '', ...(app ? { app: true } : {}) })+ }+ }+ return claims+ },+ async busy(owner): Promise<boolean | null> {+ return owner.record ? grokTurnOpen(owner.record) : null+ },+ }+}diff --git a/cli/src/lib/sessionSearch/externals/hermes.spec.ts b/cli/src/lib/sessionSearch/externals/hermes.spec.tsnew file mode 100644index 000000000..f5b0435e1--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/hermes.spec.ts@@ -0,0 +1,732 @@+/**+ * Hermes discovery against real stores: fixture databases built from the schema dumped (read-only)+ * from this machine's `~/.hermes/state.db` (schema 22) and from the schema 17 the installed CLI's+ * code writes, in WAL mode, read through both of Harness's SQLite paths. No real conversation text.+ */++import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++import { builtinSqlite, closeSqliteHandles, overrideBuiltinSqlite } from '../../sqliteRead.js'+import {+ activeProfile, argvProfile, bestContinuation, compressionTip, hermesChains, hermesHomes, hermesKind, hermesLeases,+ hermesListSql, hermesProvider, hermesRow, hermesTurnOpen, leaseHeldBy, type HermesRow, type HermesSession,+} from './hermes.js'+import { LIST_LIMIT, ownerRecord, readSql, type SqlRead } from './opencode.js'+import { scanMemo } from './support.js'+import type { ProcessView, RunningProcess, ScanContext } from './types.js'++const Database = builtinSqlite()!+type Db = InstanceType<typeof Database>++const dirs: string[] = []+function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ext-hermes-'))+ dirs.push(dir)+ return dir+}+afterEach(() => {+ closeSqliteHandles()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++/** `sessions` as Hermes's schema 17 creates it (`hermes_state.py`, v0.18.0). */+const V17_SESSION_COLUMNS = `id TEXT PRIMARY KEY, source TEXT NOT NULL, user_id TEXT, session_key TEXT, chat_id TEXT,+ chat_type TEXT, thread_id TEXT, model TEXT, model_config TEXT, system_prompt TEXT, parent_session_id TEXT,+ started_at REAL NOT NULL, ended_at REAL, end_reason TEXT, message_count INTEGER DEFAULT 0,+ tool_call_count INTEGER DEFAULT 0, input_tokens INTEGER DEFAULT 0, output_tokens INTEGER DEFAULT 0,+ cache_read_tokens INTEGER DEFAULT 0, cache_write_tokens INTEGER DEFAULT 0, reasoning_tokens INTEGER DEFAULT 0,+ cwd TEXT, git_branch TEXT, git_repo_root TEXT, billing_provider TEXT, billing_base_url TEXT, billing_mode TEXT,+ estimated_cost_usd REAL, actual_cost_usd REAL, cost_status TEXT, cost_source TEXT, pricing_version TEXT, title TEXT,+ api_call_count INTEGER DEFAULT 0, handoff_state TEXT, handoff_platform TEXT, handoff_error TEXT,+ compression_failure_cooldown_until REAL, compression_failure_error TEXT, rewind_count INTEGER NOT NULL DEFAULT 0,+ archived INTEGER NOT NULL DEFAULT 0`+const V17_MESSAGE_COLUMNS = `id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL REFERENCES sessions(id),+ role TEXT NOT NULL, content TEXT, tool_call_id TEXT, tool_calls TEXT, tool_name TEXT, timestamp REAL NOT NULL,+ token_count INTEGER, finish_reason TEXT, reasoning TEXT, reasoning_content TEXT, reasoning_details TEXT,+ codex_reasoning_items TEXT, codex_message_items TEXT, platform_message_id TEXT, observed INTEGER DEFAULT 0,+ active INTEGER NOT NULL DEFAULT 1, compacted INTEGER NOT NULL DEFAULT 0`+const TAIL = `+CREATE TABLE compression_locks (session_id TEXT PRIMARY KEY, holder TEXT NOT NULL, acquired_at REAL NOT NULL, expires_at REAL NOT NULL);+CREATE INDEX idx_sessions_source ON sessions(source);+CREATE INDEX idx_sessions_parent ON sessions(parent_session_id);+CREATE INDEX idx_sessions_started ON sessions(started_at DESC);+CREATE INDEX idx_messages_session ON messages(session_id, timestamp);+CREATE UNIQUE INDEX idx_sessions_title_unique ON sessions(title) WHERE title IS NOT NULL;`+const V17 = `CREATE TABLE sessions (${V17_SESSION_COLUMNS}, FOREIGN KEY (parent_session_id) REFERENCES sessions(id));+CREATE TABLE messages (${V17_MESSAGE_COLUMNS});${TAIL}`+/** Schema 22 as measured on this machine: the columns newer Hermes versions appended. */+const V22 = `CREATE TABLE sessions (${V17_SESSION_COLUMNS}, "display_name" TEXT, "origin_json" TEXT,+ "expiry_finalized" INTEGER DEFAULT 0, "compression_fallback_streak" INTEGER NOT NULL DEFAULT 0, "profile_name" TEXT,+ FOREIGN KEY (parent_session_id) REFERENCES sessions(id));+CREATE TABLE messages (${V17_MESSAGE_COLUMNS}, "effect_disposition" TEXT, "api_content" TEXT);${TAIL}`++/** Real-shaped ids: CLI/TUI `YYYYMMDD_HHMMSS_<6 hex>` in local time, and an editor's uuid4. */+const id = (n: number, hex = 'a1b2c3'): string => `20260920_${String(n).padStart(6, '0')}_${hex}`+const ACP = '3f2a9c1e-8b4d-4e6f-9a1b-2c3d4e5f6a7b'+const S0 = 1_789_900_000 // REAL epoch seconds, as Hermes writes them++interface SessionRow {+ source?: string+ cwd?: string | null+ config?: Record<string, unknown> | string | null+ repo?: string | null+ title?: string | null+ displayName?: string | null+ parent?: string | null+ started?: number+ ended?: number | null+ endReason?: string | null+ archived?: number+}++class Store {+ readonly db: Db+ private readonly v22: boolean+ constructor(readonly path: string, schema = V22) {+ mkdirSync(join(path, '..'), { recursive: true })+ this.db = new Database(path, { readOnly: false })+ this.db.exec('PRAGMA journal_mode = WAL')+ this.db.exec(schema)+ this.v22 = schema === V22+ }++ session(sessionId: string, row: SessionRow = {}): this {+ const config = row.config === undefined ? null : typeof row.config === 'string' ? row.config : JSON.stringify(row.config)+ this.db.prepare(+ 'INSERT INTO sessions (id, source, model_config, parent_session_id, started_at, ended_at, end_reason, cwd, git_repo_root, title, archived)'+ + ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',+ ).all(sessionId, row.source ?? 'cli', config, row.parent ?? null, row.started ?? S0, row.ended ?? null,+ row.endReason ?? null, row.cwd === undefined ? '/work/app' : row.cwd, row.repo ?? null, row.title ?? null, row.archived ?? 0)+ if (this.v22 && row.displayName) this.db.prepare('UPDATE sessions SET display_name = ? WHERE id = ?').all(row.displayName, sessionId)+ return this+ }++ message(sessionId: string, role: string, at: number, finish: string | null = null): this {+ this.db.prepare('INSERT INTO messages (session_id, role, content, finish_reason, timestamp) VALUES (?, ?, ?, ?, ?)')+ .all(sessionId, role, role === 'user' ? 'please look at the tests' : 'ok', finish, at)+ return this+ }++ /** A person's ask and a finished answer. */+ turn(sessionId: string, at = S0 + 1): this {+ return this.message(sessionId, 'user', at).message(sessionId, 'assistant', at + 0.5, 'stop')+ }++ close(): void { this.db.close() }+}++function context(excluded: string[] = []): ScanContext {+ return scanMemo({ excluded }).context()+}++const byId = (sessions: readonly unknown[]): Map<string, HermesSession> =>+ new Map((sessions as HermesSession[]).map((s) => [s.sessionId, s]))++const READERS: Array<[string, typeof Database | null]> = [['node:sqlite', Database], ['the sqlite3 CLI', null]]++describe.each(READERS)('Hermes discovery read through %s', (_name, reader) => {+ beforeAll(() => { overrideBuiltinSqlite(reader) })+ afterAll(() => { overrideBuiltinSqlite(Database) })++ it('lists what a person started in the REPL, the terminal UI or an editor, and nothing else', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1), { source: 'cli', cwd: '/work/repl', title: 'Repl work' }).turn(id(1), S0 + 10.25)+ // The terminal UI records no folder unless its client passed one; the repository root still says where.+ store.session(id(2), { source: 'tui', cwd: null, repo: '/work/repo' }).turn(id(2))+ store.session(id(3), { source: 'tui', cwd: null }).turn(id(3))+ store.session(ACP, { source: 'acp', cwd: null, config: { cwd: '/work/editor' }, title: 'Editor chat' }).turn(ACP)+ for (const [n, source] of [[4, 'tool'], [5, 'subagent'], [6, 'cron'], [7, 'telegram'], [8, 'api_server']] as const) {+ store.session(id(n), { source }).turn(id(n))+ }+ store.session(id(9), { archived: 1 }).turn(id(9))+ // An older delegation child still says `cli`: its marker gives it away.+ store.session(id(10), { config: { _delegate_from: id(1) } }).turn(id(10))+ store.session(id(11)) // opened and closed without a word+ store.session(id(12), { cwd: 'relative/dir', config: '{not json' }).turn(id(12))+ store.session(id(13), { cwd: join(root, 'harness-data', 'x') }).turn(id(13))+ store.session('gw-8f3a2b1c', { source: 'cli' }).turn('gw-8f3a2b1c')++ const provider = hermesProvider({ root })+ const found = byId(await provider.scan(context([join(root, 'harness-data')])))+ expect([...found.keys()].sort()).toEqual([id(1), id(2), ACP].sort())+ expect(provider.lastScan()).toEqual({ found: 3, source: 5, archived: 1, delegated: 1, empty: 1, noFolder: 2, excluded: 1, badId: 1 })+ expect(found.get(id(1))).toMatchObject({+ engine: 'hermes', cwd: '/work/repl', origin: 'terminal', title: 'Repl work', transcriptPath: null,+ mtime: Math.round((S0 + 10.75) * 1000), aliases: [],+ })+ expect(found.get(id(1))!.launchArgs).toBeUndefined()+ expect(found.get(id(2))).toMatchObject({ cwd: '/work/repo', origin: 'terminal', title: '' })+ expect(found.get(ACP)).toMatchObject({ cwd: '/work/editor', origin: 'editor', title: 'Editor chat' })+ // An editor's uuid id reads its history like any other.+ expect((await found.get(ACP)!.readHistory!()).map((e) => e.type)).toEqual(['user_message', 'text_delta', 'done'])+ store.close()+ })++ it('lists a branch on its own and hides a sub-agent child', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1), { ended: S0 + 5, endReason: 'branched' }).turn(id(1))+ store.session(id(2), { parent: id(1), config: { _branched_from: id(1) } }).turn(id(2))+ // Hermes's older rule: the parent ended `branched` before the child began.+ store.session(id(3), { parent: id(1), started: S0 + 6 }).turn(id(3))+ // Began before the parent ended: a child of the running conversation, not a branch.+ store.session(id(4), { parent: id(1), started: S0 + 4 }).turn(id(4))+ store.session(id(5), { ended: null, endReason: 'branched' }).turn(id(5))+ store.session(id(6), { parent: id(5), started: S0 + 6 }).turn(id(6))+ store.session(id(7)).turn(id(7))+ store.session(id(8), { parent: id(7) }).turn(id(8))+ const provider = hermesProvider({ root })+ expect([...byId(await provider.scan(context())).keys()].sort()).toEqual([id(1), id(2), id(3), id(5), id(7)])+ expect(provider.lastScan()).toEqual({ found: 5, child: 3 })+ store.close()+ })++ it('lists a compressed conversation once, under its newest id, with every id it had', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1), { title: 'Long refactor', ended: S0 + 100, endReason: 'compression', cwd: '/work/long' })+ .turn(id(1), S0 + 50)+ store.session(id(2), { parent: id(1), started: S0 + 100, ended: S0 + 200, endReason: 'compression', cwd: null, title: 'Long refactor #2' })+ .turn(id(2), S0 + 150)+ // A reaped websocket's sibling: closed, and not the one the chain follows.+ store.session(id(3), { parent: id(2), started: S0 + 200, ended: S0 + 201, endReason: 'ws_orphan_reap', cwd: null })+ .turn(id(3), S0 + 999)+ store.session(id(4), { parent: id(2), started: S0 + 200, cwd: null }).turn(id(4), S0 + 300)+ const provider = hermesProvider({ root })+ const found = byId(await provider.scan(context()))+ expect([...found.keys()]).toEqual([id(4)])+ expect(found.get(id(4))).toMatchObject({+ // The stale sibling's later message is not this conversation's.+ cwd: '/work/long', title: 'Long refactor #2', aliases: [id(1), id(2)], mtime: Math.round((S0 + 300.5) * 1000),+ })+ expect(provider.lastScan()).toEqual({ found: 1, compressed: 2, stale: 1 })+ // The history is the whole conversation, oldest first.+ const events = await found.get(id(4))!.readHistory!()+ expect(events.filter((e) => e.type === 'user_message')).toHaveLength(3)+ store.close()+ })++ it('follows a chain whose start is older than the list, and says which id it started from', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.db.exec('BEGIN')+ store.session(id(1), { ended: S0 + 1, endReason: 'compression' }).message(id(1), 'user', S0)+ for (let n = 0; n < LIST_LIMIT; n++) store.session(id(1000 + n, 'bbbbbb')).message(id(1000 + n, 'bbbbbb'), 'user', S0 + 10 + n)+ store.session(id(2), { parent: id(1), started: S0 + 1 }).message(id(2), 'user', S0 + 10_000)+ store.db.exec('COMMIT')+ const provider = hermesProvider({ root })+ const found = byId(await provider.scan(context()))+ expect(found.size).toBe(LIST_LIMIT)+ expect(found.get(id(2))).toMatchObject({ aliases: [id(1)] })+ expect(provider.lastScan()).toMatchObject({ found: LIST_LIMIT, older: 2 })+ store.close()+ })++ it('hides a conversation no id of which has a message, and times one by its start when it has none', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1), { ended: S0 + 1, endReason: 'compression' })+ store.session(id(2), { parent: id(1) })+ store.session(id(3), { ended: S0 + 1, endReason: 'compression', started: S0 }).turn(id(3), S0 + 0.5)+ store.session(id(4), { parent: id(3), started: 0 })+ const provider = hermesProvider({ root })+ const found = byId(await provider.scan(context()))+ expect([...found.keys()]).toEqual([id(4)])+ expect(found.get(id(4))!.mtime).toBe(Math.round((S0 + 1) * 1000))+ expect(provider.lastScan()).toEqual({ found: 1, empty: 1, compressed: 2 })+ store.close()+ })++ it('reads every home, and resumes a profile\'s conversation in its profile', async () => {+ const root = tempDir()+ const main = new Store(join(root, 'state.db'))+ main.session(id(1)).turn(id(1))+ const work = new Store(join(root, 'profiles', 'work', 'state.db'))+ work.session(id(2)).turn(id(2))+ mkdirSync(join(root, 'profiles', 'fresh')) // a profile whose first session has not run+ const odd = new Store(join(root, 'profiles', 'Not_A_Profile', 'state.db'))+ odd.session(id(3)).turn(id(3))+ const named = new Store(join(root, 'profiles', 'default', 'state.db')) // never used: `-p default` is the root+ named.session(id(4)).turn(id(4))+ writeFileSync(join(root, 'profiles', 'notes.txt'), 'x')++ const provider = hermesProvider({ root })+ let found = byId(await provider.scan(context()))+ expect([...found.keys()].sort()).toEqual([id(1), id(2)])+ expect(found.get(id(1))!.launchArgs).toBeUndefined()+ expect(found.get(id(2))!.launchArgs).toEqual(['-p', 'work'])+ expect(provider.lastScan()).toEqual({ found: 2 })++ // A sticky profile sends a plain `hermes` elsewhere: the default home's sessions must say so.+ writeFileSync(join(root, 'active_profile'), 'work\n')+ found = byId(await provider.scan(context()))+ expect(found.get(id(1))!.launchArgs).toEqual(['-p', 'default'])+ expect(found.get(id(2))!.launchArgs).toEqual(['-p', 'work'])+ main.close(); work.close(); odd.close(); named.close()+ })++ it('reads the schema each store has: 17, and older', async () => {+ const root = tempDir()+ const v17 = new Store(join(root, 'state.db'), V17)+ v17.session(id(1), { title: 'Old title' }).turn(id(1))+ const old = new Store(join(root, 'profiles', 'old', 'state.db'),+ 'CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, started_at REAL NOT NULL, cwd TEXT);'+ + 'CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, content TEXT, timestamp REAL);')+ old.db.exec(`INSERT INTO sessions VALUES ('${id(2)}', 'cli', ${S0}, '/work/old'), ('${id(3)}', 'tool', ${S0}, '/work/old')`)+ old.db.exec(`INSERT INTO messages (session_id, role, content, timestamp) VALUES ('${id(2)}', 'user', 'hi', ${S0 + 2})`)+ const bare = new Store(join(root, 'profiles', 'bare', 'state.db'),+ `CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT NOT NULL, cwd TEXT); INSERT INTO sessions VALUES ('${id(4)}', 'cli', '/w');`)+ const alien = new Store(join(root, 'profiles', 'alien', 'state.db'), 'CREATE TABLE things (id TEXT);')++ const provider = hermesProvider({ root })+ const found = byId(await provider.scan(context()))+ expect([...found.keys()].sort()).toEqual([id(1), id(2)])+ expect(found.get(id(1))!.title).toBe('Old title')+ expect(found.get(id(2))).toMatchObject({ cwd: '/work/old', title: '', mtime: (S0 + 2) * 1000, launchArgs: ['-p', 'old'] })+ expect(provider.lastScan()).toEqual({ found: 2, source: 1, empty: 1 })+ v17.close(); old.close(); bare.close(); alien.close()+ })++ it('reads a store once until its files change', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1)).turn(id(1))+ const read = vi.fn(readSql)+ const provider = hermesProvider({ root, read })+ const memo = scanMemo({ excluded: [] })+ expect((await provider.scan(memo.context())).map((s) => s.sessionId)).toEqual([id(1)])+ expect(read).toHaveBeenCalledTimes(2)+ memo.prune()+ expect((await provider.scan(memo.context())).map((s) => s.sessionId)).toEqual([id(1)])+ expect(read).toHaveBeenCalledTimes(2)+ store.session(id(2)).turn(id(2))+ expect(await provider.scan(memo.context())).toHaveLength(2)+ expect(read).toHaveBeenCalledTimes(4)+ store.close()+ })++ it('says from the last message whether a turn is running, and waits out a compression', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ const now = S0 * 1000+ const provider = hermesProvider({ root, now: () => now })+ const busy = (sessionId: string) => provider.busy!({ pid: 1, record: ownerRecord(store.path, sessionId) })+ store.session(id(1))+ expect(await busy(id(1))).toBe(false)+ store.session(id(2)).message(id(2), 'user', S0)+ expect(await busy(id(2))).toBe(true)+ store.session(id(3)).message(id(3), 'user', S0).message(id(3), 'assistant', S0 + 1, 'tool_calls')+ expect(await busy(id(3))).toBe(true)+ store.message(id(3), 'tool', S0 + 2)+ expect(await busy(id(3))).toBe(true)+ store.message(id(3), 'assistant', S0 + 3, 'stop')+ expect(await busy(id(3))).toBe(false)+ store.session(id(4)).message(id(4), 'assistant', S0)+ expect(await busy(id(4))).toBe(true)+ store.session(id(5)).message(id(5), 'session_meta', S0)+ expect(await busy(id(5))).toBeNull()++ store.db.prepare('INSERT INTO compression_locks VALUES (?, ?, ?, ?)').all(id(3), 'pid:1', S0 - 1, S0 + 60)+ expect(await busy(id(3))).toBe(true)+ store.db.prepare('UPDATE compression_locks SET expires_at = ? WHERE session_id = ?').all(S0 - 1, id(3))+ expect(await busy(id(3))).toBe(false)++ // A store too old for compression locks still has a tail.+ const old = new Store(join(root, 'old.db'), 'CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, finish_reason TEXT, timestamp REAL);')+ old.db.exec(`INSERT INTO messages (session_id, role, timestamp) VALUES ('${id(6)}', 'user', 1)`)+ expect(await provider.busy!({ pid: 1, record: ownerRecord(old.path, id(6)) })).toBe(true)++ expect(await provider.busy!({ pid: 1, record: 'nothing' })).toBeNull()+ expect(await provider.busy!({ pid: 1, record: ownerRecord(join(root, 'gone.db'), id(1)) })).toBeNull()+ store.close(); old.close()+ })+})++describe('a Hermes store that cannot be read right now', () => {+ it('keeps each home\'s last list when it fails, and throws only when every home fails', async () => {+ const root = tempDir()+ const main = new Store(join(root, 'state.db'))+ main.session(id(1)).turn(id(1))+ const work = new Store(join(root, 'profiles', 'work', 'state.db'))+ work.session(id(2)).turn(id(2))+ const broken = new Set<string>()+ const read: SqlRead = async (dbPath, sql, params) => (broken.has(dbPath)+ ? { ok: false, reason: 'transient', error: new Error('database is locked') }+ : readSql(dbPath, sql, params))+ const provider = hermesProvider({ root, read })+ const memo = scanMemo({ excluded: [] })+ expect((await provider.scan(memo.context())).map((s) => s.sessionId).sort()).toEqual([id(1), id(2)])++ // The default home locks and changes: its last list stands in, the profile still answers.+ broken.add(main.path)+ main.session(id(3)).turn(id(3))+ work.session(id(4)).turn(id(4))+ expect((await provider.scan(memo.context())).map((s) => s.sessionId).sort()).toEqual([id(1), id(2), id(4)])++ // Every home failing is the store failing: the scan throws and discovery keeps its own last list.+ broken.add(work.path)+ work.session(id(5)).turn(id(5))+ await expect(provider.scan(memo.context())).rejects.toThrow('state.db not readable: database is locked')++ // A home that never read cleanly has nothing to stand in.+ const fresh = hermesProvider({ root, read: async (dbPath, sql, params) => (dbPath === main.path ? { ok: false, reason: 'transient' } : readSql(dbPath, sql, params)) })+ broken.clear()+ expect((await fresh.scan(context())).map((s) => s.sessionId).sort()).toEqual([id(2), id(4), id(5)])+ main.close(); work.close()+ })++ it('finds nothing with no store, no SQLite reader, or a reader that goes missing', async () => {+ const root = tempDir()+ expect(await hermesProvider({ root }).scan(context())).toEqual([])+ const store = new Store(join(root, 'state.db'))+ store.session(id(1)).turn(id(1))+ const read = vi.fn(readSql)+ const none = hermesProvider({ root, read, available: () => false })+ expect(await none.scan(context())).toEqual([])+ expect(none.lastScan()).toEqual({})+ expect(read).not.toHaveBeenCalled()+ expect(await hermesProvider({ root, read: async () => ({ ok: false, reason: 'missing' }) }).scan(context())).toEqual([])+ let calls = 0+ const vanishing: SqlRead = async (dbPath, sql, params) => (++calls === 1 ? readSql(dbPath, sql, params) : { ok: false, reason: 'missing' })+ expect(await hermesProvider({ root, read: vanishing }).scan(context())).toEqual([])+ store.close()+ })++ it('fails on a store that is not a database', async () => {+ const root = tempDir()+ writeFileSync(join(root, 'state.db'), 'not a database at all '.repeat(100))+ await expect(hermesProvider({ root }).scan(context())).rejects.toThrow(/^state\.db not readable: /)+ })++ it('answers unknowable when a busy read fails partway', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1)).message(id(1), 'user', S0)+ const failAt = (n: number): SqlRead => {+ let calls = 0+ return async (dbPath, sql, params) => (++calls === n ? { ok: false, reason: 'transient' } : readSql(dbPath, sql, params))+ }+ const record = ownerRecord(store.path, id(1))+ expect(await hermesProvider({ root, read: failAt(2) }).busy!({ pid: 1, record })).toBeNull()+ expect(await hermesProvider({ root, read: failAt(3) }).busy!({ pid: 1, record })).toBeNull()+ expect(await hermesProvider({ root, read: failAt(99) }).busy!({ pid: 1, record })).toBe(true)+ store.close()+ })+})++describe('Hermes owners', () => {+ const HERMES = '/Users/me/.hermes/hermes-agent/venv/bin'+ const py = (pid: number, ppid: number, rest: string): RunningProcess =>+ ({ pid, ppid, executable: 'python3.12', args: `${HERMES}/python3 ${HERMES}/hermes${rest ? ` ${rest}` : ''}` })+ const proc = (pid: number, ppid: number, args: string): RunningProcess => ({ pid, ppid, executable: args.split(' ')[0], args })+ const view = (rows: RunningProcess[], dead: number[] = []): ProcessView => ({+ list: async () => rows,+ openFiles: async () => new Map(),+ openFilesOf: async () => new Map(),+ alive: (pid) => !dead.includes(pid),+ })++ function homes(): { root: string; main: Store; work: Store } {+ const root = tempDir()+ const main = new Store(join(root, 'state.db'))+ main.session(id(1)).turn(id(1))+ main.session(id(2), { ended: S0 + 5, endReason: 'compression' }).turn(id(2))+ main.session(id(3), { parent: id(2), started: S0 + 5 }).turn(id(3), S0 + 6)+ const work = new Store(join(root, 'profiles', 'work', 'state.db'))+ work.session(id(4)).turn(id(4))+ return { root, main, work }+ }++ it('claims from the id a Hermes process was resumed with, in the home it runs in, at its chain\'s tip', async () => {+ const { root, main, work } = homes()+ const claims = await hermesProvider({ root }).owners!(view([+ proc(1, 0, 'launchd'),+ py(100, 1, `--resume ${id(1)}`),+ // Resumed from a compressed id: Hermes carries on at the tip, and so does the claim.+ py(101, 1, `-r ${id(2)}`),+ py(102, 1, `-p work --resume=${id(4)}`),+ // Found by looking when no profile is named.+ py(103, 1, `-r ${id(4)}`),+ // Not Hermes, whatever its arguments say: a Node that lives under ~/.hermes.+ proc(104, 1, `/Users/me/.hermes/node/bin/node test.js -r ${id(9)}`),+ py(105, 1, '--tui'),+ py(106, 1, `-r not-an-id`),+ // An id no store has yet is still what it holds.+ py(107, 1, `-p default -r ${id(8)}`),+ ]))+ // Arguments name the session a process started on, not necessarily the one it has now.+ expect(claims).toEqual([+ { sessionId: id(1), pid: 100, record: ownerRecord(main.path, id(1)), fromArgs: true },+ { sessionId: id(3), pid: 101, record: ownerRecord(main.path, id(3)), fromArgs: true },+ { sessionId: id(4), pid: 102, record: ownerRecord(work.path, id(4)), fromArgs: true },+ { sessionId: id(8), pid: 107, record: ownerRecord(main.path, id(8)), fromArgs: true },+ ])+ main.close(); work.close()+ })++ it('asks the sticky profile first for a plain `hermes`, even one with no store yet', async () => {+ const { root, main, work } = homes()+ writeFileSync(join(root, 'active_profile'), 'work')+ const claims = await hermesProvider({ root }).owners!(view([py(100, 0, `-r ${id(4)}`), py(101, 0, `-r ${id(1)}`)]))+ expect(claims.map((c) => [c.sessionId, c.record])).toEqual([+ [id(4), ownerRecord(work.path, id(4))], [id(1), ownerRecord(main.path, id(1))],+ ])+ writeFileSync(join(root, 'active_profile'), 'gone')+ const orphan = await hermesProvider({ root }).owners!(view([py(100, 0, `-r ${id(7)}`), py(101, 0, `-r ${id(4)}`)]))+ expect(orphan.map((c) => c.record)).toEqual([+ ownerRecord(join(root, 'profiles', 'gone', 'state.db'), id(7)), ownerRecord(work.path, id(4)),+ ])+ main.close(); work.close()+ })++ it('reads the active-session leases, and owns a terminal UI\'s through its `hermes`', async () => {+ const { root, main, work } = homes()+ mkdirSync(join(root, 'runtime'))+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: [+ { lease_id: 'a', session_id: id(1), surface: 'cli', pid: 200 },+ // hermes --tui (201) → node UI (202) → python gateway (203), which holds the lease.+ { lease_id: 'b', session_id: id(2), surface: 'tui', pid: 203, metadata: { live_session_id: 'abcd1234' } },+ { lease_id: 'c', session_id: 'agent:main:telegram:dm:42', surface: 'gateway:telegram', pid: 204 },+ { lease_id: 'd', session_id: id(5), surface: 'cli', pid: 205 }, // dead+ { lease_id: 'e', session_id: id(6), surface: 'cli', pid: 206 }, // a reused pid: not Hermes+ { lease_id: 'f', session_id: id(7), surface: 'cli', pid: '207' },+ { lease_id: 'g', session_id: id(7), surface: 'cli', pid: -1 },+ { lease_id: 'h', session_id: id(7), surface: 'cli', pid: 1.5 },+ 'garbage',+ ] }))+ mkdirSync(join(root, 'profiles', 'work', 'runtime'))+ // An older Hermes wrote the list bare.+ writeFileSync(join(root, 'profiles', 'work', 'runtime', 'active_sessions.json'), JSON.stringify([+ { session_id: id(4), surface: 'cli', pid: 300 },+ ]))+ const claims = await hermesProvider({ root }).owners!(view([+ py(200, 1, ''),+ py(201, 1, '--tui'),+ proc(202, 201, 'node /Users/me/.hermes/hermes-agent/ui-tui/dist/entry.js'),+ proc(203, 202, 'python3 -m tui_gateway.entry'),+ proc(204, 1, 'python3 -m gateway.run'),+ proc(206, 1, 'vim notes.txt'),+ py(300, 1, '-p work'),+ // Also named in another process's arguments: the lease is exact, and wins.+ py(400, 1, `-r ${id(1)}`),+ ], [205]))+ expect(claims).toEqual([+ { sessionId: id(1), pid: 200, record: ownerRecord(main.path, id(1)) },+ { sessionId: id(3), pid: 201, record: ownerRecord(main.path, id(3)) },+ { sessionId: id(4), pid: 300, record: ownerRecord(work.path, id(4)) },+ ])+ main.close(); work.close()+ })++ it('checks a lease against the start of the process now under its pid', async () => {+ const { root, main, work } = homes()+ const T = 1_790_000_000_000+ mkdirSync(join(root, 'runtime'))+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: [+ // Its REPL: psutil's create_time (float seconds) against ps's whole second.+ { session_id: id(1), surface: 'cli', pid: 200, process_start_time: T / 1000 + 0.731 },+ // A Hermes crashed and left this; its pid now belongs to a tool another live Hermes runs, and+ // the walk up would have handed that Hermes a claim it could be stopped on.+ { session_id: id(4), surface: 'cli', pid: 601, process_start_time: T / 1000 },+ // No start recorded (Hermes without psutil): the pid is all there is.+ { session_id: id(3), surface: 'cli', pid: 700, process_start_time: null },+ // Alive but not in the process list: nothing to check, and no Hermes to own it.+ { session_id: id(8), surface: 'cli', pid: 800, process_start_time: T / 1000 },+ ] }))+ const at = (row: RunningProcess, started?: number): RunningProcess => (started === undefined ? row : { ...row, started })+ const claims = await hermesProvider({ root }).owners!(view([+ at(py(200, 1, ''), T),+ at(py(600, 1, ''), T - 86_400_000),+ at(proc(601, 600, 'python3 tool.py'), T + 3_600_000),+ at(py(700, 1, ''), T),+ ]))+ expect(claims).toEqual([+ { sessionId: id(1), pid: 200, record: ownerRecord(main.path, id(1)) },+ { sessionId: id(3), pid: 700, record: ownerRecord(main.path, id(3)) },+ ])+ main.close(); work.close()+ })++ it('never offers to stop what serves another client', async () => {+ const { root, main, work } = homes()+ mkdirSync(join(root, 'runtime'))+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: [+ { session_id: id(1), surface: 'tui', pid: 503 },+ ] }))+ const claims = await hermesProvider({ root }).owners!(view([+ // The dashboard runs a terminal chat in a pty: it has a terminal, and is still the desktop app's.+ py(500, 1, 'dashboard --port 9119'),+ proc(502, 500, 'node /Users/me/.hermes/hermes-agent/ui-tui/dist/entry.js'),+ proc(503, 502, 'python3 -m tui_gateway.entry'),+ py(600, 500, `--tui --resume ${id(4)} -p work`),+ // A Hermes agent that started another from its shell: the outer one is not a server.+ py(700, 1, ''),+ proc(701, 700, 'zsh -c hermes'),+ py(702, 701, `-r ${id(2)}`),+ py(800, 1, `-m some/model gateway run -r ${id(8)}`),+ ]))+ expect(claims).toEqual([+ { sessionId: id(1), pid: 500, record: ownerRecord(main.path, id(1)), app: true },+ { sessionId: id(4), pid: 600, record: ownerRecord(work.path, id(4)), app: true, fromArgs: true },+ { sessionId: id(3), pid: 702, record: ownerRecord(main.path, id(3)), fromArgs: true },+ { sessionId: id(8), pid: 800, record: ownerRecord(main.path, id(8)), app: true, fromArgs: true },+ ])+ main.close(); work.close()+ })+})++describe('Hermes pieces', () => {+ const row = (over: Partial<HermesRow>): HermesRow => ({+ id: id(1), source: 'cli', parent: null, started: S0, ended: null, endReason: null, cwd: null, configCwd: null, repo: null,+ title: '', displayName: '', branched: false, parentEnd: null, parentEnded: null, lastMsg: null, ...over,+ })++ it('reads the profile a process names the way Hermes does', () => {+ expect(argvProfile('hermes -p work')).toBe('work')+ expect(argvProfile('hermes --profile work -p other')).toBe('work')+ expect(argvProfile('hermes --profile=work')).toBe('work')+ expect(argvProfile('hermes -p default')).toBe('default')+ expect(argvProfile('hermes -p Bad_Name')).toBeNull()+ expect(argvProfile('hermes --profile=')).toBeNull()+ expect(argvProfile('hermes -p')).toBeNull()+ expect(argvProfile('hermes -m -p -p work')).toBe('work')+ expect(argvProfile('hermes -c -p work')).toBe('work')+ expect(argvProfile('hermes -c mychat -p work')).toBe('work')+ expect(argvProfile('hermes -c')).toBeNull()+ expect(argvProfile('hermes -- -p work')).toBeNull()+ expect(argvProfile('hermes -r 20260920_101500_a1b2c3')).toBeNull()+ })++ it('tells a conversation\'s start from its continuation and from a sub-agent\'s child', () => {+ expect(hermesKind(row({}))).toBe('head')+ expect(hermesKind(row({ parent: 'p', branched: true }))).toBe('head')+ expect(hermesKind(row({ parent: 'p', parentEnd: 'branched', parentEnded: S0 - 1 }))).toBe('head')+ expect(hermesKind(row({ parent: 'p', parentEnd: 'branched', parentEnded: S0 + 1 }))).toBe('child')+ expect(hermesKind(row({ parent: 'p', parentEnd: 'branched', parentEnded: null }))).toBe('child')+ expect(hermesKind(row({ parent: 'p', parentEnd: 'branched', parentEnded: S0, started: null }))).toBe('child')+ expect(hermesKind(row({ parent: 'p', parentEnd: 'compression' }))).toBe('continuation')+ expect(hermesKind(row({ parent: 'p' }))).toBe('child')+ })++ it('follows the continuation Hermes follows', () => {+ const compressed = row({ id: 'a', endReason: 'compression', ended: S0 })+ const open = row({ id: 'b' })+ const closed = row({ id: 'c', ended: S0, lastMsg: S0 + 99 })+ expect(bestContinuation([closed, open, compressed]).id).toBe('a')+ expect(bestContinuation([closed, open]).id).toBe('b')+ expect(bestContinuation([row({ id: 'd', lastMsg: S0 + 1 }), row({ id: 'e', lastMsg: S0 + 2 })]).id).toBe('e')+ expect(bestContinuation([row({ id: 'f', lastMsg: S0 + 5, started: S0 + 1 }), row({ id: 'g', lastMsg: S0 + 5, started: S0 + 2 })]).id).toBe('g')+ expect(bestContinuation([row({ id: 'h', lastMsg: S0 + 5, started: null }), row({ id: 'i', lastMsg: S0 + 5, started: S0 })]).id).toBe('i')+ expect(bestContinuation([row({ id: 'j', lastMsg: S0 + 5, started: S0 }), row({ id: 'k', lastMsg: S0 + 5, started: null })]).id).toBe('j')+ expect(bestContinuation([row({ id: 'o', started: null }), row({ id: 'p', started: null })]).id).toBe('p')+ expect(bestContinuation([row({ id: 'm' }), row({ id: 'l' }), row({ id: 'n' })]).id).toBe('n')+ expect(bestContinuation([row({ id: 'n' }), row({ id: 'm' }), row({ id: 'l' })]).id).toBe('n')+ })++ it('never loops on a chain that points at itself', () => {+ const counts = {}+ const chains = hermesChains([+ row({ id: 'a', parent: 'a', parentEnd: 'compression' }),+ row({ id: 'b', parent: 'c', parentEnd: 'compression' }),+ row({ id: 'c', parent: 'b', parentEnd: 'compression' }),+ ], counts)+ expect(chains).toEqual([])+ expect(counts).toEqual({ stale: 3 })+ })++ it('reads a row from either SQLite path', () => {+ expect(hermesRow({ id: 'x', source: 'cli', started: 1.5, branched: 0, parent: '', last_msg: 'NaN' }))+ .toMatchObject({ id: 'x', started: 1.5, branched: true, parent: null, lastMsg: null, title: '', displayName: '' })+ expect(hermesRow({ id: 'x', branched: null }).branched).toBe(false)+ })++ it('matches a lease to its process by start, within ps\'s whole second', () => {+ const lease = { sessionId: id(1), pid: 5, started: 1_000_000 }+ const row = (started?: number): RunningProcess => ({ pid: 5, ppid: 1, executable: 'hermes', args: 'hermes', ...(started === undefined ? {} : { started }) })+ expect(leaseHeldBy(lease, row(999_000))).toBe(true)+ expect(leaseHeldBy(lease, row(1_002_000))).toBe(true)+ expect(leaseHeldBy(lease, row(997_999))).toBe(false)+ expect(leaseHeldBy(lease, row(1_002_001))).toBe(false)+ expect(leaseHeldBy(lease, row())).toBe(true)+ expect(leaseHeldBy(lease, undefined)).toBe(true)+ expect(leaseHeldBy({ sessionId: id(1), pid: 5 }, row(1))).toBe(true)+ })++ it('reads a lease\'s start in milliseconds, and only a real one', async () => {+ const dir = tempDir()+ mkdirSync(join(dir, 'runtime'))+ writeFileSync(join(dir, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: [+ { session_id: id(1), surface: 'cli', pid: 1, process_start_time: 1_790_000_000.5 },+ { session_id: id(2), surface: 'cli', pid: 2, process_start_time: 0 },+ { session_id: id(3), surface: 'cli', pid: 3, process_start_time: '1790000000' },+ ] }))+ expect(await hermesLeases(dir)).toEqual([+ { sessionId: id(1), pid: 1, started: 1_790_000_000_500 },+ { sessionId: id(2), pid: 2 },+ { sessionId: id(3), pid: 3 },+ ])+ })++ it('reads leases only from what Hermes writes', async () => {+ const dir = tempDir()+ expect(await hermesLeases(dir)).toEqual([])+ mkdirSync(join(dir, 'runtime'))+ writeFileSync(join(dir, 'runtime', 'active_sessions.json'), '{"entries": "nope"}')+ expect(await hermesLeases(dir)).toEqual([])+ writeFileSync(join(dir, 'runtime', 'active_sessions.json'), '{half')+ expect(await hermesLeases(dir)).toEqual([])+ })++ it('lists homes with the sticky profile ahead, and keeps it under the cap', async () => {+ const root = tempDir()+ for (let n = 0; n < 70; n++) mkdirSync(join(root, 'profiles', `p${String(n).padStart(2, '0')}`), { recursive: true })+ mkdirSync(join(root, 'elsewhere'))+ symlinkSync(join(root, 'elsewhere'), join(root, 'profiles', 'linked'))+ const all = await hermesHomes(root, null)+ expect(all).toHaveLength(65)+ expect(all[0]).toEqual({ home: root, dbPath: join(root, 'state.db'), profile: null })+ expect(all[1].profile).toBe('linked')+ const sticky = await hermesHomes(root, 'p69')+ expect(sticky.map((home) => home.profile).slice(0, 3)).toEqual([null, 'p69', 'linked'])+ expect(sticky).toHaveLength(65)+ expect((await hermesHomes(root, 'missing')).map((home) => home.profile).slice(0, 2)).toEqual([null, 'linked'])+ })++ it('reads the sticky profile, and ignores one Hermes would not use', async () => {+ const root = tempDir()+ expect(await activeProfile(root)).toBeNull()+ for (const [content, expected] of [['work\n', 'work'], ['default', null], ['Bad Name', null], ['', null]] as const) {+ writeFileSync(join(root, 'active_profile'), content)+ expect(await activeProfile(root)).toBe(expected)+ }+ })++ it('follows a chain to its tip, and stops where the store cannot say', async () => {+ const root = tempDir()+ const store = new Store(join(root, 'state.db'))+ store.session(id(1), { endReason: 'compression', ended: S0 }).session(id(2), { parent: id(1), endReason: 'compression', ended: S0 + 1 })+ store.session(id(3), { parent: id(2) })+ // A branch and a delegation off a compressed parent are not its continuation.+ store.session(id(4), { endReason: 'compression', ended: S0 }).session(id(5), { parent: id(4), config: { _branched_from: id(4) } })+ store.session(id(6), { parent: id(4), config: { _delegate_from: id(4) } }).session(id(7), { parent: id(4), source: 'tool' })+ expect(await compressionTip(readSql, store.path, id(1))).toBe(id(3))+ expect(await compressionTip(readSql, store.path, id(3))).toBe(id(3))+ expect(await compressionTip(readSql, store.path, id(4))).toBe(id(4))+ expect(await compressionTip(async () => ({ ok: false, reason: 'transient' }), store.path, id(1))).toBe(id(1))+ // A loop in the store ends where it started.+ const looping: SqlRead = async (_db, _sql, params) => ({ ok: true, via: 'builtin', rows: [{ id: params?.[0] === 'a' ? 'b' : 'a' }] })+ expect(await compressionTip(looping, store.path, 'a')).toBe('b')+ store.close()+ })++ it('builds no list without the columns that name a session', () => {+ expect(hermesListSql(new Set(['id']), new Set())).toBeNull()+ expect(hermesTurnOpen([])).toBe(false)+ expect(hermesTurnOpen([{ role: 'assistant', finish_reason: 5 }])).toBe(true)+ })+})diff --git a/cli/src/lib/sessionSearch/externals/hermes.ts b/cli/src/lib/sessionSearch/externals/hermes.tsnew file mode 100644index 000000000..a27869594--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/hermes.ts@@ -0,0 +1,477 @@+/**+ * Hermes: one SQLite store per home, `<home>/state.db`. A machine has the default home and one per+ * profile (`<root>/profiles/<name>`, what `hermes -p <name>` runs in); `<root>/active_profile` makes a+ * plain `hermes` run in a profile instead. Several Hermes versions write one store, so its columns are+ * read from the store before the list is asked for (measured: schema 22 on disk, 17 in the CLI's code).+ *+ * `sessions.source` says who started one: `cli` (the REPL, and one-shots), `tui` (the terminal UI and+ * the desktop app), `acp` (an editor). Everything else is a gateway, cron, a tool or a sub-agent.+ * `parent_session_id` means three things: a delegation child (`_delegate_from` in `model_config`,+ * hidden), a `/branch` (listed on its own), and a compression continuation: the parent ended with+ * `end_reason = 'compression'` and the conversation carries on under the child's id. A chain is one+ * conversation, listed once under its newest id (its tip), as Hermes lists it (`hermes_state.py`,+ * `list_sessions_rich` and `get_compression_tip`, v0.18.0). Times are REAL epoch seconds.+ *+ * Where it ran: `cwd` is written for the REPL only; an editor keeps it in `model_config.cwd`; else the+ * repository root. A terminal UI session has none (measured: all three here), so it cannot be resumed.+ *+ * Owners: `<home>/runtime/active_sessions.json` (exact; Hermes writes it only when+ * `max_concurrent_sessions` is set), then the id in a Hermes process's arguments (`-r/--resume`),+ * followed to its chain's tip: only where the process started, so `fromArgs`.+ */++import { readFile } from 'node:fs/promises'+import { join } from 'node:path'++import { hermesMessagesToEvents, isTerminalFinish } from '../../../engines/hermes/normalizer.js'+import { HERMES_HISTORY_ID_RE, readHermesMessages } from '../../../engines/hermes/reader.js'+import { hasSqliteReader } from '../../sqliteAvailability.js'+import type { SqliteParam, SqliteRow } from '../../sqliteRead.js'+import { argvTokens, resumeSessionId } from '../../tmux.js'+import {+ LIST_LIMIT, ancestry, argvSubcommand, engineProcess, ownerRecord, parseOwnerRecord, readSql, rowsOf, splitCounts,+ storeStamp, tableColumns, tally, type Counting, type SqlRead, type Tally,+} from './opencode.js'+import { absoluteFolder, entries, epochMs, readJson, record, text } from './support.js'+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'++export interface HermesOptions {+ root: string+ /** How a statement is run; tests replace it. */+ read?: SqlRead+ /** Whether this machine can read SQLite at all; tests replace it. */+ available?: () => boolean+ /** Epoch ms; tests replace it. */+ now?: () => number+}++/**+ * One conversation under several ids: a compression chain. `aliases` are its other ids, oldest first,+ * so a caller that holds any of them (a Harness agent bound before the chain moved on) can tell it is+ * the same conversation.+ */+export type HermesSession = ExternalSession & { aliases: readonly string[] }++/** Hermes's own rule for a profile's name (`hermes_cli/profiles.py`). */+const PROFILE_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/+/** A person with hundreds of profile folders has a different problem; this keeps the scan bounded. */+const MAX_PROFILES = 64++/** Subcommands that serve other clients (the desktop app, a browser, a chat platform, an editor). */+const SERVERS = new Set(['serve', 'dashboard', 'desktop', 'gui', 'gateway', 'acp'])+/** Hermes's top-level flags that take a value (`hermes_cli/main.py`). */+const VALUE_FLAGS = new Set(['-z', '--oneshot', '-m', '--model', '--provider', '-t', '--toolsets', '-r', '--resume', '-s', '--skills', '-p', '--profile'])+/** `-c [name]`: a value only when one follows. */+const OPTIONAL_VALUE_FLAGS = new Set(['-c', '--continue'])+const SUBCOMMAND_FLAGS = new Set([...VALUE_FLAGS, ...OPTIONAL_VALUE_FLAGS])++export interface HermesHome {+ home: string+ dbPath: string+ /** The profile's name; null for the default home. */+ profile: string | null+}++/** The profile `hermes profile use <name>` made sticky, or null for the default. */+export async function activeProfile(root: string): Promise<string | null> {+ const name = (await readFile(join(root, 'active_profile'), 'utf8').catch(() => '')).trim()+ return PROFILE_ID.test(name) && name !== 'default' ? name : null+}++function homeOf(root: string, profile: string | null): HermesHome {+ const home = profile ? join(root, 'profiles', profile) : root+ return { home, dbPath: join(home, 'state.db'), profile }+}++/** Every home: the default first, then the profiles, the sticky one ahead so a cap never drops it. */+export async function hermesHomes(root: string, active: string | null): Promise<HermesHome[]> {+ const names = (await entries(join(root, 'profiles')))+ .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && PROFILE_ID.test(entry.name) && entry.name !== 'default')+ .map((entry) => entry.name)+ .sort()+ const ordered = active && names.includes(active) ? [active, ...names.filter((name) => name !== active)] : names+ return [homeOf(root, null), ...ordered.slice(0, MAX_PROFILES).map((name) => homeOf(root, name))]+}++/**+ * One statement: the newest rows a person could have started, with what a chain needs to be put+ * together, and how many rows each rule kept out (a row with a null id is a count). Built from the+ * columns the store has.+ */+export function hermesListSql(sessions: ReadonlySet<string>, messages: ReadonlySet<string>): string | null {+ if (!sessions.has('id') || !sessions.has('source')) return null+ const col = (name: string): string => (sessions.has(name) ? `s.${name}` : 'NULL')+ const config = sessions.has('model_config') ? 'CASE WHEN json_valid(s.model_config) THEN s.model_config END' : ''+ const marker = (key: string): string => (config ? `json_extract(${config}, '$.${key}')` : 'NULL')+ const parent = (name: string): string => (sessions.has('parent_session_id') && sessions.has(name)+ ? `(SELECT p.${name} FROM sessions p WHERE p.id = s.parent_session_id)`+ : 'NULL')+ const lastMessage = messages.has('session_id') && messages.has('timestamp')+ ? '(SELECT max(m.timestamp) FROM messages m WHERE m.session_id = s.id)'+ : 'NULL'+ const skip = "CASE WHEN s.source IS NULL OR s.source NOT IN ('cli', 'tui', 'acp') THEN 'source'"+ + (sessions.has('archived') ? " WHEN COALESCE(s.archived, 0) <> 0 THEN 'archived'" : '')+ + (config ? ` WHEN ${marker('_delegate_from')} IS NOT NULL THEN 'delegated'` : '')+ + " ELSE '' END"+ const columns = [+ 's.id AS id', 's.source AS source', `${col('parent_session_id')} AS parent`, `${col('started_at')} AS started`,+ `${col('ended_at')} AS ended`, `${col('end_reason')} AS end_reason`, `${col('cwd')} AS cwd`,+ `${marker('cwd')} AS config_cwd`, `${col('git_repo_root')} AS repo`, `${col('title')} AS title`,+ `${col('display_name')} AS display_name`, `${marker('_branched_from')} AS branched`,+ `${parent('end_reason')} AS parent_end`, `${parent('ended_at')} AS parent_ended`, `${lastMessage} AS last_msg`,+ "'' AS skip", 'NULL AS n',+ ]+ return `SELECT * FROM (SELECT ${columns.join(', ')} FROM sessions s WHERE ${skip} = '' `+ + `ORDER BY coalesce(${lastMessage}, ${col('started_at')}, 0) DESC LIMIT ${LIST_LIMIT}) `+ + `UNION ALL SELECT ${'NULL, '.repeat(columns.length - 2)}${skip} AS skip, count(*) AS n FROM sessions s GROUP BY skip`+}++/** One `sessions` row, as the list reads it. Times are epoch seconds. */+export interface HermesRow {+ id: string+ source: string+ parent: string | null+ started: number | null+ ended: number | null+ endReason: string | null+ cwd: string | null+ configCwd: string | null+ repo: string | null+ title: string+ displayName: string+ branched: boolean+ parentEnd: string | null+ parentEnded: number | null+ lastMsg: number | null+}++const orNull = (value: unknown): string | null => (typeof value === 'string' && value ? value : null)+const number = (value: unknown): number | null => (typeof value === 'number' && Number.isFinite(value) ? value : null)++export function hermesRow(row: SqliteRow): HermesRow {+ return {+ id: text(row.id), source: text(row.source), parent: orNull(row.parent), started: number(row.started),+ ended: number(row.ended), endReason: orNull(row.end_reason), cwd: orNull(row.cwd), configCwd: orNull(row.config_cwd),+ repo: orNull(row.repo), title: text(row.title), displayName: text(row.display_name),+ branched: row.branched !== null && row.branched !== undefined, parentEnd: orNull(row.parent_end),+ parentEnded: number(row.parent_ended), lastMsg: number(row.last_msg),+ }+}++/**+ * What a row is to a person: the start of a conversation (a root, or a `/branch`, by its marker or by+ * Hermes's older rule: the parent ended `branched` before the child began), the continuation of one+ * (its parent was compressed), or a sub-agent's child, hidden.+ */+export function hermesKind(row: HermesRow): 'head' | 'continuation' | 'child' {+ if (!row.parent) return 'head'+ if (row.branched) return 'head'+ if (row.parentEnd === 'branched' && row.parentEnded !== null && row.started !== null && row.started >= row.parentEnded) return 'head'+ return row.parentEnd === 'compression' ? 'continuation' : 'child'+}++const rank = (row: HermesRow): number => (row.endReason === 'compression' ? 0 : row.ended === null ? 1 : 2)+const activity = (row: HermesRow): number => row.lastMsg ?? row.started ?? 0++/**+ * The continuation a chain follows, as `get_compression_tip` picks it: one compressed again, then one+ * still open, then the most recently active; a stale sibling (a reaped websocket's) loses.+ */+export function bestContinuation(children: readonly HermesRow[]): HermesRow {+ return [...children].sort((a, b) => rank(a) - rank(b)+ || activity(b) - activity(a)+ || (b.started ?? 0) - (a.started ?? 0)+ || (a.id < b.id ? 1 : -1))[0]+}++export interface HermesChain {+ /** Oldest first; the last is the tip, the id a resume takes. */+ members: HermesRow[]+ /** The id the chain started from when that row is older than the list: part of it, not listed. */+ lost: string | null+}++/** The listed rows put together into conversations: each root or branch followed to its tip. */+export function hermesChains(rows: readonly HermesRow[], counts: Tally): HermesChain[] {+ const byId = new Map(rows.map((row) => [row.id, row]))+ const continuations = new Map<string, HermesRow[]>()+ const starts: HermesChain[] = []+ for (const row of rows) {+ const kind = hermesKind(row)+ if (kind === 'head') starts.push({ members: [row], lost: null })+ else if (kind === 'continuation') continuations.set(row.parent!, [...continuations.get(row.parent!) ?? [], row])+ else tally(counts, 'child')+ }+ // A continuation whose parent is older than the list: the conversation starts there, unlisted.+ for (const [parent, children] of continuations) {+ if (!byId.has(parent)) starts.push({ members: [bestContinuation(children)], lost: parent })+ }+ const placed = new Set(starts.map((chain) => chain.members[0].id))+ for (const chain of starts) {+ for (;;) {+ const tip = chain.members[chain.members.length - 1]+ const next = (continuations.get(tip.id) ?? []).filter((child) => !placed.has(child.id))+ if (!next.length) break+ const chosen = bestContinuation(next)+ placed.add(chosen.id)+ chain.members.push(chosen)+ }+ }+ // Continuations no chain reached: a stale sibling, or one under a hidden child.+ for (const children of continuations.values()) for (const child of children) if (!placed.has(child.id)) tally(counts, 'stale')+ return starts+}++/** The first answer, newest member first. */+function newestFirst<T>(members: readonly HermesRow[], pick: (row: HermesRow) => T | null): T | null {+ for (let i = members.length - 1; i >= 0; i--) {+ const value = pick(members[i])+ if (value) return value+ }+ return null+}++interface Listed { rows: HermesRow[]; counts: Tally }++async function listSessions(read: SqlRead, dbPath: string): Promise<Listed | null> {+ const columns = await tableColumns(read, dbPath, ['sessions', 'messages'])+ if (!columns) return null+ const sql = hermesListSql(columns.get('sessions') ?? new Set(), columns.get('messages') ?? new Set())+ if (!sql) return { rows: [], counts: {} }+ const rows = await rowsOf(read, dbPath, sql)+ if (!rows) return null+ const split = splitCounts(rows)+ return { rows: split.rows.map(hermesRow), counts: split.counts }+}++/**+ * The chain [sessionId] belongs to, followed forward to its tip, as Hermes resumes it. A store too+ * old to have chains, or one that cannot be read, answers the id itself.+ */+const TIP_SQL = 'SELECT child.id AS id FROM sessions parent JOIN sessions child ON child.parent_session_id = parent.id'+ + " WHERE parent.id = ? AND parent.end_reason = 'compression'"+ + " AND json_extract(CASE WHEN json_valid(child.model_config) THEN child.model_config END, '$._branched_from') IS NULL"+ + " AND json_extract(CASE WHEN json_valid(child.model_config) THEN child.model_config END, '$._delegate_from') IS NULL"+ + " AND COALESCE(child.source, '') <> 'tool'"+ + " ORDER BY CASE WHEN child.end_reason = 'compression' THEN 0 WHEN child.ended_at IS NULL THEN 1 ELSE 2 END,"+ + ' COALESCE((SELECT max(m.timestamp) FROM messages m WHERE m.session_id = child.id), child.started_at) DESC,'+ + ' child.started_at DESC, child.id DESC LIMIT 1'++export async function compressionTip(read: SqlRead, dbPath: string, sessionId: string): Promise<string> {+ const seen = new Set([sessionId])+ let current = sessionId+ for (;;) {+ const result = await read(dbPath, TIP_SQL, [current])+ const next = result.ok ? text(result.rows[0]?.id) : ''+ if (!next || seen.has(next)) return current+ seen.add(next)+ current = next+ }+}++async function found(read: SqlRead, dbPath: string, sql: string, params: SqliteParam[]): Promise<boolean> {+ const result = await read(dbPath, sql, params)+ return result.ok && result.rows.length > 0+}++/** The profile a Hermes process's arguments name (`-p work`, `--profile=work`, `-p default`), or null. */+export function argvProfile(args: string): string | null {+ const tokens = argvTokens(args)+ for (let i = 1; i < tokens.length; i++) {+ const token = tokens[i]+ if (token === '--') break+ // Hermes takes the first one, and ignores a name it would refuse.+ if (token === '-p' || token === '--profile') return PROFILE_ID.test(tokens[i + 1] ?? '') ? tokens[i + 1] : null+ if (token.startsWith('--profile=')) return PROFILE_ID.test(token.slice(10)) ? token.slice(10) : null+ if (VALUE_FLAGS.has(token) || (OPTIONAL_VALUE_FLAGS.has(token) && !(tokens[i + 1] ?? '-').startsWith('-'))) i+++ }+ return null+}++export interface HermesLease {+ sessionId: string+ pid: number+ /** When the lease's process started, epoch ms (Hermes writes psutil's `create_time`, seconds), when known. */+ started?: number+}++/** How far a lease's start may sit from `ps`'s (whole seconds) and still be the same process. */+const START_SLACK_MS = 2_000++/** Hermes's active-session leases: the stored sessions a live CLI or terminal UI holds, by pid. */+export async function hermesLeases(home: string): Promise<HermesLease[]> {+ const file = await readJson(join(home, 'runtime', 'active_sessions.json'))+ const list = Array.isArray(file) ? file : record(file)?.entries+ if (!Array.isArray(list)) return []+ const leases: HermesLease[] = []+ for (const item of list) {+ const entry = record(item)+ const sessionId = text(entry?.session_id)+ const pid = entry?.pid+ const started = entry?.process_start_time+ // A gateway's lease names a chat's key, not a stored session.+ if (!HERMES_HISTORY_ID_RE.test(sessionId) || text(entry?.surface).startsWith('gateway')) continue+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) continue+ leases.push({ sessionId, pid, ...(typeof started === 'number' && started > 0 ? { started: started * 1000 } : {}) })+ }+ return leases+}++/**+ * Whether [lease] still names the process now running under its pid. A Hermes that crashed leaves its+ * lease behind, and the pid can go to anything after, a tool another Hermes runs among them; the+ * process's start says which. Either side unknown: the pid is all there is to go on.+ */+export function leaseHeldBy(lease: HermesLease, row: RunningProcess | undefined): boolean {+ if (lease.started === undefined || row?.started === undefined) return true+ return Math.abs(row.started - lease.started) <= START_SLACK_MS+}++/**+ * Whether the tail says a turn runs: a person's message waits for an answer, a tool's result for the+ * model, and an assistant message runs on unless it finished (`stop`, not `tool_calls`).+ */+export function hermesTurnOpen(rows: readonly SqliteRow[]): boolean | null {+ const tail = rows[0]+ if (!tail) return false+ if (tail.role === 'user' || tail.role === 'tool') return true+ if (tail.role !== 'assistant') return null+ return !isTerminalFinish(typeof tail.finish_reason === 'string' ? tail.finish_reason : null)+}++export function hermesProvider(options: HermesOptions): ExternalProvider & Counting {+ const { root } = options+ const read = options.read ?? readSql+ const available = options.available ?? hasSqliteReader+ const now = options.now ?? Date.now+ const lastGood = new Map<string, Listed | null>()+ let counts: Tally = {}++ function conversations(home: HermesHome, listed: Listed, ctx: ScanContext, active: string | null): HermesSession[] {+ const out: HermesSession[] = []+ // A profile's session resumes in its profile; the default home's, when a sticky profile would+ // otherwise send a plain `hermes` elsewhere, says so.+ const launchArgs = home.profile ? ['-p', home.profile] : active ? ['-p', 'default'] : null+ for (const { members, lost } of hermesChains(listed.rows, counts)) {+ const tip = members[members.length - 1]+ if (members.length > 1) tally(counts, 'compressed', members.length - 1)+ if (!HERMES_HISTORY_ID_RE.test(tip.id)) { tally(counts, 'badId'); continue }+ if (members.every((row) => row.lastMsg === null)) { tally(counts, 'empty'); continue }+ const cwd = newestFirst(members, (row) => absoluteFolder(row.cwd) ?? absoluteFolder(row.configCwd) ?? absoluteFolder(row.repo))+ // A terminal UI session records no folder: there is nowhere to resume it.+ if (!cwd) { tally(counts, 'noFolder'); continue }+ if (ctx.excluded(cwd)) { tally(counts, 'excluded'); continue }+ const ids = [...(lost ? [lost] : []), ...members.map((row) => row.id)]+ out.push({+ sessionId: tip.id,+ engine: 'hermes',+ cwd,+ origin: members[0].source === 'acp' ? 'editor' : 'terminal',+ title: newestFirst(members, (row) => row.displayName.trim() || row.title.trim()) ?? '',+ mtime: Math.max(...members.map((row) => epochMs(row.lastMsg ?? row.started) ?? 0)),+ transcriptPath: null,+ // The whole chain, oldest first: what was said before each compression is the same conversation.+ readHistory: async () => hermesMessagesToEvents((await Promise.all(ids.map((id) => readHermesMessages(home.dbPath, id)))).flat()),+ ...(launchArgs ? { launchArgs } : {}),+ aliases: ids.filter((id) => id !== tip.id),+ })+ }+ return out+ }++ return {+ engine: 'hermes',+ lastScan: () => counts,+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ counts = {}+ if (!available()) return []+ const active = await activeProfile(root)+ const sessions: HermesSession[] = []+ const failures: unknown[] = []+ let stores = 0+ for (const home of await hermesHomes(root, active)) {+ const stamp = await storeStamp(home.dbPath)+ if (!stamp) continue+ stores+++ let listed: Listed | null+ try {+ listed = await ctx.memo(`hermes:${home.dbPath}`, stamp, () => listSessions(read, home.dbPath))+ lastGood.set(home.dbPath, listed)+ } catch (error) {+ // One home locked or broken keeps what it said last time; the others still answer.+ failures.push(error)+ listed = lastGood.get(home.dbPath) ?? null+ }+ await ctx.pace()+ if (!listed) continue+ for (const [reason, n] of Object.entries(listed.counts)) tally(counts, reason, n)+ sessions.push(...conversations(home, listed, ctx, active))+ }+ if (failures.length && failures.length === stores) throw failures[0]+ counts.found = sessions.length+ return sessions+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const processes = await view.list()+ const byPid = new Map(processes.map((row) => [row.pid, row]))+ const isHermes = engineProcess('hermes')+ const active = await activeProfile(root)+ const homes = await hermesHomes(root, active)+ // A plain `hermes` runs in the sticky profile: ask its store first.+ const sticky = active ? homes.find((home) => home.profile === active) ?? homeOf(root, active) : null+ const plain = sticky ? [sticky, ...homes.filter((home) => home !== sticky)] : homes+ const claims = new Map<string, OwnerClaim>()+ // Served to another client (the desktop app, a dashboard's terminal): never stopped from here.+ const served = (owner: RunningProcess): boolean => ancestry(byPid, owner.pid, 4)+ .some((row) => isHermes(row) && SERVERS.has(argvSubcommand(row.args, SUBCOMMAND_FLAGS)))+ const claim = async (candidates: readonly HermesHome[], sessionId: string, owner: RunningProcess, fromArgs: boolean): Promise<void> => {+ let at = { dbPath: candidates[0].dbPath, sessionId }+ for (const home of candidates) {+ if (!await found(read, home.dbPath, 'SELECT id FROM sessions WHERE id = ?', [sessionId])) continue+ // Compression moves a running conversation to a new id: the tip is the one listed.+ at = { dbPath: home.dbPath, sessionId: await compressionTip(read, home.dbPath, sessionId) }+ break+ }+ if (claims.has(at.sessionId)) return+ claims.set(at.sessionId, {+ sessionId: at.sessionId, pid: owner.pid, record: ownerRecord(at.dbPath, at.sessionId),+ ...(served(owner) ? { app: true } : {}),+ ...(fromArgs ? { fromArgs: true } : {}),+ })+ }+ // A lease is exact, so it is read first and wins over the same session named in arguments.+ for (const home of homes) {+ for (const lease of await hermesLeases(home.home)) {+ if (!view.alive(lease.pid) || !leaseHeldBy(lease, byPid.get(lease.pid))) continue+ // The lease's pid is the REPL itself, or a terminal UI's gateway two levels under its+ // `hermes` (hermes → node UI → python gateway). A pid that is neither was reused.+ const owner = ancestry(byPid, lease.pid, 2).find(isHermes)+ if (owner) await claim([home], lease.sessionId, owner, false)+ }+ }+ // The id a process was started on: it may have moved to another conversation since (`/resume`).+ for (const row of processes) {+ if (!isHermes(row)) continue+ const sessionId = resumeSessionId('hermes', row.args)+ if (!sessionId) continue+ const profile = argvProfile(row.args)+ await claim(profile ? [homeOf(root, profile === 'default' ? null : profile)] : plain, sessionId, row, true)+ }+ return [...claims.values()]+ },+ async busy(owner): Promise<boolean | null> {+ const at = parseOwnerRecord(owner.record)+ if (!at) return null+ const locks = await read(at.dbPath, "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'compression_locks'")+ if (!locks.ok) return null+ if (locks.rows.length) {+ // Compressing: the conversation is being rewritten under a new id right now.+ const held = await read(at.dbPath, 'SELECT 1 AS held FROM compression_locks WHERE session_id = ? AND expires_at > ? LIMIT 1', [at.sessionId, now() / 1000])+ if (!held.ok) return null+ if (held.rows.length) return true+ }+ const tail = await read(at.dbPath, 'SELECT role, finish_reason FROM messages WHERE session_id = ? ORDER BY id DESC LIMIT 1', [at.sessionId])+ return tail.ok ? hermesTurnOpen(tail.rows) : null+ },+ }+}diff --git a/cli/src/lib/sessionSearch/externals/index.spec.ts b/cli/src/lib/sessionSearch/externals/index.spec.tsnew file mode 100644index 000000000..e15bd6fff--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/index.spec.ts@@ -0,0 +1,45 @@+import { join } from 'node:path'++import { describe, expect, it } from 'vitest'++import { env } from '../../../config/env.js'+import { externalPaths, externalProviders } from './index.js'+import { EXTERNAL_ENGINES } from './types.js'++describe('where each engine keeps its conversations', () => {+ it("follows each engine's own overrides before Harness's defaults", () => {+ const paths = externalPaths({+ CURSOR_CONFIG_DIR: '/cfg/cursor', CURSOR_DATA_DIR: '/data/cursor',+ OPENCODE_DB: '/db/opencode.db', KILO_DB: 'kilo-dev.db',+ PI_CODING_AGENT_DIR: '/pi/agent', PI_CODING_AGENT_SESSION_DIR: '/pi/moved',+ })+ expect(paths).toMatchObject({+ cursorConfigDir: '/cfg/cursor', cursorDataDir: '/data/cursor',+ opencodeDb: '/db/opencode.db', kiloDb: join(env.KILO_DATA_DIR, 'kilo-dev.db'),+ piAgentDir: '/pi/agent', piSessionDir: '/pi/moved',+ })+ })++ it("uses the defaults where nothing is overridden, and XDG for Cursor's chats", () => {+ const paths = externalPaths({ XDG_CONFIG_HOME: '/xdg', OPENCODE_DB: ':memory:' })+ expect(paths).toMatchObject({+ claudeProjectsDir: env.CLAUDE_PROJECTS_DIR, codexHome: env.CODEX_HOME,+ cursorConfigDir: '/xdg/cursor', cursorDataDir: env.CURSOR_HOME,+ opencodeDb: join(env.OPENCODE_DATA_DIR, 'opencode.db'), kiloDb: join(env.KILO_DATA_DIR, 'kilo.db'),+ piAgentDir: join(env.PI_HOME, 'agent'),+ })+ expect(paths.piSessionDir).toBeUndefined()+ expect(externalPaths({}).cursorConfigDir).toBe(env.CURSOR_HOME)+ expect(externalPaths({ CURSOR_CONFIG_DIR: ' ', XDG_CONFIG_HOME: ' ', CURSOR_DATA_DIR: '' })).toMatchObject({+ cursorConfigDir: env.CURSOR_HOME, cursorDataDir: env.CURSOR_HOME,+ })+ // The process's own environment by default.+ expect(externalPaths().codexHome).toBe(env.CODEX_HOME)+ })++ it('has one provider per engine that keeps its conversations on disk, Kilo through OpenCode’s', () => {+ const engines = externalProviders(externalPaths({ PI_CODING_AGENT_SESSION_DIR: '/pi/moved' })).map((provider) => provider.engine)+ expect([...engines].sort()).toEqual([...EXTERNAL_ENGINES].sort())+ expect(externalProviders().length).toBe(EXTERNAL_ENGINES.length)+ })+})diff --git a/cli/src/lib/sessionSearch/externals/index.ts b/cli/src/lib/sessionSearch/externals/index.tsnew file mode 100644index 000000000..b7b7a45d9--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/index.ts@@ -0,0 +1,88 @@+/**+ * Every engine's discovery, pointed at where that engine keeps its conversations on this machine.+ * Each path follows the engine's own rules (its env overrides first), not Harness's defaults alone.+ */++import { isAbsolute, join } from 'node:path'++import { env } from '../../../config/env.js'+import { agyProvider } from './agy.js'+import { claudeProvider } from './claude.js'+import { codexProvider } from './codex.js'+import { commandcodeProvider } from './commandcode.js'+import { copilotProvider } from './copilot.js'+import { cursorProvider } from './cursor.js'+import { devinProvider } from './devin.js'+import { grokProvider } from './grok.js'+import { hermesProvider } from './hermes.js'+import { museProvider } from './muse.js'+import { opencodeProvider } from './opencode.js'+import { piProvider } from './pi.js'+import type { ExternalProvider } from './types.js'++export interface ExternalPaths {+ claudeProjectsDir: string+ codexHome: string+ /** Cursor keeps chats under its config folder and transcripts under its data folder: two roots. */+ cursorConfigDir: string+ cursorDataDir: string+ grokHome: string+ copilotHome: string+ opencodeDb: string+ kiloDb: string+ hermesRoot: string+ devinHome: string+ piAgentDir: string+ /** Pi's moved sessions folder (`PI_CODING_AGENT_SESSION_DIR`), when set. */+ piSessionDir?: string+ commandcodeHome: string+ museHome: string+ agyHome: string+}++/** An engine's database file: its own override (absolute, or relative to its data folder), else the default. */+function databasePath(override: string | undefined, dataDir: string, file: string): string {+ if (!override || override === ':memory:') return join(dataDir, file)+ return isAbsolute(override) ? override : join(dataDir, override)+}++/** Where each engine keeps its conversations, from this process's environment. */+export function externalPaths(vars: NodeJS.ProcessEnv = process.env): ExternalPaths {+ return {+ claudeProjectsDir: env.CLAUDE_PROJECTS_DIR,+ codexHome: env.CODEX_HOME,+ // Cursor ignores these when blank, as it ignores them unset.+ cursorConfigDir: vars.CURSOR_CONFIG_DIR?.trim() || (vars.XDG_CONFIG_HOME?.trim() ? join(vars.XDG_CONFIG_HOME, 'cursor') : env.CURSOR_HOME),+ cursorDataDir: vars.CURSOR_DATA_DIR?.trim() || env.CURSOR_HOME,+ grokHome: env.GROK_HOME,+ copilotHome: env.COPILOT_HOME,+ opencodeDb: databasePath(vars.OPENCODE_DB, env.OPENCODE_DATA_DIR, 'opencode.db'),+ kiloDb: databasePath(vars.KILO_DB, env.KILO_DATA_DIR, 'kilo.db'),+ hermesRoot: env.HERMES_HOME,+ devinHome: env.DEVIN_HOME,+ piAgentDir: vars.PI_CODING_AGENT_DIR || join(env.PI_HOME, 'agent'),+ ...(vars.PI_CODING_AGENT_SESSION_DIR ? { piSessionDir: vars.PI_CODING_AGENT_SESSION_DIR } : {}),+ commandcodeHome: env.COMMANDCODE_HOME,+ museHome: env.MUSE_HOME,+ agyHome: env.AGY_HOME,+ }+}++/** One provider per engine that keeps its conversations on this machine's disk. */+export function externalProviders(paths: ExternalPaths = externalPaths()): ExternalProvider[] {+ return [+ claudeProvider({ projectsDir: paths.claudeProjectsDir, home: join(paths.claudeProjectsDir, '..') }),+ codexProvider({ home: paths.codexHome }),+ cursorProvider({ configDir: paths.cursorConfigDir, dataDir: paths.cursorDataDir }),+ grokProvider({ home: paths.grokHome }),+ copilotProvider({ home: paths.copilotHome }),+ opencodeProvider({ engine: 'opencode', dbPath: paths.opencodeDb }),+ opencodeProvider({ engine: 'kilo', dbPath: paths.kiloDb }),+ hermesProvider({ root: paths.hermesRoot }),+ devinProvider({ home: paths.devinHome }),+ piProvider({ agentDir: paths.piAgentDir, ...(paths.piSessionDir ? { sessionDir: paths.piSessionDir } : {}) }),+ commandcodeProvider({ home: paths.commandcodeHome }),+ museProvider({ home: paths.museHome }),+ agyProvider({ home: paths.agyHome }),+ ]+}diff --git a/cli/src/lib/sessionSearch/externals/muse.spec.ts b/cli/src/lib/sessionSearch/externals/muse.spec.tsnew file mode 100644index 000000000..1fd74b93b--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/muse.spec.ts@@ -0,0 +1,223 @@+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { museActivity, museOwnRun, museProvider, museTurnOpen, readMuseHead } from './muse.js'+import { scanMemo } from './support.js'+import { type ExternalProvider, type ProcessView, type RunningProcess, UNSETTLED } from './types.js'++// Shapes follow the repo's recorded Muse session (lib/__fixtures__/muse-session.jsonl): one envelope a+// record, `recorded_at` in microseconds, sub-agent streams mirrored into the parent. Values are made up.+const ID = '8a5b11e5-5eae-441c-ba9d-903608a9632e'+const ID2 = '9b6c22f6-0000-4000-8000-000000000002'+const CHILD = 'c0c0c0c0-0000-4000-8000-00000000c41d'+const T0 = Date.parse('2026-09-01T10:00:00.000Z')++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function temp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'muse-external-'))+ dirs.push(dir)+ return dir+}++let sequence = 0+const micros = (seconds: number) => (T0 + seconds * 1000) * 1000+/** One record, spaced as the recorded fixture is. */+const rec = (stream: string, seconds: number | null, payload: Record<string, unknown>) =>+ JSON.stringify({+ schema_version: 1, id: `r-${++sequence}`, stream: { kind: 'session', id: stream }, sequence,+ ...(seconds === null ? {} : { recorded_at: micros(seconds) }),+ record_type: 'event', durability: 'durable', causation_id: null, payload_type: 'runtime.session', payload_schema_version: 1, payload,+ }, null, 0).replace(/,"/g, ', "').replace(/":/g, '": ')+const metadata = (stream: string, cwd: unknown, seconds: number | null = 0) =>+ rec(stream, seconds, { kind: 'metadata', record: { workspace_root: cwd, provider_id: 'meta', build: { sha: 'x', semver: '0.1.0' } } })+const run = (stream: string, kind: string, seconds: number, event: Record<string, unknown> = {}) =>+ rec(stream, seconds, { kind: 'run', run_id: `run-${stream}`, event: { kind, ...event } })+const task = (stream: string, seconds: number) => rec(stream, seconds, { kind: 'task', run_id: 'x', task_id: 't', event: { kind: 'started', task_id: 't' } })+const jsonl = (...lines: string[]) => `${lines.join('\n')}\n`++function write(path: string, content: string, mtimeSeconds?: number): string {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, content)+ if (mtimeSeconds !== undefined) utimesSync(path, new Date(T0 + mtimeSeconds * 1000), new Date(T0 + mtimeSeconds * 1000))+ return path+}++/** A log where Muse puts it: `sessions/YYYY/MM/DD/<id>/session.jsonl`. */+function log(home: string, id: string, lines: string[], day = ['2026', '09', '01'], mtimeSeconds?: number): string {+ return write(join(home, 'sessions', ...day, id, 'session.jsonl'), jsonl(...lines), mtimeSeconds)+}++function scanner(provider: ExternalProvider, excluded: string[] = []) {+ const memo = scanMemo({ excluded })+ return async () => {+ const found = await provider.scan(memo.context())+ memo.prune()+ return found+ }+}++const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })+const view = (rows: RunningProcess[]): ProcessView => ({+ list: async () => rows, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,+})++describe('readMuseHead', () => {+ const head = async (content: string, folderId = ID) => readMuseHead(write(join(temp(), 'session.jsonl'), content), folderId)++ it("reads the session's folder from its own stream's metadata", async () => {+ expect(await head(jsonl(metadata(ID, '/Users/me/Work/app'), run(ID, 'started', 1)))).toEqual({ sessionId: ID, cwd: '/Users/me/Work/app' })+ })++ it('refuses a first record of another stream, not metadata, or without an absolute workspace', async () => {+ expect(await head(jsonl(metadata(ID2, '/w')))).toBeNull()+ expect(await head(jsonl(run(ID, 'started', 1)))).toBeNull()+ expect(await head(jsonl(metadata(ID, 'relative')))).toBeNull()+ expect(await head(jsonl(metadata(ID, null)))).toBeNull()+ expect(await head(jsonl('{torn'))).toBeNull()+ })++ it('says "not yet" while the first record is being written, and "never" past the bound', async () => {+ expect(await head(metadata(ID, '/w'))).toBe(UNSETTLED)+ expect(await head('x'.repeat(256 * 1024 + 1))).toBeNull()+ // A first record larger than the first read is read whole on a second.+ const long = rec(ID, 0, { kind: 'metadata', record: { workspace_root: '/w', notes: 'y'.repeat(40_000) } })+ expect(await head(jsonl(long, run(ID, 'started', 1)))).toEqual({ sessionId: ID, cwd: '/w' })+ })+})++describe('museOwnRun', () => {+ const ran = (...lines: string[]) => museOwnRun(write(join(temp(), 'session.jsonl'), jsonl(metadata(ID, '/w'), ...lines)), ID)++ it('is true once the session opens a run of its own, a scheduled one (no prompt) included', async () => {+ expect(await ran(run(ID, 'started', 1, { prompt: 'hi' }))).toBe(true)+ expect(await ran(task(ID, 1), run(ID, 'started', 2, { prompt: '' }), run(ID, 'terminal', 3), ...Array.from({ length: 50 }, (_, i) => task(ID, 4 + i)))).toBe(true)+ })++ it("is false for a memory reminder's session, a metadata-only one, and one where only a mirrored stream ran", async () => {+ expect(await ran(task(ID, 1), rec(ID, 2, { kind: 'memory', event: { kind: 'memory_reminder_child_session_linked' } }))).toBe(false)+ expect(await ran()).toBe(false)+ expect(await ran(run(CHILD, 'started', 1, { prompt: `mentions ${ID}` }), run(CHILD, 'terminal', 2), `{"torn": "${ID}`)).toBe(false)+ expect(await museOwnRun(join(temp(), 'gone.jsonl'), ID)).toBe(false)+ })+})++describe('museActivity', () => {+ it("is the time of the session's own newest record, in milliseconds", async () => {+ const dir = temp()+ expect(await museActivity(write(join(dir, 'a.jsonl'), jsonl(metadata(ID, '/w'), run(ID, 'started', 5), run(ID, 'terminal', 9), run(CHILD, 'terminal', 60))), ID)).toBe(T0 + 9_000)+ expect(await museActivity(write(join(dir, 'b.jsonl'), jsonl(metadata(ID, '/w', null), run(CHILD, 'started', 60))), ID)).toBeNull()+ expect(await museActivity(join(dir, 'gone.jsonl'), ID)).toBeNull()+ })++ it('reads only the end of a long log', async () => {+ const dir = temp()+ const big = run(ID, 'reasoning_committed', 3, { text: 'x'.repeat(70_000) })+ expect(await museActivity(write(join(dir, 'a.jsonl'), jsonl(metadata(ID, '/w'), big, run(ID, 'terminal', 4))), ID)).toBe(T0 + 4_000)+ })+})++describe('museTurnOpen', () => {+ const turn = (...lines: string[]) => museTurnOpen(write(join(temp(), ID, 'session.jsonl'), jsonl(metadata(ID, '/w'), ...lines)))++ it("is open while the session's own run has started and not ended, whatever its sub-agents do", async () => {+ expect(await turn(run(ID, 'started', 1), task(ID, 2), run(CHILD, 'started', 3), run(CHILD, 'terminal', 4))).toBe(true)+ expect(await turn(run(ID, 'started', 1), run(ID, 'terminal', 2), run(CHILD, 'started', 3), task(ID, 4))).toBe(false)+ })++ it('cannot say when no run of its own is near the end', async () => {+ expect(await turn()).toBeNull()+ expect(await turn(run(CHILD, 'started', 1))).toBeNull()+ expect(await museTurnOpen('')).toBeNull()+ expect(await museTurnOpen(join(temp(), ID, 'gone.jsonl'))).toBeNull()+ })++ it('looks further back when one long record fills the end of the log', async () => {+ expect(await turn(run(ID, 'started', 1), run(ID, 'tool_result_batch_committed', 2, { results: [{ text: 'x'.repeat(300_000) }] }))).toBe(true)+ })+})++describe('museProvider', () => {+ it('lists each log at exactly YYYY/MM/DD/<id>/ that someone talked to, under its workspace', async () => {+ const home = temp()+ const path = log(home, ID, [metadata(ID, '/Users/me/Work/app'), run(ID, 'started', 1, { prompt: 'hi' }), run(ID, 'terminal', 2)])+ expect(await scanner(museProvider({ home }))()).toEqual([+ { sessionId: ID, engine: 'muse', cwd: '/Users/me/Work/app', origin: 'terminal', title: '', mtime: T0 + 2_000, transcriptPath: path },+ ])+ })++ it("leaves out sub-agents, reminder sessions, metadata-only logs, another stream's log, excluded folders, and stray folders", async () => {+ const home = temp()+ const kept = log(home, ID, [metadata(ID, '/w'), run(ID, 'started', 1)])+ // A sub-agent one level deeper, and a reminder session beside the person's with the same folder.+ write(join(home, 'sessions', '2026', '09', '01', ID, 'subagent', CHILD, 'session.jsonl'), jsonl(metadata(CHILD, '/w'), run(CHILD, 'started', 1)))+ log(home, ID2, [metadata(ID2, '/w'), task(ID2, 1)])+ log(home, 'aaaaaaaa-0000-4000-8000-000000000003', [metadata('aaaaaaaa-0000-4000-8000-000000000003', '/w')])+ log(home, 'bbbbbbbb-0000-4000-8000-000000000004', [metadata(ID, '/w'), run(ID, 'started', 1)])+ log(home, 'cccccccc-0000-4000-8000-000000000005', [metadata('cccccccc-0000-4000-8000-000000000005', '/data/harness/summary-scratch'), run('cccccccc-0000-4000-8000-000000000005', 'started', 1)])+ log(home, 'not-a-session-id', [metadata('not-a-session-id', '/w'), run('not-a-session-id', 'started', 1)])+ log(home, 'dddddddd-0000-4000-8000-000000000006', [metadata('dddddddd-0000-4000-8000-000000000006', '/w'), run('dddddddd-0000-4000-8000-000000000006', 'started', 1)], ['index', '09', '01'])+ mkdirSync(join(home, 'sessions', '2026', '09', '02', 'eeeeeeee-0000-4000-8000-000000000007'), { recursive: true })+ write(join(home, 'sessions', '2026', '09', 'notes.txt'), 'x')+ const found = await scanner(museProvider({ home }), ['/data/harness'])()+ expect(found.map((s) => s.transcriptPath)).toEqual([kept])+ })++ it('dates a log whose own records carry no time by its file', async () => {+ const home = temp()+ log(home, ID, [metadata(ID, '/w', null), rec(ID, null, { kind: 'run', event: { kind: 'started' } })], undefined, 300)+ expect((await scanner(museProvider({ home }))())[0].mtime).toBe(T0 + 300_000)+ })++ it('lists a log whose metadata was still being written once it is whole, and one that opens its first run later', async () => {+ const home = temp()+ const path = write(join(home, 'sessions', '2026', '09', '01', ID, 'session.jsonl'), metadata(ID, '/w'))+ const scan = scanner(museProvider({ home }))+ expect(await scan()).toEqual([])+ appendFileSync(path, '\n')+ expect(await scan()).toEqual([])+ appendFileSync(path, jsonl(run(ID, 'started', 1)))+ expect((await scan()).map((s) => s.sessionId)).toEqual([ID])+ })++ it('reads a log again only when it changed, and for a run never once one is found', async () => {+ const home = temp()+ const path = log(home, ID, [metadata(ID, '/w'), run(ID, 'started', 1)], undefined, 100)+ const scan = scanner(museProvider({ home }))+ expect((await scan())[0].mtime).toBe(T0 + 1_000)+ // A run once written stays: the log is not read for one again, even when it no longer shows one.+ write(path, jsonl(metadata(ID, '/w'), task(ID, 5)), 200)+ expect((await scan())[0].mtime).toBe(T0 + 5_000)+ // The metadata record is read once.+ write(path, jsonl(metadata(ID, '/w/elsewhere'), run(ID, 'started', 6)), 300)+ expect((await scan())[0].cwd).toBe('/w')+ // Gone, then back: read from nothing again.+ rmSync(path)+ expect(await scan()).toEqual([])+ write(path, jsonl(metadata(ID, '/w'), task(ID, 7)), 400)+ expect(await scan()).toEqual([])+ })++ it('says which Muse has a session open from `muse resume <id>`, and whether its own run is going', async () => {+ const home = temp()+ const path = log(home, ID, [metadata(ID, '/w'), run(ID, 'started', 1)])+ const provider = museProvider({ home })+ await scanner(provider)()+ const claims = await provider.owners!(view([+ row(31, 'muse-bin-0.1.0-R708.1', `muse-bin-0.1.0-R708.1 resume ${ID}`),+ row(32, 'muse', `muse --session-id ${ID2}`),+ row(33, 'muse', 'muse resume --last'),+ row(34, 'muse-bin-0.1.0-R708.1', 'muse-bin-0.1.0-R708.1'),+ row(35, 'zsh', `zsh -c "echo resume ${ID}"`),+ ]))+ expect(claims).toEqual([+ { sessionId: ID, pid: 31, record: path, fromArgs: true },+ { sessionId: ID2, pid: 32, record: '', fromArgs: true },+ ])+ expect(await provider.busy!(claims[0])).toBe(true)+ expect(await provider.busy!(claims[1])).toBeNull()+ })+})diff --git a/cli/src/lib/sessionSearch/externals/muse.ts b/cli/src/lib/sessionSearch/externals/muse.tsnew file mode 100644index 000000000..ff6421b3c--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/muse.ts@@ -0,0 +1,181 @@+/**+ * Muse: `<home>/sessions/YYYY/MM/DD/<id>/session.jsonl`, one append-only log per session. Nothing in+ * the path names the project: the first record, the session's metadata, carries `workspace_root`,+ * and its `stream.id` is the session's id, which must be the folder's. Sub-agents live one level+ * deeper (`<id>/subagent/<child>/`) and are never read.+ *+ * Every record names its stream: Muse mirrors its sub-agents' records (and a memory reminder's) into+ * the parent's log, so only the session's own stream counts. A session somebody talked to has+ * opened a run in it; Muse's own reminder sessions sit beside the person's with the same folder and+ * never do. Times are `recorded_at`, in microseconds.+ *+ * Muse's hooks never fire and how it locks a session is not known, so only an argv that names the+ * session (`muse resume <id>`) says which process has it. A run of its own that has started and not+ * ended means a turn is running.+ */++import { basename, dirname, join } from 'node:path'++import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'+import { engineProcessMatch, resumeSessionId } from '../../tmux.js'+import { forEachLine } from '../transcript.js'+import { absoluteFolder, entries, epochMs, fileStamp, parseLine, readHead, readTail, record, text, UUID } from './support.js'+import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'++/** A log's first record is a few hundred bytes: this much is read first, and never more than the bound. */+const FIRST_BYTES = 16 * 1024+const HEAD_BYTES = 256 * 1024+const TAIL_BYTES = 64 * 1024+const DATE_PART = /^\d+$/++/**+ * A process row carries no file identity, so the PATH walk behind a full ownership snapshot could+ * not change a match: one empty snapshot serves every row.+ */+const NO_FILE_OWNERS: AgentCommandOwnershipSnapshot = {+ cursorFileKeys: new Set(), grokFileKeys: new Set(), conflictingFileKeys: new Set(),+ agentCandidates: [], cursorAgentCandidates: [], grokCandidates: [],+}++export interface MuseHead { sessionId: string; cwd: string }++/** A log's session and folder, from its first record: the metadata of the stream its folder names. */+export async function readMuseHead(path: string, folderId: string): Promise<MuseHead | null | typeof UNSETTLED> {+ let first: string | undefined+ for (const bytes of [FIRST_BYTES, HEAD_BYTES]) {+ const head = await readHead(path, bytes)+ const newline = head.indexOf('\n')+ if (newline >= 0) {+ first = head.slice(0, newline)+ break+ }+ // The whole log, and no complete record in it yet: the first is still being written.+ if (Buffer.byteLength(head) < bytes) return UNSETTLED+ }+ if (first === undefined) return null+ const row = record(parseLine(first))+ const payload = record(row?.payload)+ const cwd = absoluteFolder(record(payload?.record)?.workspace_root)+ if (record(row?.stream)?.id !== folderId || payload?.kind !== 'metadata' || !cwd) return null+ return { sessionId: folderId, cwd }+}++interface OwnRecord { run: boolean; kind: string; at: number | null }++/** One record of [sessionId]'s own stream (its run lifecycle, and when), or null for another stream's. */+function ownRecord(line: string, sessionId: string): OwnRecord | null {+ if (!line.includes(sessionId)) return null+ const row = record(parseLine(line))+ if (record(row?.stream)?.id !== sessionId) return null+ const payload = record(row?.payload)+ return { run: payload?.kind === 'run', kind: text(record(payload?.event)?.kind), at: epochMs(row?.recorded_at) }+}++/** Whether [sessionId] has opened a run of its own: somebody (or their schedule) has talked to it. */+export async function museOwnRun(path: string, sessionId: string): Promise<boolean> {+ let ran = false+ // Other streams' records are dropped unread, and so is everything once a run is found.+ await forEachLine(path, 0, ({ text: line }) => {+ const own = ownRecord(line, sessionId)+ if (own?.run && own.kind === 'started') ran = true+ }, { skip: (head) => ran || !head.includes(sessionId), shouldStop: () => ran }).catch(() => undefined)+ return ran+}++/** A log's last complete lines, newest first: the first piece is dropped when the read began mid-line. */+function tailLines(tail: string, bytes: number): string[] {+ const lines = tail.split('\n')+ return (Buffer.byteLength(tail) < bytes ? lines : lines.slice(1)).reverse()+}++/** When the session's own stream last moved: its newest record's `recorded_at`. */+export async function museActivity(path: string, sessionId: string): Promise<number | null> {+ for (const line of tailLines(await readTail(path, TAIL_BYTES), TAIL_BYTES)) {+ const at = ownRecord(line, sessionId)?.at+ if (at) return at+ }+ return null+}++/**+ * Whether the session's own run is still going: its last run `started` has no `terminal` after it.+ * Null when neither is near the end of the log.+ */+export async function museTurnOpen(path: string): Promise<boolean | null> {+ if (!path) return null+ const sessionId = basename(dirname(path))+ for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {+ const tail = await readTail(path, bytes)+ for (const line of tailLines(tail, bytes)) {+ const own = ownRecord(line, sessionId)+ if (own?.run && own.kind === 'started') return true+ if (own?.run && own.kind === 'terminal') return false+ }+ // The whole log was read: a larger look finds nothing more.+ if (Buffer.byteLength(tail) < bytes) break+ }+ return null+}++/** Every log at exactly `YYYY/MM/DD/<id>/session.jsonl`: a sub-agent's, one level deeper, is not one. */+async function logs(dir: string): Promise<Array<{ path: string; id: string }>> {+ const out: Array<{ path: string; id: string }> = []+ const within = async (at: string, pattern: RegExp): Promise<string[]> =>+ (await entries(at)).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => join(at, entry.name))+ for (const year of await within(dir, DATE_PART)) {+ for (const month of await within(year, DATE_PART)) {+ for (const day of await within(month, DATE_PART)) {+ for (const session of await within(day, UUID)) out.push({ path: join(session, 'session.jsonl'), id: basename(session) })+ }+ }+ }+ return out+}++export interface MuseOptions { home: string }++export function museProvider(options: MuseOptions): ExternalProvider {+ /** Each id's log, from the last scan: what `busy` reads. */+ let known = new Map<string, string>()+ /** Logs known to hold a run of their own. A run once written stays, so they are not read for it again. */+ const ran = new Set<string>()+ return {+ engine: 'muse',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const found: ExternalSession[] = []+ for (const { path, id } of await logs(join(options.home, 'sessions'))) {+ const stamp = await fileStamp(path)+ if (!stamp) continue+ // The metadata record never changes: read once it is whole, however the log grows.+ const head = await ctx.head(`muse:${path}`, stamp.stamp, () => readMuseHead(path, id))+ await ctx.pace()+ if (!head || ctx.excluded(head.cwd)) continue+ const info = await ctx.memo(`muse:info:${path}`, stamp.stamp, async () => ({+ ran: ran.has(path) || await museOwnRun(path, id),+ mtime: await museActivity(path, id),+ }))+ if (!info.ran) continue+ ran.add(path)+ found.push({+ sessionId: head.sessionId, engine: 'muse', cwd: head.cwd, origin: 'terminal',+ title: '', mtime: info.mtime ?? stamp.mtime, transcriptPath: path,+ })+ }+ known = new Map(found.map((session) => [session.sessionId, session.transcriptPath!]))+ const listed = new Set(known.values())+ for (const path of ran) if (!listed.has(path)) ran.delete(path)+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const claims: OwnerClaim[] = []+ for (const row of await view.list()) {+ if (!engineProcessMatch(row, 'muse', NO_FILE_OWNERS).score) continue+ const sessionId = resumeSessionId('muse', row.args)+ // Only the arguments say so, and a /resume inside moves on: never stopped on this.+ if (sessionId) claims.push({ sessionId, pid: row.pid, record: known.get(sessionId) ?? '', fromArgs: true })+ }+ return claims+ },+ busy: (owner) => museTurnOpen(owner.record),+ }+}diff --git a/cli/src/lib/sessionSearch/externals/opencode.spec.ts b/cli/src/lib/sessionSearch/externals/opencode.spec.tsnew file mode 100644index 000000000..6b3a8ac6a--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/opencode.spec.ts@@ -0,0 +1,531 @@+/**+ * OpenCode and Kilo discovery against real stores: fixture databases built from the schema dumped+ * (read-only) from opencode 1.18.31's `opencode.db`, in WAL mode, read through both of Harness's+ * SQLite paths (`node:sqlite`, and the `sqlite3` CLI a Node without it falls back to). No real+ * conversation text: every row here is made up.+ */++import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++import { builtinSqlite, closeSqliteHandles, overrideBuiltinSqlite } from '../../sqliteRead.js'+import {+ LIST_LIMIT, ancestry, argvSubcommand, engineProcess, opencodeListSql, opencodeProvider, opencodeTurnOpen,+ ownerRecord, parseOwnerRecord, readSql, rowsOf, splitCounts, storeStamp, tableColumns, tally, type SqlRead,+} from './opencode.js'+import { scanMemo } from './support.js'+import type { ProcessView, RunningProcess, ScanContext } from './types.js'++const Database = builtinSqlite()!+type Db = InstanceType<typeof Database>++const dirs: string[] = []+function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ext-opencode-'))+ dirs.push(dir)+ return dir+}+afterEach(() => {+ closeSqliteHandles()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})++/** opencode 1.18.31's own DDL for the tables discovery reads (`.schema`, read-only, this machine). */+const SCHEMA = `+CREATE TABLE \`project\` (+ \`id\` text PRIMARY KEY, \`worktree\` text NOT NULL, \`vcs\` text, \`name\` text, \`icon_url\` text,+ \`icon_url_override\` text, \`icon_color\` text, \`time_created\` integer NOT NULL, \`time_updated\` integer NOT NULL,+ \`time_initialized\` integer, \`sandboxes\` text NOT NULL, \`commands\` text+);+CREATE TABLE \`message\` (+ \`id\` text PRIMARY KEY, \`session_id\` text NOT NULL, \`time_created\` integer NOT NULL, \`time_updated\` integer NOT NULL,+ \`data\` text NOT NULL,+ CONSTRAINT \`fk_message_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE+);+CREATE TABLE \`part\` (+ \`id\` text PRIMARY KEY, \`message_id\` text NOT NULL, \`session_id\` text NOT NULL, \`time_created\` integer NOT NULL,+ \`time_updated\` integer NOT NULL, \`data\` text NOT NULL,+ CONSTRAINT \`fk_part_message_id_message_id_fk\` FOREIGN KEY (\`message_id\`) REFERENCES \`message\`(\`id\`) ON DELETE CASCADE+);+CREATE TABLE \`session\` (+ \`id\` text PRIMARY KEY, \`project_id\` text NOT NULL, \`workspace_id\` text, \`parent_id\` text, \`slug\` text NOT NULL,+ \`directory\` text NOT NULL, \`path\` text, \`title\` text NOT NULL, \`version\` text NOT NULL, \`share_url\` text,+ \`summary_additions\` integer, \`summary_deletions\` integer, \`summary_files\` integer, \`summary_diffs\` text,+ \`metadata\` text, \`cost\` real DEFAULT 0 NOT NULL, \`tokens_input\` integer DEFAULT 0 NOT NULL,+ \`tokens_output\` integer DEFAULT 0 NOT NULL, \`tokens_reasoning\` integer DEFAULT 0 NOT NULL,+ \`tokens_cache_read\` integer DEFAULT 0 NOT NULL, \`tokens_cache_write\` integer DEFAULT 0 NOT NULL, \`revert\` text,+ \`permission\` text, \`agent\` text, \`model\` text, \`time_created\` integer NOT NULL, \`time_updated\` integer NOT NULL,+ \`time_compacting\` integer, \`time_archived\` integer,+ CONSTRAINT \`fk_session_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE+);+CREATE INDEX \`message_session_time_created_id_idx\` ON \`message\` (\`session_id\`,\`time_created\`,\`id\`);+CREATE INDEX \`part_message_id_id_idx\` ON \`part\` (\`message_id\`,\`id\`);+CREATE INDEX \`part_session_idx\` ON \`part\` (\`session_id\`);+CREATE INDEX \`session_project_idx\` ON \`session\` (\`project_id\`);+CREATE INDEX \`session_parent_idx\` ON \`session\` (\`parent_id\`);+`++/** What `opencode run` writes (measured, 1.18.32): no one is there to answer a question. */+const RUN_PERMISSION = JSON.stringify([+ { permission: 'question', pattern: '*', action: 'deny' },+ { permission: 'plan_enter', pattern: '*', action: 'deny' },+ { permission: 'plan_exit', pattern: '*', action: 'deny' },+])++const T0 = 1_789_900_000_000++interface SessionRow {+ directory?: string+ title?: string+ parent?: string | null+ archived?: number | null+ permission?: string | null+ updated?: number+}++class Store {+ readonly db: Db+ private seq = 0+ constructor(readonly path: string, schema = SCHEMA) {+ this.db = new Database(path, { readOnly: false })+ this.db.exec('PRAGMA journal_mode = WAL')+ this.db.exec(schema)+ if (schema === SCHEMA) {+ this.db.prepare("INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('p', '/', 0, 0, '[]')").all()+ }+ }++ session(id: string, row: SessionRow = {}): this {+ this.db.prepare(+ 'INSERT INTO session (id, project_id, parent_id, slug, directory, title, version, permission, time_created, time_updated, time_archived)'+ + " VALUES (?, 'p', ?, 'slug', ?, ?, '1.18.31', ?, ?, ?, ?)",+ ).all(id, row.parent ?? null, row.directory ?? `/work/${id}`, row.title ?? 'A title', row.permission ?? null,+ T0, row.updated ?? T0, row.archived ?? null)+ return this+ }++ message(sessionId: string, data: Record<string, unknown>, at = T0, parts: Array<Record<string, unknown>> = []): string {+ const id = `msg_${String(++this.seq).padStart(4, '0')}`+ this.db.prepare('INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)')+ .all(id, sessionId, at, at, JSON.stringify(data))+ parts.forEach((part, index) => {+ this.db.prepare('INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)')+ .all(`prt_${id}_${index}`, id, sessionId, at + index, at + index, JSON.stringify(part))+ })+ return id+ }++ /** A person's ask and a finished answer. */+ turn(sessionId: string, at = T0): this {+ this.message(sessionId, { role: 'user', time: { created: at } }, at, [{ type: 'text', text: 'please fix the build' }])+ this.message(sessionId, { role: 'assistant', time: { created: at + 1, completed: at + 2 }, finish: 'stop' }, at + 1, [+ { type: 'text', text: 'Done.' }, { type: 'step-finish', reason: 'stop' },+ ])+ return this+ }++ close(): void { this.db.close() }+}++function context(excluded: string[] = []): { ctx: ScanContext; memo: ReturnType<typeof scanMemo> } {+ const memo = scanMemo({ excluded })+ return { ctx: memo.context(), memo }+}++const READERS: Array<[string, typeof Database | null]> = [['node:sqlite', Database], ['the sqlite3 CLI', null]]++describe.each(READERS)('OpenCode discovery read through %s', (_name, reader) => {+ beforeAll(() => { overrideBuiltinSqlite(reader) })+ afterAll(() => { overrideBuiltinSqlite(Database) })++ it('lists only the conversations a person started and can resume, and says why each other one is left out', async () => {+ const dir = tempDir()+ const store = new Store(join(dir, 'opencode.db'))+ store.session('ses_person', { directory: '/work/app', title: 'Fix the build', updated: T0 + 10 }).turn('ses_person', T0 + 5)+ store.session('ses_placeholder', { title: 'New session - 2026-09-20T10:00:00.000Z' }).turn('ses_placeholder')+ store.session('ses_childplaceholder', { title: 'Child session - 2026-09-20T10:00:00.000Z' }).turn('ses_childplaceholder')+ store.session('ses_notplaceholder', { title: 'New session - my notes' }).turn('ses_notplaceholder')+ store.session('ses_subagent', { parent: 'ses_person' }).turn('ses_subagent')+ store.session('ses_archived', { archived: T0 }).turn('ses_archived')+ store.session('ses_run', { permission: RUN_PERMISSION }).turn('ses_run')+ store.session('ses_github', { permission: JSON.stringify([{ permission: 'question', action: 'deny' }]) }).turn('ses_github')+ store.session('ses_askallowed', { permission: JSON.stringify([{ permission: 'question', action: 'allow' }]) }).turn('ses_askallowed')+ store.session('ses_otherdeny', { permission: JSON.stringify([{ permission: 'bash', action: 'deny' }]) }).turn('ses_otherdeny')+ store.session('ses_badpermission', { permission: 'not json at all' }).turn('ses_badpermission')+ store.session('ses_stringpermission', { permission: '["question","deny"]' }).turn('ses_stringpermission')+ store.session('ses_empty')+ store.session('ses_relative', { directory: 'relative/folder' }).turn('ses_relative')+ store.session('ses_recap', { directory: join(dir, 'harness-data', 'opencode-recap') }).turn('ses_recap')+ store.session('not-an-id').turn('not-an-id')++ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const found = await provider.scan(context([join(dir, 'harness-data')]).ctx)+ const byId = new Map(found.map((s) => [s.sessionId, s]))+ expect([...byId.keys()].sort()).toEqual([+ 'ses_askallowed', 'ses_badpermission', 'ses_childplaceholder', 'ses_notplaceholder', 'ses_otherdeny',+ 'ses_person', 'ses_placeholder', 'ses_stringpermission',+ ])+ expect(provider.lastScan()).toEqual({+ found: 8, child: 1, archived: 1, headless: 2, empty: 1, noFolder: 1, excluded: 1, badId: 1,+ })+ const person = byId.get('ses_person')!+ expect(person).toMatchObject({+ engine: 'opencode', cwd: '/work/app', origin: 'terminal', title: 'Fix the build', transcriptPath: null, mtime: T0 + 10,+ })+ expect(person.launchArgs).toBeUndefined()+ // A placeholder is no title: the index names it by its first ask instead.+ expect(byId.get('ses_placeholder')!.title).toBe('')+ expect(byId.get('ses_childplaceholder')!.title).toBe('')+ expect(byId.get('ses_notplaceholder')!.title).toBe('New session - my notes')+ const events = await person.readHistory!()+ expect(events.map((e) => e.type)).toEqual(['user_message', 'text_delta', 'done'])+ store.close()+ })++ it('takes the later of time_updated and the last message, in milliseconds', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ // time_updated lagged its messages by 75 minutes on this machine.+ store.session('ses_lagging', { updated: T0 }).turn('ses_lagging', T0 + 4_500_000)+ store.session('ses_current', { updated: T0 + 9_000_000 }).turn('ses_current', T0)+ // No usable time at all still lists it, as the oldest.+ store.session('ses_timeless', { updated: 0 }).message('ses_timeless', { role: 'user' }, 0)+ const found = await opencodeProvider({ engine: 'opencode', dbPath: store.path }).scan(context().ctx)+ expect(Object.fromEntries(found.map((s) => [s.sessionId, s.mtime]))).toEqual({+ ses_lagging: T0 + 4_500_001, ses_current: T0 + 9_000_000, ses_timeless: 0,+ })+ store.close()+ })++ it('reads a store once until its files change, and not at all when the machine has no SQLite reader', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ store.session('ses_one').turn('ses_one')+ const read = vi.fn(readSql)+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path, read })+ const { ctx, memo } = context()+ expect((await provider.scan(ctx)).map((s) => s.sessionId)).toEqual(['ses_one'])+ const reads = read.mock.calls.length+ expect(reads).toBe(2) // the schema, then the list+ memo.prune()+ expect((await provider.scan(memo.context())).map((s) => s.sessionId)).toEqual(['ses_one'])+ expect(read.mock.calls.length).toBe(reads)+ expect(provider.lastScan()).toEqual({ found: 1 })++ store.session('ses_two').turn('ses_two', T0 + 50)+ expect((await provider.scan(memo.context())).map((s) => s.sessionId).sort()).toEqual(['ses_one', 'ses_two'])+ expect(read.mock.calls.length).toBe(reads + 2)++ const none = opencodeProvider({ engine: 'opencode', dbPath: store.path, read, available: () => false })+ expect(await none.scan(context().ctx)).toEqual([])+ expect(none.lastScan()).toEqual({})+ expect(read.mock.calls.length).toBe(reads + 2)+ store.close()+ })++ it('finds nothing where there is no store, and fails loudly on a store it cannot read', async () => {+ const dir = tempDir()+ const read = vi.fn(readSql)+ expect(await opencodeProvider({ engine: 'opencode', dbPath: join(dir, 'missing.db'), read }).scan(context().ctx)).toEqual([])+ mkdirSync(join(dir, 'folder.db'))+ expect(await opencodeProvider({ engine: 'opencode', dbPath: join(dir, 'folder.db'), read }).scan(context().ctx)).toEqual([])+ expect(read).not.toHaveBeenCalled()++ // Not a database: the scan throws, so discovery keeps what it found last time and says why.+ writeFileSync(join(dir, 'garbage.db'), 'this is not a database, just text '.repeat(200))+ await expect(opencodeProvider({ engine: 'opencode', dbPath: join(dir, 'garbage.db') }).scan(context().ctx))+ .rejects.toThrow(/^garbage\.db not readable: /)+ })++ it('sees committed rows only, whether a writer holds a transaction open or the log is gone', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ store.session('ses_committed').turn('ses_committed')+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const { memo } = context()+ store.db.exec('BEGIN IMMEDIATE')+ store.session('ses_uncommitted').turn('ses_uncommitted')+ expect((await provider.scan(memo.context())).map((s) => s.sessionId)).toEqual(['ses_committed'])+ store.db.exec('COMMIT')+ expect((await provider.scan(memo.context())).map((s) => s.sessionId).sort()).toEqual(['ses_committed', 'ses_uncommitted'])+ closeSqliteHandles()+ store.close()+ // The last connection closed: SQLite checkpointed and removed the log, as an idle engine leaves it.+ expect(existsSync(`${store.path}-wal`)).toBe(false)+ expect((await provider.scan(context().ctx)).map((s) => s.sessionId).sort()).toEqual(['ses_committed', 'ses_uncommitted'])+ // …and reading it created nothing in the engine's folder.+ expect(existsSync(`${store.path}-wal`)).toBe(false)+ expect(existsSync(`${store.path}-shm`)).toBe(false)+ })++ it('lists the newest 500 and counts the rest as older', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ store.db.exec('BEGIN')+ for (let i = 0; i < LIST_LIMIT + 3; i++) {+ const id = `ses_many${String(i).padStart(4, '0')}`+ store.session(id, { updated: T0 + i }).message(id, { role: 'user' }, T0)+ }+ store.db.exec('COMMIT')+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const found = await provider.scan(context().ctx)+ expect(found).toHaveLength(LIST_LIMIT)+ expect(found.some((s) => s.sessionId === 'ses_many0000')).toBe(false)+ expect(found.some((s) => s.sessionId === `ses_many${String(LIST_LIMIT + 2).padStart(4, '0')}`)).toBe(true)+ expect(provider.lastScan()).toEqual({ found: LIST_LIMIT, older: 3 })+ store.close()+ })++ it('reads an older schema by the columns it has', async () => {+ const dir = tempDir()+ // No title, parent, archive or permission column yet; messages as today.+ const lean = new Store(join(dir, 'lean.db'), 'CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT NOT NULL, time_updated INTEGER NOT NULL);'+ + 'CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL);')+ lean.db.exec(`INSERT INTO session VALUES ('ses_lean', '/work/lean', ${T0}), ('ses_leanempty', '/work/lean', ${T0})`)+ lean.message('ses_lean', { role: 'user' })+ const provider = opencodeProvider({ engine: 'opencode', dbPath: lean.path })+ expect(await provider.scan(context().ctx)).toMatchObject([{ sessionId: 'ses_lean', title: '', cwd: '/work/lean' }])+ expect(provider.lastScan()).toEqual({ found: 1, empty: 1 })++ // No message table: nothing was ever said in any of them.+ const bare = new Store(join(dir, 'bare.db'), 'CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT NOT NULL, time_updated INTEGER NOT NULL);')+ bare.db.exec(`INSERT INTO session VALUES ('ses_bare', '/work/bare', ${T0})`)+ const bareProvider = opencodeProvider({ engine: 'opencode', dbPath: bare.path })+ expect(await bareProvider.scan(context().ctx)).toEqual([])+ expect(bareProvider.lastScan()).toEqual({ found: 0, empty: 1 })++ // Not OpenCode's store at all.+ const other = new Store(join(dir, 'other.db'), 'CREATE TABLE notes (id TEXT);')+ const otherProvider = opencodeProvider({ engine: 'opencode', dbPath: other.path })+ expect(await otherProvider.scan(context().ctx)).toEqual([])+ expect(otherProvider.lastScan()).toEqual({ found: 0 })+ lean.close(); bare.close(); other.close()+ })++ it('says from the last message whether a turn is running', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const busy = (id: string) => provider.busy!({ pid: 1, record: ownerRecord(store.path, id) })+ const at = { created: T0, completed: T0 + 1 }++ store.session('ses_new')+ expect(await busy('ses_new')).toBe(false)++ store.session('ses_asked').message('ses_asked', { role: 'user' })+ expect(await busy('ses_asked')).toBe(true)++ store.session('ses_streaming').message('ses_streaming', { role: 'assistant', time: { created: T0 } }, T0, [{ type: 'text', text: '…' }])+ expect(await busy('ses_streaming')).toBe(true)++ store.session('ses_done').turn('ses_done')+ expect(await busy('ses_done')).toBe(false)++ store.session('ses_toolcalls').message('ses_toolcalls', { role: 'assistant', time: at, finish: 'tool-calls' }, T0, [+ { type: 'tool', tool: 'bash', state: { status: 'completed' } }, { type: 'step-finish', reason: 'tool-calls' },+ ])+ expect(await busy('ses_toolcalls')).toBe(true)++ // `!cmd`: a shell run leaves a completed assistant with no finish and one completed tool (measured).+ store.session('ses_shell').message('ses_shell', { role: 'assistant', time: at }, T0, [+ { type: 'tool', tool: 'bash', state: { status: 'completed' } },+ ])+ expect(await busy('ses_shell')).toBe(false)++ for (const status of ['running', 'pending']) {+ store.session(`ses_tool${status}`).message(`ses_tool${status}`, { role: 'assistant', time: at }, T0, [+ { type: 'reasoning', text: 'hmm' }, { type: 'tool', tool: 'bash', state: { status } },+ ])+ expect(await busy(`ses_tool${status}`)).toBe(true)+ }++ // Esc mid-tool: the step had finished with tool-calls, then the message took the abort.+ store.session('ses_aborted').message('ses_aborted', { role: 'assistant', time: at, finish: 'tool-calls', error: { name: 'MessageAbortedError' } }, T0, [+ { type: 'tool', tool: 'bash', state: { status: 'error', error: 'aborted', metadata: { interrupted: true } } },+ ])+ expect(await busy('ses_aborted')).toBe(false)++ store.session('ses_nullerror').message('ses_nullerror', { role: 'assistant', time: { created: T0 }, error: null })+ expect(await busy('ses_nullerror')).toBe(true)++ // A refused permission ends the turn with tool-calls and no stop (kilo, measured).+ store.session('ses_refused').message('ses_refused', { role: 'assistant', time: at, finish: 'tool-calls' }, T0, [+ { type: 'tool', tool: 'bash', state: { status: 'error', error: 'The user rejected permission to use this specific tool call.' } },+ ])+ expect(await busy('ses_refused')).toBe(false)++ store.session('ses_failedtool').message('ses_failedtool', { role: 'assistant', time: at, finish: 'tool-calls' }, T0, [+ { type: 'tool', tool: 'read', state: { status: 'error', error: 'ENOENT: no such file' } },+ ])+ expect(await busy('ses_failedtool')).toBe(true)++ store.session('ses_odd').message('ses_odd', { role: 'system' })+ expect(await busy('ses_odd')).toBeNull()++ expect(await provider.busy!({ pid: 1, record: 'no-hash-here' })).toBeNull()+ expect(await provider.busy!({ pid: 1, record: ownerRecord(join(tempDir(), 'gone.db'), 'ses_x') })).toBeNull()+ store.close()+ })+})++describe('Kilo discovery', () => {+ it('reads kilo.db the same way and replays its history with the kilo reader', async () => {+ const store = new Store(join(tempDir(), 'kilo.db'))+ store.session('ses_024a007fdffe11yG68JPxsHJly', { directory: '/work/kilo', title: 'Kilo work' }).turn('ses_024a007fdffe11yG68JPxsHJly')+ store.session('ses_kilorun', { permission: RUN_PERMISSION }).turn('ses_kilorun')+ const provider = opencodeProvider({ engine: 'kilo', dbPath: store.path })+ const found = await provider.scan(context().ctx)+ expect(found).toMatchObject([{ sessionId: 'ses_024a007fdffe11yG68JPxsHJly', engine: 'kilo', cwd: '/work/kilo', title: 'Kilo work' }])+ expect(provider.lastScan()).toEqual({ found: 1, headless: 1 })+ expect((await found[0].readHistory!()).map((e) => e.type)).toEqual(['user_message', 'text_delta', 'done'])+ store.close()+ })++ it('keeps the memo of each engine apart', async () => {+ const dir = tempDir()+ const opencode = new Store(join(dir, 'opencode.db'))+ opencode.session('ses_oc').turn('ses_oc')+ const { ctx } = context()+ expect((await opencodeProvider({ engine: 'opencode', dbPath: opencode.path }).scan(ctx))[0].engine).toBe('opencode')+ // The same file under the other engine is read again, not served from opencode's memo.+ expect((await opencodeProvider({ engine: 'kilo', dbPath: opencode.path }).scan(ctx))[0].engine).toBe('kilo')+ opencode.close()+ })+})++describe('a store that cannot be read right now', () => {+ const failing = (result: Awaited<ReturnType<SqlRead>>): SqlRead => async () => result++ it('throws for a locked store so the last list is kept, and finds nothing when SQLite goes missing', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ store.close()+ await expect(opencodeProvider({ engine: 'opencode', dbPath: store.path, read: failing({ ok: false, reason: 'transient' }) }).scan(context().ctx))+ .rejects.toThrow('opencode.db not readable: locked')+ await expect(opencodeProvider({ engine: 'opencode', dbPath: store.path, read: failing({ ok: false, reason: 'transient', error: new Error('database is locked') }) }).scan(context().ctx))+ .rejects.toThrow('opencode.db not readable: database is locked')+ expect(await opencodeProvider({ engine: 'opencode', dbPath: store.path, read: failing({ ok: false, reason: 'missing' }) }).scan(context().ctx)).toEqual([])++ // The schema reads, then the CLI vanishes before the list.+ let calls = 0+ const vanishing: SqlRead = async (db, sql, params) => (++calls === 1 ? readSql(db, sql, params) : { ok: false, reason: 'missing' })+ expect(await opencodeProvider({ engine: 'opencode', dbPath: store.path, read: vanishing }).scan(context().ctx)).toEqual([])+ })+})++describe('OpenCode owners', () => {+ const view = (rows: Array<Partial<RunningProcess> & { pid: number; args: string }>): ProcessView => ({+ list: async () => rows.map((row) => ({ ppid: 1, executable: row.args.split(' ')[0], ...row })),+ openFiles: async () => new Map(),+ openFilesOf: async () => new Map(),+ alive: () => true,+ })++ // Arguments name the session a process started on: a guess once the TUI switches, so `fromArgs`.+ it('claims a session only from the id in an OpenCode process\'s own arguments', async () => {+ const provider = opencodeProvider({ engine: 'opencode', dbPath: '/data/opencode.db' })+ const claims = await provider.owners!(view([+ { pid: 10, args: 'opencode -s ses_resumed' },+ { pid: 11, args: 'opencode --session=ses_equals' },+ { pid: 12, args: '/opt/homebrew/bin/node /usr/lib/node_modules/opencode-ai/bin/opencode --session ses_npm', executable: 'node' },+ // `--fork` writes a new session: the id named is the parent's.+ { pid: 13, args: 'opencode -s ses_parent --fork' },+ { pid: 14, args: 'opencode -c' },+ { pid: 15, args: 'opencode' },+ // Not OpenCode, whatever its arguments say.+ { pid: 16, args: '/Users/x/.hermes/node/bin/node script.js -s ses_decoy', executable: 'node' },+ { pid: 17, args: 'python3 worker.py opencode -s ses_decoy2', executable: 'python3' },+ { pid: 18, args: 'kilo -s ses_kilos' },+ { pid: 19, args: 'opencode serve -s ses_served --port 4096' },+ ]))+ expect(claims).toEqual([+ { sessionId: 'ses_resumed', pid: 10, record: '/data/opencode.db#ses_resumed', fromArgs: true },+ { sessionId: 'ses_equals', pid: 11, record: '/data/opencode.db#ses_equals', fromArgs: true },+ { sessionId: 'ses_npm', pid: 12, record: '/data/opencode.db#ses_npm', fromArgs: true },+ { sessionId: 'ses_served', pid: 19, record: '/data/opencode.db#ses_served', app: true, fromArgs: true },+ ])+ })++ it("claims kilo's own processes for kilo, and a daemon's as an app", async () => {+ const provider = opencodeProvider({ engine: 'kilo', dbPath: '/data/kilo.db' })+ const claims = await provider.owners!(view([+ { pid: 20, args: 'kilo -s ses_tui' },+ { pid: 21, args: 'kilo serve --port 4097 --session ses_daemon' },+ { pid: 22, args: 'kilo --session ses_forked --fork' },+ { pid: 23, args: 'opencode -s ses_notkilo' },+ ]))+ expect(claims).toEqual([+ { sessionId: 'ses_tui', pid: 20, record: '/data/kilo.db#ses_tui', fromArgs: true },+ { sessionId: 'ses_daemon', pid: 21, record: '/data/kilo.db#ses_daemon', app: true, fromArgs: true },+ ])+ })+})++describe('the shared helpers', () => {+ it('reads an interpreter-launched engine\'s subcommand, past flags and their values', () => {+ const flags = new Set(['-p', '-s'])+ expect(argvSubcommand('opencode serve --port 1', flags)).toBe('serve')+ expect(argvSubcommand('node /x/opencode-ai/bin/opencode web', flags)).toBe('web')+ expect(argvSubcommand('python3 /x/venv/bin/hermes -p work gateway run', flags)).toBe('gateway')+ expect(argvSubcommand('opencode /work/project -s ses_1', flags)).toBe('')+ expect(argvSubcommand('opencode --verbose -- serve', flags)).toBe('')+ expect(argvSubcommand('opencode -s', flags)).toBe('')+ })++ it('names the store and session a claim is about, and refuses anything else', () => {+ expect(parseOwnerRecord(ownerRecord('/a#b/state.db', 'ses_1'))).toEqual({ dbPath: '/a#b/state.db', sessionId: 'ses_1' })+ expect(parseOwnerRecord('#ses_1')).toBeNull()+ expect(parseOwnerRecord('/a/state.db#')).toBeNull()+ expect(parseOwnerRecord('nothing')).toBeNull()+ })++ it('walks a process up to its ancestors, and stops at a loop', () => {+ const rows = new Map<number, RunningProcess>([+ [1, { pid: 1, ppid: 1, executable: 'launchd', args: 'launchd' }],+ [5, { pid: 5, ppid: 1, executable: 'zsh', args: 'zsh' }],+ [9, { pid: 9, ppid: 5, executable: 'hermes', args: 'hermes' }],+ ])+ expect(ancestry(rows, 9, 4).map((row) => row.pid)).toEqual([9, 5, 1])+ expect(ancestry(rows, 9, 1).map((row) => row.pid)).toEqual([9, 5])+ expect(ancestry(rows, 42, 4)).toEqual([])+ })++ it('matches an engine by its executable, never by a word in the arguments', () => {+ const isOpencode = engineProcess('opencode')+ expect(isOpencode({ pid: 1, ppid: 0, executable: 'opencode', args: 'opencode' })).toBe(true)+ expect(isOpencode({ pid: 1, ppid: 0, executable: 'grep', args: 'grep opencode' })).toBe(false)+ })++ it('counts', () => {+ const counts = {}+ tally(counts, 'a')+ tally(counts, 'a', 2)+ expect(counts).toEqual({ a: 3 })+ expect(splitCounts([+ { id: 'x' }, { id: null, skip: 'child', n: 2 }, { id: null, skip: '', n: 7 }, { id: null, skip: '', n: LIST_LIMIT + 4 },+ { id: null, skip: 'weird', n: 'NaN' },+ ])).toEqual({ rows: [{ id: 'x' }], counts: { child: 2, older: 4, weird: 0 } })+ expect(opencodeListSql(new Set(['id', 'directory']), new Set())).toBeNull()+ })++ it('fingerprints a store by its database and its log', async () => {+ const dir = tempDir()+ expect(await storeStamp(join(dir, 'none.db'))).toBeNull()+ writeFileSync(join(dir, 'a.db'), 'x')+ expect(await storeStamp(join(dir, 'a.db'))).toMatch(/^1:[\d.]+\|-$/)+ writeFileSync(join(dir, 'a.db-wal'), 'xyz')+ expect(await storeStamp(join(dir, 'a.db'))).toMatch(/^1:[\d.]+\|3:[\d.]+$/)+ })++ it('reads a table\'s columns, and gives up with the reader', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'))+ const columns = await tableColumns(readSql, store.path, ['session', 'nothing'])+ expect(columns?.get('session')?.has('time_archived')).toBe(true)+ expect(columns?.has('nothing')).toBe(false)+ expect(await tableColumns(async () => ({ ok: false, reason: 'missing' }), store.path, ['session'])).toBeNull()+ expect(await rowsOf(readSql, store.path, 'SELECT 1 AS one')).toEqual([{ one: 1 }])+ store.close()+ })++ it('reads no tail as idle, and an unknown role as unknowable', () => {+ expect(opencodeTurnOpen([])).toBe(false)+ expect(opencodeTurnOpen([{ role: 'tool' }])).toBeNull()+ })+})diff --git a/cli/src/lib/sessionSearch/externals/opencode.ts b/cli/src/lib/sessionSearch/externals/opencode.tsnew file mode 100644index 000000000..5ca9cc3a5--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/opencode.ts@@ -0,0 +1,300 @@+/**+ * OpenCode and Kilo (an OpenCode fork): one SQLite store each, `opencode.db` and `kilo.db`, with the+ * same `session` / `message` / `part` tables (measured: opencode 1.18.31, kilo 7.4.20). One list query+ * per store, run again only when the store's files changed.+ *+ * Who started a session is in its row: a sub-agent's has a `parent_id`, an archived one a+ * `time_archived`, and a headless `opencode run` writes a permission list that denies `question`+ * (measured in the 1.18.32 binary; the TUI leaves it NULL). A session with no message was never used.+ * Times are epoch milliseconds.+ *+ * Neither engine leaves a per-session lock or pid file: the only owner evidence is the id in a+ * process's arguments (`-s/--session`, never with `--fork`, which writes a NEW session), and it names+ * the session the process started on, not necessarily the one it has now (`fromArgs`). Whether it is+ * mid-turn is read from the last message.+ *+ * The helpers below the provider are shared with `hermes.ts` and `devin.ts`: the other two stores+ * are read the same way.+ */++import { basename } from 'node:path'++import { kiloMessagesToEvents, isPermissionRejection } from '../../../engines/kilo/normalizer.js'+import { readKiloMessages } from '../../../engines/kilo/reader.js'+import { opencodeMessagesToEvents } from '../../../engines/opencode/normalizer.js'+import { readOpencodeMessages } from '../../../engines/opencode/reader.js'+import { agentCommandOwnershipSnapshot } from '../../engineBin.js'+import { hasSqliteReader } from '../../sqliteAvailability.js'+import { sqliteReadAll, type SqliteParam, type SqliteReadResult, type SqliteRow } from '../../sqliteRead.js'+import { argvTokens, engineProcessMatch, resumeSessionId } from '../../tmux.js'+import { absoluteFolder, epochMs, fileStamp, text } from './support.js'+import type { ExternalEngine, ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'++export interface OpencodeOptions {+ engine: 'opencode' | 'kilo'+ dbPath: string+ /** How a statement is run; tests replace it. */+ read?: SqlRead+ /** Whether this machine can read SQLite at all; tests replace it. */+ available?: () => boolean+}++/** The newest sessions a scan lists: a person looks for a recent conversation, not the thousandth. */+export const LIST_LIMIT = 500++/** OpenCode's ids: `ses_` and 26 base62 characters (kilo's too). What `--session` takes. */+const SESSION_ID = /^ses_[A-Za-z0-9]{1,64}$/++/** The title OpenCode gives a session until it names it (the regex is OpenCode's own, 1.18.32). */+const PLACEHOLDER_TITLE = /^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/++/** A headless `run` (and the GitHub agent) denies the `question` tool: nobody is there to answer. */+const HEADLESS = "EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(s.permission) THEN s.permission ELSE '[]' END) r"+ + " WHERE CASE WHEN r.type = 'object' THEN json_extract(r.value, '$.permission') END = 'question'"+ + " AND CASE WHEN r.type = 'object' THEN json_extract(r.value, '$.action') END = 'deny')"++/** Subcommands that serve other clients (an editor, the desktop app, a browser): never stopped from here. */+const SERVERS = new Set(['serve', 'web', 'acp', 'daemon'])+const VALUE_FLAGS = new Set(['-s', '--session', '-m', '--model', '--agent', '--prompt', '--port', '--hostname', '--log-level'])++interface Listed { rows: SqliteRow[]; counts: Tally }++/**+ * One statement: the newest sessions a person can resume, and how many rows each rule kept out (a+ * row with a null id is a count). Columns come from the store's own schema, since versions differ.+ */+export function opencodeListSql(session: ReadonlySet<string>, message: ReadonlySet<string>): string | null {+ if (!session.has('id') || !session.has('directory') || !session.has('time_updated')) return null+ const lastMessage = message.has('session_id') && message.has('time_created')+ ? '(SELECT max(m.time_created) FROM message m WHERE m.session_id = s.id)'+ : 'NULL'+ const skip = `CASE${session.has('parent_id') ? " WHEN s.parent_id IS NOT NULL THEN 'child'" : ''}`+ + `${session.has('time_archived') ? " WHEN s.time_archived IS NOT NULL THEN 'archived'" : ''}`+ + `${session.has('permission') ? ` WHEN ${HEADLESS} THEN 'headless'` : ''}`+ + ` WHEN ${lastMessage} IS NULL THEN 'empty' ELSE '' END`+ const title = session.has('title') ? 's.title' : "''"+ return 'SELECT * FROM (SELECT s.id AS id, s.directory AS directory, '+ + `${title} AS title, s.time_updated AS updated, ${lastMessage} AS last_msg, '' AS skip, NULL AS n `+ + `FROM session s WHERE ${skip} = '' `+ + `ORDER BY max(coalesce(s.time_updated, 0), coalesce(${lastMessage}, 0)) DESC LIMIT ${LIST_LIMIT}) `+ + `UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, ${skip} AS skip, count(*) AS n FROM session s GROUP BY skip`+}++async function listSessions(read: SqlRead, dbPath: string): Promise<Listed | null> {+ const columns = await tableColumns(read, dbPath, ['session', 'message'])+ if (!columns) return null+ const sql = opencodeListSql(columns.get('session') ?? new Set(), columns.get('message') ?? new Set())+ if (!sql) return { rows: [], counts: {} }+ const rows = await rowsOf(read, dbPath, sql)+ return rows && splitCounts(rows)+}++/**+ * The tail says whether a turn runs: a user message waits for its answer; an assistant one is done+ * when it completed with no tool still pending and did not stop to call tools. A `!cmd` shell run+ * leaves an assistant message with no `finish` and a completed tool: done. A refused permission+ * (kilo's measured shape, and OpenCode's by inheritance) or an error (an abort) ends the turn too.+ */+const TAIL_SQL = "SELECT json_extract(m.data, '$.role') AS role, json_extract(m.data, '$.finish') AS finish,"+ + " json_extract(m.data, '$.time.completed') AS completed, json_type(m.data, '$.error') AS failed,"+ + " json_extract(p.data, '$.type') AS part, json_extract(p.data, '$.state.status') AS status,"+ + " json_extract(p.data, '$.state.error') AS part_error"+ + ' FROM (SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created DESC, id DESC LIMIT 1) m'+ + ' LEFT JOIN part p ON p.message_id = m.id'++export function opencodeTurnOpen(rows: readonly SqliteRow[]): boolean | null {+ const head = rows[0]+ if (!head) return false+ if (head.role === 'user') return true+ if (head.role !== 'assistant') return null+ const parts = rows.filter((row) => row.part !== null && row.part !== undefined)+ const rejected = parts.some((row) => isPermissionRejection({+ id: '', type: text(row.part), data: { state: { status: row.status, error: row.part_error } },+ }))+ // `json_type` names a present key's type, 'null' for a JSON null.+ const failed = typeof head.failed === 'string' && head.failed !== 'null'+ if (rejected || failed) return false+ if (!head.completed) return true+ if (parts.some((row) => row.part === 'tool' && (row.status === 'pending' || row.status === 'running'))) return true+ return head.finish === 'tool-calls'+}++export function opencodeProvider(options: OpencodeOptions): ExternalProvider & Counting {+ const { engine, dbPath } = options+ const read = options.read ?? readSql+ const available = options.available ?? hasSqliteReader+ let counts: Tally = {}+ const history = (sessionId: string) => engine === 'kilo'+ ? async () => kiloMessagesToEvents(await readKiloMessages(dbPath, sessionId))+ : async () => opencodeMessagesToEvents(await readOpencodeMessages(dbPath, sessionId))+ return {+ engine,+ lastScan: () => counts,+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ counts = {}+ if (!available()) return []+ const stamp = await storeStamp(dbPath)+ if (!stamp) return []+ const listed = await ctx.memo(`${engine}:${dbPath}`, stamp, () => listSessions(read, dbPath))+ await ctx.pace()+ if (!listed) return []+ counts = { ...listed.counts }+ const found: ExternalSession[] = []+ for (const row of listed.rows) {+ const sessionId = text(row.id)+ const cwd = absoluteFolder(row.directory)+ if (!SESSION_ID.test(sessionId)) { tally(counts, 'badId'); continue }+ // A session with no folder cannot be resumed: there is nowhere to run it.+ if (!cwd) { tally(counts, 'noFolder'); continue }+ if (ctx.excluded(cwd)) { tally(counts, 'excluded'); continue }+ const title = text(row.title).trim()+ found.push({+ sessionId, engine, cwd, origin: 'terminal',+ title: PLACEHOLDER_TITLE.test(title) ? '' : title,+ // `time_updated` can lag the messages by an hour (measured): the later of the two.+ mtime: Math.max(epochMs(row.updated) ?? 0, epochMs(row.last_msg) ?? 0),+ transcriptPath: null,+ readHistory: history(sessionId),+ })+ }+ counts.found = found.length+ return found+ },+ async owners(view: ProcessView): Promise<OwnerClaim[]> {+ const processes = await view.list()+ const isEngine = engineProcess(engine)+ const claims: OwnerClaim[] = []+ for (const row of processes) {+ if (!isEngine(row)) continue+ const sessionId = resumeSessionId(engine, row.args)+ if (!sessionId) continue+ // The session it was started on: the TUI may have switched to another since.+ claims.push({+ sessionId, pid: row.pid, record: ownerRecord(dbPath, sessionId), fromArgs: true,+ ...(SERVERS.has(argvSubcommand(row.args, VALUE_FLAGS)) ? { app: true } : {}),+ })+ }+ return claims+ },+ async busy(owner): Promise<boolean | null> {+ const at = parseOwnerRecord(owner.record)+ if (!at) return null+ const result = await read(at.dbPath, TAIL_SQL, [at.sessionId])+ return result.ok ? opencodeTurnOpen(result.rows) : null+ },+ }+}++// ---- shared with hermes.ts and devin.ts ---------------------------------------------------------++/** How a provider runs one read-only statement against a store. Tests replace it. */+export type SqlRead = (dbPath: string, sql: string, params?: SqliteParam[]) => Promise<SqliteReadResult>++export const readSql: SqlRead = (dbPath, sql, params = []) => sqliteReadAll(dbPath, sql, params)++/** How many rows each rule kept out of a scan, and how many it found. */+export type Tally = Record<string, number>++export interface Counting {+ /** What the last scan counted, by reason: for a person asking why a conversation is missing. */+ lastScan(): Readonly<Tally>+}++export function tally(counts: Tally, reason: string, n = 1): void {+ counts[reason] = (counts[reason] ?? 0) + n+}++/**+ * A statement's rows; null when this machine has no way to read SQLite. A store that is locked,+ * mid-migration or not a database throws, so the caller keeps what it found last time.+ */+export async function rowsOf(read: SqlRead, dbPath: string, sql: string, params: SqliteParam[] = []): Promise<SqliteRow[] | null> {+ const result = await read(dbPath, sql, params)+ if (result.ok) return result.rows+ if (result.reason === 'missing') return null+ throw new Error(`${basename(dbPath)} not readable: ${result.error?.message ?? 'locked'}`)+}++/** The columns each table has, read from the store: engines migrate their schemas, and versions share one. */+export async function tableColumns(read: SqlRead, dbPath: string, tables: readonly string[]): Promise<Map<string, Set<string>> | null> {+ const sql = tables.map((table) => `SELECT '${table}' AS t, name FROM pragma_table_info('${table}')`).join(' UNION ALL ')+ const rows = await rowsOf(read, dbPath, sql)+ if (!rows) return null+ const columns = new Map<string, Set<string>>()+ for (const row of rows) {+ const table = text(row.t)+ const set = columns.get(table) ?? new Set<string>()+ set.add(text(row.name))+ columns.set(table, set)+ }+ return columns+}++/** A list statement's rows, with the counts (the rows whose id is null) taken out. */+export function splitCounts(rows: readonly SqliteRow[]): { rows: SqliteRow[]; counts: Tally } {+ const counts: Tally = {}+ const listed: SqliteRow[] = []+ for (const row of rows) {+ if (row.id !== null && row.id !== undefined) { listed.push(row); continue }+ const reason = text(row.skip)+ if (reason) tally(counts, reason, Number(row.n) || 0)+ // The rows every rule kept, of which only the newest are listed.+ else if (Number(row.n) > LIST_LIMIT) tally(counts, 'older', Number(row.n) - LIST_LIMIT)+ }+ return { rows: listed, counts }+}++/**+ * A store's fingerprint: the database and its write-ahead log, each by size and time. A commit moves+ * one of them. Null when there is no database.+ */+export async function storeStamp(dbPath: string): Promise<string | null> {+ const db = await fileStamp(dbPath)+ if (!db) return null+ const wal = await fileStamp(`${dbPath}-wal`)+ return `${db.stamp}|${wal?.stamp ?? '-'}`+}++/** What a claim carries for busy(): the store and the session, `<db>#<id>`. */+export function ownerRecord(dbPath: string, sessionId: string): string {+ return `${dbPath}#${sessionId}`+}++export function parseOwnerRecord(record: string): { dbPath: string; sessionId: string } | null {+ const hash = record.lastIndexOf('#')+ if (hash <= 0 || hash === record.length - 1) return null+ return { dbPath: record.slice(0, hash), sessionId: record.slice(hash + 1) }+}++/**+ * The engine's subcommand: its first positional argument. The interpreter's script path before it+ * (`node …/opencode serve`, `python …/hermes gateway`) is skipped, as are flags and their values; a+ * subcommand never contains a slash.+ */+export function argvSubcommand(args: string, valueFlags: ReadonlySet<string>): string {+ const tokens = argvTokens(args)+ for (let i = 1; i < tokens.length; i++) {+ const token = tokens[i]+ if (token === '--') return ''+ if (valueFlags.has(token)) { i++; continue }+ if (token.startsWith('-') || token.includes('/')) continue+ return token+ }+ return ''+}++/** [pid]'s process and up to [depth] of its ancestors, nearest first. */+export function ancestry(processes: ReadonlyMap<number, RunningProcess>, pid: number, depth: number): RunningProcess[] {+ const chain: RunningProcess[] = []+ let row = processes.get(pid)+ while (row && chain.length <= depth && !chain.includes(row)) {+ chain.push(row)+ row = processes.get(row.ppid)+ }+ return chain+}++/** Whether [row] is [engine]'s process, by its executable or package entrypoint, never by a word in its arguments. */+export function engineProcess(engine: ExternalEngine, ownership = agentCommandOwnershipSnapshot()): (row: RunningProcess) => boolean {+ return (row) => engineProcessMatch(row, engine, ownership).score > 0+}diff --git a/cli/src/lib/sessionSearch/externals/pi.spec.ts b/cli/src/lib/sessionSearch/externals/pi.spec.tsnew file mode 100644index 000000000..348e317d7--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/pi.spec.ts@@ -0,0 +1,358 @@+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { piActivity, piProvider, piSessionFolder, piTurnOpen, readPiHead, readPiTitle } from './pi.js'+import { scanMemo } from './support.js'+import { type ExternalProvider, type ProcessView, type RunningProcess, UNSETTLED } from './types.js'++// Shapes follow Pi 0.85.1's own writer (session-manager.js) and the repo's recorded Pi session+// (engines/pi/normalizer.spec.ts); every value here is made up.+const ID = '019fa2a5-a26d-700c-bf8c-97af19ae3d5f'+const ID2 = '019fa2a6-0000-7000-8000-000000000002'+const T0 = Date.parse('2026-09-01T10:00:00.000Z')++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function temp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'pi-external-'))+ dirs.push(dir)+ return dir+}++const at = (seconds: number) => new Date(T0 + seconds * 1000).toISOString()+const header = (id: string, cwd: string, extra: Record<string, unknown> = {}) =>+ JSON.stringify({ type: 'session', version: 3, id, timestamp: at(0), cwd, ...extra })+const message = (role: string, seconds: number, extra: Record<string, unknown> = {}) =>+ JSON.stringify({ type: 'message', id: `m${seconds}`, parentId: null, timestamp: at(seconds), message: { role, content: [{ type: 'text', text: 'words' }], ...extra } })+const info = (name: unknown, seconds = 50) => JSON.stringify({ type: 'session_info', id: `i${seconds}`, parentId: null, timestamp: at(seconds), name })+const jsonl = (...lines: string[]) => `${lines.join('\n')}\n`++function write(path: string, content: string, mtimeSeconds?: number): string {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, content)+ if (mtimeSeconds !== undefined) utimesSync(path, new Date(T0 + mtimeSeconds * 1000), new Date(T0 + mtimeSeconds * 1000))+ return path+}++/** A session file where Pi would put it: `<agentDir>/sessions/<folder of cwd>/<time>_<id>.jsonl`. */+function session(agentDir: string, cwd: string, id: string, lines: string[], mtimeSeconds?: number): string {+ return write(join(agentDir, 'sessions', piSessionFolder(cwd), `2026-09-01T10-00-00-000Z_${id}.jsonl`), jsonl(header(id, cwd), ...lines), mtimeSeconds)+}++/** Scans the way ExternalSessions does: one memo across scans, pruned after each. */+function scanner(provider: ExternalProvider, excluded: string[] = []) {+ const memo = scanMemo({ excluded })+ return async () => {+ const found = await provider.scan(memo.context())+ memo.prune()+ return found+ }+}++const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })+const view = (rows: RunningProcess[]): ProcessView => ({+ list: async () => rows, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,+})++describe('readPiHead', () => {+ it('reads the id and folder from the header, as Pi resolves the folder', async () => {+ const dir = temp()+ expect(await readPiHead(write(join(dir, 'a.jsonl'), jsonl(header(ID, '/work/app/'))))).toEqual({ sessionId: ID, cwd: '/work/app' })+ expect(await readPiHead(write(join(dir, 'b.jsonl'), jsonl(header(ID, '/work/x/../app'), message('user', 1))))).toEqual({ sessionId: ID, cwd: '/work/app' })+ })++ it("takes a person's own id, within what Pi and Harness both accept", async () => {+ const dir = temp()+ const head = (id: unknown) => readPiHead(write(join(dir, `${Math.random()}.jsonl`), jsonl(header(id as string, '/w'))))+ expect(await head('my.session_2')).toEqual({ sessionId: 'my.session_2', cwd: '/w' })+ expect(await head('ab')).toEqual({ sessionId: 'ab', cwd: '/w' })+ expect(await head('a')).toBeNull() // Harness takes two characters at least+ expect(await head('-abc')).toBeNull() // Pi: starts and ends with a letter or digit+ expect(await head('abc-')).toBeNull()+ expect(await head('a/b')).toBeNull()+ expect(await head('x'.repeat(129))).toBeNull()+ expect(await head('notes.jsonl')).toBeNull() // `--session notes.jsonl` is read as a path+ expect(await head(42)).toBeNull()+ })++ it('reads every header version (Pi migrates old ones on load) and a fork, which is a conversation of its own', async () => {+ const dir = temp()+ const v1 = JSON.stringify({ type: 'session', id: ID, timestamp: at(0), cwd: '/w' })+ expect(await readPiHead(write(join(dir, 'v1.jsonl'), jsonl(v1, JSON.stringify({ type: 'message', message: { role: 'user', content: 'x' } }))))).toEqual({ sessionId: ID, cwd: '/w' })+ expect(await readPiHead(write(join(dir, 'v2.jsonl'), jsonl(header(ID, '/w', { version: 2 }))))).toEqual({ sessionId: ID, cwd: '/w' })+ expect(await readPiHead(write(join(dir, 'fork.jsonl'), jsonl(header(ID2, '/w', { parentSession: join(dir, 'v2.jsonl') }))))).toEqual({ sessionId: ID2, cwd: '/w' })+ })++ it('skips blank and malformed lines before the header, as Pi does', async () => {+ const dir = temp()+ expect(await readPiHead(write(join(dir, 'a.jsonl'), `\n \n{broken\nnull\n${header(ID, '/w')}\n`))).toEqual({ sessionId: ID, cwd: '/w' })+ })++ it('refuses a file whose first entry is not a session header, or one without an absolute folder', async () => {+ const dir = temp()+ expect(await readPiHead(write(join(dir, 'a.jsonl'), jsonl(message('user', 1), header(ID, '/w'))))).toBeNull()+ expect(await readPiHead(write(join(dir, 'b.jsonl'), jsonl('[1,2]')))).toBeNull()+ expect(await readPiHead(write(join(dir, 'c.jsonl'), jsonl(header(ID, 'relative/dir'))))).toBeNull()+ expect(await readPiHead(write(join(dir, 'd.jsonl'), jsonl(JSON.stringify({ type: 'session', id: ID }))))).toBeNull()+ })++ it('says "not yet" while the header is being written, and "never" past Pi\'s own bound', async () => {+ const dir = temp()+ expect(await readPiHead(write(join(dir, 'a.jsonl'), header(ID, '/w')))).toBe(UNSETTLED)+ expect(await readPiHead(write(join(dir, 'b.jsonl'), ''))).toBe(UNSETTLED)+ expect(await readPiHead(write(join(dir, 'c.jsonl'), 'x'.repeat(1024 * 1024 + 10)))).toBeNull()+ // A header larger than the first read (a long folder, extra fields) is read whole on a second.+ expect(await readPiHead(write(join(dir, 'd.jsonl'), jsonl(header(ID, '/w', { extra: 'y'.repeat(40_000) }), message('user', 1))))).toEqual({ sessionId: ID, cwd: '/w' })+ })+})++describe('piSessionFolder', () => {+ it("names a working directory's folder as Pi does, collisions and all", () => {+ expect(piSessionFolder('/Users/me/a-b/c')).toBe('--Users-me-a-b-c--')+ expect(piSessionFolder('/Users/me/a/b-c')).toBe('--Users-me-a-b-c--')+ expect(piSessionFolder('/tmp/with space')).toBe('--tmp-with space--')+ expect(piSessionFolder('/c:\\x')).toBe('--c--x--')+ })+})++describe('readPiTitle', () => {+ it("takes the latest session_info name; an empty one clears it; other lines never count", async () => {+ const dir = temp()+ const path = write(join(dir, 'a.jsonl'), jsonl(header(ID, '/w'), message('user', 1), info(' First name ', 2)))+ expect((await readPiTitle(path)).title).toBe('First name')+ appendFileSync(path, jsonl(info('', 3)))+ expect((await readPiTitle(path)).title).toBe('')+ // A message that mentions the entry type is still a message.+ appendFileSync(path, jsonl(info('Second', 4), message('user', 5, { content: 'what is "session_info"?' }), '{"type":"session_info", torn', info(7, 6)))+ expect((await readPiTitle(path)).title).toBe('')+ expect((await readPiTitle(write(join(dir, 'b.jsonl'), jsonl(header(ID, '/w'), message('user', 1))))).title).toBe('')+ })++ it('reads on from where it stopped while the file only grows', async () => {+ const dir = temp()+ const path = write(join(dir, 'a.jsonl'), jsonl(header(ID, '/w'), info('Named', 1)))+ const first = await readPiTitle(path)+ expect(first).toMatchObject({ end: statSync(path).size, title: 'Named' })+ // Planted where a resumed read never looks: proof that it did not start over.+ const planted = { ...first, title: 'Kept from before' }+ appendFileSync(path, jsonl(message('user', 2)))+ expect(await readPiTitle(path, planted)).toEqual({ end: statSync(path).size, lead: first.lead, title: 'Kept from before' })+ appendFileSync(path, jsonl(info('Renamed', 3)))+ expect((await readPiTitle(path, planted)).title).toBe('Renamed')+ })++ it('starts over when the file was rewritten (a migration changes its header) or shrank', async () => {+ const dir = temp()+ const path = write(join(dir, 'a.jsonl'), jsonl(header(ID, '/w', { version: 2 }), info('Old', 1), message('user', 2)))+ const first = await readPiTitle(path)+ const planted = { ...first, title: 'stale' }+ write(path, jsonl(header(ID, '/w'), info('Old', 1), message('user', 2), message('assistant', 3, { stopReason: 'stop' })))+ expect((await readPiTitle(path, planted)).title).toBe('Old')+ write(path, jsonl(header(ID, '/w', { version: 2 })))+ expect(await readPiTitle(path, { ...first, lead: (await readPiTitle(path)).lead, title: 'stale' })).toMatchObject({ title: '' })+ })++ it('gives nothing to carry over when the file cannot be read', async () => {+ const dir = temp()+ expect(await readPiTitle(join(dir, 'gone.jsonl'))).toEqual({ end: 0, lead: '', title: '' })+ expect(await readPiTitle(join(dir, 'gone.jsonl'), { end: 10, lead: '', title: 'x' })).toEqual({ end: 0, lead: '', title: '' })+ })+})++describe('piActivity', () => {+ it("is Pi's own time: the newest user or assistant message, its own time first", async () => {+ const dir = temp()+ const path = write(join(dir, 'a.jsonl'), jsonl(+ header(ID, '/w'),+ message('user', 10),+ message('assistant', 20, { stopReason: 'toolUse', timestamp: T0 + 15_000 }),+ message('toolResult', 30),+ info('Named', 40),+ JSON.stringify({ type: 'message', message: 'not an object' }),+ '{"message": broken',+ JSON.stringify({ type: 'message', timestamp: 'never', message: { role: 'user', content: 'x' } }),+ ))+ expect(await piActivity(path)).toBe(T0 + 15_000)+ })++ it('reads only the end of a long file, and says nothing when no message is there', async () => {+ const dir = temp()+ const big = write(join(dir, 'a.jsonl'), jsonl(header(ID, '/w'), message('user', 5), JSON.stringify({ type: 'custom', data: 'x'.repeat(70_000) }), message('assistant', 9, { stopReason: 'stop' })))+ expect(await piActivity(big)).toBe(T0 + 9_000)+ expect(await piActivity(write(join(dir, 'b.jsonl'), jsonl(header(ID, '/w'), info('n'))))).toBeNull()+ expect(await piActivity(join(dir, 'gone.jsonl'))).toBeNull()+ })+})++describe('piTurnOpen', () => {+ const turn = async (...lines: string[]) => piTurnOpen(write(join(temp(), 's.jsonl'), jsonl(header(ID, '/w'), ...lines)))++ it("is open after a person's message or a tool's result, and while the assistant calls tools", async () => {+ expect(await turn(message('user', 1))).toBe(true)+ expect(await turn(message('user', 1), message('assistant', 2, { stopReason: 'toolUse' }), message('toolResult', 3))).toBe(true)+ expect(await turn(message('user', 1), message('assistant', 2, { stopReason: 'toolUse' }))).toBe(true)+ })++ it('is closed on any other stop, whatever bookkeeping follows it', async () => {+ for (const stopReason of ['stop', 'length', 'error', 'aborted']) {+ expect(await turn(message('user', 1), message('assistant', 2, { stopReason }))).toBe(false)+ }+ expect(await turn(message('user', 1), message('assistant', 2, { stopReason: 'stop' }), info('Named', 3),+ message('bashExecution', 4, { command: 'ls' }), JSON.stringify({ type: 'label', targetId: 'm1', label: 'x' }))).toBe(false)+ })++ it('cannot say without a message, or with an assistant message that names no stop', async () => {+ expect(await turn()).toBeNull()+ expect(await turn(message('assistant', 2))).toBeNull()+ expect(await piTurnOpen('')).toBeNull()+ expect(await piTurnOpen(join(temp(), 'gone.jsonl'))).toBeNull()+ })++ it('looks further back when one long entry fills the end of the file', async () => {+ expect(await turn(message('user', 1), message('assistant', 2, { stopReason: 'stop' }), JSON.stringify({ type: 'custom', data: 'x'.repeat(300_000) }))).toBe(false)+ })+})++describe('piProvider', () => {+ it("lists each session under its header's id and folder, folder-name collisions included", async () => {+ const agentDir = temp()+ const a = session(agentDir, '/tmp/a-b/c', ID, [message('user', 1), message('assistant', 2, { stopReason: 'stop' })])+ const b = session(agentDir, '/tmp/a/b-c', 'my.custom_id', [message('user', 3)], 100)+ expect(a.split('/').at(-2)).toBe(b.split('/').at(-2))+ const found = await scanner(piProvider({ agentDir }))()+ expect(found.sort((x, y) => x.sessionId.localeCompare(y.sessionId))).toEqual([+ { sessionId: ID, engine: 'pi', cwd: '/tmp/a-b/c', origin: 'terminal', title: '', mtime: T0 + 2_000, transcriptPath: a },+ { sessionId: 'my.custom_id', engine: 'pi', cwd: '/tmp/a/b-c', origin: 'terminal', title: '', mtime: T0 + 3_000, transcriptPath: b },+ ])+ })++ it('names a session by its latest session_info, and dates one with no message by its file', async () => {+ const agentDir = temp()+ session(agentDir, '/w/one', ID, [message('user', 1), info('Refactor auth', 2)])+ session(agentDir, '/w/two', ID2, [info('Just a name', 2)], 500)+ const found = await scanner(piProvider({ agentDir }))()+ expect(found.find((s) => s.sessionId === ID)).toMatchObject({ title: 'Refactor auth', mtime: T0 + 1_000 })+ expect(found.find((s) => s.sessionId === ID2)).toMatchObject({ title: 'Just a name', mtime: T0 + 500_000 })+ })++ it("leaves out what is not a resumable session: a file in another's folder, a bad header, an excluded folder, and what is not a file", async () => {+ const agentDir = temp()+ const sessions = join(agentDir, 'sessions')+ // A session whose folder is not its header's: `pi --session` from its folder would offer to fork it.+ write(join(sessions, piSessionFolder('/w/other'), `x_${ID}.jsonl`), jsonl(header(ID, '/w/moved'), message('user', 1)))+ write(join(sessions, piSessionFolder('/w/bad'), 'x_bad.jsonl'), jsonl(message('user', 1)))+ session(agentDir, '/data/harness/summary-scratch', ID2, [message('user', 1)])+ write(join(sessions, piSessionFolder('/w/ok'), 'notes.txt'), 'not a session')+ mkdirSync(join(sessions, piSessionFolder('/w/ok'), 'dir.jsonl'), { recursive: true })+ write(join(sessions, 'stray.jsonl'), jsonl(header(ID, '/w/ok')))+ const ok = session(agentDir, '/w/ok', 'kept-one', [message('user', 1)])+ const found = await scanner(piProvider({ agentDir }), ['/data/harness'])()+ expect(found.map((s) => s.transcriptPath)).toEqual([ok])+ })++ it('follows a linked folder, as Pi does', async () => {+ const agentDir = temp()+ const elsewhere = temp()+ const real = write(join(elsewhere, `x_${ID}.jsonl`), jsonl(header(ID, '/w/linked'), message('user', 1)))+ mkdirSync(join(agentDir, 'sessions'), { recursive: true })+ symlinkSync(elsewhere, join(agentDir, 'sessions', piSessionFolder('/w/linked')))+ const found = await scanner(piProvider({ agentDir }))()+ expect(found.map((s) => [s.sessionId, s.cwd])).toEqual([[ID, '/w/linked']])+ expect(real).toContain(elsewhere)+ })++ it('reads a moved sessions folder, flat, when the env or the settings file names one, and then only that', async () => {+ const agentDir = temp()+ const home = temp()+ session(agentDir, '/w/default', ID, [message('user', 1)])+ const flat = write(join(home, 'pi-sessions', `x_${ID2}.jsonl`), jsonl(header(ID2, '/w/anywhere'), message('user', 1)))+ const byEnv = await scanner(piProvider({ agentDir, sessionDir: join(home, 'pi-sessions') }))()+ expect(byEnv.map((s) => [s.sessionId, s.transcriptPath])).toEqual([[ID2, flat]])++ write(join(agentDir, 'settings.json'), JSON.stringify({ sessionDir: '~/pi-sessions' }))+ expect((await scanner(piProvider({ agentDir, home }))()).map((s) => s.sessionId)).toEqual([ID2])+ write(join(agentDir, 'settings.json'), JSON.stringify({ sessionDir: '~' }))+ expect(await scanner(piProvider({ agentDir, home }))()).toEqual([])+ write(join(agentDir, 'settings.json'), JSON.stringify({ sessionDir: 'relative/sessions' }))+ expect(await scanner(piProvider({ agentDir, home }))()).toEqual([])+ })++ it("uses Pi's own tree when the settings file names no folder, or cannot be read", async () => {+ const agentDir = temp()+ session(agentDir, '/w/default', ID, [message('user', 1)])+ for (const settings of [JSON.stringify({ theme: 'dark' }), JSON.stringify({ sessionDir: 5 }), '{torn', '[]']) {+ write(join(agentDir, 'settings.json'), settings)+ expect((await scanner(piProvider({ agentDir }))()).map((s) => s.sessionId)).toEqual([ID])+ }+ // No settings file, no sessions folder: nothing, and no error.+ expect((await scanner(piProvider({ agentDir: temp() }))())).toEqual([])+ })++ it('lists a session whose header was still being written once it is whole', async () => {+ const agentDir = temp()+ const path = write(join(agentDir, 'sessions', piSessionFolder('/w'), `x_${ID}.jsonl`), header(ID, '/w'))+ const scan = scanner(piProvider({ agentDir }))+ expect(await scan()).toEqual([])+ appendFileSync(path, `\n${message('user', 1)}\n`)+ expect((await scan()).map((s) => s.sessionId)).toEqual([ID])+ })++ it('reads a file again only when it changed; its header never', async () => {+ const agentDir = temp()+ const path = session(agentDir, '/w', ID, [message('user', 1), info('Before', 2)], 100)+ const scan = scanner(piProvider({ agentDir }))+ expect((await scan())[0]).toMatchObject({ title: 'Before', cwd: '/w' })+ // Same size and time: the memo answers, so a changed name goes unseen.+ write(path, jsonl(header(ID, '/w'), message('user', 1), info('Beforx', 2)), 100)+ expect((await scan())[0].title).toBe('Before')+ // Changed: read again, from where the last read stopped.+ appendFileSync(path, jsonl(info('After', 3)))+ expect((await scan())[0]).toMatchObject({ title: 'After', mtime: T0 + 1_000 })+ // The header is read once: what it says is not read again.+ write(path, jsonl(header(ID, '/w/elsewhere'), message('user', 1), info('Again', 4)), 200)+ expect((await scan())[0]).toMatchObject({ cwd: '/w', title: 'Again' })+ })++ it('forgets a deleted file, and reads a new one at its path from the start', async () => {+ const agentDir = temp()+ const kept = session(agentDir, '/w/kept', ID2, [message('user', 1)])+ const path = session(agentDir, '/w', ID, [info('Long gone name', 1), message('user', 1)])+ const scan = scanner(piProvider({ agentDir }))+ expect((await scan()).length).toBe(2)+ rmSync(path)+ expect((await scan()).map((s) => s.transcriptPath)).toEqual([kept])+ write(path, jsonl(header(ID, '/w'), message('user', 1)))+ expect((await scan()).find((s) => s.sessionId === ID)?.title).toBe('')+ })++ it("says which Pi has a session open from its arguments, and whether it is mid-turn from the session's file", async () => {+ const agentDir = temp()+ // Two files of one id (a copy): Pi's `--session` opens the one that moved last, and so does `busy`.+ const newer = write(join(agentDir, 'sessions', piSessionFolder('/w'), `a_${ID}.jsonl`), jsonl(header(ID, '/w'), message('user', 30)), 10)+ const older = write(join(agentDir, 'sessions', piSessionFolder('/w'), `b_${ID}.jsonl`), jsonl(header(ID, '/w'), message('user', 1), message('assistant', 2, { stopReason: 'stop' })), 20)+ const provider = piProvider({ agentDir })+ // Before any scan nothing says where a session's file is: it cannot say whether it is mid-turn.+ const early = await provider.owners!(view([row(7, 'pi', `pi --session ${ID}`)]))+ expect(early).toEqual([{ sessionId: ID, pid: 7, record: '', fromArgs: true }])+ expect(await provider.busy!(early[0])).toBeNull()++ await scanner(provider)()+ const claims = await provider.owners!(view([+ row(7, 'pi', `pi --session ${ID}`),+ row(8, 'node', `node /opt/lib/node_modules/pi-coding-agent/dist/cli.js --session-id ${ID2}`),+ // Pi renames its process, which leaves nothing to read.+ row(9, 'pi', 'pi'),+ row(10, 'node', `node server.js --session ${ID}`),+ row(11, 'pi', 'pi --session my.custom_id'),+ ]))+ expect(claims).toEqual([+ { sessionId: ID, pid: 7, record: newer, fromArgs: true },+ { sessionId: ID2, pid: 8, record: '', fromArgs: true },+ ])+ expect(await provider.busy!(claims[0])).toBe(true)+ expect(await provider.busy!({ pid: 7, record: older })).toBe(false)+ })+})diff --git a/cli/src/lib/sessionSearch/externals/pi.ts b/cli/src/lib/sessionSearch/externals/pi.tsnew file mode 100644index 000000000..62e734544--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/pi.ts@@ -0,0 +1,248 @@+/**+ * Pi: `<agentDir>/sessions/--<folder>--/<time>_<id>.jsonl`, or one flat folder when the person moved+ * them (`PI_CODING_AGENT_SESSION_DIR`, else `sessionDir` in `<agentDir>/settings.json`; Pi then+ * reads no other). The first entry is the header, `{type:'session', id, cwd}`, and it is the only+ * authority for either: the folder name is lossy (`/a/b-c` and `/a-b/c` share one) and an id can be+ * the person's own (`--session-id`). Pi writes a file only once the first reply lands. Print, JSON+ * and RPC runs are saved the same way and cannot be told apart; Pi's own picker lists them, and so+ * does this.+ *+ * A session's name is the latest `session_info` entry anywhere in the file (an empty one clears it),+ * read incrementally: only what a scan has not seen yet. Its time is Pi's own: the newest user or+ * assistant message.+ *+ * Pi keeps no descriptor open and writes no process record, and it renames its process to `pi`,+ * which erases its arguments from `ps`: only an argv that still names the session says which process+ * has it. The last message says whether a turn is running.+ */++import { stat } from 'node:fs/promises'+import { homedir } from 'node:os'+import { isAbsolute, join, resolve } from 'node:path'++import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'+import { engineProcessMatch, resumeSessionId } from '../../tmux.js'+import { forEachLine } from '../transcript.js'+import { absoluteFolder, entries, fileStamp, parseLine, readHead, readJson, readTail, record, text } from './support.js'+import { type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView, type ScanContext, UNSETTLED } from './types.js'++/** How much of a file is read for its header first: headers are a few hundred bytes. */+const FIRST_BYTES = 16 * 1024+/** Pi's own bound on a header: a larger first entry is not a session. */+const HEAD_BYTES = 1024 * 1024+/** Enough of a header to see its version, which a migration rewrites. */+const LEAD_BYTES = 256+const TAIL_BYTES = 64 * 1024+/**+ * Pi's rule for an id (`--session-id` takes any such), kept to what Harness takes as one: 2 to 128+ * characters. One that ends `.jsonl` is read by `--session` as a file path, so it cannot be resumed.+ */+const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/++/**+ * A process row carries no file identity, so the PATH walk behind a full ownership snapshot could+ * not change a match: one empty snapshot serves every row.+ */+const NO_FILE_OWNERS: AgentCommandOwnershipSnapshot = {+ cursorFileKeys: new Set(), grokFileKeys: new Set(), conflictingFileKeys: new Set(),+ agentCandidates: [], cursorAgentCandidates: [], grokCandidates: [],+}++export interface PiHead { sessionId: string; cwd: string }++/**+ * A session file's id and folder, from its first entry. Blank and malformed lines before it are+ * skipped, as Pi skips them; any other first entry means the file is not a session.+ */+export async function readPiHead(path: string): Promise<PiHead | null | typeof UNSETTLED> {+ for (const bytes of [FIRST_BYTES, HEAD_BYTES]) {+ const head = await readHead(path, bytes)+ // The last piece has no newline: an entry still being written, or one cut by the read.+ for (const line of head.split('\n').slice(0, -1)) {+ if (!line.trim()) continue+ const value = parseLine(line)+ if (value === null) continue+ const row = record(value)+ if (row?.type !== 'session') return null+ const id = text(row.id)+ const cwd = absoluteFolder(row.cwd)+ return SESSION_ID.test(id) && !id.endsWith('.jsonl') && cwd ? { sessionId: id, cwd: resolve(cwd) } : null+ }+ // The whole file, and no entry in it yet: its first one is still being written.+ if (Buffer.byteLength(head) < bytes) return UNSETTLED+ }+ return null+}++/** The folder Pi keeps a working directory's sessions in, named as Pi names it. */+export function piSessionFolder(cwd: string): string {+ return `--${cwd.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`+}++/** How far a title read got: where it stopped, the header's start then, and the name so far. */+export interface PiTitleRead { end: number; lead: string; title: string }++/**+ * A session's name: the latest `session_info` entry, '' when there is none or it was cleared. Reads on+ * from [prior] when the file only grew; one that shrank or was rewritten (a migration changes its+ * header) is read again from the start. Only lines that name `session_info` are parsed.+ */+export async function readPiTitle(path: string, prior?: PiTitleRead): Promise<PiTitleRead> {+ const [start, info] = await Promise.all([readHead(path, LEAD_BYTES), stat(path).catch(() => null)])+ const lead = start.split('\n')[0]+ const from = prior && info && prior.lead === lead && info.size >= prior.end ? prior : { end: 0, lead, title: '' }+ let title = from.title+ const read = await forEachLine(path, from.end, ({ text: line }) => {+ const row = record(parseLine(line))+ if (row?.type === 'session_info') title = text(row.name).trim()+ }, { skip: (head) => !head.includes('"session_info"') }).catch(() => null)+ // Unreadable now (gone, or being replaced): nothing is carried over, and the next change reads it whole.+ return read ? { end: read.end, lead, title } : { end: 0, lead: '', title: '' }+}++/** A file's last complete lines, newest first: the first piece is dropped when the read began mid-line. */+function tailLines(tail: string, bytes: number): string[] {+ const lines = tail.split('\n')+ return (Buffer.byteLength(tail) < bytes ? lines : lines.slice(1)).reverse()+}++/** One `message` entry near a file's end, or null for any other line. */+function messageOf(line: string): { row: Record<string, unknown>; message: Record<string, unknown> } | null {+ if (!line.includes('"message"')) return null+ const row = record(parseLine(line))+ const message = record(row?.message)+ return row?.type === 'message' && message ? { row, message } : null+}++/**+ * When the conversation last moved, as Pi's own picker measures it: its newest user or assistant+ * message (the message's own time, else its entry's). Null when none is near the end.+ */+export async function piActivity(path: string): Promise<number | null> {+ let latest: number | null = null+ for (const line of tailLines(await readTail(path, TAIL_BYTES), TAIL_BYTES)) {+ const found = messageOf(line)+ if (!found || (found.message.role !== 'user' && found.message.role !== 'assistant')) continue+ const at = typeof found.message.timestamp === 'number' ? found.message.timestamp : Date.parse(text(found.row.timestamp))+ if (at > 0 && (latest === null || at > latest)) latest = at+ }+ return latest+}++/**+ * Whether a session's turn is running, from its last message: a person's message or a tool's result+ * means the agent is on it, an assistant message is mid-turn only while it calls tools. Null when+ * the file cannot say (no message near its end, or none at all).+ */+export async function piTurnOpen(path: string): Promise<boolean | null> {+ if (!path) return null+ for (const bytes of [256 * 1024, 4 * 1024 * 1024]) {+ const tail = await readTail(path, bytes)+ for (const line of tailLines(tail, bytes)) {+ const message = messageOf(line)?.message+ if (message?.role === 'user' || message?.role === 'toolResult') return true+ if (message?.role === 'assistant') return text(message.stopReason) ? message.stopReason === 'toolUse' : null+ }+ // The whole file was read: a larger look finds nothing more.+ if (Buffer.byteLength(tail) < bytes) break+ }+ return null+}++export interface PiOptions {+ agentDir: string+ /** `PI_CODING_AGENT_SESSION_DIR`, which outranks the settings file. */+ sessionDir?: string+ /** The folder a `~` stands for; tests replace it. */+ home?: string+}++interface PiLayout { dir: string; flat: boolean }++/** A moved sessions folder as Pi reads it: `~`, `~/…` or absolute. A relative one depends on where+ * Pi was started, so no one folder holds its sessions. */+function movedFolder(value: string, home: string): string | null {+ if (value === '~') return home+ if (value.startsWith('~/')) return join(home, value.slice(2))+ return isAbsolute(value) ? value : null+}++/** Where Pi keeps its sessions: the env's folder, else the settings file's, else its own per-folder tree. */+async function piLayout(options: PiOptions, ctx: ScanContext): Promise<PiLayout | null> {+ let moved = options.sessionDir ?? ''+ if (!moved) {+ const path = join(options.agentDir, 'settings.json')+ const stamp = await fileStamp(path)+ const settings = stamp ? record(await ctx.memo(`pi:settings:${path}`, stamp.stamp, () => readJson(path))) : null+ moved = text(settings?.sessionDir)+ }+ if (!moved) return { dir: join(options.agentDir, 'sessions'), flat: false }+ const dir = movedFolder(moved, options.home ?? homedir())+ return dir ? { dir, flat: true } : null+}++/** Every `.jsonl` Pi would list, with the folder it is in (null in a flat one). Pi follows linked folders. */+async function piFiles(layout: PiLayout): Promise<Array<{ path: string; folder: string | null }>> {+ const out: Array<{ path: string; folder: string | null }> = []+ const add = async (dir: string, folder: string | null): Promise<void> => {+ for (const file of await entries(dir)) if (file.name.endsWith('.jsonl')) out.push({ path: join(dir, file.name), folder })+ }+ if (layout.flat) {+ await add(layout.dir, null)+ return out+ }+ for (const folder of await entries(layout.dir)) {+ if (folder.isDirectory() || folder.isSymbolicLink()) await add(join(layout.dir, folder.name), folder.name)+ }+ return out+}++/** The session each running Pi names on its command line (`--session <id>`, `--session-id <id>`). */+async function argvClaims(view: ProcessView, recordOf: (sessionId: string) => string): Promise<OwnerClaim[]> {+ const claims: OwnerClaim[] = []+ for (const row of await view.list()) {+ if (!engineProcessMatch(row, 'pi', NO_FILE_OWNERS).score) continue+ const sessionId = resumeSessionId('pi', row.args)+ // Only the arguments say so, and Pi can move to another session inside: never stopped on this.+ if (sessionId) claims.push({ sessionId, pid: row.pid, record: recordOf(sessionId), fromArgs: true })+ }+ return claims+}++export function piProvider(options: PiOptions): ExternalProvider {+ /** Each id's transcript, from the last scan: what `busy` reads. The newest file of an id wins. */+ let transcripts = new Map<string, string>()+ const titles = new Map<string, PiTitleRead>()+ return {+ engine: 'pi',+ async scan(ctx: ScanContext): Promise<ExternalSession[]> {+ const layout = await piLayout(options, ctx)+ const found: ExternalSession[] = []+ for (const { path, folder } of layout ? await piFiles(layout) : []) {+ const stamp = await fileStamp(path)+ if (!stamp) continue+ // What the header says never changes (a migration rewrites only its version): read once it is whole.+ const head = await ctx.head(`pi:${path}`, stamp.stamp, () => readPiHead(path))+ await ctx.pace()+ // In Pi's own tree an id resumes only from the folder its header's folder names; from any+ // other, Pi asks whether to fork it instead.+ if (!head || (folder !== null && folder !== piSessionFolder(head.cwd)) || ctx.excluded(head.cwd)) continue+ const info = await ctx.memo(`pi:info:${path}`, stamp.stamp, async () => {+ const read = await readPiTitle(path, titles.get(path))+ titles.set(path, read)+ return { title: read.title, mtime: await piActivity(path) }+ })+ found.push({+ sessionId: head.sessionId, engine: 'pi', cwd: head.cwd, origin: 'terminal',+ title: info.title, mtime: info.mtime ?? stamp.mtime, transcriptPath: path,+ })+ }+ const listed = new Set(found.map((session) => session.transcriptPath))+ for (const path of titles.keys()) if (!listed.has(path)) titles.delete(path)+ transcripts = new Map([...found].sort((a, b) => a.mtime - b.mtime).map((session) => [session.sessionId, session.transcriptPath!]))+ return found+ },+ owners: (view: ProcessView) => argvClaims(view, (sessionId) => transcripts.get(sessionId) ?? ''),+ busy: (owner) => piTurnOpen(owner.record),+ }+}diff --git a/cli/src/lib/sessionSearch/externals/support.spec.ts b/cli/src/lib/sessionSearch/externals/support.spec.tsnew file mode 100644index 000000000..b00aa6054--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/support.spec.ts@@ -0,0 +1,256 @@+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, describe, expect, it } from 'vitest'++import { UNSETTLED } from './types.js'+import {+ absoluteFolder, entries, epochMs, fileStamp, firstLine, harnessTtys, listProcesses, parseLine, parseLsof, parseTtys,+ processAlive, processTtys, processView, readHead, readJson, readTail, readText, record, run, scanMemo, text, UUID,+ within,+} from './support.js'++const dirs: string[] = []+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })+function home(): string {+ const dir = mkdtempSync(join(tmpdir(), 'externals-support-'))+ dirs.push(dir)+ return dir+}++describe('reading files', () => {+ it('reads a head, a tail and a first line, and reads nothing from what is not there', async () => {+ const dir = home()+ const path = join(dir, 'a.jsonl')+ writeFileSync(path, 'first line\nsecond line\nthird')+ expect(await readHead(path, 5)).toBe('first')+ expect(await readTail(path, 5)).toBe('third')+ expect(await readTail(path, 1_000)).toBe('first line\nsecond line\nthird')+ expect(await firstLine(path, 1_000)).toBe('first line')+ // A first line longer than what is read is not a line.+ expect(await firstLine(path, 4)).toBeNull()+ expect(await readHead(join(dir, 'none'), 5)).toBe('')+ expect(await readTail(join(dir, 'none'), 5)).toBe('')+ expect(await firstLine(join(dir, 'none'), 5)).toBeNull()+ })++ it('lists a folder, and nothing for one that is missing', async () => {+ const dir = home()+ writeFileSync(join(dir, 'x'), '')+ expect((await entries(dir)).map((entry) => entry.name)).toEqual(['x'])+ expect(await entries(join(dir, 'none'))).toEqual([])+ })++ it('reads JSON files and lines, and says null for anything half-written', async () => {+ const dir = home()+ writeFileSync(join(dir, 'ok.json'), '{"a":1}')+ writeFileSync(join(dir, 'bad.json'), '{"a":')+ expect(await readJson(join(dir, 'ok.json'))).toEqual({ a: 1 })+ expect(await readJson(join(dir, 'bad.json'))).toBeNull()+ expect(await readJson(join(dir, 'none.json'))).toBeNull()+ expect(await readText(join(dir, 'ok.json'))).toBe('{"a":1}')+ expect(await readText(join(dir, 'none.json'))).toBe('')+ expect(parseLine('[1]')).toEqual([1])+ expect(parseLine('nope')).toBeNull()+ })++ it("stamps a file by size and time, and nothing that is not a file", async () => {+ const dir = home()+ const path = join(dir, 'f')+ writeFileSync(path, 'abc')+ const stamp = await fileStamp(path)+ expect(stamp?.stamp).toMatch(/^3:\d/)+ expect(stamp?.mtime).toBeGreaterThan(0)+ expect(await fileStamp(dir)).toBeNull()+ expect(await fileStamp(join(dir, 'none'))).toBeNull()+ })+})++describe('reading values', () => {+ it('takes strings, records, uuids and absolute folders only when they are what they say', () => {+ expect(text('a')).toBe('a')+ expect(text(1)).toBe('')+ expect(record({ a: 1 })).toEqual({ a: 1 })+ expect(record([1])).toBeNull()+ expect(record(null)).toBeNull()+ expect(record('x')).toBeNull()+ expect(UUID.test('11111111-2222-4333-8444-555555555555')).toBe(true)+ expect(UUID.test('not-a-uuid')).toBe(false)+ expect(absoluteFolder('/work')).toBe('/work')+ expect(absoluteFolder('work')).toBeNull()+ expect(absoluteFolder(3)).toBeNull()+ })++ it('reads a time in every unit the engines write', () => {+ const ms = Date.parse('2026-09-27T10:00:00Z')+ expect(epochMs(ms / 1000)).toBe(ms)+ expect(epochMs(ms / 1000 + 0.25)).toBe(ms + 250)+ expect(epochMs(ms)).toBe(ms)+ expect(epochMs(ms * 1000)).toBe(ms)+ expect(epochMs(ms * 1_000_000)).toBe(ms)+ expect(epochMs('2026-09-27T10:00:00Z')).toBe(ms)+ expect(epochMs(String(ms / 1000))).toBe(ms)+ expect(epochMs('no time')).toBeNull()+ expect(epochMs(0)).toBeNull()+ expect(epochMs(-5)).toBeNull()+ expect(epochMs(Number.NaN)).toBeNull()+ expect(epochMs(null)).toBeNull()+ })++ it('says whether a path is a folder or inside it', () => {+ expect(within('/a/b', '/a/b')).toBe(true)+ expect(within('/a/b', '/a/b/c/d')).toBe(true)+ expect(within('/a/b', '/a/bc')).toBe(false)+ expect(within('/a/b', '/a')).toBe(false)+ })+})++describe('scanMemo', () => {+ it('reads again only what changed, and forgets what a scan did not ask for', async () => {+ const memo = scanMemo({ excluded: ['/data/harness'] })+ let reads = 0+ const read = async () => ++reads+ const ctx = memo.context()+ expect(await ctx.memo('a', '1', read)).toBe(1)+ expect(await ctx.memo('a', '1', read)).toBe(1)+ expect(await ctx.memo('a', '2', read)).toBe(2)+ expect(await ctx.memo('b', '1', read)).toBe(3)+ memo.prune()+ // The next scan asks only for a: b is forgotten, and read again when asked.+ const next = memo.context()+ expect(await next.memo('a', '2', read)).toBe(2)+ memo.prune()+ expect(await memo.context().memo('b', '1', read)).toBe(4)+ expect(ctx.excluded('/data/harness/summary-scratch')).toBe(true)+ expect(ctx.excluded('/work')).toBe(false)+ })++ it("keeps a file's head for good once it can be judged, and reads it again until then", async () => {+ const memo = scanMemo()+ let reads = 0+ let answer: string | null | typeof UNSETTLED = UNSETTLED+ const read = async () => { reads++; return answer }+ const ctx = memo.context()+ expect(await ctx.head('f', '1', read)).toBeNull()+ expect(await ctx.head('f', '1', read)).toBeNull()+ expect(reads).toBe(1)+ answer = 'head'+ expect(await ctx.head('f', '2', read)).toBe('head')+ expect(await ctx.head('f', '3', read)).toBe('head')+ expect(reads).toBe(2)+ answer = null+ expect(await ctx.head('g', '1', read)).toBeNull()+ expect(await ctx.head('g', '2', read)).toBeNull()+ expect(reads).toBe(3)+ memo.prune()+ memo.prune()+ expect(await memo.context().head('g', '9', read)).toBeNull()+ expect(reads).toBe(4)+ })++ it('lets the daemon breathe every so often, and has sensible defaults', async () => {+ const ctx = scanMemo({ excluded: [], paceEvery: 2 }).context()+ await ctx.pace()+ await ctx.pace()+ const plain = scanMemo().context()+ expect(plain.excluded('/anything')).toBe(false)+ for (let i = 0; i < 64; i++) await plain.pace()+ })+})++describe('processes', () => {+ it('knows this process is alive, and one that cannot exist is not', () => {+ expect(processAlive(process.pid)).toBe(true)+ expect(processAlive(2 ** 22 + 7)).toBe(false)+ })++ it("runs a command and keeps what it printed, even when it fails", async () => {+ expect(await run('/bin/sh', ['-c', 'printf ok'], 5_000)).toBe('ok')+ expect(await run('/bin/sh', ['-c', 'printf partial; exit 1'], 5_000)).toBe('partial')+ expect(await run('/bin/sh', ['-c', 'exit 1'], 5_000)).toBeNull()+ })++ it('reads lsof and ps output', () => {+ expect(parseLsof('p10\nf3\nn/a\nn/b\np11\nn/c\nx\n')).toEqual(new Map([[10, ['/a', '/b']], [11, ['/c']]]))+ expect(parseLsof('n/orphan\np0\nn/zero\n')).toEqual(new Map())+ expect(parseTtys(' 10 ttys003\n 11 ??\n 12 ?\n\n')).toEqual(new Map([+ [10, '/dev/ttys003'], [11, null], [12, null],+ ]))+ })++ it("asks the machine through one view, and reads each process's terminal", async () => {+ const calls: string[] = []+ const exec = async (command: string, args: readonly string[]) => {+ calls.push(`${command} ${args.join(' ')}`)+ return command === 'lsof' ? 'p7\nn/f\n' : ' 7 ttys001\n'+ }+ let listed = 0+ const view = processView(exec, () => true, async () => { listed++; return [{ pid: 7, ppid: 1, executable: 'x', args: '' }] })+ expect(await view.list()).toHaveLength(1)+ await view.list()+ expect(listed).toBe(1)+ expect(await view.openFiles([7, 8])).toEqual(new Map([[7, ['/f']]]))+ expect(await view.openFiles([])).toEqual(new Map())+ expect(await view.openFilesOf(['codex', 'Codex'])).toEqual(new Map([[7, ['/f']]]))+ expect(await view.openFilesOf([])).toEqual(new Map())+ expect(view.alive(1)).toBe(true)+ expect(calls).toEqual([+ 'lsof -n -P -Fpn -a -p 7,8',+ 'lsof -n -P -Fpn -c codex -c Codex',+ ])+ expect(await processTtys([7], exec)).toEqual(new Map([[7, '/dev/ttys001']]))+ expect(await processTtys([], exec)).toEqual(new Map())+ const quiet = processView(async () => null)+ expect(await quiet.openFiles([1])).toEqual(new Map())+ expect(await quiet.openFilesOf(['x'])).toEqual(new Map())+ expect(await processTtys([1], async () => null)).toEqual(new Map())+ })++ it('lists the real machine: this very process is among them, with its own open files', async () => {+ const view = processView()+ const me = (await view.list()).find((row) => row.pid === process.pid)+ expect(me?.args).toContain('node')+ const dir = home()+ const held = join(dir, 'held.txt')+ writeFileSync(held, 'x')+ const { open } = await import('node:fs/promises')+ const handle = await open(held, 'r')+ try {+ const files = await view.openFiles([process.pid])+ expect((files.get(process.pid) ?? []).some((path) => path.endsWith('held.txt'))).toBe(true)+ } finally {+ await handle.close()+ }+ expect((await processTtys([process.pid])).has(process.pid)).toBe(true)+ })++ it('lists no processes when ps cannot be read, and each start time when it can be read', async () => {+ expect(await listProcesses(async () => null)).toEqual([])+ const row = { pid: 5, parentPid: 1, executable: 'grok', args: 'grok', startMarker: 'Sun Sep 27 09:05:03 2026' }+ expect(await listProcesses(async () => [row, { ...row, pid: 6, startMarker: 'soon' }])).toEqual([+ { pid: 5, ppid: 1, executable: 'grok', args: 'grok', started: Date.parse('Sun Sep 27 09:05:03 2026') },+ { pid: 6, ppid: 1, executable: 'grok', args: 'grok' },+ ])+ })++ it("knows Harness's own panes by their tmux session names", async () => {+ const out = '/dev/ttys001\tharness-claude-1\n/dev/ttys002\tmy-own\n\n/dev/ttys003\n'+ expect(await harnessTtys(async () => ({ stdout: out, failed: false, stderr: '' }))).toEqual(new Set(['/dev/ttys001']))+ // No server running: no panes of Harness's. Could not ask: nobody can say.+ expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: 'no server running on /tmp/tmux-501/default' }))).toEqual(new Set())+ expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: 'error connecting to /tmp/x (No such file or directory)' }))).toEqual(new Set())+ expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: '' }))).toBeNull()+ // The real tmux answers one way or the other.+ const real = await harnessTtys()+ expect(real === null || real instanceof Set).toBe(true)+ })++ it('reads entries through a symlinked folder too', async () => {+ const dir = home()+ mkdirSync(join(dir, 'real'))+ writeFileSync(join(dir, 'real', 'f'), '')+ symlinkSync(join(dir, 'real'), join(dir, 'link'))+ expect((await entries(join(dir, 'link'))).map((entry) => entry.name)).toEqual(['f'])+ })+})diff --git a/cli/src/lib/sessionSearch/externals/support.ts b/cli/src/lib/sessionSearch/externals/support.tsnew file mode 100644index 000000000..a635be5c0--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/support.ts@@ -0,0 +1,264 @@+/**+ * What every provider reads with: bounded file reads, a scan's memo, and the machine's processes.+ * Each system call here is small, read-only, and has a timeout.+ */++import { execFile } from 'node:child_process'+import type { Dirent } from 'node:fs'+import { open, readdir, readFile, stat } from 'node:fs/promises'+import { isAbsolute, relative, resolve } from 'node:path'++import { isHarnessSession } from '../../harnessSessionLabel.js'+import { processRows } from '../../tmux.js'+import { type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'++/** A folder's entries, or none when it is missing or unreadable. */+export async function entries(dir: string): Promise<Dirent[]> {+ return readdir(dir, { withFileTypes: true }).catch(() => [])+}++/** Up to [bytes] from the start of a file; '' when it cannot be read. */+export async function readHead(path: string, bytes: number): Promise<string> {+ const handle = await open(path, 'r').catch(() => null)+ if (!handle) return ''+ try {+ const buffer = Buffer.alloc(bytes)+ const { bytesRead } = await handle.read(buffer, 0, bytes, 0)+ return buffer.subarray(0, bytesRead).toString('utf8')+ } finally {+ await handle.close()+ }+}++/** Up to [bytes] from the end of a file; '' when it cannot be read. */+export async function readTail(path: string, bytes: number): Promise<string> {+ const handle = await open(path, 'r').catch(() => null)+ if (!handle) return ''+ try {+ const { size } = await handle.stat()+ const length = Math.min(size, bytes)+ const buffer = Buffer.alloc(length)+ await handle.read(buffer, 0, length, size - length)+ return buffer.toString('utf8')+ } finally {+ await handle.close()+ }+}++/** A file's first line, whole, when it fits in [bytes]; null otherwise. */+export async function firstLine(path: string, bytes: number): Promise<string | null> {+ const text = await readHead(path, bytes)+ const newline = text.indexOf('\n')+ return newline < 0 ? null : text.slice(0, newline)+}++/** A file's text, or '' when it is missing or unreadable. */+export async function readText(path: string): Promise<string> {+ return readFile(path, 'utf8').catch(() => '')+}++/** A JSON file's value, or null when it is missing, unreadable or being written. */+export async function readJson(path: string): Promise<unknown> {+ try {+ return JSON.parse(await readFile(path, 'utf8'))+ } catch {+ return null+ }+}++/** One JSON line's value, or null. */+export function parseLine(line: string): unknown {+ try {+ return JSON.parse(line)+ } catch {+ return null+ }+}++/** A file's size and change time, the fingerprint a memo is keyed on; null when it is not a file. */+export async function fileStamp(path: string): Promise<{ stamp: string; mtime: number } | null> {+ const info = await stat(path).catch(() => null)+ if (!info?.isFile()) return null+ return { stamp: `${info.size}:${info.mtimeMs}`, mtime: Math.floor(info.mtimeMs) }+}++/** An object's field when it is a non-empty string, else ''. */+export function text(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++/** A record, when [value] is one. */+export function record(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null+}++export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++/** An absolute folder, as a session records it. */+export function absoluteFolder(value: unknown): string | null {+ return typeof value === 'string' && value.startsWith('/') ? value : null+}++/** Epoch ms from seconds, milliseconds, microseconds or an ISO string; null for anything else. */+export function epochMs(value: unknown): number | null {+ if (typeof value === 'string') {+ if (/^\d+(?:\.\d+)?$/.test(value)) return epochMs(Number(value))+ const parsed = Date.parse(value)+ return Number.isFinite(parsed) ? parsed : null+ }+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null+ if (value < 1e11) return Math.round(value * 1000)+ if (value < 1e14) return Math.round(value)+ if (value < 1e17) return Math.round(value / 1000)+ return Math.round(value / 1e6)+}++/** Whether [path] is [dir] or inside it. */+export function within(dir: string, path: string): boolean {+ const rel = relative(resolve(dir), resolve(path))+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))+}++export interface ScanMemo {+ context(): ScanContext+ /** Forgets whatever this scan did not ask for again. */+ prune(): void+}++/**+ * A scan's memory between scans: each key's last value, kept while its fingerprint holds. A first+ * scan reads everything once; later ones read only what changed.+ */+export function scanMemo(options: { excluded: readonly string[]; paceEvery?: number } = { excluded: [] }): ScanMemo {+ const kept = new Map<string, { fingerprint: string; value: unknown; settled?: boolean }>()+ let touched = new Set<string>()+ let reads = 0+ const every = options.paceEvery ?? 64+ return {+ context: () => ({+ memo: async <T>(key: string, fingerprint: string, read: () => Promise<T>): Promise<T> => {+ touched.add(key)+ const found = kept.get(key)+ if (found && found.fingerprint === fingerprint) return found.value as T+ const value = await read()+ kept.set(key, { fingerprint, value })+ return value+ },+ head: async <T>(key: string, stamp: string, read: () => Promise<T | null | typeof UNSETTLED>): Promise<T | null> => {+ touched.add(key)+ const found = kept.get(key)+ if (found && (found.settled || found.fingerprint === stamp)) return found.value as T | null+ const value = await read()+ const settled = value !== UNSETTLED+ kept.set(key, { fingerprint: stamp, value: settled ? value : null, settled })+ return settled ? value : null+ },+ excluded: (cwd) => options.excluded.some((dir) => within(dir, cwd)),+ pace: async () => {+ if (++reads % every === 0) await new Promise<void>((resolve) => setImmediate(resolve))+ },+ }),+ prune: () => {+ for (const key of [...kept.keys()]) if (!touched.has(key)) kept.delete(key)+ touched = new Set()+ },+ }+}++export function processAlive(pid: number): boolean {+ try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }+}++type Run = (command: string, args: readonly string[], timeout: number) => Promise<string | null>++/** A command's output; what it printed even when it exits non-zero (lsof does, for a gone pid). */+export const run: Run = (command, args, timeout) => new Promise((resolve) => {+ execFile(command, [...args], { timeout, maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {+ resolve(error && !stdout ? null : String(stdout))+ })+})++/** `lsof -F pn` output as files by pid. */+export function parseLsof(stdout: string): Map<number, string[]> {+ const files = new Map<number, string[]>()+ let pid = 0+ for (const line of stdout.split('\n')) {+ if (line.startsWith('p')) {+ pid = Number(line.slice(1)) || 0+ if (pid && !files.has(pid)) files.set(pid, [])+ } else if (pid && line.startsWith('n')) {+ files.get(pid)!.push(line.slice(1))+ }+ }+ return files+}++/** `ps -o pid=,tty=` output as each process's terminal (`/dev/ttys003`), or null for none. */+export function parseTtys(stdout: string): Map<number, string | null> {+ const ttys = new Map<number, string | null>()+ for (const line of stdout.split('\n')) {+ const [pid, tty] = line.trim().split(/\s+/)+ if (!pid) continue+ ttys.set(Number(pid), tty && !tty.startsWith('?') ? `/dev/${tty}` : null)+ }+ return ttys+}++/** The machine's processes, as the daemon's own process scan reads them (it repairs rewritten rows);+ * none when `ps` could not be read. */+export async function listProcesses(read: typeof processRows = processRows): Promise<RunningProcess[]> {+ const rows = await read()+ return (rows ?? []).map((row) => {+ const started = Date.parse(row.startMarker)+ return { pid: row.pid, ppid: row.parentPid, executable: row.executable, args: row.args, ...(Number.isFinite(started) ? { started } : {}) }+ })+}++/** The machine's processes, looked at once per view: the list is read on first use and kept. */+export function processView(+ exec: Run = run,+ alive: (pid: number) => boolean = processAlive,+ list: () => Promise<RunningProcess[]> = listProcesses,+): ProcessView {+ let listed: Promise<RunningProcess[]> | null = null+ return {+ list: () => (listed ??= list()),+ openFiles: async (pids) => pids.length+ ? parseLsof(await exec('lsof', ['-n', '-P', '-Fpn', '-a', '-p', pids.join(',')], 3_000) ?? '')+ : new Map(),+ openFilesOf: async (commands) => commands.length+ ? parseLsof(await exec('lsof', ['-n', '-P', '-Fpn', ...commands.flatMap((name) => ['-c', name])], 3_000) ?? '')+ : new Map(),+ alive,+ }+}++/** Each of [pids]' terminal, or null for a process with none (an app, a server). */+export async function processTtys(pids: readonly number[], exec: Run = run): Promise<Map<number, string | null>> {+ if (!pids.length) return new Map()+ return parseTtys(await exec('ps', ['-o', 'pid=,tty=', '-p', pids.join(',')], 3_000) ?? '')+}++type Ask = (command: string, args: readonly string[], timeout: number) => Promise<{ stdout: string; failed: boolean; stderr: string }>++const ask: Ask = (command, args, timeout) => new Promise((resolve) => {+ execFile(command, [...args], { timeout }, (error, stdout, stderr) => {+ resolve({ stdout: String(stdout), failed: !!error, stderr: String(stderr) })+ })+})++/**+ * The terminals of Harness's own panes: tmux sessions named `harness-…`. A process there is one of+ * Harness's agents, whatever its session looks like while the daemon is still binding it. None when+ * no tmux server is running; null when tmux could not be asked (a timeout): then nobody can say.+ */+export async function harnessTtys(exec: Ask = ask): Promise<Set<string> | null> {+ const { stdout, failed, stderr } = await exec('tmux', ['list-panes', '-a', '-F', '#{pane_tty}\t#{session_name}'], 3_000)+ if (failed && !/no server running|error connecting to/i.test(stderr)) return null+ const ttys = new Set<string>()+ for (const line of stdout.split('\n')) {+ const [tty, session] = line.split('\t')+ if (tty && session && isHarnessSession(session)) ttys.add(tty)+ }+ return ttys+}diff --git a/cli/src/lib/sessionSearch/externals/types.ts b/cli/src/lib/sessionSearch/externals/types.tsnew file mode 100644index 000000000..ed88c981d--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/types.ts@@ -0,0 +1,114 @@+/**+ * The shapes every engine's discovery shares: what a conversation Harness did not start looks like,+ * how an engine lists them, and how it says which process has one open.+ *+ * One provider per engine (`claude.ts`, `codex.ts`, …), gathered in `index.ts`, used by+ * `../external.ts`. A provider reads the engine's own store and nothing else: it never writes, never+ * starts the engine, and never logs a process's arguments (they can carry a key).+ */++import type { LiveEvent } from '../../normalize.js'++/**+ * The engines whose conversations can be found on this machine's disk. Amp is not one: it keeps its+ * threads on its server, and nothing local holds what was said.+ */+export const EXTERNAL_ENGINES = [+ 'claude', 'codex', 'cursor', 'opencode', 'kilo', 'hermes', 'devin', 'pi', 'commandcode', 'muse', 'grok',+ 'agy', 'copilot',+] as const+export type ExternalEngine = typeof EXTERNAL_ENGINES[number]++/**+ * Where a conversation was held. `claude-app` and `codex-app` name the engines' own desktop apps;+ * `app` is another engine's app, `editor` an editor's extension.+ */+export type ExternalOrigin = 'terminal' | 'editor' | 'app' | 'claude-app' | 'codex-app'++export interface ExternalSession {+ sessionId: string+ engine: ExternalEngine+ /** The folder it ran in, and so the folder it resumes in. */+ cwd: string+ origin: ExternalOrigin+ /** The engine's own name for it, or '' (the index then titles it by its first ask). */+ title: string+ /** When the conversation last moved, epoch ms. */+ mtime: number+ /** The JSONL transcript the index reads line by line; null for an engine that keeps a database. */+ transcriptPath: string | null+ /** A database engine's history, read whole. */+ readHistory?: () => Promise<readonly LiveEvent[]>+ /** Arguments a resume needs besides the id: a Hermes profile (`-p work`). */+ launchArgs?: readonly string[]+ /** Its other ids: one Hermes conversation carries on under a new id each time it is compressed. */+ aliases?: readonly string[]+}++/** A file's head that cannot be judged yet: the engine is still writing its first lines. */+export const UNSETTLED: unique symbol = Symbol('unsettled')++export interface ScanContext {+ /** `read`, run again only when `fingerprint` (a file's size and time) changed since the last scan. */+ memo<T>(key: string, fingerprint: string, read: () => Promise<T>): Promise<T>+ /**+ * A file's head, read once for good — unless `read` says it cannot judge it yet (UNSETTLED: the+ * first lines are still being written). Then it is read again when [stamp] changes, and counts as+ * no session meanwhile.+ */+ head<T>(key: string, stamp: string, read: () => Promise<T | null | typeof UNSETTLED>): Promise<T | null>+ /** A folder whose sessions are Harness's own byproducts (its data folder): never offered. */+ excluded(cwd: string): boolean+ /** Lets the daemon breathe between files on a long first scan. */+ pace(): Promise<void>+}++/** A running process. Its arguments identify it and are never logged: a worker's can carry a key. */+export interface RunningProcess {+ pid: number+ ppid: number+ /** The command's name as the system reports it (`comm`). */+ executable: string+ args: string+ /**+ * When it started, epoch ms to the second (`ps` lstart), when known. A record or lock older than+ * the process named in it was left by another process that once had the same pid.+ */+ started?: number+}++/** What a provider may ask about the machine's processes. One view serves one look. */+export interface ProcessView {+ list(): Promise<readonly RunningProcess[]>+ /** The files each of [pids] has open. */+ openFiles(pids: readonly number[]): Promise<Map<number, string[]>>+ /** The files processes with these command names have open, by pid (`lsof -c`). */+ openFilesOf(commands: readonly string[]): Promise<Map<number, string[]>>+ alive(pid: number): boolean+}++/** A provider's word that [pid] has [sessionId] open. */+export interface OwnerClaim {+ sessionId: string+ pid: number+ /** What says whether it is mid-turn: a record, a transcript, a database. */+ record: string+ /** An app or a shared server holds it (a Grok leader, `kilo serve`): never stopped from here. */+ app?: boolean+ /**+ * The only evidence is the process's arguments: they name the session it STARTED on, and a TUI can+ * move to another conversation since (`/resume` in it). The session may be open there, so it is not+ * opened a second time; but the process is never stopped on the strength of it.+ */+ fromArgs?: boolean+}++export interface ExternalProvider {+ readonly engine: ExternalEngine+ /** Every conversation of this engine on disk that a person started and Harness can resume. */+ scan(ctx: ScanContext): Promise<ExternalSession[]>+ /** Which of them a process has open right now, when the engine leaves exact evidence of it. */+ owners?(view: ProcessView): Promise<OwnerClaim[]>+ /** Whether the owner is mid-turn; null when the engine's store cannot say. */+ busy?(owner: { pid: number; record: string }): Promise<boolean | null>+}diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.tsindex 37672a97a..1b2b9b5c8 100644--- a/cli/src/lib/sessionSearch/indexer.spec.ts+++ b/cli/src/lib/sessionSearch/indexer.spec.ts@@ -99,6 +99,36 @@ describe('SessionSearchIndex', () => {expect(await index.tail('unknown')).toBeNull()})+ it("dates a conversation Harness did not start by its engine's time when its lines carry none, and indexes a database's under its title", async () => {+ const dir = mkdtempSync(join(tmpdir(), 'session-search-external-times-'))+ dirs.push(dir)+ // Cursor's lines have no time.+ const cursorFile = join(dir, 'c1.jsonl')+ writeFileSync(cursorFile, JSON.stringify({ role: 'user', message: { content: [{ type: 'text', text: '<user_query>ship the dial</user_query>' }] } }) + '\n'+ + JSON.stringify({ role: 'assistant', message: { content: [{ type: 'text', text: 'Shipped.' }] } }) + '\n')+ const events: LiveEvent[] = [+ { type: 'user_message', payload: { content: 'compare cohorts in the warehouse' } },+ { type: 'text_delta', payload: { content: 'Day-7 is 35%.' } },+ ]+ const store = SessionSearchStore.open(':memory:')!+ const sources: SearchSource[] = [+ { agentId: '', sessionId: 'c1', engine: 'cursor', transcriptPath: cursorFile, header: '', changedAt: 1_790_000_000_000, external: { cwd: '/work/dial', origin: 'terminal', title: 'Dial release' } },+ { agentId: '', sessionId: 'ses_1', engine: 'opencode', transcriptPath: null, header: '', changedAt: 1_790_000_100_000, readHistory: async () => events, external: { cwd: '/work/cohorts', origin: 'terminal', title: '' } },+ ]+ const index = new SessionSearchIndex({ store, sources: () => sources, agents: () => [] })+ cleanups.push(() => { index.stop(); store.close() })+ index.sweep()+ await vi.waitFor(() => { expect((index as unknown as { running: boolean }).running).toBe(false) })+ expect(store.session('c1')).toMatchObject({ lastAt: 1_790_000_000_000, title: 'Dial release', cwd: '/work/dial' })+ // A database's conversation, titled by its first ask, with its folder and origin.+ expect(store.session('ses_1')).toMatchObject({ title: 'compare cohorts in the warehouse', cwd: '/work/cohorts', origin: 'terminal', lastAt: 1_790_000_100_000 })+ expect(index.search('warehouse').hits[0]).toMatchObject({ sessionId: 'ses_1', external: { title: 'compare cohorts in the warehouse' } })+ // Read again unchanged: its heading is kept.+ index.sweep()+ await vi.waitFor(() => { expect((index as unknown as { running: boolean }).running).toBe(false) })+ expect(store.session('ses_1')?.title).toBe('compare cohorts in the warehouse')+ })+it("indexes a conversation Harness did not start under its own title, says if it is open, and drops it with its file", async () => {const dir = mkdtempSync(join(tmpdir(), 'session-search-external-'))dirs.push(dir)diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.tsindex e5f5587df..3d16ae9b4 100644--- a/cli/src/lib/sessionSearch/indexer.ts+++ b/cli/src/lib/sessionSearch/indexer.ts@@ -103,7 +103,7 @@ export interface SessionSearchIndexOptions {* Which sessions are open in a running process right now (external.ts `OpenSessions`), so a* conversation Harness did not start says whether a terminal still has it. `known` never waits.*/- openSessions?: { known(): ReadonlyMap<string, 'terminal' | 'app'>; fresh(): Promise<ReadonlyMap<string, 'terminal' | 'app'>> }+ openSessions?: { known(): ReadonlyMap<string, 'terminal' | 'app' | 'harness' | 'maybe'>; fresh(): Promise<ReadonlyMap<string, 'terminal' | 'app' | 'harness' | 'maybe'>> }/** Looks again for conversations Harness did not start, before each sweep lists its sources. */discover?: () => Promise<unknown>/** Between full sweeps. */@@ -371,7 +371,9 @@ export class SessionSearchIndex {size: file.size, mtime,resumeOffset: open ? open.offset : end,resumeTurn: open ? open.turn : collector.next,- lastAt: lastAt ?? (resume ? existing.lastAt : null) ?? mtime,+ // Lines with no time of their own (Cursor's) date the session by when its conversation last+ // moved, as its engine says, before the file's own time.+ lastAt: lastAt ?? (resume ? existing.lastAt : null) ?? (source.external && source.changedAt ? source.changedAt : mtime),turns: 0,...externalFields(source, title),}@@ -403,9 +405,12 @@ export class SessionSearchIndex {private async historyPass(source: SearchSource, existing: IndexedSession | undefined, dirty: boolean): Promise<void> {const store = this.opts.storeconst stamp = source.changedAt+ // A conversation Harness did not start is headed by its own title and folder, as a transcript's is.+ const headed = (title: string) => ({ header: headerFor(source, title), ...externalFields(source, title) })if (existing && !dirty && existing.mtime === stamp) {- if (existing.header !== source.header || existing.agentId !== source.agentId) {- store.writeSession({ ...existing, header: source.header, agentId: source.agentId }, NO_TURN_DELETE, [])+ const again = source.external ? headed(existing.title ?? '') : { header: source.header }+ if (existing.header !== again.header || existing.agentId !== source.agentId) {+ store.writeSession({ ...existing, ...again, agentId: source.agentId }, NO_TURN_DELETE, [])}return}@@ -418,14 +423,16 @@ export class SessionSearchIndex {}const { closed, open } = collector.finish()const turns = open ? [...closed, open] : closed+ const title = source.external ? titleLine(source.external.title || turns.find((turn) => turn.ask)?.ask || '') : ''+ const head = source.external ? headed(title) : { header: source.header }// The size field holds the fingerprint: how much conversation there was when last read.const fingerprint = turns.reduce((sum, turn) => sum + turn.ask.length + turn.answer.length + turn.tools.length + 1, 0)if (existing && existing.size === fingerprint && existing.mtime === stamp- && existing.header === source.header && existing.agentId === source.agentId) return+ && existing.header === head.header && existing.agentId === source.agentId) returnconst changed = !existing || existing.size !== fingerprintstore.writeSession({sessionId: source.sessionId, agentId: source.agentId, engine: source.engine, path: '',- header: source.header, size: fingerprint, mtime: stamp, resumeOffset: 0, resumeTurn: 0,+ ...head, size: fingerprint, mtime: stamp, resumeOffset: 0, resumeTurn: 0,// Its turns carry no time: the session's is its activity stamp, or now for a turn just seen.lastAt: !changed ? existing!.lastAt : dirty ? Math.max(Date.now(), stamp) : stamp || null,turns: 0,diff --git a/cli/src/lib/sessionSearch/store.spec.ts b/cli/src/lib/sessionSearch/store.spec.tsindex 487a5047c..6856ff86f 100644--- a/cli/src/lib/sessionSearch/store.spec.ts+++ b/cli/src/lib/sessionSearch/store.spec.ts@@ -253,17 +253,21 @@ describe('SessionSearchStore', () => {expect(store.search('alpha', { now: NOW })).toHaveLength(1)})- it('rebuilds an index written by another schema version', () => {+ it.each(['0', '8', '9'])('rebuilds an index written by schema %s', (version) => {const dir = mkdtempSync(join(tmpdir(), 'session-search-'))dirs.push(dir)const path = join(dir, 'index.db')const first = open(path)first.writeSession(session('s', 'S', NOW), 0, [turn(0, 'alpha')])- ;(first as unknown as { db: { exec(sql: string): void } }).db.exec("UPDATE meta SET value = '0' WHERE key = 'schema'")+ ;(first as unknown as { db: { exec(sql: string): void } }).db.exec(`UPDATE meta SET value = '${version}' WHERE key = 'schema'`)first.close()stores.splice(stores.indexOf(first), 1)+ expect(SessionSearchStore.openReader(path)).toBe('outdated')const second = open(path)expect(second.counts()).toEqual({ sessions: 0, turns: 0 })+ second.writeSession(session('s', 'S', NOW), 0, [turn(0, 'rebuilt conversation')])+ expect(second.search('alpha', { now: NOW })).toEqual([])+ expect(second.search('rebuilt', { now: NOW })).toHaveLength(1)})})diff --git a/cli/src/lib/sessionSearch/store.ts b/cli/src/lib/sessionSearch/store.tsindex 08ee51495..abf0d61dd 100644--- a/cli/src/lib/sessionSearch/store.ts+++ b/cli/src/lib/sessionSearch/store.ts@@ -16,7 +16,9 @@ import { chmodSync, existsSync, rmSync } from 'node:fs'import { builtinSqlite } from '../sqliteRead.js'import type { IndexedTurn } from './turns.js'-const SCHEMA_VERSION = '8'+// Rebuild existing turns with the external-engine timestamps and Muse/Copilot stream filters.+// Version 9 belongs to the Codex context-block change (#388), which may land in either order.+const SCHEMA_VERSION = '10'/** The row that holds a session's name, title and folder: searchable beside its turns. */export const HEADER_TURN = -1@@ -65,8 +67,10 @@ export interface ExternalHit {origin: string/** Open in a running process elsewhere (a terminal, the engine's app): not to be opened twice. */open?: boolean- /** Where it is open: a terminal, which Harness can take it over from, or an app, which it cannot. */- openIn?: 'terminal' | 'app'+ /** Where it is open: a terminal, which Harness can take it over from; an app, which it cannot; or+ * one of Harness's own panes, an agent the daemon is still binding; or `maybe` a terminal whose+ * process was started on it and may have moved on. */+ openIn?: 'terminal' | 'app' | 'harness' | 'maybe'}export interface SearchHit {diff --git a/cli/src/lib/sessionSearch/transcript.spec.ts b/cli/src/lib/sessionSearch/transcript.spec.tsindex 58fd3ef8a..40b71658d 100644--- a/cli/src/lib/sessionSearch/transcript.spec.ts+++ b/cli/src/lib/sessionSearch/transcript.spec.ts@@ -4,7 +4,7 @@ import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'-import { forEachLine, lineNormalizer, lineTime, skipPredicate } from './transcript.js'+import { copilotOwnLine, forEachLine, lineNormalizer, lineTime, museOwnStream, skipPredicate } from './transcript.js'import { TurnCollector, type IndexedTurn } from './turns.js'const dirs: string[] = []@@ -75,6 +75,11 @@ describe('lineTime', () => {it('reads the record time wherever the field sits', () => {expect(lineTime(claude.answer('hi', 3))).toBe(Date.parse(at(3)))expect(lineTime('{"type":"x"}')).toBeNull()+ // Grok: epoch seconds; Muse: microseconds; Antigravity: an ISO created_at.+ expect(lineTime('{"timestamp":1790500000,"method":"session/update"}')).toBe(1790500000000)+ expect(lineTime('{"id":"r","recorded_at":1790500000123456,"sequence":1}')).toBe(1790500000123)+ expect(lineTime('{"step":3,"created_at":"2026-09-27T10:00:00Z"}')).toBe(Date.parse('2026-09-27T10:00:00Z'))+ expect(lineTime('{"timestamp":"not a date at all"}')).toBeNull()})})@@ -167,3 +172,30 @@ describe("the person's words outside Claude's prompt records", () => {expect(text).not.toContain('Base directory')})})++describe("engines' own lines", () => {+ it("keeps a Muse session's own stream, and records that name none", () => {+ expect(museOwnStream('{"stream":{"kind":"session","id":"s1"},"payload":{}}', 's1')).toBe(true)+ expect(museOwnStream('{"stream":{"kind":"session","id":"child"},"payload":{}}', 's1')).toBe(false)+ expect(museOwnStream('{"payload":{}}', 's1')).toBe(true)+ })++ it("keeps Copilot's own events, not a sub-agent's or a prompt nobody typed", () => {+ expect(copilotOwnLine('{"type":"assistant.message","data":{"content":"hi"}}')).toBe(true)+ expect(copilotOwnLine('{"type":"assistant.message","agentId":"a1","data":{}}')).toBe(false)+ expect(copilotOwnLine('{"type":"assistant.message","agentId":"","data":{}}')).toBe(true)+ expect(copilotOwnLine('{"type":"user.message","data":{"content":"x","source":"skill-review"}}')).toBe(false)+ expect(copilotOwnLine('{"type":"user.message","data":{"content":"x","source":""}}')).toBe(true)+ expect(copilotOwnLine('{"type":"user.message","data":{"content":"x","source":"agent-a1"}}')).toBe(false)+ // Any other source is the person's: only skills and agents are left out.+ expect(copilotOwnLine('{"type":"user.message","data":{"content":"x","source":"cli"}}')).toBe(true)+ expect(copilotOwnLine('{"type":"user.message","data":{"content":"go on","isAutopilotContinuation":true}}')).toBe(false)+ expect(copilotOwnLine('{"type":"tool.call","data":{"source":"x"}}')).toBe(true)+ expect(copilotOwnLine('{"type":"user.message","data":{"source": half')).toBe(true)+ // Through the search reader: a sub-agent's answer is not the conversation's.+ const normalize = lineNormalizer('copilot', 'c1')!+ expect(normalize('{"type":"assistant.message","agentId":"a1","data":{"content":"sub"}}')).toEqual([])+ const muse = lineNormalizer('muse', 's1')!+ expect(muse('{"stream":{"kind":"session","id":"child"},"payload":{}}')).toEqual([])+ })+})diff --git a/cli/src/lib/sessionSearch/transcript.ts b/cli/src/lib/sessionSearch/transcript.tsindex 7198148d3..411d3b5e0 100644--- a/cli/src/lib/sessionSearch/transcript.ts+++ b/cli/src/lib/sessionSearch/transcript.ts@@ -15,6 +15,7 @@ import { lineToEvents, newTurnState } from '../normalize.js'import { AgyNormalizer } from '../../engines/agy/normalizer.js'import { AmpNormalizer } from '../../engines/amp/normalizer.js'import { CodexNormalizer } from '../../engines/codex/normalizer.js'+import { epochMs } from './externals/support.js'import { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'import { CursorNormalizer } from '../../engines/cursor/normalizer.js'@@ -48,11 +49,13 @@ export function lineNormalizer(engine: string, sessionId: string): LineNormalizeconst normalizer = new CursorNormalizer('live', sessionId)return (line) => normalizer.ingest(line)}- case 'muse': return ingestWith(new MuseNormalizer())+ // A Muse session log mirrors its sub-agents' and reminders' streams: only its own is the conversation.+ case 'muse': return kept(ingestWith(new MuseNormalizer()), (line) => museOwnStream(line, sessionId))case 'amp': return ingestWith(new AmpNormalizer())case 'grok': return ingestWith(new GrokNormalizer())case 'agy': return ingestWith(new AgyNormalizer())- case 'copilot': return ingestWith(new CopilotNormalizer())+ // A Copilot session file holds its sub-agents' events too, and prompts nobody typed.+ case 'copilot': return kept(ingestWith(new CopilotNormalizer()), copilotOwnLine)case 'pi': return ingestWith(new PiNormalizer('live'))case 'commandcode': return ingestWith(new CommandCodeNormalizer('live'))default: return null@@ -105,6 +108,34 @@ function ingestWith(normalizer: { ingest(line: string): LiveEvent[] }): LineNormreturn (line) => normalizer.ingest(line)}+/** [normalize], for the lines [keep] accepts only. */+function kept(normalize: LineNormalizer, keep: (line: string) => boolean): LineNormalizer {+ return (line) => keep(line) ? normalize(line) : []+}++const MUSE_STREAM = /"stream"\s*:\s*\{[^{}]*"id"\s*:\s*"([^"]+)"/++/** Whether a Muse record belongs to [sessionId]'s own stream (a record naming none is kept). */+export function museOwnStream(line: string, sessionId: string): boolean {+ const stream = MUSE_STREAM.exec(line)?.[1]+ return !stream || stream === sessionId+}++/**+ * Whether a Copilot event is the conversation's own: not a sub-agent's (those carry `agentId`), and not+ * a prompt nobody typed (a skill's or another agent's, whose `source` is `skill-…` or `agent-…`, or+ * an autopilot continuation).+ */+export function copilotOwnLine(line: string): boolean {+ if (!line.includes('"agentId"') && !line.includes('"source"') && !line.includes('isAutopilotContinuation')) return true+ let event: { agentId?: unknown; type?: unknown; data?: { source?: unknown; isAutopilotContinuation?: unknown } }+ try { event = JSON.parse(line) } catch { return true }+ if (typeof event.agentId === 'string' && event.agentId) return false+ if (event.type !== 'user.message') return true+ const source = typeof event.data?.source === 'string' ? event.data.source : ''+ return !/^(?:skill|agent)-/.test(source) && event.data?.isAutopilotContinuation !== true+}+/*** Records that carry only tool output, reasoning or accounting, told apart by their opening bytes.* Skipping them is safe because the turn collector reads prompts, answer text and tool calls only;@@ -128,13 +159,26 @@ export function skipPredicate(engine: string): ((head: string) => boolean) | nul}const TIMESTAMP = /"timestamp"\s*:\s*"([^"]{10,40})"/+/** The fields other engines date their lines with: Grok's epoch seconds, Muse's microseconds,+ * Antigravity's ISO `created_at`. */+const OTHER_TIMES = [+ /"timestamp"\s*:\s*(\d{9,19}(?:\.\d+)?)[,}]/,+ /"recorded_at"\s*:\s*(\d{9,19})[,}]/,+ /"created_at"\s*:\s*"([^"]{10,40})"/,+]-/** When a transcript line was written, from its own `timestamp` field; null when it has none. */+/** When a transcript line was written, from its own time field; null when it has none. */export function lineTime(line: string): number | null {- const match = TIMESTAMP.exec(line)- if (!match) return null- const at = Date.parse(match[1])- return Number.isFinite(at) ? at : null+ const iso = TIMESTAMP.exec(line)+ if (iso) {+ const at = Date.parse(iso[1])+ return Number.isFinite(at) ? at : null+ }+ for (const pattern of OTHER_TIMES) {+ const match = pattern.exec(line)+ if (match) return epochMs(match[1])+ }+ return null}export interface LineVisit {diff --git a/cli/src/lib/sqliteRead.spec.ts b/cli/src/lib/sqliteRead.spec.tsindex 7264b1c72..4030c0f8b 100644--- a/cli/src/lib/sqliteRead.spec.ts+++ b/cli/src/lib/sqliteRead.spec.ts@@ -1,10 +1,10 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { execFileSync } from 'node:child_process'-import { chmodSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import {- builtinSqlite, closeSqliteHandles, inlineSqlParams, overrideBuiltinSqlite, sqliteReadAll,+ builtinSqlite, closeSqliteHandles, idleWalStore, inlineSqlParams, overrideBuiltinSqlite, sqliteReadAll,} from './sqliteRead.js'const hasCli = (() => {@@ -63,6 +63,7 @@ withCli('sqliteReadAll', () => {['cli', () => overrideBuiltinSqlite(null)],...(hasBuiltin ? [['builtin', () => overrideBuiltinSqlite(undefined)] as ['builtin', () => void]] : []),]+ const withBuiltin = hasBuiltin ? it : it.skipfor (const [via, select] of paths) {describe(`via ${via}`, () => {@@ -102,6 +103,56 @@ withCli('sqliteReadAll', () => {expect(Date.now() - started).toBeLessThan(5_000)})+ // An engine's idle store must come back exactly as it was: no -wal or -shm made beside it (they+ // would be the daemon's, in the engine's folder, and a held handle keeps the engine from tidying).+ it('reads an idle WAL store without creating anything beside it, and a live one live', async () => {+ run(db, 'PRAGMA journal_mode=WAL;')+ expect(existsSync(`${db}-wal`)).toBe(false)+ expect(idleWalStore(db)).toBe(true)+ const idle = await sqliteReadAll(db, 'SELECT count(*) AS n FROM message;', [])+ expect(idle).toEqual({ ok: true, via, rows: [{ n: 3 }] })+ expect(existsSync(`${db}-wal`)).toBe(false)+ expect(existsSync(`${db}-shm`)).toBe(false)+ if (!hasBuiltin) return+ // Its engine opens it and writes: the next read is live, and sees the new row.+ // The engine's own connection, whichever way this test reads.+ type Writer = { exec(sql: string): void; close(): void }+ const sqlite = (process as unknown as { getBuiltinModule(id: string): { DatabaseSync: new (path: string) => Writer } })+ .getBuiltinModule('node:sqlite')+ const writer = new sqlite.DatabaseSync(db)+ try {+ writer.exec("INSERT INTO message VALUES ('m9','ses_c',9,'{}')")+ expect(existsSync(`${db}-wal`)).toBe(true)+ expect(idleWalStore(db)).toBe(false)+ expect(await sqliteReadAll(db, 'SELECT count(*) AS n FROM message;', [])).toEqual({ ok: true, via, rows: [{ n: 4 }] })+ } finally {+ writer.close()+ }+ })++ withBuiltin('sees a WAL write that finishes between reads, without leaving sidecars', async () => {+ run(db, 'PRAGMA journal_mode=WAL;')+ const query = "SELECT time_created AS time FROM message WHERE id = 'm1';"+ expect(await sqliteReadAll(db, query)).toEqual({ ok: true, via, rows: [{ time: 1 }] })+ expect(await sqliteReadAll(db, query)).toEqual({ ok: true, via, rows: [{ time: 1 }] })+ // The engine starts, updates an existing row, checkpoints, and closes before the next poll.+ // There is no WAL left to tell a cached immutable reader that its snapshot is stale.+ type Writer = { exec(sql: string): void; close(): void }+ const sqlite = (process as unknown as { getBuiltinModule(id: string): { DatabaseSync: new (path: string) => Writer } })+ .getBuiltinModule('node:sqlite')+ const writer = new sqlite.DatabaseSync(db)+ try {+ writer.exec("UPDATE message SET time_created = 9 WHERE id = 'm1'")+ } finally {+ writer.close()+ }+ expect(existsSync(`${db}-wal`)).toBe(false)+ expect(existsSync(`${db}-shm`)).toBe(false)+ expect(await sqliteReadAll(db, query)).toEqual({ ok: true, via, rows: [{ time: 9 }] })+ expect(existsSync(`${db}-wal`)).toBe(false)+ expect(existsSync(`${db}-shm`)).toBe(false)+ })+it('reports a missing store as transient, and creates nothing', async () => {const result = await sqliteReadAll(join(dir, 'absent.db'), 'SELECT 1;', [])expect(result.ok).toBe(false)@@ -112,8 +163,6 @@ withCli('sqliteReadAll', () => {})}- const withBuiltin = hasBuiltin ? it : it.skip-// The handle is cached per path for the pollers' sake; a store rebuilt under the same name must// not keep answering from the file that was there before.withBuiltin('follows a store replaced on disk', async () => {@@ -127,6 +176,13 @@ withCli('sqliteReadAll', () => {expect(second).toEqual({ ok: true, via: 'builtin', rows: [{ n: 1 }] })})+ it('never reads a store in the older journal mode, or no store, as idle', () => {+ expect(idleWalStore(db)).toBe(false)+ expect(idleWalStore(join(dir, 'absent.db'))).toBe(false)+ writeFileSync(join(dir, 'short.db'), 'tiny')+ expect(idleWalStore(join(dir, 'short.db'))).toBe(false)+ })+it('reports missing when neither reader exists', async () => {overrideBuiltinSqlite(null)const realPath = process.env.PATHdiff --git a/cli/src/lib/sqliteRead.ts b/cli/src/lib/sqliteRead.tsindex 1c7e5bf40..17a885d76 100644--- a/cli/src/lib/sqliteRead.ts+++ b/cli/src/lib/sqliteRead.ts@@ -21,7 +21,8 @@*/import { execFile } from 'node:child_process'-import { statSync } from 'node:fs'+import { closeSync, existsSync, openSync, readSync, statSync } from 'node:fs'+import { pathToFileURL } from 'node:url'import { promisify } from 'node:util'const execFileAsync = promisify(execFile)@@ -55,7 +56,29 @@ interface DatabaseLike {exec(sql: string): voidclose(): void}-interface DatabaseConstructor { new (path: string, options: { readOnly: boolean }): DatabaseLike }+interface DatabaseConstructor { new (path: string | URL, options: { readOnly: boolean }): DatabaseLike }++/**+ * A WAL store its engine is not using right now: its header says WAL (file format versions 2) and no+ * `-wal` file is beside it. Opening one read-only would CREATE `-wal` and `-shm` in the engine's+ * folder — and a handle held open keeps the engine from tidying them away when it next closes the+ * store. Opened immutable it creates nothing, and nothing can be changing it: a writer would have+ * made the `-wal` first. A store in the older journal mode is never opened immutable, since a writer+ * may be changing it in place; it gets the ordinary locked read.+ */+export function idleWalStore(dbPath: string): boolean {+ if (existsSync(`${dbPath}-wal`)) return false+ let fd: number | null = null+ try {+ fd = openSync(dbPath, 'r')+ const header = Buffer.alloc(20)+ return readSync(fd, header, 0, 20, 0) === 20 && header[18] === 2 && header[19] === 2+ } catch {+ return false+ } finally {+ if (fd !== null) closeSync(fd)+ }+}let builtin: DatabaseConstructor | null | undefined@@ -88,7 +111,7 @@ export function builtinSqlite(): DatabaseConstructor | null {return builtin}-interface Handle { db: DatabaseLike; dev: number; ino: number }+interface Handle { db: DatabaseLike; dev: number; ino: number; immutable: boolean; stamp: string }/** One open handle per store: the readers poll every second, and opening is the expensive part. */const handles = new Map<string, Handle>()@@ -99,14 +122,22 @@ const handles = new Map<string, Handle>()* from a database nobody writes to any more — a poller that never sees another row, with no error.*/function openHandle(Database: DatabaseConstructor, dbPath: string, busyTimeoutMs: number): DatabaseLike {- const { dev, ino } = statSync(dbPath)+ const { dev, ino, size, mtimeMs, ctimeMs } = statSync(dbPath)+ const stamp = `${size}:${mtimeMs}:${ctimeMs}`+ // 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)- if (cached && cached.dev === dev && cached.ino === ino) return cached.db+ // 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.dbif (cached) dropHandle(dbPath)- const db = new Database(dbPath, { readOnly: true })+ 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 })+ handles.set(dbPath, { db, dev, ino, immutable, stamp })return db}@@ -191,7 +222,7 @@ async function readCli(// `mode=ro` so a path that does not exist yet is an error, not a freshly created empty store.;({ stdout } = await execFileAsync('sqlite3',- ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', `file:${uriPath(dbPath)}?mode=ro`, inlined],+ ['-json', '-cmd', '.timeout 3000', '-cmd', 'PRAGMA query_only=1', `file:${uriPath(dbPath)}?mode=ro${idleWalStore(dbPath) ? '&immutable=1' : ''}`, inlined],{ maxBuffer, timeout: timeoutMs, killSignal: 'SIGKILL' },))} catch (err) {diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.tsindex 52f9e6218..da1683a1c 100644--- a/cli/src/lib/tmux.spec.ts+++ b/cli/src/lib/tmux.spec.ts@@ -280,7 +280,13 @@ describe('tmux process primitives', () => {expect(resumeSessionId('grok', 'grok -r 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBe('53d3843c-724e-47ff-ae3a-9fedfa328bba')expect(resumeSessionId('commandcode', 'cmd -r Greeting')).toBeNull()- expect(resumeSessionId('devin', 'devin --resume 53d3843c-724e-47ff-ae3a-9fedfa328bba')).toBeNull()+ // Devin's ids are word slugs; a bare word is not one.+ expect(resumeSessionId('devin', 'devin --resume brisk-otter')).toBe('brisk-otter')+ expect(resumeSessionId('devin', 'devin -r blue-agustinia --model x')).toBe('blue-agustinia')+ expect(resumeSessionId('devin', 'devin -r latest')).toBeNull()+ // Hermes takes -r too; opencode's --fork names the parent, never the session.+ expect(resumeSessionId('hermes', 'hermes -r 20260927_101500_ab12cd')).toBe('20260927_101500_ab12cd')+ expect(resumeSessionId('opencode', 'opencode -s ses_abc --fork')).toBeNull()})it('reads a claude/codex resume id from argv, but never the parent of a fork', () => {diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex dfc0f8374..47772096f 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -604,14 +604,18 @@ const RESUME_ARGS: Partial<Record<RegisteredSession['engine'], { flags: string[]claude: { flags: ['--resume', '-r'], id: /^[0-9a-f-]{16,}$/i, unless: ['--fork-session'] },codex: { flags: ['resume'], id: /^[0-9a-f-]{16,}$/i },cursor: { flags: ['--resume'], id: /^[0-9a-f-]{16,}$/i },- opencode: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/ },+ // `--fork` continues from the id but writes a NEW session, so the id in argv is the parent's.+ opencode: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/, unless: ['--fork'] },// Kilo inherits opencode's resume flags and its `ses_` id prefix — measured on this machine's kilo.db:// `ses_024a007fdffe11yG68JPxsHJly`. `--fork` is deliberately NOT here: it CONTINUES from an id but// writes a NEW session, so the id in argv is the parent's and would bind the agent to the wrong row.- kilo: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/ },+ kilo: { flags: ['--session', '-s'], id: /^ses_[A-Za-z0-9]+$/, unless: ['--fork'] },pi: { flags: ['--session', '--session-id'], id: /^[0-9a-f][0-9a-f-]{7,}$/i },// Hermes ids are timestamps: 20260728_115628_f2c86a.- hermes: { flags: ['--resume'], id: /^\d{8}_\d{6}_[0-9a-z]+$/i },+ // Hermes ids are timestamps (20260728_115628_f2c86a), or uuids for an editor's (ACP) sessions.+ hermes: { flags: ['--resume', '-r'], id: /^(?:\d{8}_\d{6}_[0-9a-z]+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i },+ // `devin -r <id>` / `--resume <id>`: ids are word slugs (`brisk-otter`).+ devin: { flags: ['--resume', '-r'], id: /^[a-z0-9]+(?:-[a-z0-9]+)+$/ },commandcode: { flags: ['--resume', '-r', '--session'], id: /^[0-9a-f-]{16,}$/i },// `muse resume <uuid>` names the session; `muse resume --last` does not, so that form falls through// to the scan in sessionRepair instead.diff --git a/desktop/lib/state/session_content_search.dart b/desktop/lib/state/session_content_search.dartindex 0f60c501a..913f7cea1 100644--- a/desktop/lib/state/session_content_search.dart+++ b/desktop/lib/state/session_content_search.dart@@ -130,7 +130,14 @@ class SessionContentHit {title: title is String ? title : '',open: external['open'] == true,openIn: switch (external['openIn']) {- final String where when where == 'terminal' || where == 'app' => where,+ final String where+ when const {+ 'terminal',+ 'app',+ 'harness',+ 'maybe',+ }.contains(where) =>+ where,_ => null,},);diff --git a/desktop/lib/state/session_tail.dart b/desktop/lib/state/session_tail.dartindex bcf23e246..bf8a2efc7 100644--- a/desktop/lib/state/session_tail.dart+++ b/desktop/lib/state/session_tail.dart@@ -86,7 +86,12 @@ class SessionTail {(reply['external'] as Map)['open'] == true,openIn: switch (reply['external']) {{'openIn': final String where}- when where == 'terminal' || where == 'app' =>+ when const {+ 'terminal',+ 'app',+ 'harness',+ 'maybe',+ }.contains(where) =>where,_ => null,},diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dartindex e4a1238d2..6f7d6f042 100644--- a/desktop/lib/state/swarm_navigation.dart+++ b/desktop/lib/state/swarm_navigation.dart@@ -265,9 +265,11 @@ class ExternalSessionRef {/// processes writing one conversation.final bool open;- /// Where it is open: `terminal`, which Harness can take it over from, or- /// `app`, which it cannot. Null when it is not open, or the machine predates- /// taking over.+ /// Where it is open: `terminal`, which Harness can take it over from; `app`,+ /// which it cannot; `harness`, one of Harness's own panes whose agent the+ /// machine is still binding; or `maybe` a terminal, whose process was started+ /// on it and may have moved on (never stopped from here). Null when it is not+ /// open, or the machine predates taking over.final String? openIn;/// Open, and only in a terminal: opening it here moves it, once asked.@@ -278,10 +280,22 @@ class ExternalSessionRef {'claude-app' => 'Claude app','codex-app' => 'Codex app','editor' => 'editor',+ 'app' => 'app',_ => 'terminal',};++ /// The engine, as a person calls it.+ String get engineName => externalEngineName(engine);}+/// An engine's name for a conversation Harness did not start: Claude Code and+/// Codex by their products' names, every other engine by its own.+String externalEngineName(String engine) => switch (engine) {+ 'claude' => 'Claude Code',+ 'codex' => 'Codex',+ final other => engineIdentity(other).label,+};+String externalDestinationId(String machineId, String sessionId) =>'external:$machineId:$sessionId';diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dartindex 5c64e4b6e..79ae96e0f 100644--- a/desktop/lib/state/swarm_search.dart+++ b/desktop/lib/state/swarm_search.dart@@ -1542,9 +1542,13 @@ class SwarmSearchController extends ChangeNotifier {// One in a terminal can be moved here: opening it asks how.final where = previewed?.openIn ?? external.openIn;if (where == 'terminal') return null;- return external.origin == 'terminal' && where == null- ? 'Open in another terminal'- : 'Open in the ${external.originLabel}';+ if (where == 'harness') return 'Already in Harness';+ if (where == 'maybe') return 'May be open in a terminal';+ if (external.origin == 'terminal') {+ // A machine that predates taking over; or no terminal holds it now.+ return where == null ? 'Open in another terminal' : 'Open in an app';+ }+ return 'Open in the ${external.originLabel}';}final machine = app.stateOf(row.machineId ?? '');return machine == null || machine.nodeOnline == false@@ -1681,11 +1685,7 @@ SwarmDestination externalSessionDestination(ExternalSessionRef external, {String machineLabel = '',}) {- final engine = switch (external.engine) {- 'claude' => 'Claude Code',- 'codex' => 'Codex',- final other => other,- };+ final engine = external.engineName;final folder =external.cwd.split('/').where((part) => part.isNotEmpty).lastOrNull ??external.cwd;diff --git a/desktop/lib/state/take_over.dart b/desktop/lib/state/take_over.dartindex f6aab54d5..004cb7b59 100644--- a/desktop/lib/state/take_over.dart+++ b/desktop/lib/state/take_over.dart@@ -1,3 +1,8 @@+/// The engines that can resume with a first message, so Take Over Now can tell+/// them to continue (`FIRST_PROMPT_ARGS` in cli/src/lib/engineLaunch.ts). Any+/// other resumes where it was stopped and waits.+const engineResumesWithMessage = {'claude', 'codex', 'opencode'};+/// How to take a conversation over from the terminal that has it open: the/// `takeOver` of `agent_create`.enum TakeOver {diff --git a/desktop/lib/widgets/take_over_dialog.dart b/desktop/lib/widgets/take_over_dialog.dartindex d417bba19..3987a52c9 100644--- a/desktop/lib/widgets/take_over_dialog.dart+++ b/desktop/lib/widgets/take_over_dialog.dart@@ -1,6 +1,7 @@import 'package:flutter/material.dart';import '../shortcuts/app_keymap.dart';+import '../state/swarm_navigation.dart' show externalEngineName;import '../state/take_over.dart';import '../terminal/terminal_text.dart';import 'box_chrome.dart';@@ -62,11 +63,7 @@ class _TakeOverPromptState extends State<_TakeOverPrompt> {void _pick(TakeOver? choice) => Navigator.pop(context, choice);- String get _engineName => switch (widget.engine) {- 'claude' => 'Claude Code',- 'codex' => 'Codex',- final other => other,- };+ String get _engineName => externalEngineName(widget.engine);@overrideWidget build(BuildContext context) {@@ -113,8 +110,11 @@ class _TakeOverPromptState extends State<_TakeOverPrompt> {const SizedBox(height: 8),Text(busy- ? 'Wait moves it here when this turn ends. '- 'Take Over Now stops the turn and tells it to continue.'+ ? engineResumesWithMessage.contains(widget.engine)+ ? 'Wait moves it here when this turn ends. '+ 'Take Over Now stops the turn and tells it to continue.'+ : 'Wait moves it here when this turn ends. '+ 'Take Over Now stops the turn; it picks up when you ask.': 'The conversation is kept.',style: boxMonoStyle(color: kBoxFaint),),diff --git a/desktop/test/session_search_rendering_test.dart b/desktop/test/session_search_rendering_test.dartindex fa8045e42..862fbbd5b 100644--- a/desktop/test/session_search_rendering_test.dart+++ b/desktop/test/session_search_rendering_test.dart@@ -308,6 +308,9 @@ void main() {const session = '01a0c4ad-de5e-7000-8000-000000000001';const busy = '01a0c4ad-de5e-7000-8000-000000000002';const movable = '01a0c4ad-de5e-7000-8000-000000000003';+ const binding = '01a0c4ad-de5e-7000-8000-000000000004';+ const inApp = '01a0c4ad-de5e-7000-8000-000000000005';+ const maybe = '01a0c4ad-de5e-7000-8000-000000000006';Map<String, dynamic> external(String id, {required bool open,@@ -338,6 +341,9 @@ void main() {external(session, open: false),external(busy, open: true),external(movable, open: true, openIn: 'terminal'),+ external(binding, open: true, openIn: 'harness'),+ external(inApp, open: true, openIn: 'app'),+ external(maybe, open: true, openIn: 'maybe'),],},tail: (payload) => {@@ -423,6 +429,21 @@ void main() {);expect(search.sessionUnavailable(inTerminal), isNull);expect(search.canSubmit(inTerminal), isTrue);+ // One of Harness's own panes has it (an agent still being bound), or an app does: not here.+ final bound = search.rows.firstWhere(+ (row) => row.external?.sessionId == binding,+ );+ expect(search.sessionUnavailable(bound), 'Already in Harness');+ expect(search.canSubmit(bound), isFalse);+ final heldByApp = search.rows.firstWhere(+ (row) => row.external?.sessionId == inApp,+ );+ expect(search.sessionUnavailable(heldByApp), 'Open in an app');+ final guessed = search.rows.firstWhere(+ (row) => row.external?.sessionId == maybe,+ );+ expect(search.sessionUnavailable(guessed), 'May be open in a terminal');+ expect(search.canSubmit(guessed), isFalse);// Previewed like any session: what it is, where it ran, its latest turn.while (search.selected?.id != row.id) {diff --git a/desktop/test/take_over_dialog_test.dart b/desktop/test/take_over_dialog_test.dartnew file mode 100644index 000000000..a274bc8c4--- /dev/null+++ b/desktop/test/take_over_dialog_test.dart@@ -0,0 +1,86 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/widgets/take_over_dialog.dart';++void main() {+ Future<TakeOver?> ask(+ WidgetTester tester, {+ required String engine,+ required bool busy,+ String? pick,+ }) async {+ TakeOver? chosen;+ var answered = false;+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => TextButton(+ onPressed: () async {+ chosen = await askTakeOver(+ context,+ title: 'Retention cohorts',+ engine: engine,+ busy: busy,+ machine: 'M2',+ );+ answered = true;+ },+ child: const Text('open'),+ ),+ ),+ ),+ );+ await tester.tap(find.text('open'));+ await tester.pumpAndSettle();+ if (pick != null) {+ await tester.tap(find.byKey(Key(pick)));+ await tester.pumpAndSettle();+ expect(answered, isTrue);+ }+ return chosen;+ }++ testWidgets(+ 'an idle session is moved; the engine is named as people call it',+ (tester) async {+ final chosen = await ask(+ tester,+ engine: 'claude',+ busy: false,+ pick: 'take-over-move',+ );+ expect(chosen, TakeOver.idle);+ },+ );++ testWidgets(+ 'mid-turn, the prompt promises "continue" only to an engine that can take one',+ (tester) async {+ await ask(tester, engine: 'codex', busy: true);+ expect(+ find.text('Codex is working on it in a terminal.'),+ findsOneWidget,+ );+ expect(find.textContaining('tells it to continue'), findsOneWidget);+ await tester.tap(find.byKey(const Key('take-over-now')));+ await tester.pumpAndSettle();++ await ask(tester, engine: 'grok', busy: true);+ expect(find.text('Grok is working on it in a terminal.'), findsOneWidget);+ expect(find.textContaining('tells it to continue'), findsNothing);+ expect(find.textContaining('it picks up when you ask'), findsOneWidget);+ expect(find.text('M2'), findsOneWidget);+ },+ );++ testWidgets('Wait waits, and Cancel leaves it where it is', (tester) async {+ expect(+ await ask(tester, engine: 'opencode', busy: true, pick: 'take-over-wait'),+ TakeOver.wait,+ );+ await ask(tester, engine: 'pi', busy: false);+ await tester.tap(find.text('Cancel'));+ await tester.pumpAndSettle();+ expect(find.text('Move to Harness'), findsNothing);+ });+}diff --git a/docs/research/2026-09-26-session-search.md b/docs/research/2026-09-26-session-search.mdindex 394a08df0..2799ecbaf 100644--- a/docs/research/2026-09-26-session-search.md+++ b/docs/research/2026-09-26-session-search.md@@ -282,8 +282,10 @@ socket, about 0.4 s from another machine over the relay.## Conversations Harness did not start-⌘P also finds Claude Code and Codex conversations run in a terminal or in the engines' own apps, and-Enter opens one as a harness resuming it (`lib/sessionSearch/external.ts`).+⌘P also finds conversations run outside Harness, in a terminal, an editor or an engine's own app, for+every engine that keeps them on this computer. Enter opens one as a harness resuming it+(`lib/sessionSearch/external.ts`; one provider per engine in `externals/`, see+[Every engine](#every-engine)). Claude Code and Codex came first and are described here.- **Found on disk.** Every local Codex session, whether from the terminal, the Codex app or ascript, is a rollout under `~/.codex/sessions/YYYY/MM/DD/`. Its first line says who wrote it:@@ -344,6 +346,79 @@ own terminals:- *Take Over Now* resumed with `continue`.- Each terminal got its cursor back.+### Every engine++Thirteen engines (`EXTERNAL_ENGINES`). Each provider reads only its engine's store. It never writes+to it, never starts the engine, and never logs a process's arguments, which can carry a key.++| Engine | Where its conversations are | Left out | Who has one open | Mid-turn |+| --- | --- | --- | --- | --- |+| Claude Code | `~/.claude/projects/<folder>/<id>.jsonl` | `sdk-cli` | `sessions/<pid>.json` | the record's `status` |+| Codex | `~/.codex/sessions/…/rollout-*.jsonl` | `exec`, sub-agents | the rollout held open | last task event |+| Cursor | `chats/<md5(folder)>/<id>/store.db` + `meta.json`; transcript under the data folder | sub-agents, empty chats, no `store.db` | `store.db` held open; else `--resume <id>` | the transcript |+| OpenCode, Kilo | `opencode.db` / `kilo.db` (SQLite) | `parent_id`, archived, headless `run`, never used | `-s <id>` (not with `--fork`) | last message |+| Hermes | `state.db` per home and profile | gateways, cron, delegation children; a compression chain is one conversation under its newest id | `runtime/active_sessions.json`; else `-r <id>` | compression lock, last message |+| Devin | `sessions.db` | `hidden` | `session_locks/<id>.lock` with a live Devin pid; else `-r <id>` | last message node |+| Pi | `sessions/--<folder>--/<time>_<id>.jsonl` (or the moved folder) | nothing: Pi's own picker lists every run | argv only | last message |+| Command Code | `projects/<slug>/<id>.jsonl` + `.meta.json` | `entrypoint: 'print'`, files before the v3 header | argv only | unknown |+| Muse | `sessions/YYYY/MM/DD/<id>/session.jsonl` | sub-agents, Muse's own reminder sessions | argv only | an open run |+| Grok | `sessions/<folder>/<id>/` (`summary.json`, `updates.jsonl`) | headless, sub-agents | `active_sessions.json` with a live pid; a leader or server is an app | last update |+| Antigravity | `brain/<id>/…/transcript_full.jsonl`, placed by `history.jsonl` | sub-agents, a conversation no file places | `presence/<id>.lock` held open | unknown |+| Copilot | `session-state/<id>/` (`events.jsonl`, `workspace.yaml`) | cloud tasks, detached rem-agent runs, SDK programs | newest `inuse.<pid>.lock`; the SDK runtime is an app | the event stream |++Amp is not one: its threads live on its server, and nothing on this computer holds what was said.++**Only exact evidence stops a process.** A record, a lock whose pid is alive, is that engine, and+started before the lock was written, or a file the process holds open: that session is `open` in+`terminal` and can be taken over. When only a process's arguments name the session, it is `maybe`:+the process started on that session and may have moved to another since (`/resume` in its TUI).+Harness does not open it a second time, but never stops that process+(`SESSION_OPEN_ELSEWHERE`, "It may be open in OpenCode in a terminal"). The same goes when Harness's+own panes cannot be listed. A process with no terminal, or a shared server (a Grok leader,+`kilo serve`, the Codex app server, Copilot's SDK runtime), is an `app`. One in a Harness pane is+`harness`. An engine whose store cannot say whether a turn is running counts as busy, so the person+is asked first.++**Resuming** uses each engine's own flag (`LAUNCH_RESUME_FLAG`), in the session's folder: `--resume`+(Claude, Cursor, Hermes with its profile's `-p`, Devin, Command Code, Grok, Copilot), `--session`+(OpenCode, Kilo, Pi), `resume` (Codex, Muse) and `--conversation` (Antigravity). *Take Over Now* sends `continue` only to+engines that take a first message on the command line (Claude, Codex, OpenCode). The others resume+and wait for the person.++**Edge cases handled** (each with a test; all new code at 100% statement, branch, function and line+coverage, no ignores):+- A pid reused after a crash: a record or lock older than its process's start is ignored. This fixes+ a Claude Code bug in 0.3.13, where a stale `sessions/<pid>.json` could name an unrelated process.+- Before stopping, the daemon checks again that the same process still has the session, and the Wait+ watcher checks on every loop.+- A store being written: a head that is not finished yet is read again when the file changes. An idle+ SQLite WAL store is opened `immutable`, so reading never leaves `-wal` or `-shm` files behind.+ A main-file change also invalidates its cached immutable handle, catching a writer that opens,+ checkpoints and closes between scans.+- Folder names that lose information (Cursor, Pi, Command Code slugs) are never read as the folder.+ The folder comes from the store itself, or the conversation is left out.+- One engine's store failing keeps its last good list. Harness's own data folder is never offered.++**Checked on this machine** through a sandboxed daemon, read-only against the real stores:+- 229 sessions indexed, 210 of them outside conversations from Claude Code, Codex, Grok, Hermes+ (editor and terminal) and OpenCode, each previewed.+- Stand-in engines confirmed the resume launches: OpenCode `--session`, Hermes `--resume` in its+ folder, and Grok `--resume`.++Take-over was checked with made-up stores and stand-in processes:+- A Grok session busy in a terminal was refused as busy. *Take Over Now* stopped it and resumed it+ without `continue`. *Wait* held until `turn_completed` landed, then did the same.+- An OpenCode session named only by `-s` was refused both times, and its process was left running.+- A stale `active_sessions.json` entry with a dead pid claimed nothing.++**Found in Harness's own code, not changed here:**+- Cursor's config and data folders are one `CURSOR_HOME` in `discovery.ts`, `subagent.ts` and+ `oneshot.ts`. `CURSOR_CONFIG_DIR` and `CURSOR_DATA_DIR` split them.+- Setting `OPENCODE_DATA_DIR` for a recap does not keep the recap out of the person's store.+- The hook server and notifier treat a Hermes `tui` session as a sub-agent.+- Command Code's slug in Harness does not match the one Command Code writes.+- Pi and Command Code leave no process record. If they ever do, it becomes their owner evidence.+## Protocol`session_search { query, limit, from?, to? }` → `{ hits: [{ agentId, sessionId, engine, turn, at,diff --git a/docs/research/2026-09-27-external-engines-handoff.md b/docs/research/2026-09-27-external-engines-handoff.mdnew file mode 100644index 000000000..45fc41f11--- /dev/null+++ b/docs/research/2026-09-27-external-engines-handoff.md@@ -0,0 +1,135 @@+# Handoff: external sessions for every engine++Continued from `external-engines` at `40f12db0` on branch `codex/external-engines`.+Rebased onto `93f148d6` (`origin/main`, including #391 and #392) without conflicts.+The original branch and worktree are preserved.++## What it is++⌘P and the welcome page already found Claude Code and Codex conversations that Harness did not start,+and could take one over from a terminal (#380, #385). This branch does the same for every engine that+keeps its conversations on this computer: Cursor, OpenCode, Kilo, Hermes, Devin, Pi, Command Code,+Muse, Grok, Antigravity and Copilot. Amp is left out: its threads are on its server.++The design, each engine's store and evidence, the edge cases and the test results are in+[the session search note](2026-09-26-session-search.md#every-engine). Read that first.++## Where the code is++- `cli/src/lib/sessionSearch/externals/`: one provider per engine (`scan`, `owners`, `busy`), with+ `types.ts`, `support.ts` (file, process and memo helpers) and `index.ts` (paths and the provider+ list). Every file has a spec beside it.+- `cli/src/lib/sessionSearch/external.ts`: `ExternalSessions` (one list), `OpenSessions` (who has a+ session open, as `terminal`, `app`, `harness` or `maybe`), `stopSessionOwner`.+- `cli/src/cli.ts`: `adoptableSession`, `heldBy`, `takeOverWhenIdle`, and the `onCreateAgent` resume+ path.+- `cli/src/lib/sqliteRead.ts`: an idle WAL store is opened `immutable=1`, so reading never creates+ `-wal`/`-shm` files in an engine's folder. Its cached handle is invalidated when the main file's+ size, modification time or change time moves, including a writer that opens and closes between scans.+- Index: `transcript.ts` (`lineTime`, `copilotOwnLine`, `museOwnStream`), `indexer.ts`+ (`historyPass` for database engines).+- Desktop: `swarm_search.dart` (`sessionUnavailable`), `take_over.dart`+ (`engineResumesWithMessage`), `take_over_dialog.dart`, `swarm_navigation.dart`+ (`externalEngineName`).++## Rules this code keeps++- Never write to an engine's store. Never log a scanned process's arguments (they can carry keys).+- Never stop a process on a guess. Only a record, a live lock, or a file held open counts. A process's+ arguments alone make the session `maybe`: refused, never stopped.+- `continue` is sent on *Take Over Now* only to engines that take a first message (Claude, Codex,+ OpenCode).++## State after continuation++Checked on macOS with Node 22.23.1, Flutter 3.47.2 and Dart 3.13.2:++- CLI: `npm run typecheck`, `npm run build`, and the full `npx vitest run` pass: **5,168 passed,+ 63 skipped**, 304 passing files. Both `hookNotify` and `backendSocket.gridReads` passed this run;+ #390 remains a separate open PR.+- Focused CLI run: **556 tests in 29 files** pass, covering session search, SQLite reads, launch,+ resume, tmux, and the changed Hermes/Devin helpers. `external.ts` and all `externals/*.ts` have+ **100% statements, branches, functions and lines**, with no coverage ignores.+- Desktop: **3,682 passed, 12 skipped, 33 failed** in the complete suite. All 33 failures reproduced+ when their 13 files were run at clean `93f148d6`; the baseline also had one extra test-file load+ error. `flutter analyze` reports the same 18 diagnostics on both branches (one error, one warning,+ 16 informational diagnostics), including the missing `WorkspaceBarControl.selection` getter in+ `grid_model_picker_test.dart`.+- The original timer question is resolved: `environment_recheck_timer_test.dart` loads on both+ `40f12db0` and `244cfe71` and fails the same assertion at line 163: expected `unauthenticated`,+ observed `bootstrapping`. The same failure occurs on current main. It is not introduced here.+- The five affected desktop search/take-over files pass all **31 tests**. A separate synthetic+ Grok dialog fixture also passed and supplied+ [the PR screenshot](../../.github/assets/external-engines/take-over-grok.png).+- Real tmux 3.5a checks, with a temporary home and an explicit isolated socket: **9 passed,+ 9 skipped**. Discovery and process-only deletion passed for Claude, Codex, OpenCode, Pi, Hermes+ and Grok, including the installed Grok `agent` alias. Other engine binaries were unavailable.+- Real Herdr checks were attempted in a private isolated home: installed Herdr 0.9.1 speaks+ protocol 22, but Harness expects protocol 19. Setup rejects the connection, so none of its+ 26 cases ran. The fixture servers were stopped; this is not a passing Herdr result.+- Earlier end-to-end evidence from the original handoff, through a sandboxed daemon: real stores+ read-only (229 sessions indexed, 210 of them+ external), then take-over with made-up stores and stand-in engines (Grok *Now* and *Wait*, OpenCode+ `maybe` refused, stale lock ignored). Results are in the session search note; this continuation+ did not rerun that live-store scan.++The 33 desktop failures shared with main are in these files:++| File under `desktop/test/` | Failures |+| --- | ---: |+| `workspace_account_lifecycle_test.dart` | 8 |+| `boot_flow_widget_test.dart` | 4 |+| `workspace_expiry_screen_test.dart` | 4 |+| `machines_manager_test.dart` | 4 |+| `terminal_panel_presentation_test.dart` | 4 |+| `signout_recovery_test.dart` | 2 |+| `orchestrator_test.dart` | 1 |+| `local_cli_discovery_test.dart` | 1 |+| `environment_setup_screen_test.dart` | 1 |+| `grid_model_picker_test.dart` | 1 (load error) |+| `open_picker_rendering_test.dart` | 1 |+| `first_workspace_test.dart` | 1 |+| `environment_recheck_timer_test.dart` | 1 |++## Fixes from the continuation++- **Refresh an idle SQLite snapshot after a complete write cycle.** A cached immutable reader+ previously kept returning old rows if the engine wrote, checkpointed and closed between scans.+ A real SQLite regression fails before the fix and passes for both the built-in reader and CLI+ fallback afterward; neither leaves WAL/SHM files beside the idle store.+- **Rebuild existing search content with schema 10.** The new Muse/Copilot filters and transcript+ timestamps must apply to conversations indexed before this branch. Reader and rebuild tests+ cover schemas 8 and 9 as well as an older schema.++## Left to do++1. Review the PR against `main` and the baseline desktop failures above.+2. Reconcile merge order with #388, which changes `turns.ts` and reserves schema 9. If #388 lands+ first, keep schema 10 here after rebasing. If this branch lands first, #388 must use **11** when+ it lands, so an index already written by schema 10 rebuilds for its context filtering too.+3. The owner merges and releases (`make release-cli`, then the desktop release); never merge or+ release without their explicit go-ahead.++## Sandbox end-to-end recipe++Never run a test daemon or tmux against the person's real ones:++- `mkdir -p` the `TMUX_TMPDIR` folder first. tmux falls back to the real default server when it does+ not exist.+- Run with `env -u TMUX -u TMUX_PANE -u XDG_DATA_HOME -u XDG_CONFIG_HOME` and set `HOME=<sandbox>`,+ `PORT=<free port>`, `TMUX_TMPDIR=<folder>`, `ADAPTER_UPDATE_DISABLE=true`,+ `DISABLE_HOOK_INSTALL=true` and `DISABLE_GRID_INSTALL=true`.+- Point each engine's home at its store (read-only), or at a made-up one for take-over tests.+- Set `<ENGINE>_PATH` to a stand-in script that records its argv and forwards `--help`/`--version` to+ the real binary.+- Hold a session with a stand-in owner process in its own `tmux -S <socket>`.+- Afterwards, stop the sandbox daemon and kill both tmux servers. Check that no pane on the real+ server sits in the sandbox folder, and that no new `-wal`/`-shm` appeared in the engines' folders.++## Found in Harness's own code, not changed here++- Cursor's config and data folders are one `CURSOR_HOME` in `discovery.ts`, `subagent.ts` and+ `oneshot.ts`.+- `OPENCODE_DATA_DIR` does not keep a recap out of the person's OpenCode store.+- The hook server and notifier treat a Hermes `tui` session as a sub-agent.+- Command Code's slug in Harness does not match the one Command Code writes.