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
refactor(cli): move change-agent handoff into the edge host (#931)
Dee600f6def0924
diff --git a/cli/e2e/compat.e2e.ts b/cli/e2e/compat.e2e.tsindex 93fef09f9..5ac26d306 100644--- a/cli/e2e/compat.e2e.ts+++ b/cli/e2e/compat.e2e.ts@@ -18,7 +18,7 @@* sides' answers and every difference, for reading one by one.*/import { execFileSync, spawn } from 'node:child_process'-import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { hostname, tmpdir } from 'node:os'import { dirname, join } from 'node:path'import { afterAll, beforeAll, describe, expect, it } from 'vitest'@@ -279,6 +279,16 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {await ask(`terminal_info ${engine}`, 'terminal_info', { agentId: agent[engine] })await ask(`agent_read_file ${engine}`, 'agent_read_file', { agentId: agent[engine], path: 'README.md' })await ask(`git_pull_request ${engine}`, 'git_pull_request', { agentId: agent[engine] })+ // Quiet-machine QA: the handoff's edge-host move must preserve both the reply and what the next+ // engine actually reads. Empty/error replies cannot pass merely by matching each other.+ const handoff = await ask(`agent_handoff_prepare ${engine}`, 'agent_handoff_prepare', {+ agentId: agent[engine], changeId: '0123456789abcdef0123456789abcdef', targetEngine: engine === 'claude' ? 'codex' : 'claude',+ })+ expect(handoff.error, JSON.stringify(handoff)).toBeUndefined()+ expect(handoff.file).toEqual(expect.any(String))+ for (const [kind, path] of [['summary', handoff.file], ['transcript', handoff.file.replace(/\.md$/, '.transcript.md')]]) {+ answers[`handoff ${kind} ${engine}`] = walk(readFileSync(join(cwd(engine), path), 'utf8'))+ }}await ask('models_list', 'models_list')await ask('git_project_info', 'git_project_info', { path: cwd('claude') })@@ -337,6 +347,9 @@ async function scenario(d: IsolatedDaemon): Promise<Answers> {await ask('session_get codex while stopped', 'session_get', { sessionId: session.codex, limit: 1 })await ask('sessions_list codex while stopped', 'sessions_list', { agentId: agent.codex })await ask('agent_recent codex while stopped', 'agent_recent', { agentId: agent.codex })+ await ask('agent_handoff_prepare codex while stopped', 'agent_handoff_prepare', {+ agentId: agent.codex, changeId: 'fedcba9876543210fedcba9876543210', targetEngine: 'claude',+ })// The model a resumed agent runs is what its engine reports once it is back, a race with the reply// on either build: v0.3.58 and this build each answered null in some runs and the model in others.// It is compared settled, in the rows read at the end.diff --git a/cli/e2e/handoff.e2e.ts b/cli/e2e/handoff.e2e.tsnew file mode 100644index 000000000..b8b8559b7--- /dev/null+++ b/cli/e2e/handoff.e2e.ts@@ -0,0 +1,134 @@+/** Change agent prepares its file in the edge host. A failure there costs no agent its turn. */+import { execFileSync } from 'node:child_process'+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { pathToFileURL } from 'node:url'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'++const CHANGE = '0123456789abcdef0123456789abcdef'++describe('change agent in the edge host', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })++ async function start(env: Record<string, string> = {}, engine = 'claude') {+ daemon = await IsolatedDaemon.create({ env })+ const d = daemon+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-160).join('\n')}`))+ await d.start()+ const client = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, 'handoff-project')+ mkdirSync(cwd, { recursive: true })+ execFileSync('git', ['init', '-q', cwd])+ execFileSync('git', ['-C', cwd, '-c', 'user.name=QA', '-c', '[email protected]', 'commit', '-qm', 'fixture', '--allow-empty'])+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 60_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const agentId: string = created.agent.id+ await until('the handoff agent to bind', async () => {+ const { agents } = await client.request('agents_list')+ return agents.find((row: Record<string, any>) => row.id === agentId)?.sessionId || null+ }, 45_000, 250)+ return { d, client, cwd, agentId }+ }++ async function turn(client: LocalClient, agentId: string, content: string) {+ const ended = client.next(frame => frame.type === 'turn_ended' && frame.agentId === agentId, 30_000, content)+ client.send('message', { agentId, content })+ await ended+ }++ for (const mode of ['edge', 'inline']) {+ it(`a handoff that cannot start is unavailable, while the agent keeps working (${mode})`, async () => {+ const { d, client, agentId } = await start({ HARNESSD_TEST_FAULTS: 'handoff', ...(mode === 'inline' ? { HARNESSD_SERVICES: 'none' } : {}) })+ await turn(client, agentId, 'keep this agent working')+ expect(await client.request('agent_handoff_prepare', { agentId, changeId: CHANGE, targetEngine: 'codex' }))+ .toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'handoff', retryable: mode === 'edge' })+ await turn(client, agentId, 'still working after the unavailable handoff')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })+ }++ it.each(['claude', 'codex'])('keeps the same handoff and conversation for a stopped %s agent', async (engine) => {+ const { d, client, cwd, agentId } = await start({}, engine)+ await turn(client, agentId, 'remember the handoff request')+ const prepared = await client.request('agent_handoff_prepare', { agentId, changeId: CHANGE, targetEngine: 'codex' })+ expect(prepared).toMatchObject({ agentId, gitRepo: true, cwd, degraded: [] })+ expect(prepared.file).toBe(`.harness/handoff/${agentId}-${CHANGE}.md`)+ expect(readFileSync(join(cwd, prepared.file), 'utf8')).toContain('remember the handoff request')+ const deleted = await client.request('agent_delete', { agentId }, 30_000)+ expect(deleted.error, JSON.stringify(deleted)).toBeUndefined()+ await until('the handoff agent to stop', async () => {+ const { agents } = await client.request('agents_list', { includeStopped: true })+ return agents.find((row: Record<string, any>) => row.id === agentId)?.status === 'stopped' || null+ }, 30_000, 250)+ const stopped = await client.request('agent_handoff_prepare', { agentId, changeId: 'fedcba9876543210fedcba9876543210', targetEngine: 'codex' })+ expect(stopped).toMatchObject({ agentId, gitRepo: true, cwd, degraded: [] })+ expect(readFileSync(join(cwd, stopped.file), 'utf8')).toContain('remember the handoff request')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it.each(['claude', 'codex'])('a stopped %s fork that never bound inherits only the conversation before the fork from its stopped parent', async (engine) => {+ const { d, client, cwd, agentId } = await start({}, engine)+ await turn(client, agentId, 'the request before the fork')+ // The next process is slow to start, while the parent's already running process keeps going.+ // Stop this fork before its first hook: the retained record must still name its parent.+ const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).href+ const wrapper = join(d.root, 'bin', engine)+ const config = { ...d.engineConfig, startDelayMs: 60_000 }+ writeFileSync(`${wrapper}.new`, `#!${process.execPath}\nimport(${JSON.stringify(module)}).then(m => m.run(${JSON.stringify(engine)}, ${JSON.stringify(config)}))\n`, { mode: 0o755 })+ renameSync(`${wrapper}.new`, wrapper)+ const forked = await client.request('agent_fork', { agentId, name: 'handoff fork' }, 60_000)+ expect(forked.error, JSON.stringify(forked)).toBeUndefined()+ const forkId: string = forked.agent.id+ const pending = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')).find((row: Record<string, any>) => row.agentId === forkId)+ expect(pending.forkedFrom.agentId).toBe(agentId)+ expect(pending.sessionId).toBe('')+ await turn(client, agentId, 'the request after the fork must stay with its parent')+ expect((await client.request('agent_delete', { agentId }, 30_000)).error).toBeUndefined()+ expect((await client.request('agent_delete', { agentId: forkId }, 30_000)).error).toBeUndefined()+ client.close()+ await d.stop()+ // Exercise the handoff reader against the exact pending row observed above. Stop's separate+ // resume-identity capture can find the source named on a fork's argv; it is not the state this+ // case covers. With the daemon off, seed the retained unbound record as the store would save it.+ const savedPath = join(d.dataDir, 'stopped-agents', `${forkId}.json`)+ writeFileSync(savedPath, JSON.stringify({ version: 1, session: { ...pending, active: false, launch: { state: 'ready' } } }))+ await d.start()+ await until('handoff to reconnect after the restart', () => d.log().split('[services] handoff connected').length >= 3 || null, 30_000, 200)+ const restarted = await LocalClient.connect(d)+ const inherited = await restarted.request('agent_handoff_prepare', { agentId: forkId, changeId: CHANGE, targetEngine: 'codex' })+ expect(inherited).toMatchObject({ agentId: forkId, gitRepo: true, cwd, degraded: [] })+ const summary = readFileSync(join(cwd, inherited.file), 'utf8')+ expect(summary).toContain('the request before the fork')+ expect(summary).not.toContain('the request after the fork')+ // Found by QA on a quiet machine: these reads must still resolve a stopped parent through the+ // core after handoff rendering moves to the edge host, without borrowing later parent turns.+ expect(summary).toContain('History: inherited from')+ expect(d.coresStarted()).toBe(2)+ restarted.close()+ })++ it('the edge host can die without an agent losing its turn, then prepare another handoff after recovery', async () => {+ const { d, client, cwd, agentId } = await start({ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '5000' })+ await until('handoff to connect', () => d.log().includes('[services] handoff connected') || null, 30_000, 200)+ const match = [...d.log().matchAll(/\[harnessd\] service edge started \(pid (\d+)\)/g)].at(-1)+ expect(match).toBeDefined()+ const pid = Number(match![1])+ expect(execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).trim()).toBe('harnessd-edge')+ process.kill(pid, 'SIGKILL')+ await until('handoff to disconnect', () => d.log().includes('[services] handoff disconnected') || null, 15_000, 100)+ expect(await client.request('agent_handoff_prepare', { agentId, changeId: CHANGE, targetEngine: 'codex' }))+ .toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'handoff', retryable: true })+ await turn(client, agentId, 'a turn while the handoff host is gone')+ await until('handoff to reconnect', () => d.log().split('[services] handoff connected').length >= 3 || null, 30_000, 200)+ const prepared = await client.request('agent_handoff_prepare', { agentId, changeId: CHANGE, targetEngine: 'codex' })+ expect(prepared).toMatchObject({ agentId, gitRepo: true, cwd, degraded: [] })+ expect(readFileSync(join(cwd, prepared.file), 'utf8')).toContain('a turn while the handoff host is gone')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })+})diff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.tsindex 1aaa52095..51dbdeea3 100644--- a/cli/e2e/lean.e2e.ts+++ b/cli/e2e/lean.e2e.ts@@ -22,7 +22,7 @@ type Engine = 'claude' | 'codex'/** The processes the master runs the services in, and the services, each on its own link to the core. The* experiments' start only once they are on (e2e/experiments.e2e.ts, from the run's bundle). */const PROCESSES = ['search', 'viewers', 'edge', 'models']-const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'models']+const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'handoff', 'models']const commandOf = (pid: number): string => execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }).trim()const rssMiB = (pid: number): number => Number(execFileSync('ps', ['-o', 'rss=', '-p', String(pid)], { encoding: 'utf8' }).trim()) / 1024diff --git a/cli/e2e/serviceProcesses.e2e.ts b/cli/e2e/serviceProcesses.e2e.tsindex 9b2a6dda1..9c16ae46c 100644--- a/cli/e2e/serviceProcesses.e2e.ts+++ b/cli/e2e/serviceProcesses.e2e.ts@@ -168,7 +168,7 @@ function edgePids(d: IsolatedDaemon): number[] {.filter(([, pid, command]) => command.trim() === 'harnessd-edge' && ours.has(Number(pid))).map(([, pid]) => Number(pid))}/** The services the edge host runs, each on its own link to the core. */-const EDGE = ['workspaces', 'usage', 'monitor', 'projects']+const EDGE = ['workspaces', 'usage', 'monitor', 'projects', 'handoff']/** How many times each of the edge host's services has connected to the core. */const edgeConnections = (d: IsolatedDaemon): number => Math.min(...EDGE.map((service) => d.log().split(`[services] ${service} connected`).length - 1))/** The edge host answers, through the core: the home folder's subfolders, and the machine's own totals. */diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex ee44aab68..f111bdc87 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -54,7 +54,7 @@ const QUICK_TO_PARK = { HARNESSD_SERVICE_PARK_CRASHES: '3', HARNESSD_SERVICE_INI/** The processes the services run in by default, and what makes every one of them fail as it starts. The* experiments' (the teams', the orchestrator's) start only once they are on: e2e/experiments.e2e.ts. */const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'models'] as const-const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,models'+const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,handoff,models'describe('a failing service never takes the core down', () => {let daemon: IsolatedDaemon | undefineddiff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex da23636f1..a9dfe600c 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -166,9 +166,6 @@ const BACKEND_SOCKET_BUDGET = 1_185/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {- // The search process builds, in its own process, the core API search runs on; this reader is a pure- // function of a session row, the same one the core hands search through CoreApi.- 'services/searchProcess.ts → ../core/transcripts/databaseHistory.js': 'the core API search runs on, built in its own process',// A pure function of a session row. Move it out of registry.ts when workspaces leaves the core's process.'services/workspaces.ts → ../lib/registry.js': 'sessionDisplayTitle, a pure helper',}@@ -293,13 +290,18 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// (lib/commandBar.ts) and the OpenRouter key reader only it still loaded here (lib/openrouter.ts) leave.// Its HTTP door stays, forwarding to it (lib/commandBarHttp.ts), and so does ⌘K's task delivery, the// devices'.-const CORE_CLOSURE_BUDGET = 74_730+//+// Quiet-machine QA moves handoff history folding, redaction and file writes to the edge host;+// the core keeps narrow conversation reads: 73,025 lines in 336 files after the command-bar extraction.+const CORE_CLOSURE_BUDGET = 73_125/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [/^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,/^lib\/grid(Attach|Credentials|Derive|Ensure|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,/^lib\/localModels\.ts$/,+ // The change-agent handoff reads and redacts history and runs git: the edge host owns that work.+ /^lib\/agentHandoff\.ts$/,// The relay's own parts, the gateway's alone: the windows' sessions to other machines, P2P and STUN, the// remote viewers' proxy, and the shaping of what goes up the link./^lib\/(remoteRelay|terminalP2p|stunSelect|remoteViewerProxy|deviceRecentTrim|commanderReplay)\.ts$/,@@ -322,9 +324,7 @@ const CORE_MAY_REACH: Record<string, string> = {'dsh/registry.ts': 'with dsh/builtins.ts, which checks the bundled harnesses against the catalog\'s entries','dsh/updates.ts': 'with dsh/builtins.ts','lib/autonomous-device/localApi.ts': 'the hook server\'s routes for `harness device`, which the core serves: the pairings they answer are the gateway\'s, the receipts the Wi-Fi device\'s service\'s',- 'lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads','lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder',- 'lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads','services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',}diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 561218523..bdd18324a 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -251,11 +251,6 @@ export class BackendSocket {/** Answers `sessions_list` with the whole reply: the conversation an agent holds and how many lines it* has (cli.ts binds core/transcripts/history.ts). Null answers UNSUPPORTED. */sessionsProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null- /** Answers `agent_handoff_prepare` through its last argument, for the owner alone: the structured handoff- * file for an agent whose engine is about to change, written where it says, never text for the next- * engine (cli.ts binds core/agents/handoff.ts over lib/agentHandoff.ts). Null answers UNSUPPORTED. */- handoffRequestProvider: ((payload: Record<string, unknown>, asker: { local: boolean; owner: boolean },- reply: (result: Record<string, unknown>) => void) => void) | null = null/** How each agent's last turn ended, from the turn frames this socket sends: the monitor's activity* once a turn is over (`agents_list`, core/agents/list.ts). */readonly monitorCompletions = new MonitorCompletions()@@ -961,12 +956,6 @@ export class BackendSocket {reply(type, requestId, this.agentRecentProvider ? this.agentRecentProvider(payload) : { error: 'UNSUPPORTED' })return- // "Change agent": what the old engine did, written for the new one (core/agents/handoff.ts, bound by cli.ts).- case 'agent_handoff_prepare':- if (this.handoffRequestProvider) this.handoffRequestProvider(payload, asker, answer)- else answer({ error: 'UNSUPPORTED' })- return-// A rename, a model and effort, or an app opening the agent (core/agents/update.ts, bound by cli.ts).case 'agent_update':if (this.agentUpdateProvider) await this.agentUpdateProvider(payload, answer)diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex a1e306f89..523095edc 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, SHARING_FALLBACKS, TEAMS_FALLBACKS, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'+import { CONVERSATIONS_OFF, ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, SHARING_FALLBACKS, TEAMS_FALLBACKS, TERMINALS_OFF, WIFI_FALLBACKS, WIFI_OFF, type CoreApiDeps } from './api.js'import { FAIL, readFallback } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -85,6 +85,9 @@ describe('the core API services stand on', () => {it('lists every agent, live then stopped, and names them as the apps do', async () => {const deps = coreDeps()const core = createCoreApi(deps)+ expect(core.conversations).toBe(CONVERSATIONS_OFF)+ const conversations = { ...CONVERSATIONS_OFF }+ expect(createCoreApi({ ...deps, conversations }).conversations).toBe(conversations)expect(core.dataDir).toBe('/data')expect(await core.terminals.open({ argv: ['/bin/zsh'], cwd: '/work' })).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })const terminals = { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })), watch: TERMINALS_OFF.watch }diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 09b5d529c..85853ebd2 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -73,6 +73,31 @@ export const TERMINALS_OFF: TerminalsPort = {watch: { frame: async () => {}, close: async () => {}, onOutput: () => () => {} },}+/** Read-only conversation facts for the handoff in the edge host. Each lookup asks the core now;+ * a stopped record is never replaced by a stale live-agent list in another process. */+export interface ConversationReads {+ /** A live agent by agent/session id, otherwise the stopped record by agent id. */+ resolve(id: string): Promise<RegisteredSession | null>+ recentAsks(sessionId: string, n: number): Promise<string[]>+ lastFullText(sessionId: string): Promise<string | null>+ recaps(sessionId: string, n: number): Promise<string[]>+ /** The core verifies process birth, ownership and deletion; discovery never binds the agent. */+ discover(agentId: string): Promise<{ engine: AgentEngine; sessionId: string; transcriptPath: string | null } | null>+ findTranscript(engine: AgentEngine, sessionId: string, options: { codexHome?: string }): Promise<string | null>+ transcriptOk(engine: AgentEngine, path: string, codexHome: string | null): Promise<boolean>+}++/** No retained record or history, no discovered session and no permission to read a guessed path. */+export const CONVERSATIONS_OFF: ConversationReads = {+ resolve: async () => null,+ recentAsks: async () => [],+ lastFullText: async () => null,+ recaps: async () => [],+ discover: async () => null,+ findTranscript: async () => null,+ transcriptOk: async () => false,+}+export interface CoreApi {/** The daemon's data folder; a service keeps its own files in it. */dataDir: string@@ -86,6 +111,7 @@ export interface CoreApi {/** Its display name, else "This machine". */name(): string}+ conversations: ConversationReadsagents: {/** Every agent on this machine: the live ones, then the stopped ones. */all(): RegisteredSession[]@@ -406,6 +432,8 @@ export const MONITOR_REQUESTS = ['machine_resources'] as constexport const COMMAND_BAR_REQUESTS = ['command_bar', 'command_bar_http'] as const/** The project and folder readers (services/projects.ts). */export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const+/** Change agent's handoff file, prepared in the edge host (services/handoff.ts). */+export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as const/*** Models (services/models.ts).*@@ -1146,6 +1174,7 @@ export function emptyPorts(): CorePorts {export interface CoreApiDeps {terminals?: TerminalsPort+ conversations?: ConversationReadsdataDir: stringregistry: Pick<typeof registry, 'list' | 'byAgent' | 'resolve' | 'advertised' | 'terminalAvailable'>stoppedAgents: Pick<StoppedAgentStore, 'list'>@@ -1197,7 +1226,7 @@ export interface CoreApiDeps {export function createCoreApi({dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, observer, privateGridName, machineName, backend, onNotice,- runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, viewerFrame, machine, activityText,+ runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText,signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, log = (line) => console.warn(line),}: CoreApiDeps): CoreApi {// The devices reach the windows through these alone, and only with their own frames: a devices process@@ -1209,6 +1238,7 @@ export function createCoreApi({dataDir,terminals,machine,+ conversations,agents: {all: () => [...registry.list(), ...stoppedAgents.list()],live: () => registry.list(),diff --git a/cli/src/core/conversationQueries.spec.ts b/cli/src/core/conversationQueries.spec.tsnew file mode 100644index 000000000..1a6827714--- /dev/null+++ b/cli/src/core/conversationQueries.spec.ts@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from 'vitest'+import type { HandoffDeps } from '../lib/agentHandoff.js'+import type { RegisteredSession } from '../lib/registry.js'+import { fakeCore } from '../testing/fakeCore.js'+import { CONVERSATIONS_OFF } from './api.js'+import { answerConversationQuery, conversationReads } from './conversationQueries.js'++const session = { agentId: 'retained', sessionId: 's1', engine: 'claude' } as RegisteredSession+const source = { engine: 'claude', sessionId: 's1', transcriptPath: '/claude/s1.jsonl' }++describe('the conversation reads the handoff asks of the core', () => {+ it('has explicit empty fallbacks, including a refused transcript path', async () => {+ const reads = CONVERSATIONS_OFF+ expect(await reads.resolve('a')).toBeNull()+ expect(await reads.recentAsks('s', 20)).toEqual([])+ expect(await reads.lastFullText('s')).toBeNull()+ expect(await reads.recaps('s', 5)).toEqual([])+ expect(await reads.discover('a')).toBeNull()+ expect(await reads.findTranscript('codex', 's', {})).toBeNull()+ expect(await reads.transcriptOk('codex', '/x', null)).toBe(false)+ })++ const deps = (): HandoffDeps => ({+ resolve: vi.fn(id => id === 'retained' ? session : null), readHistory: () => undefined,+ recentAsks: vi.fn(() => ['ask']), lastFullText: vi.fn(() => 'answer'), recaps: vi.fn(() => ['recap']),+ discoverSession: vi.fn(async () => source), findTranscript: vi.fn(async () => '/codex/s.jsonl'), transcriptOk: vi.fn(() => true),+ })++ it('reads retained agents and their recaps now, and discovers from the core record alone', async () => {+ const d = deps(), reads = conversationReads(d)+ expect(await reads.resolve('retained')).toBe(session)+ expect(await reads.resolve('missing')).toBeNull()+ expect(await reads.recentAsks('s', 20)).toEqual(['ask'])+ expect(d.recentAsks).toHaveBeenCalledWith('s', 20)+ expect(await reads.lastFullText('s')).toBe('answer')+ expect(d.lastFullText).toHaveBeenCalledWith('s')+ expect(await reads.recaps('s', 5)).toEqual(['recap'])+ expect(d.recaps).toHaveBeenCalledWith('s', 5)+ expect(await reads.discover('retained')).toEqual(source)+ expect(d.discoverSession).toHaveBeenCalledWith(session)+ expect(await reads.discover('missing')).toBeNull()+ expect(await reads.findTranscript('codex', 's', { codexHome: '/home' })).toBe('/codex/s.jsonl')+ expect(d.findTranscript).toHaveBeenCalledWith('codex', 's', { codexHome: '/home' })+ expect(await reads.transcriptOk('codex', '/path', '/home')).toBe(true)+ expect(d.transcriptOk).toHaveBeenCalledWith('codex', '/path', '/home')+ })++ it('keeps missing and optional data empty instead of guessing a conversation or a path', async () => {+ const d = deps()+ const reads = conversationReads({ ...d, lastFullText: () => undefined, recaps: undefined, discoverSession: undefined, findTranscript: undefined, transcriptOk: undefined })+ expect(await reads.lastFullText('s')).toBeNull()+ expect(await reads.recaps('s', 5)).toEqual([])+ expect(await reads.discover('retained')).toBeNull()+ expect(await reads.findTranscript('claude', 's', {})).toBeNull()+ expect(await reads.transcriptOk('claude', '/x', null)).toBe(false)+ expect(await conversationReads({ ...d, discoverSession: async () => ({ engine: 'claude', sessionId: 's', transcriptPath: null }) }).discover('retained'))+ .toEqual({ engine: 'claude', sessionId: 's', transcriptPath: null })+ })++ it('answers only the declared read queries, preserving all arguments', async () => {+ const core = fakeCore({ conversations: conversationReads(deps()) })+ const ask = (query: string, payload: Record<string, unknown>) => answerConversationQuery(core, query, payload)+ expect(await ask('resolve', { id: 'retained' })).toEqual({ value: session })+ expect(await ask('discover', { id: 'retained' })).toEqual({ value: source })+ expect(await ask('lastFullText', { id: 's' })).toEqual({ value: 'answer' })+ expect(await ask('recentAsks', { id: 's', n: 20 })).toEqual({ value: ['ask'] })+ expect(await ask('recaps', { id: 's', n: 5 })).toEqual({ value: ['recap'] })+ for (const codexHome of [undefined, null, '/home']) {+ expect(await ask('findTranscript', { engine: 'codex', id: 's', codexHome })).toEqual({ value: '/codex/s.jsonl' })+ expect(await ask('transcriptOk', { engine: 'codex', path: '/path', codexHome })).toEqual({ value: true })+ }+ expect(await ask('credentials', {})).toEqual({ error: 'UNKNOWN_QUERY' })+ for (const query of ['resolve', 'discover', 'lastFullText', 'recentAsks', 'recaps', 'findTranscript', 'transcriptOk']) {+ expect(await ask(query, {}), query).toEqual({ error: 'BAD_QUERY' })+ }+ for (const n of [undefined, '5', 0, -1, 21, 1.5]) expect(await ask('recaps', { id: 's', n })).toEqual({ error: 'BAD_QUERY' })+ for (const payload of [{ engine: 'unknown', id: 's' }, { engine: 'codex', id: 's', codexHome: 5 }, { engine: 'codex' }]) {+ expect(await ask('findTranscript', payload)).toEqual({ error: 'BAD_QUERY' })+ }+ expect(await ask('transcriptOk', { engine: 'claude', path: '' })).toEqual({ error: 'BAD_QUERY' })+ })+})diff --git a/cli/src/core/conversationQueries.ts b/cli/src/core/conversationQueries.tsnew file mode 100644index 000000000..65c69d89c--- /dev/null+++ b/cli/src/core/conversationQueries.ts@@ -0,0 +1,49 @@+/** The handoff's read-only queries. The core owns these facts; all file rendering and git work stays+ * in the edge host (quiet-machine QA, handoff extraction). No service receives the registry itself. */+import { ENGINES, type AgentEngine } from '../engines/types.js'+import type { HandoffDeps } from '../lib/agentHandoff.js'+import { CONVERSATIONS_OFF, type ConversationReads, type CoreApi } from './api.js'++export function conversationReads(deps: HandoffDeps): ConversationReads {+ return {+ resolve: async (id) => (await deps.resolve(id)) ?? null,+ recentAsks: async (id, n) => deps.recentAsks(id, n),+ lastFullText: async (id) => (await deps.lastFullText(id)) ?? null,+ recaps: async (id, n) => (await deps.recaps?.(id, n)) ?? [],+ discover: async (id) => {+ const session = await deps.resolve(id)+ const found = session && await deps.discoverSession?.(session)+ return found ? { engine: found.engine as AgentEngine, sessionId: found.sessionId, transcriptPath: found.transcriptPath ?? null } : null+ },+ findTranscript: deps.findTranscript ?? CONVERSATIONS_OFF.findTranscript,+ transcriptOk: async (engine, path, home) => (await deps.transcriptOk?.(engine, path, home)) ?? false,+ }+}++const text = (value: unknown): value is string => typeof value === 'string' && value.length > 0+const count = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 20++export async function answerConversationQuery(core: Pick<CoreApi, 'conversations'>, query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {+ const reads = core.conversations+ const id = payload.id+ if (query === 'resolve' || query === 'discover' || query === 'lastFullText') {+ if (!text(id)) return { error: 'BAD_QUERY' }+ return { value: await reads[query](id) }+ }+ if (query === 'recentAsks' || query === 'recaps') {+ if (!text(id) || !count(payload.n)) return { error: 'BAD_QUERY' }+ return { value: await reads[query](id, payload.n) }+ }+ if (query === 'findTranscript' || query === 'transcriptOk') {+ if (!text(payload.engine) || !(ENGINES as readonly string[]).includes(payload.engine)+ || (payload.codexHome !== undefined && payload.codexHome !== null && !text(payload.codexHome))) return { error: 'BAD_QUERY' }+ const engine = payload.engine as AgentEngine+ if (query === 'findTranscript') {+ if (!text(id)) return { error: 'BAD_QUERY' }+ return { value: await reads.findTranscript(engine, id, { codexHome: typeof payload.codexHome === 'string' ? payload.codexHome : undefined }) }+ }+ if (!text(payload.path)) return { error: 'BAD_QUERY' }+ return { value: await reads.transcriptOk(engine, payload.path, typeof payload.codexHome === 'string' ? payload.codexHome : null) }+ }+ return { error: 'UNKNOWN_QUERY' }+}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 8536cc03a..29dbb2dc5 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -55,7 +55,6 @@ import { OpenTabProtection } from '../lib/openTabProtection.js'import { sessionCheckpoints } from '../lib/sessionCheckpoint.js'import { repairClaudeCwd } from '../lib/cwdRepair.js'import { stoppedAgents } from '../lib/stoppedAgents.js'-import { prepareAgentHandoff } from '../lib/agentHandoff.js'import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'import { externalProviders } from '../lib/sessionSearch/externals/index.js'import { type LaunchOverridesDeps } from '../lib/launchOverrides.js'@@ -112,14 +111,14 @@ import { createAgentRetargeter } from './agents/retarget.js'import { createAgentRestarter } from './agents/restart.js'import { createAgentLifecycle, createPurgeRequest, createStopRequest } from './agents/lifecycle.js'import { createAgentClosing, createCloseRequests } from './agents/close.js'-import { createHandoffRequest } from './agents/handoff.js'+import { answerConversationQuery, conversationReads } from './conversationQueries.js'import { createLaunchRequests } from './agents/launches.js'import { createAgentList } from './agents/list.js'import { createAgentUpdate } from './agents/update.js'import { createEngineHooks, installEngineHooks } from './engines/hooks.js'import { createCursorTaskHooks } from './engines/cursorTasks.js'import { databaseHistory } from './transcripts/databaseHistory.js'-import { COMMAND_BAR_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'+import { COMMAND_BAR_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -1117,10 +1116,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// and the voice router know. Resolve across the two, or every tile restores empty.backend.agentRecentProvider = recaps.agentRecent- // "Change agent": the desktop asks for the structured handoff file (lib/agentHandoff.ts) before it- // closes the old engine; the new one is then told to read it.- // Built ONCE: its discovery keeps "one search per agent" across requests.- const handoffDeps = handoffProviderDeps({+ // Quiet-machine QA: the edge host renders Change agent's handoff from these conversation reads.+ // Build discovery once to keep "one search per agent" across requests.+ coreApi.conversations = conversationReads(handoffProviderDeps({registry,stopped: {get: (id) => stoppedAgents.get(id),@@ -1134,12 +1132,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {isRecentlyDeleted,findResumedTranscript,validTranscriptPath,- })- backend.handoffRequestProvider = createHandoffRequest({ prepare: (req) => prepareAgentHandoff(handoffDeps, req) })+ }))// The requests each service that can run in its own process answers, as core/api.ts declares them.const requestsOf: Record<string, readonly string[]> = {- search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS,+ search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS,devices: DEVICES_REQUESTS,...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),}@@ -1202,6 +1199,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {: service === 'teams' || service === 'collaboration' ? teamsLink.answer(query, payload): service === 'devices' ? devicesLink.answer(query, payload): service === 'wifi' ? wifiLink.answer(query, payload)+ : service === 'handoff' ? answerConversationQuery(coreApi, query, payload): service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query)),// The gateway's own traffic: its remote clients and what they sent, and its comings and goings; and what// the devices tell the core (a turn, a frame for the windows, a dial on the wire); a viewer stream's answers.@@ -1274,6 +1272,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// media file from an agent's project (services/projects.ts): in this process, or in the edge host.if (!outOfProcess.has('projects')) serviceHost.serve('projects', inline!.startProjects, coreApi, PROJECTS_REQUESTS)if (!outOfProcess.has('commandBar')) serviceHost.serve('commandBar', inline!.startCommandBar, coreApi, COMMAND_BAR_REQUESTS)+ if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)serviceHost.serve('shell', startShell, coreApi, SHELL_REQUESTS)// Models: grid access and its pin, the model pictures on agents' frames, the keystroke prewarm, where an// agent on a grid model sends its inference, and the models requests the apps send (services/models.ts):diff --git a/cli/src/core/transcripts/databaseHistory.ts b/cli/src/core/transcripts/databaseHistory.tsindex 6bf643510..2ca5eae64 100644--- a/cli/src/core/transcripts/databaseHistory.ts+++ b/cli/src/core/transcripts/databaseHistory.ts@@ -1,29 +1,2 @@-/**- * The engines that keep a conversation in a database instead of a transcript file, read through- * the same readers and replay normalizers as `session_get`.- *- * Moved verbatim out of `runForeground` (the core boundary, step 13: docs/design/2026-10-03-harnessd.md).- */-import { join } from 'node:path'-import { env } from '../../config/env.js'-import { devinMessagesToEvents } from '../../engines/devin/normalizer.js'-import { readDevinMessages } from '../../engines/devin/reader.js'-import { hermesMessagesToEvents } from '../../engines/hermes/normalizer.js'-import { readHermesMessages } from '../../engines/hermes/reader.js'-import { kiloMessagesToEvents } 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 { hermesDbForSession } from '../../lib/hermesHome.js'-import type { LiveEvent } from '../../lib/normalize.js'-import type { RegisteredSession } from '../../lib/registry.js'--export const databaseHistory = (s: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined => {- switch (s.engine) {- case 'opencode': return async () => opencodeMessagesToEvents(await readOpencodeMessages(join(env.OPENCODE_DATA_DIR, 'opencode.db'), s.sessionId))- case 'kilo': return async () => kiloMessagesToEvents(await readKiloMessages(join(env.KILO_DATA_DIR, 'kilo.db'), s.sessionId))- case 'devin': return async () => devinMessagesToEvents(await readDevinMessages(join(env.DEVIN_HOME, 'sessions.db'), s.sessionId))- case 'hermes': return async () => hermesMessagesToEvents(await readHermesMessages(await hermesDbForSession(s), s.sessionId))- default: return undefined- }-}+// Shared by core history and services, with no live daemon state.+export { databaseHistory } from '../../lib/databaseHistory.js'diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex 3ac13795a..26648029e 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -364,7 +364,7 @@ describe('ServiceSupervisor', () => {const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)expect(KNOWN_SERVICES).toEqual(hosted)expect(new Set(hosted).size).toBe(hosted.length)- expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects'])+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff'])})})@@ -380,7 +380,7 @@ describe('which services the core leaves to its master', () => {expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS))).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })// By service, not by process: a core from before the edge host routes the services it knows of it.const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)- expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects' })+ expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff' })expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted) }, known)]).toEqual(['workspaces'])expect(serviceProcessesEnv([])).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none' })expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs) }, known)]).toEqual(['search', 'workspaces'])diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 86c2d4286..1586bbcde 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -334,7 +334,7 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// samples in ps's and ioreg's; what it holds is the agents the core sent it and one parsed sample.// The monitor parses up to 8 MB of ioreg output per Monitor poll on a Mac with a GPU, hence more// than workspaces alone had.- edge: { services: ['workspaces', 'usage', 'monitor', 'projects'], heapLimitMiB: 384, rssLimitMiB: 768 },+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff'], heapLimitMiB: 384, rssLimitMiB: 768 },// The orchestrator (services/orchestratorProcess.ts), an experiment: started only once it is on, for a// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their// Directors; the agents it runs are the core's.diff --git a/cli/src/lib/agentHandoff.spec.ts b/cli/src/lib/agentHandoff.spec.tsindex 64e958370..e168fc0d1 100644--- a/cli/src/lib/agentHandoff.spec.ts+++ b/cli/src/lib/agentHandoff.spec.ts@@ -746,6 +746,30 @@ describe('prepareAgentHandoff: no repository', () => {describe('prepareAgentHandoff: refusals and limits', () => {beforeEach(writeTranscript)+ it('awaits the retained agent and recap reads across the service boundary', async () => {+ const d = depsFor([], {+ resolve: (async () => session({ transcriptPath: null })) as never,+ recentAsks: (async () => ['the retained request']) as never,+ lastFullText: (async () => 'the retained full answer') as never,+ recaps: (async () => ['the retained recap']) as never,+ })+ const result = await prepareAgentHandoff(d, request())+ expect(result.degraded).toEqual(['transcript', 'git'])+ const text = readFileSync(mdOf(), 'utf8')+ expect(text).toContain('the retained request')+ expect(text).toContain('the retained full answer')+ expect(readFileSync(mdOf().replace(/\.md$/, '.transcript.md'), 'utf8')).toContain('the retained recap')+ })++ it('counts waiting for the core against the deadline and never writes after a late answer', async () => {+ let resolve!: (value: RegisteredSession) => void+ const d = depsFor([], { deadlineMs: 30, resolve: (() => new Promise<RegisteredSession>(done => { resolve = done })) as never })+ await expect(prepareAgentHandoff(d, request())).rejects.toMatchObject({ code: 'TIMEOUT' })+ resolve(session())+ await new Promise(done => setTimeout(done, 20))+ expect(existsSync(join(ws, '.harness'))).toBe(false)+ })+it('names what is wrong with the request', async () => {const d = depsFor([session(), session({ agentId: 'nowhere', cwd: null }), session({ agentId: 'relative', cwd: 'rel/dir' })])await expect(prepareAgentHandoff(d, request(C, 'ghost'))).rejects.toMatchObject({ name: 'HandoffError', code: 'UNKNOWN_AGENT' })diff --git a/cli/src/lib/agentHandoff.ts b/cli/src/lib/agentHandoff.tsindex 84f405a31..5d4320282 100644--- a/cli/src/lib/agentHandoff.ts+++ b/cli/src/lib/agentHandoff.ts@@ -43,6 +43,8 @@ import type { RegisteredSession } from './registry.js'import { SQLITE_BACKED_ENGINES } from './sqliteAvailability.js'import { omitLongRuns, readSessionTurns, SessionTurnsError, type TurnSource } from './sessionSearch/sessionTurns.js'import type { IndexedTurn } from './sessionSearch/turns.js'+import { isSubagentTranscript } from './subagentTranscript.js'+export { isSubagentTranscript } from './subagentTranscript.js'export const HANDOFF_DIR = '.harness/handoff'const HANDOFF_EXCLUDE = { pattern: '**/.harness/handoff/', comment: 'Harness agent handoffs (untracked)' }@@ -489,17 +491,19 @@ export class HandoffError extends Error {}}+type Read<T> = T | Promise<T>+export interface HandoffDeps {/** The agent's record, running or stopped; also how a fork's parents are found. */- resolve(agentId: string): RegisteredSession | null | undefined+ resolve(agentId: string): Read<RegisteredSession | null | undefined>/** The whole history of a session a database engine keeps (OpenCode, Kilo, Hermes, Devin); undefined for a file engine. */readHistory(session: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined/** The mirror's newest `n` requests by the person, newest first: the floor's asks when the session can't be read. */- recentAsks(sessionId: string, n: number): string[]+ recentAsks(sessionId: string, n: number): Read<string[]>/** The mirror's last full answer: preferred over the transcript's for the Last answer section. */- lastFullText(sessionId: string): string | undefined+ lastFullText(sessionId: string): Read<string | undefined>/** The mirror's stored recaps of the session's last turns, newest first: the floor's answers. */- recaps?(sessionId: string, n: number): string[]+ recaps?(sessionId: string, n: number): Read<string[]>/** The session an unbound, live, NON-fork agent runs (`handoffDiscovery.ts`), or null. Never called for a fork. */discoverSession?(session: RegisteredSession): Promise<TurnSource | null>/** Budget for `discoverSession`: 1.5 s by default, and never past the deadline. */@@ -507,7 +511,7 @@ export interface HandoffDeps {/** A transcript by session id (claude and codex only). Absent: none is found. */findTranscript?(engine: AgentEngine, sessionId: string, opts: { codexHome?: string }): Promise<string | null>/** May this path be read as `engine`'s transcript? Default: an absolute path to a plain file. */- transcriptOk?(engine: AgentEngine, path: string, codexHome: string | null): boolean+ transcriptOk?(engine: AgentEngine, path: string, codexHome: string | null): Read<boolean>/** The git binary. Default `git`. */git?: string/** Limit for each git command, ms. Default 2 s. */@@ -529,22 +533,23 @@ const inFlight = new Map<string, { changeId: string; promise: Promise<HandoffRes* be added, resolves with `file: null` and `file` in `degraded`.*/export function prepareAgentHandoff(deps: HandoffDeps, req: HandoffRequest): Promise<HandoffResult> {- // Always a promise, never a throw: the socket chains `.then/.catch` on the call, unguarded.- try { return start(deps, req) } catch (error) { return Promise.reject(error) }-}--function start(deps: HandoffDeps, req: HandoffRequest): Promise<HandoffResult> {- if (typeof req.changeId !== 'string' || !CHANGE_ID.test(req.changeId)) return Promise.reject(new HandoffError('BAD_CHANGE_ID'))- const session = deps.resolve(req.agentId)- if (!session) return Promise.reject(new HandoffError('UNKNOWN_AGENT'))- const cwd = session.cwd- if (!cwd || !isAbsolute(cwd) || !isDirectory(cwd)) return Promise.reject(new HandoffError('NO_PROJECT'))- const key = session.agentId- const running = inFlight.get(key)- if (running) return running.changeId === req.changeId ? running.promise : Promise.reject(new HandoffError('BUSY'))- if (inFlight.size >= MAX_IN_FLIGHT) return Promise.reject(new HandoffError('BUSY'))- const promise = withDeadline(deps, (expired) => prepare(deps, session, cwd, req, expired)).finally(() => { inFlight.delete(key) })- inFlight.set(key, { changeId: req.changeId, promise })+ // Found by QA on a quiet machine: a service boundary adds waits before the first file read. They+ // share the original deadline; a late core answer must never start work after the caller gave up.+ let key: string | null = null+ const promise = withDeadline(deps, async (expired) => {+ if (typeof req.changeId !== 'string' || !CHANGE_ID.test(req.changeId)) throw new HandoffError('BAD_CHANGE_ID')+ const session = await deps.resolve(req.agentId)+ if (expired()) throw new HandoffError('TIMEOUT')+ if (!session) throw new HandoffError('UNKNOWN_AGENT')+ const cwd = session.cwd+ if (!cwd || !isAbsolute(cwd) || !isDirectory(cwd)) throw new HandoffError('NO_PROJECT')+ const running = inFlight.get(session.agentId)+ if (running) return running.changeId === req.changeId ? running.promise : Promise.reject(new HandoffError('BUSY'))+ if (inFlight.size >= MAX_IN_FLIGHT) throw new HandoffError('BUSY')+ key = session.agentId+ inFlight.set(key, { changeId: req.changeId, promise })+ return prepare(deps, session, cwd, req, expired)+ }).finally(() => { if (key && inFlight.get(key)?.promise === promise) inFlight.delete(key) })return promise}@@ -586,7 +591,8 @@ async function prepare(deps: HandoffDeps, session: RegisteredSession, cwd: strinconst turns = await secureTurns(pick.turns, tick)const asks = turns.filter((turn) => turn.ask).map((turn) => turn.ask).reverse()// The mirror speaks only for the session that was read: never for an inherited or discovered history.- const mirrored = pick.mirrorSessionId ? deps.lastFullText(pick.mirrorSessionId)?.trim() : ''+ const mirrored = pick.mirrorSessionId ? (await deps.lastFullText(pick.mirrorSessionId))?.trim() : ''+ tick()const lastAnswer = (mirrored ? secureText(mirrored) : '') || [...turns].reverse().find((turn) => turn.answer)?.answer || nullif (!asks.length && !lastAnswer) return { file: null, gitRepo, cwd, degraded }@@ -653,9 +659,9 @@ function forkLink(session: RegisteredSession): ForkLink | null {}/** The agent's record, or null: a record that cannot be read is a record that is not there. */-function safeResolve(deps: HandoffDeps, agentId: string): RegisteredSession | null {+async function safeResolve(deps: HandoffDeps, agentId: string): Promise<RegisteredSession | null> {try {- const found = deps.resolve(agentId)+ const found = await deps.resolve(agentId)return found && typeof found === 'object' ? found : null} catch { return null }}@@ -665,20 +671,11 @@ function sameFolder(a: unknown, b: unknown): boolean {try { return realpathSync(a) === realpathSync(b) } catch { return false }}-/**- * A Claude subagent's transcript: `<session>/subagents/agent-*.jsonl`. Only the file's own folder is checked, so a- * home or projects root that happens to sit under a folder named `subagents` does not refuse every transcript.- */-export function isSubagentTranscript(path: string): boolean {- const parts = path.split(/[\\/]/).filter(Boolean)- return parts.length >= 2 && parts[parts.length - 2] === 'subagents'-}-/** May `path` be read as `engine`'s transcript: vouched for, and not a subagent's (`<session>/subagents/agent-*.jsonl`). */-function gate(deps: HandoffDeps, engine: string, path: string, codexHome: string | null): boolean {+async function gate(deps: HandoffDeps, engine: string, path: string, codexHome: string | null): Promise<boolean> {if (typeof path !== 'string' || !path || isSubagentTranscript(path)) return falsetry {- return deps.transcriptOk ? deps.transcriptOk(engine as AgentEngine, path, codexHome) : isAbsolute(path) && isPlainFile(path)+ return deps.transcriptOk ? await deps.transcriptOk(engine as AgentEngine, path, codexHome) : isAbsolute(path) && isPlainFile(path)} catch { return false }}@@ -737,13 +734,13 @@ async function pickHistory(deps: HandoffDeps, session: RegisteredSession, cwd: s}if (!ownEmpty) {// The floor: what the mirror remembers (the newest asks, and the recaps of the last turns).- const floor = floorTurns(deps.recentAsks(session.sessionId, FLOOR_ASKS), safeRecaps(deps, session.sessionId))- if (hasContent(floor) || deps.lastFullText(session.sessionId)?.trim()) return { ...none(), turns: floor, mirrorSessionId: session.sessionId, floor: true, missing: false }+ const floor = floorTurns(await deps.recentAsks(session.sessionId, FLOOR_ASKS), await safeRecaps(deps, session.sessionId))+ if (hasContent(floor) || (await deps.lastFullText(session.sessionId))?.trim()) return { ...none(), turns: floor, mirrorSessionId: session.sessionId, floor: true, missing: false }}} else if (session.forkedFrom == null && deps.discoverSession) {const found = await discover(deps, session, remainingMs())tick()- if (found?.transcriptPath && !DATABASE_ENGINES.has(found.engine) && gate(deps, found.engine, found.transcriptPath, session.codexHome ?? null)) {+ if (found?.transcriptPath && !DATABASE_ENGINES.has(found.engine) && await gate(deps, found.engine, found.transcriptPath, session.codexHome ?? null)) {const turns = await read({ engine: found.engine, sessionId: found.sessionId, transcriptPath: found.transcriptPath })if (turns && hasContent(turns)) return { ...none(), turns, sessionId: found.sessionId, missing: false }}@@ -793,7 +790,8 @@ async function inheritHistory(const link = forkLink(node)if (!link || seen.has(link.agentId)) return nullseen.add(link.agentId)- const parent = safeResolve(deps, link.agentId)+ const parent = await safeResolve(deps, link.agentId)+ tick()if (!parent || !sameFolder(parent.cwd, cwd)) return nullif (!link.sessionId && !parent.sessionId) { node = parent; continue }if (DATABASE_ENGINES.has(parent.engine)) return null@@ -803,18 +801,18 @@ async function inheritHistory(if (link.sessionId) {sessionId = link.sessionIdfor (const candidate of [link.transcriptPath?.includes(sessionId) ? link.transcriptPath : null, parent.sessionId === sessionId ? parent.transcriptPath : null]) {- if (candidate && gate(deps, parent.engine, candidate, home)) { path = candidate; break }+ if (candidate && await gate(deps, parent.engine, candidate, home)) { path = candidate; break }}if (!path && deps.findTranscript) {let found: string | null = nulltry { found = await deps.findTranscript(parent.engine, sessionId, { codexHome: home ?? undefined }) } catch { found = null }tick()- if (found && gate(deps, parent.engine, found, home)) path = found+ if (found && await gate(deps, parent.engine, found, home)) path = found}} else {sessionId = parent.sessionIdconst boundAt = parent.boundAt- if (typeof boundAt === 'number' && Number.isFinite(boundAt) && boundAt <= cut && parent.transcriptPath && gate(deps, parent.engine, parent.transcriptPath, home)) path = parent.transcriptPath+ if (typeof boundAt === 'number' && Number.isFinite(boundAt) && boundAt <= cut && parent.transcriptPath && await gate(deps, parent.engine, parent.transcriptPath, home)) path = parent.transcriptPath}if (!path) return nullconst all = await read({ engine: parent.engine, sessionId, transcriptPath: path })@@ -825,8 +823,8 @@ async function inheritHistory(return null}-function safeRecaps(deps: HandoffDeps, sessionId: string): string[] {- try { return (deps.recaps?.(sessionId, FLOOR_RECAPS) ?? []).filter((text) => typeof text === 'string' && text.trim()) } catch { return [] }+async function safeRecaps(deps: HandoffDeps, sessionId: string): Promise<string[]> {+ try { return ((await deps.recaps?.(sessionId, FLOOR_RECAPS)) ?? []).filter((text) => typeof text === 'string' && text.trim()) } catch { return [] }}/**diff --git a/cli/src/lib/databaseHistory.ts b/cli/src/lib/databaseHistory.tsnew file mode 100644index 000000000..2b96cec26--- /dev/null+++ b/cli/src/lib/databaseHistory.ts@@ -0,0 +1,30 @@+/**+ * The engines that keep a conversation in a database instead of a transcript file, read through+ * the same readers and replay normalizers as `session_get`.+ *+ * A pure reader of the supplied session row. Search and handoff use it in their own processes, so+ * their database reads do not return to the core (quiet-machine QA, handoff extraction).+ */+import { join } from 'node:path'+import { env } from '../config/env.js'+import { devinMessagesToEvents } from '../engines/devin/normalizer.js'+import { readDevinMessages } from '../engines/devin/reader.js'+import { hermesMessagesToEvents } from '../engines/hermes/normalizer.js'+import { readHermesMessages } from '../engines/hermes/reader.js'+import { kiloMessagesToEvents } 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 { hermesDbForSession } from './hermesHome.js'+import type { LiveEvent } from './normalize.js'+import type { RegisteredSession } from './registry.js'++export const databaseHistory = (s: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined => {+ switch (s.engine) {+ case 'opencode': return async () => opencodeMessagesToEvents(await readOpencodeMessages(join(env.OPENCODE_DATA_DIR, 'opencode.db'), s.sessionId))+ case 'kilo': return async () => kiloMessagesToEvents(await readKiloMessages(join(env.KILO_DATA_DIR, 'kilo.db'), s.sessionId))+ case 'devin': return async () => devinMessagesToEvents(await readDevinMessages(join(env.DEVIN_HOME, 'sessions.db'), s.sessionId))+ case 'hermes': return async () => hermesMessagesToEvents(await readHermesMessages(await hermesDbForSession(s), s.sessionId))+ default: return undefined+ }+}diff --git a/cli/src/lib/handoffDiscovery.ts b/cli/src/lib/handoffDiscovery.tsindex 4c87aa103..50d16d1b0 100644--- a/cli/src/lib/handoffDiscovery.ts+++ b/cli/src/lib/handoffDiscovery.ts@@ -3,7 +3,8 @@// read-only: it never binds anything, and it answers only when the answer is certain — a Change agent// must not guess whose conversation it hands over. Consumed by lib/agentHandoff.ts.import type { AgentEngine } from '../engines/types.js'-import { isSubagentTranscript, type HandoffDeps } from './agentHandoff.js'+import type { HandoffDeps } from './agentHandoff.js'+import { isSubagentTranscript } from './subagentTranscript.js'import type { CommanderMirror } from './commander.js'import type { RegisteredSession } from './registry.js'import type { RepairedSession } from './sessionRepair.js'diff --git a/cli/src/lib/subagentTranscript.ts b/cli/src/lib/subagentTranscript.tsnew file mode 100644index 000000000..6101b4c27--- /dev/null+++ b/cli/src/lib/subagentTranscript.ts@@ -0,0 +1,9 @@+/**+ * A Claude subagent's transcript: `<session>/subagents/agent-*.jsonl`. Only the file's own folder is+ * checked, so a home under a folder named `subagents` does not refuse every transcript. Shared with+ * discovery without loading the handoff writer into the core (quiet-machine QA, handoff extraction).+ */+export function isSubagentTranscript(path: string): boolean {+ const parts = path.split(/[\\/]/).filter(Boolean)+ return parts.length >= 2 && parts[parts.length - 2] === 'subagents'+}diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 5f298ca73..caec86a87 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -31,6 +31,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['usage', async () => (await import('./services/usageProcess.js')).runUsageService],['monitor', async () => (await import('./services/monitorProcess.js')).runMonitorService],['projects', async () => (await import('./services/projectsProcess.js')).runProjectsService],+ ['handoff', async () => (await import('./services/handoffProcess.js')).runHandoffService],['store', async () => (await import('./services/storeProcess.js')).runStoreService],['teams', async () => (await import('./services/teamsProcess.js')).runTeamsService],['collaboration', async () => (await import('./services/collaborationProcess.js')).runCollaborationService],diff --git a/cli/src/services/devicesProcess.ts b/cli/src/services/devicesProcess.tsindex be1256573..04d6167ef 100644--- a/cli/src/services/devicesProcess.ts+++ b/cli/src/services/devicesProcess.ts@@ -105,6 +105,7 @@ export function runDevicesService(options: DevicesServiceOptions): ServiceProcesconst account = accountLink((query, payload) => ask(query, payload))const api: CoreApi = {dataDir: options.dataDir,+ conversations: unasked.conversations,// Terminals are launched by the core alone (#893).terminals: TERMINALS_OFF,machine: { id: () => view.machine.id, computerId: () => view.machine.computerId, name: () => view.machine.name },diff --git a/cli/src/services/handoff.spec.ts b/cli/src/services/handoff.spec.tsnew file mode 100644index 000000000..203732dd8--- /dev/null+++ b/cli/src/services/handoff.spec.ts@@ -0,0 +1,53 @@+import { describe, expect, it, vi } from 'vitest'+import { emptyPorts } from '../core/api.js'+import type { HandoffDeps } from '../lib/agentHandoff.js'+import type { RegisteredSession } from '../lib/registry.js'+import { fakeCore } from '../testing/fakeCore.js'+import { HANDOFF_REQUESTS, startHandoff } from './handoff.js'++const request = { agentId: 'agent', changeId: '0123456789abcdef0123456789abcdef', targetEngine: 'codex' }+const owner = { owner: true, local: true }++describe('the change-agent handoff service', () => {+ it('uses the real provider by default and preserves its unknown-agent answer', async () => {+ const handlers = startHandoff(fakeCore())+ expect(Object.keys(handlers)).toEqual([...HANDOFF_REQUESTS])+ expect(await handlers.agent_handoff_prepare!(request, owner)).toEqual({ error: 'UNKNOWN_AGENT' })+ expect(await handlers.agent_handoff_prepare!(request, { owner: false, local: false })).toEqual({ error: 'OWNER_REQUIRED' })+ })++ it('gives the provider every fact through CoreApi, including database history and stopped ancestors', async () => {+ const session = { agentId: 'agent', sessionId: 's', engine: 'claude' } as RegisteredSession+ const reader = async () => []+ const core = fakeCore({+ conversations: {+ resolve: vi.fn(async () => session), recentAsks: vi.fn(async () => ['ask']), lastFullText: vi.fn(async () => 'answer'),+ recaps: vi.fn(async () => ['recap']), discover: vi.fn(async () => ({ engine: 'claude' as const, sessionId: 's', transcriptPath: '/s.jsonl' })),+ findTranscript: vi.fn(async () => '/s.jsonl'), transcriptOk: vi.fn(async () => true),+ },+ transcripts: { databaseHistory: vi.fn(() => reader) },+ })+ let deps!: HandoffDeps+ const prepare = vi.fn(async (given: HandoffDeps) => { deps = given; return { file: '/handoff', cwd: '/work', gitRepo: true, degraded: [] } })+ const answer = await startHandoff(core, emptyPorts(), prepare).agent_handoff_prepare!(request, owner)+ expect(answer).toEqual({ agentId: 'agent', file: '/handoff', cwd: '/work', gitRepo: true, degraded: [] })+ expect(prepare).toHaveBeenCalledWith(expect.anything(), request)+ expect(await deps.resolve('agent')).toBe(session)+ expect(core.conversations.resolve).toHaveBeenCalledWith('agent')+ expect(deps.readHistory(session)).toBe(reader)+ expect(core.transcripts.databaseHistory).toHaveBeenCalledWith(session)+ expect(await deps.recentAsks('s', 20)).toEqual(['ask'])+ expect(core.conversations.recentAsks).toHaveBeenCalledWith('s', 20)+ expect(await deps.lastFullText('s')).toBe('answer')+ vi.mocked(core.conversations.lastFullText).mockResolvedValueOnce(null)+ expect(await deps.lastFullText('missing')).toBeUndefined()+ expect(await deps.recaps!('s', 5)).toEqual(['recap'])+ expect(core.conversations.recaps).toHaveBeenCalledWith('s', 5)+ expect(await deps.discoverSession!(session)).toEqual({ engine: 'claude', sessionId: 's', transcriptPath: '/s.jsonl' })+ expect(core.conversations.discover).toHaveBeenCalledWith('agent')+ expect(await deps.findTranscript!('claude', 's', {})).toBe('/s.jsonl')+ expect(core.conversations.findTranscript).toHaveBeenCalledWith('claude', 's', {})+ expect(await deps.transcriptOk!('claude', '/s.jsonl', null)).toBe(true)+ expect(core.conversations.transcriptOk).toHaveBeenCalledWith('claude', '/s.jsonl', null)+ })+})diff --git a/cli/src/services/handoff.ts b/cli/src/services/handoff.tsnew file mode 100644index 000000000..09a5a2ce5--- /dev/null+++ b/cli/src/services/handoff.ts@@ -0,0 +1,23 @@+/** Change agent's history, redaction and git work live outside the core. Its facts come only through+ * CoreApi, including stopped parents and the core's verified session discovery. */+import { HANDOFF_REQUESTS, type CoreApi, type CorePorts, type ServiceRequests } from '../core/api.js'+import { prepareAgentHandoff, type HandoffDeps } from '../lib/agentHandoff.js'+import { createHandoffRequest } from './handoffRequest.js'++export { HANDOFF_REQUESTS }++export function startHandoff(core: CoreApi, _ports?: CorePorts, prepare = prepareAgentHandoff): ServiceRequests {+ const reads = core.conversations+ const deps: HandoffDeps = {+ resolve: (id) => reads.resolve(id),+ readHistory: (session) => core.transcripts.databaseHistory(session),+ recentAsks: (id, n) => reads.recentAsks(id, n),+ lastFullText: async (id) => (await reads.lastFullText(id)) ?? undefined,+ recaps: (id, n) => reads.recaps(id, n),+ discoverSession: (session) => reads.discover(session.agentId),+ findTranscript: (engine, id, options) => reads.findTranscript(engine, id, options),+ transcriptOk: (engine, path, home) => reads.transcriptOk(engine, path, home),+ }+ const answer = createHandoffRequest({ prepare: (request) => prepare(deps, request) })+ return { agent_handoff_prepare: (payload, asker) => new Promise((reply) => answer(payload, asker, reply)) }+}diff --git a/cli/src/services/handoffProcess.spec.ts b/cli/src/services/handoffProcess.spec.tsnew file mode 100644index 000000000..dbc9ec409--- /dev/null+++ b/cli/src/services/handoffProcess.spec.ts@@ -0,0 +1,79 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { HANDOFF_REQUESTS, type CoreApi } from '../core/api.js'+import { databaseHistory } from '../lib/databaseHistory.js'+import { handoffCoreApi, runHandoffService } from './handoffProcess.js'+import { runServiceProcess, type ServiceProcessOptions } from './process.js'++vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))+afterEach(() => vi.clearAllMocks())++describe('the handoff in the edge host', () => {+ it('queries current retained records, recaps, and verified paths with their exact arguments', async () => {+ let value: unknown = { agentId: 'stopped', engine: 'claude' }+ const ask = vi.fn(async () => ({ value }))+ const core = handoffCoreApi('/data', ask)+ expect(core.dataDir).toBe('/data')+ expect(core.transcripts.databaseHistory).toBe(databaseHistory)+ expect(core.transcripts.databaseHistory({ engine: 'claude' } as never)).toBeUndefined()+ expect(await core.conversations.resolve('stopped')).toBe(value)+ expect(ask).toHaveBeenLastCalledWith('resolve', { id: 'stopped' })+ value = { agentId: 'new' }+ expect(await core.conversations.resolve('stopped')).toBe(value)+ value = ['ask', 7, null]+ expect(await core.conversations.recentAsks('s', 20)).toEqual(['ask'])+ expect(ask).toHaveBeenLastCalledWith('recentAsks', { id: 's', n: 20 })+ value = ['recap']+ expect(await core.conversations.recaps('s', 5)).toEqual(['recap'])+ expect(ask).toHaveBeenLastCalledWith('recaps', { id: 's', n: 5 })+ value = 'whole answer'+ expect(await core.conversations.lastFullText('s')).toBe(value)+ expect(ask).toHaveBeenLastCalledWith('lastFullText', { id: 's' })+ value = { engine: 'claude', sessionId: 's', transcriptPath: '/s.jsonl', ignored: true }+ expect(await core.conversations.discover('a')).toEqual({ engine: 'claude', sessionId: 's', transcriptPath: '/s.jsonl' })+ expect(ask).toHaveBeenLastCalledWith('discover', { id: 'a' })+ value = '/codex/s.jsonl'+ expect(await core.conversations.findTranscript('codex', 's', { codexHome: '/home' })).toBe(value)+ expect(ask).toHaveBeenLastCalledWith('findTranscript', { engine: 'codex', id: 's', codexHome: '/home' })+ value = true+ expect(await core.conversations.transcriptOk('codex', '/path', null)).toBe(true)+ expect(ask).toHaveBeenLastCalledWith('transcriptOk', { engine: 'codex', path: '/path', codexHome: null })+ })++ it('never uses a remembered record or guesses when a query has no valid answer', async () => {+ const core = handoffCoreApi('/data', async () => ({}))+ expect(await core.conversations.resolve('gone')).toBeNull()+ expect(await core.conversations.recentAsks('s', 20)).toEqual([])+ expect(await core.conversations.recaps('s', 5)).toEqual([])+ expect(await core.conversations.lastFullText('s')).toBeNull()+ expect(await core.conversations.discover('a')).toBeNull()+ expect(await core.conversations.findTranscript('codex', 's', {})).toBeNull()+ expect(await core.conversations.transcriptOk('codex', '/path', null)).toBe(false)+ for (const value of [null, {}, { engine: 7 }, { engine: 'unknown' }, { engine: 'claude' }, { engine: 'claude', sessionId: 's' }]) {+ expect(await handoffCoreApi('/data', async () => ({ value })).conversations.discover('a')).toBeNull()+ }+ await expect(handoffCoreApi('/data', async () => ({ error: 'QUERY_FAILED' })).conversations.resolve('a')).rejects.toThrow('the core did not answer')+ await expect(handoffCoreApi('/data', async () => { throw new Error('disconnected') }).conversations.resolve('a')).rejects.toThrow('disconnected')+ })++ it('uses each current connection and the normal service runner, without a real socket in tests', async () => {+ let options!: ServiceProcessOptions, api!: CoreApi+ const stop = vi.fn()+ const running = runHandoffService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: given => { options = given; return { stop } },+ start: core => { api = core; return { agent_handoff_prepare: async () => ({ value: await core.conversations.resolve('a') }) } },+ })+ expect(options).toMatchObject({ name: 'handoff', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(await api.conversations.resolve('a')).toBeNull()+ const query = vi.fn(async () => ({ value: { agentId: 'a' } }))+ options.onConnected!({ query })+ expect(await options.requests.agent_handoff_prepare!({}, { local: true, owner: true })).toEqual({ value: { agentId: 'a' } })+ expect(query).toHaveBeenLastCalledWith('resolve', { id: 'a' })+ options.onConnected!({ query: async () => ({ value: null }) })+ expect(await api.conversations.resolve('a')).toBeNull()+ running.stop()+ expect(stop).toHaveBeenCalledOnce()+ runHandoffService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(Object.keys(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests)).toEqual([...HANDOFF_REQUESTS])+ })+})diff --git a/cli/src/services/handoffProcess.ts b/cli/src/services/handoffProcess.tsnew file mode 100644index 000000000..e690ffe21--- /dev/null+++ b/cli/src/services/handoffProcess.ts@@ -0,0 +1,60 @@+/** The edge host asks for each retained conversation fact when it needs it. It keeps no registry+ * snapshot, and reads database history here, not back in the core (quiet-machine QA extraction). */+import type { CoreApi } from '../core/api.js'+import { ENGINES, type AgentEngine } from '../engines/types.js'+import { databaseHistory } from '../lib/databaseHistory.js'+import { startHandoff } from './handoff.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { isSession, processCoreApi } from './processCoreApi.js'++type Payload = Record<string, unknown>+const text = (value: unknown): value is string => typeof value === 'string'+const texts = (value: unknown): string[] => Array.isArray(value) ? value.filter(text) : []++export function handoffCoreApi(dataDir: string, ask: (query: string, payload: Payload) => Promise<Payload>): CoreApi {+ const core = processCoreApi(dataDir, 'handoff')+ const read = async (query: string, payload: Payload): Promise<unknown> => {+ const answer = await ask(query, payload)+ // An unreadable stopped record used to answer INTERNAL. Never disguise it as UNKNOWN_AGENT or+ // render a partial file from guessed facts merely because the read crossed a process boundary.+ if (answer.error) throw new Error('the core did not answer a conversation read')+ return answer.value+ }+ core.conversations = {+ resolve: async (id) => { const value = await read('resolve', { id }); return isSession(value) ? value : null },+ recentAsks: async (id, n) => texts(await read('recentAsks', { id, n })),+ lastFullText: async (id) => { const value = await read('lastFullText', { id }); return text(value) ? value : null },+ recaps: async (id, n) => texts(await read('recaps', { id, n })),+ discover: async (id) => {+ const value = await read('discover', { id }) as Payload | null | undefined+ return value && text(value.engine) && (ENGINES as readonly string[]).includes(value.engine) && text(value.sessionId) && text(value.transcriptPath)+ ? { engine: value.engine as AgentEngine, sessionId: value.sessionId, transcriptPath: value.transcriptPath } : null+ },+ findTranscript: async (engine, id, options) => {+ const value = await read('findTranscript', { engine, id, ...options })+ return text(value) ? value : null+ },+ transcriptOk: async (engine, path, codexHome) => (await read('transcriptOk', { engine, path, codexHome })) === true,+ }+ core.transcripts.databaseHistory = databaseHistory+ return core+}++export interface HandoffServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ run?: typeof runServiceProcess+ start?: typeof startHandoff+}++export function runHandoffService(options: HandoffServiceOptions): ServiceProcess {+ let connection: CoreConnection | null = null+ const core = handoffCoreApi(options.dataDir, (query, payload) => connection?.query(query, payload) ?? Promise.resolve({}))+ return (options.run ?? runServiceProcess)({+ name: 'handoff', socketPath: options.socketPath, machineId: options.machineId, token: options.token,+ requests: (options.start ?? startHandoff)(core),+ onConnected: (linked) => { connection = linked },+ })+}diff --git a/cli/src/core/agents/handoff.spec.ts b/cli/src/services/handoffRequest.spec.tssimilarity index 95%rename from cli/src/core/agents/handoff.spec.tsrename to cli/src/services/handoffRequest.spec.tsindex 71ae540d2..4757097e0 100644--- a/cli/src/core/agents/handoff.spec.ts+++ b/cli/src/services/handoffRequest.spec.ts@@ -1,8 +1,8 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { createHandoffRequest, type Handoff } from './handoff.js'+import { createHandoffRequest, type Handoff } from './handoffRequest.js'/**- * `agent_handoff_prepare`, answered by the core: the owner's alone, checked before anything is written,+ * `agent_handoff_prepare`, answered by the handoff service: the owner's alone, checked before anything is written,* written outside the connection's line, and answered with fixed fields and code-shaped errors only.*/const CHANGE = '0123456789abcdef0123456789abcdef'diff --git a/cli/src/core/agents/handoff.ts b/cli/src/services/handoffRequest.tssimilarity index 95%rename from cli/src/core/agents/handoff.tsrename to cli/src/services/handoffRequest.tsindex 3f8fc656d..d4e5853ab 100644--- a/cli/src/core/agents/handoff.ts+++ b/cli/src/services/handoffRequest.ts@@ -4,9 +4,9 @@* folder and runs git there, so only the owner may ask: the loopback window, or a sealed `web` session.* A `device` (the dial) and a shared viewer never do.*- * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ * Same owner guards and reply contract after the quiet-machine QA move into the edge host.*/-import { ENGINES } from '../../engines/types.js'+import { ENGINES } from '../engines/types.js'/** What the handoff is asked for, and what it answers (lib/agentHandoff.ts). */export type HandoffRequest = { agentId: string; changeId: string; targetEngine: string }diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 5b51ff9cd..e6cbbc79d 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import { startGateway } from '../gateway/start.js'import { startCommandBar } from './commandBar.js'import { startDevices } from './devices.js'+import { startHandoff } from './handoff.js'import * as inline from './inline.js'import { startModels } from './models.js'import { startTeamsInCore } from './collaboration.js'@@ -18,6 +19,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ startCommandBar, startDevices, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })+ expect({ ...inline }).toEqual({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 875adaf9d..51ab52aa7 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -15,6 +15,7 @@export { startGateway } from '../gateway/start.js'export { startCommandBar } from './commandBar.js'export { startDevices } from './devices.js'+export { startHandoff } from './handoff.js'export { startModels } from './models.js'export { startTeamsInCore } from './collaboration.js'export { startMonitor } from './monitor.js'diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex b3ef63754..6b38455ce 100644--- a/cli/src/services/modelsProcess.ts+++ b/cli/src/services/modelsProcess.ts@@ -15,7 +15,7 @@* it asks for (`service_query`), each time it needs it: a service keeps no credential.*/import type { CoreApi, ServiceRequests } from '../core/api.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'+import { ACCOUNT_BACKEND_OFF, CONVERSATIONS_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'import type { AgentGridTarget, GridGlance } from '../lib/gridAnnotation.js'import { parseGridLaunchOverride } from '../lib/gridLaunch.js'import { gridGlances, onGridModelsChanged } from '../lib/gridModels.js'@@ -55,6 +55,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Paconst told = (query: string, payload: Payload = {}): void => { void ask(query, payload).catch(() => {}) }return {dataDir,+ conversations: CONVERSATIONS_OFF,// Models opens no terminal.terminals: TERMINALS_OFF,machine: UNASKED.machine,diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 164f23c1e..e4f6061f8 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -13,7 +13,7 @@* each asked of the core over its link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its* name, whether its terminal is there and its harness's viewer.*/-import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, WIFI_OFF, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'+import { CONVERSATIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, WIFI_OFF, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'import type { AgentDshContext } from '../lib/agentFrame.js'import type { RegisteredSession } from '../lib/registry.js'import type { turnsLink } from './turnsLink.js'@@ -86,6 +86,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVieconst daemon = (): DaemonAddress => view.daemon?.() ?? DAEMON_UNKNOWNreturn {dataDir,+ conversations: CONVERSATIONS_OFF,// Terminals are launched by the core alone (the shell service, #893): a service in its own process// is refused, never handed a way to start a process outside the core.terminals: { open: TERMINALS_OFF.open, watch: view.watch ?? TERMINALS_OFF.watch },diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex ba5d1be0e..eae94456d 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -8,8 +8,8 @@* process's alone: a crash or a leak in search costs search, and the master starts it again.*/import type { CoreApi } from '../core/api.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'-import { databaseHistory } from '../core/transcripts/databaseHistory.js'+import { ACCOUNT_BACKEND_OFF, CONVERSATIONS_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'+import { databaseHistory } from '../lib/databaseHistory.js'import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'import { externalProviders } from '../lib/sessionSearch/externals/index.js'import type { RegisteredSession } from '../lib/registry.js'@@ -41,6 +41,7 @@ export function searchCoreApi(): CoreApi {return {dataDir,+ conversations: CONVERSATIONS_OFF,terminals: TERMINALS_OFF,machine: UNASKED.machine,agents: {diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex 9c42fbbea..92f7568cf 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -24,7 +24,7 @@* core's: when it goes, every stream it carried goes with it.*/import type { CoreApi } from '../core/api.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'+import { ACCOUNT_BACKEND_OFF, CONVERSATIONS_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'import { UNASKED } from './processCoreApi.js'@@ -59,6 +59,7 @@ export function viewersCoreApi(const attached = (): RegisteredSession[] => [...sessions.values()]return {dataDir,+ conversations: CONVERSATIONS_OFF,terminals: TERMINALS_OFF,machine: UNASKED.machine,agents: {diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex 7be9df8e9..1de26a860 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -13,7 +13,7 @@* alone: a hang or a crash in it costs workspaces, and the master starts them again.*/import type { CoreApi } from '../core/api.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'+import { ACCOUNT_BACKEND_OFF, CONVERSATIONS_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'import { UNASKED } from './processCoreApi.js'@@ -46,6 +46,7 @@ export function workspacesCoreApi(): CoreApi {return {dataDir,+ conversations: CONVERSATIONS_OFF,terminals: TERMINALS_OFF,machine: UNASKED.machine,agents: {diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 9a1442f8c..66dfccfea 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -4,13 +4,14 @@* one (docs/design/2026-10-03-harnessd.md, the core boundary).*/import { vi } from 'vitest'-import { TERMINALS_OFF, type CoreApi } from '../core/api.js'+import { CONVERSATIONS_OFF, TERMINALS_OFF, type CoreApi } from '../core/api.js'type Overrides = { [K in keyof CoreApi]?: CoreApi[K] extends object ? Partial<CoreApi[K]> : CoreApi[K] }export function fakeCore(over: Overrides = {}): CoreApi {return {dataDir: over.dataDir ?? '/data',+ conversations: { ...CONVERSATIONS_OFF, ...over.conversations },terminals: {open: vi.fn(TERMINALS_OFF.open),watch: { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn(() => () => {}) },diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.tsindex cf2c9f082..fabcd7200 100644--- a/cli/src/testing/socketCore.ts+++ b/cli/src/testing/socketCore.ts@@ -8,7 +8,7 @@ import { join } from 'node:path'import type { BackendSocket } from '../backendSocket.js'import { env } from '../config/env.js'import { createCloseRequests } from '../core/agents/close.js'-import { createHandoffRequest, type Handoff, type HandoffRequest } from '../core/agents/handoff.js'+import { createHandoffRequest, type Handoff, type HandoffRequest } from '../services/handoffRequest.js'import { createLaunchRequests, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from '../core/agents/launches.js'import { MODELS_OFF } from '../core/api.js'import { createPurgeRequest, createStopRequest } from '../core/agents/lifecycle.js'@@ -118,9 +118,15 @@ export function bindAgentUpdate(socket: BackendSocket): void {}).agentUpdate}-/** `agent_handoff_prepare` (core/agents/handoff.ts), written by `prepare`, or by nothing when it is null. */+/** The handoff service's request through the socket's normal service router. */export function bindHandoffRequest(socket: BackendSocket, prepare: ((req: HandoffRequest) => Promise<Handoff>) | null): void {- socket.handoffRequestProvider = createHandoffRequest({ prepare })+ const previous = socket.serviceRouter+ const answer = createHandoffRequest({ prepare })+ socket.serviceRouter = (type, payload, asker, reply) => {+ if (type !== 'agent_handoff_prepare') return previous?.(type, payload, asker, reply) ?? false+ answer(payload, asker, reply)+ return true+ }}type Launcher = { resume: ResumeAgent | null; restart: RestartAgent | null; modelTarget: LaunchRequestDeps['modelTarget'] | null }diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.tsindex c91894832..bad847817 100644--- a/cli/src/testing/teamFixture.ts+++ b/cli/src/testing/teamFixture.ts@@ -11,7 +11,7 @@*/import type { BackendSocket } from '../backendSocket.js'import { env } from '../config/env.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DELIVERIES_OFF, LANE_OFF, TERMINALS_OFF, type CoreApi, type TurnDelivery } from '../core/api.js'+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, CONVERSATIONS_OFF, DELIVERIES_OFF, LANE_OFF, TERMINALS_OFF, type CoreApi, type TurnDelivery } from '../core/api.js'import { projectDisplayName, registry } from '../lib/registry.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'import { startCollaboration, type Teams } from '../services/collaboration.js'@@ -41,6 +41,7 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixturedataDir: env.ADAPTER_DATA_DIR,terminals: TERMINALS_OFF,machine: UNASKED.machine,+ conversations: CONVERSATIONS_OFF,agents: {all: () => registry.list(), live: () => registry.list(), displayName: projectDisplayName,byAgent: (agentId) => registry.byAgent(agentId), resolve: (id) => registry.resolve(id), advertised: () => registry.advertised(),