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
Recaps run as a service, in the edge host: the core tells each turn's lifecycle and never waits (#923)
Deeb4027cbd14fa
diff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.tsindex 51dbdeea3..4c36e9c86 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', 'handoff', 'models']+const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', '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/recapsCompat.e2e.ts b/cli/e2e/recapsCompat.e2e.tsnew file mode 100644index 000000000..5375ad9b4--- /dev/null+++ b/cli/e2e/recapsCompat.e2e.ts@@ -0,0 +1,155 @@+/**+ * What the dial and the windows hear of each turn's recap, compared with another build's. The recaps moved+ * out of the core into a service of their own (services/recaps.ts, in the edge host), and the dial's+ * firmware, the desktop and the phone were written against the cards and recaps a released daemon sends:+ * moving them must not change one. A daemon of that build (`COMPAT_FROM`, its bundled `cli.js`) and one of+ * this checkout's bundle run the same scenario with a fake dial on a pseudo-terminal (harness/fakeDial.ts),+ * which is a device watching, and a window on the local socket: a turn on Claude Code and on Codex, a+ * question the window answers, a turn held and cancelled, and `agent_recent`.+ *+ * Compared: every turn card the dial heard (`turn.*`, `summary`), by type and shape, and its recap text+ * and whether it rang; every `turn_summary` and `turn_summary_pending` a window heard, by shape, and the+ * recap it carried and whether it was a notification; and what `agent_recent` answered. A difference+ * listed in CHANGED is on purpose, with why; TIMING lists what one run may hear and the other not.+ *+ * Skipped unless COMPAT_FROM names a bundle, as e2e/compat.e2e.ts is. `COMPAT_REPORT=<file>` writes both+ * sides, for reading.+ */+import { mkdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'+import { FakeDial, type DialMessage } from './harness/fakeDial.js'++const FROM = process.env.COMPAT_FROM++/** Differences on purpose, by key, each with why. */+const CHANGED: Record<string, string> = {}++/** Types that one run may hear and the other not, by timing alone, each with why. */+const TIMING: Record<string, string> = {+ // The working card's activity line is read from the pane's footer while a turn runs: a fast fake turn+ // can end before the first read.+ 'dial turn.activity': 'read from the pane while a turn runs; a fast turn can end first',+}++type Engine = 'claude' | 'codex'++/** A value's shape: its keys, all the way down; arrays as the shapes of their items. */+function shape(value: unknown): unknown {+ if (Array.isArray(value)) return [...new Set(value.map((item) => JSON.stringify(shape(item))))].sort()+ if (value && typeof value === 'object') {+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, shape((value as Record<string, unknown>)[key])]))+ }+ return typeof value+}++interface Heard {+ shapes: Map<string, Set<string>>+ values: Record<string, unknown>+}++function hear(into: Heard, key: string, value: unknown): void {+ const shapes = into.shapes.get(key) ?? new Set<string>()+ shapes.add(JSON.stringify(shape(value)))+ into.shapes.set(key, shapes)+}++/** One build's daemon, a dial and a window through the scenario; what both heard. */+async function scenario(scriptPath: string | undefined, label: string): Promise<Heard> {+ const dial = await FakeDial.open()+ const daemon = await IsolatedDaemon.create({ ...(scriptPath ? { scriptPath } : {}), env: { CABLE_DISABLE: 'false', HARNESSD_TEST_DIAL_PORT: dial.path } })+ onTestFailed(() => { console.log(`---- ${label} daemon log\n${daemon.log().split('\n').slice(-120).join('\n')}\n---- the dial heard\n${dial.messages.map((m) => m.t).join(' ')}`) })+ const heard: Heard = { shapes: new Map(), values: {} }+ try {+ await daemon.start()+ const window = await LocalClient.connect(daemon)+ await dial.greet()+ const agents: Record<Engine, string> = { claude: '', codex: '' }+ for (const engine of ['claude', 'codex'] as const) {+ const cwd = join(daemon.projectsDir, `recaps-compat-${engine}`)+ mkdirSync(cwd, { recursive: true })+ const created = await window.request('agent_create', { engine, cwd, bypassPermission: true }, 60_000)+ agents[engine] = created.agent.id+ await until(`the ${engine} agent to bind`, async () => ((await window.request('agents_list', {})).agents as Array<Record<string, unknown>>)+ .find((agent) => agent.id === created.agent.id)?.sessionId || null, 45_000, 500)+ }+ window.send('app_panes', { agentIds: Object.values(agents), foreground: true })+ for (const engine of ['claude', 'codex'] as const) {+ const agentId = agents[engine]+ // A turn: the dial's working card, then its recap; the window's recap.+ const since = dial.messages.length+ const summary = window.next((f) => f.type === 'turn_summary' && f.agentId === agentId, 45_000, `${engine}'s turn_summary`)+ window.send('message', { agentId, content: `tell me about the ${engine} narwhal` })+ const card = await dial.next((m) => m.t === 'summary' && m.agentId === agentId && !m.restore, 45_000, `${engine}'s summary card`, since)+ const frame = await summary+ heard.values[`${engine} card`] = { recap: card.recap, text: card.text, silent: card.silent ?? false, quiet: card.quiet ?? false }+ heard.values[`${engine} recap`] = { summary: frame.payload?.summary, notified: !!frame.payload?.notification }+ // A question: asked, answered from the window; the turn's end does not ring "done" over it twice.+ const asked = window.next((f) => f.type === 'commander_question' && f.agentId === agentId, 45_000, `${engine}'s question`)+ const answered = window.next((f) => f.type === 'turn_summary' && f.agentId === agentId, 60_000, `${engine}'s turn_summary after a question`)+ window.send('message', { agentId, content: '!ask' })+ const question = (await asked).payload ?? {}+ const replied = window.next((f) => f.type === 'question_response_result' && f.payload?.requestId === question.requestId, 45_000, `${engine}'s answer`)+ window.send('question_response', { requestId: question.requestId, agentId, answers: { [question.questions[0].q]: 'Coffee' } })+ const reply = (await replied).payload ?? {}+ heard.values[`${engine} answered`] = { ok: reply.ok ?? null, error: reply.error ?? null }+ const after = await answered+ heard.values[`${engine} recap after a question`] = { notified: !!after.payload?.notification, summarized: typeof after.payload?.summary === 'string' }+ // A turn held open, then cancelled: the card clears, with no recap and no ring.+ const held = dial.messages.length+ window.send('message', { agentId, content: '!hold' })+ await dial.next((m) => m.t === 'turn.started' && m.agentId === agentId, 45_000, `${engine}'s held turn`, held)+ window.send('cancel', { agentId })+ await dial.next((m) => m.t === 'turn.done' && m.agentId === agentId, 45_000, `${engine}'s cancelled turn ending`, held)+ heard.values[`${engine} cancel`] = { summaries: dial.messages.slice(held).filter((m) => m.t === 'summary' && m.agentId === agentId).length }+ // What a device restoring its tiles is answered.+ const recent = await window.request('agent_recent', { agentId, n: 3 }, 30_000)+ heard.values[`${engine} agent_recent`] = { events: recent.events, asks: recent.asks }+ }+ await new Promise((resolve) => setTimeout(resolve, 1_500))+ for (const message of dial.messages as DialMessage[]) {+ if (typeof message.t !== 'string' || !(message.t.startsWith('turn.') || message.t === 'summary')) continue+ hear(heard, `dial ${message.t}`, message)+ }+ for (const frame of window.frames as Frame[]) {+ if (frame.type !== 'turn_summary' && frame.type !== 'turn_summary_pending') continue+ hear(heard, `window ${frame.type}`, frame)+ }+ window.close()+ // Each agent's own id says nothing about the build.+ const text = JSON.stringify(heard.values).split(agents.claude).join('<claude>').split(agents.codex).join('<codex>')+ heard.values = JSON.parse(text) as Record<string, unknown>+ return heard+ } finally {+ await daemon.close()+ await dial.close()+ }+}++describe.skipIf(!FROM)('each turn\'s recap, against another build\'s', () => {+ it('the dial and the windows hear the same cards and recaps, in the same shapes', async () => {+ const before = await scenario(FROM, 'released')+ const after = await scenario(process.env.E2E_BUNDLE_PATH, 'this build')+ if (process.env.COMPAT_REPORT) {+ const side = (heard: Heard) => ({ shapes: Object.fromEntries([...heard.shapes].map(([key, set]) => [key, [...set].map((s) => JSON.parse(s))])), values: heard.values })+ writeFileSync(process.env.COMPAT_REPORT, JSON.stringify({ before: side(before), after: side(after) }, null, 2))+ }+ const differences: string[] = []+ for (const key of new Set([...before.shapes.keys(), ...after.shapes.keys()])) {+ if (CHANGED[key] || TIMING[key]) continue+ const was = before.shapes.get(key)+ const is = after.shapes.get(key)+ if (!was) { differences.push(`${key}: only in this build`); continue }+ if (!is) { differences.push(`${key}: not in this build`); continue }+ const lost = [...was].filter((s) => !is.has(s))+ const added = [...is].filter((s) => !was.has(s))+ if (lost.length || added.length) differences.push(`${key}: shapes ${JSON.stringify({ lost, added })}`)+ }+ expect(differences).toEqual([])+ expect(after.values).toEqual(before.values)+ // The scenario heard what it is about, on both builds.+ expect(before.shapes.has('dial summary') && before.shapes.has('window turn_summary')).toBe(true)+ })+})diff --git a/cli/e2e/recapsProcess.e2e.ts b/cli/e2e/recapsProcess.e2e.tsnew file mode 100644index 000000000..43276b497--- /dev/null+++ b/cli/e2e/recapsProcess.e2e.ts@@ -0,0 +1,155 @@+/**+ * The recaps in their own process, the edge host's (`HARNESSD_SERVICES=edge`), for Claude Code and Codex, on+ * the real daemon. The core tells them each turn's lifecycle and never waits on them (core/turns/recaps.ts,+ * core/recapsLink.ts). So whatever happens to their process — killed outright, hung until the master's+ * heartbeat watch kills it, or only slow (stopped, then let go before the watch fires) — every turn still+ * ends on time and every agent goes on; a turn they missed has no recap; and once they are back, the next+ * turn's recap comes as before. The core itself never restarts.+ */+import { execFileSync } from 'node:child_process'+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Engine = 'claude' | 'codex'++const row = async (client: LocalClient, agentId: string) =>+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)+ .find((agent) => agent.id === agentId)+async function create(daemon: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Record<string, any>> {+ const cwd = join(daemon.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()+ return until(`${folder} to bind its conversation`, async () => {+ const agent = await row(client, created.agent.id)+ return agent?.sessionId && agent.status === 'active' ? agent : null+ }, 60_000, 500)+}+const of = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+/** A turn, to its end: how long it took, and the frames this client saw meanwhile. */+async function turn(client: LocalClient, agentId: string, content: string, ms = 45_000): Promise<number> {+ const ended = client.next(of('turn_ended', agentId), ms, `turn_ended (${content})`)+ const at = Date.now()+ client.send('message', { agentId, content })+ await ended+ return Date.now() - at+}+/** A turn, and the recap the recaps cut from its answer: the fake engines answer with the prompt itself. */+async function recapped(client: LocalClient, agentId: string, word: string): Promise<Frame> {+ const summary = client.next((frame) => of('turn_summary', agentId)(frame) && JSON.stringify(frame.payload).includes(word), 45_000, `turn_summary (${word})`)+ await turn(client, agentId, `tell me about the ${word}`)+ return summary+}++/** This daemon's edge host: titled `harnessd-edge` AND started by its own master, by the pid it logged. */+function edgePids(d: IsolatedDaemon): number[] {+ const ours = new Set([...d.log().matchAll(/\[harnessd\] service edge started \(pid (\d+)\)/g)].map((match) => Number(match[1])))+ const table = execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')+ return table.map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)+ .filter(([, pid, command]) => command.trim() === 'harnessd-edge' && ours.has(Number(pid))).map(([, pid]) => Number(pid))+}+const recapsConnections = (d: IsolatedDaemon): number => d.log().split('[services] recaps connected').length - 1+const restarts = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => /\[harnessd\] service edge started .* restart \d+/.test(line)).length++describe('the recaps in their own process', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })+ const fresh = async (env: Record<string, string> = {}) => {+ const d = await IsolatedDaemon.create({ env: {+ HARNESSD_SERVICES: 'edge',+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',+ ...env,+ } })+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ await d.start()+ await until('the recaps to connect to the core', () => recapsConnections(d) >= 1 || null, 30_000, 200)+ return d+ }++ it('cut each turn\'s recap in the edge host, and the core answers what they hold, for both engines', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ expect(edgePids(d)).toHaveLength(1)+ for (const engine of ['claude', 'codex'] as const) {+ const agent = await create(d, client, engine, `recaps-${engine}`)+ const summary = await recapped(client, agent.id, `narwhal${engine}`)+ expect(summary.payload).toMatchObject({ sessionId: agent.sessionId, summary: expect.stringContaining(`narwhal${engine}`) })+ // What a device restoring its tiles asks: answered by the core, from what the recaps told it.+ const recent = await until(`${engine}'s recap to reach the core`, async () => {+ const answer = await client.request('agent_recent', { agentId: agent.id }, 10_000)+ return answer.events?.length ? answer : null+ }, 10_000, 200)+ expect(recent).toMatchObject({ agentId: agent.id, asks: [`tell me about the narwhal${engine}`] })+ expect(JSON.stringify(recent.events)).toContain(`narwhal${engine}`)+ }+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('killed outright: turns end on time and agents go on, and the master brings the recaps back', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'recaps-killed')+ await recapped(client, agent.id, 'pangolin')+ const before = edgePids(d)+ for (const pid of before) process.kill(pid, 'SIGKILL')+ // A turn while they are gone ends as any turn does; asked meanwhile, the core answers from what it kept.+ await turn(client, agent.id, 'while the recaps were gone')+ expect(await client.request('agent_recent', { agentId: agent.id }, 10_000)).not.toHaveProperty('error')+ await until('the master to restart the edge host', () => restarts(d) >= 1 || null, 30_000, 200)+ await until('the recaps to connect again', () => recapsConnections(d) >= 2 || null, 30_000, 200)+ await recapped(client, agent.id, 'axolotl')+ expect(edgePids(d).some((pid) => !before.includes(pid))).toBe(true)+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('hung: turns end while they are stopped, the master kills them, and recaps come again', async () => {+ const d = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '2000' })+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'codex', 'recaps-hung')+ await recapped(client, agent.id, 'okapi')+ for (const pid of edgePids(d)) process.kill(pid, 'SIGSTOP')+ // Hung: a stopped process neither beats nor reads. The core told it the turn and did not wait.+ await turn(client, agent.id, 'while the recaps were hung')+ await until('the master to find the edge host hung', () => d.log().includes('[harnessd] service edge sent no heartbeat') || null, 30_000, 200)+ await until('the edge host to be started again', () => restarts(d) >= 1 || null, 30_000, 200)+ await until('the recaps to connect again', () => recapsConnections(d) >= 2 || null, 30_000, 200)+ await recapped(client, agent.id, 'quokka')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('slow: a turn ends on time while they are stopped, and once let go they catch up without a restart', async () => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'recaps-slow')+ const usual = await turn(client, agent.id, 'how long does a turn take?')+ await recapped(client, agent.id, 'tapir')+ const pids = edgePids(d)+ for (const pid of pids) process.kill(pid, 'SIGSTOP')+ let late: Frame | null = null+ const recap = client.next((frame) => of('turn_summary', agent.id)(frame) && JSON.stringify(frame.payload).includes('dugong'), 45_000, 'the slow turn\'s recap')+ .then((frame) => { late = frame })+ try {+ // On time: as long as a turn took with the recaps answering, give or take the machine's load, and+ // with no recap yet, since the process that cuts it has not read a thing.+ const slow = await turn(client, agent.id, 'tell me about the dugong')+ expect(slow).toBeLessThan(usual + 10_000)+ expect(late).toBeNull()+ } finally {+ for (const pid of pids) process.kill(pid, 'SIGCONT')+ }+ // Let go before the master's watch: the same process reads what waited and cuts the recap, late.+ await recap+ expect(restarts(d)).toBe(0)+ await recapped(client, agent.id, 'manatee')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })+})diff --git a/cli/e2e/serviceProcesses.e2e.ts b/cli/e2e/serviceProcesses.e2e.tsindex 9c16ae46c..67b972908 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', 'handoff']+const EDGE = ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps']/** 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 856352920..25253630f 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,handoff,models'+const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,handoff,recaps,models'describe('a failing service never takes the core down', () => {let daemon: IsolatedDaemon | undefined@@ -97,7 +97,7 @@ describe('a failing service never takes the core down', () => {})it('with services in their own processes failing on every request and event, each request is answered failed, every turn reaches the client, and nothing restarts', async () => {- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search.touch,search.session_search,workspaces.nameBranches,workspaces.sweep,monitor.resources,projects.fs_list_dir' } })+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search.touch,search.session_search,workspaces.nameBranches,workspaces.sweep,monitor.resources,projects.fs_list_dir,recaps.lifecycle' } })const d = daemononTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}`) })await d.start()@@ -121,6 +121,8 @@ describe('a failing service never takes the core down', () => {'[service search] touch failed · injected fault: search.touch','[service search] session_search failed · injected fault: search.session_search','[service workspaces] nameBranches failed · injected fault: workspaces.nameBranches',+ // The recaps failing on every turn event: those turns have no recap, and every one of them still ends.+ '[service recaps] lifecycle failed · injected fault: recaps.lifecycle',]) await until(line, () => d.log().includes(line) || null, 15_000, 250)const agent = await row(client, agentId)expect(agent?.sessionId).toBeTruthy()@@ -133,15 +135,18 @@ describe('a failing service never takes the core down', () => {})it('with every service in the core failing to start, the core starts, runs an agent through turns and a restart, and says each service is off', async () => {- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store,usage,monitor,projects', ...IN_THE_CORE } })+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store,usage,monitor,projects,recaps', ...IN_THE_CORE } })onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })await daemon.start()- for (const service of ['search', 'viewers', 'models', 'workspaces', 'store', 'usage', 'monitor', 'projects']) {+ for (const service of ['search', 'viewers', 'models', 'workspaces', 'store', 'usage', 'monitor', 'projects', 'recaps']) {expect(daemon.log()).toContain(`[services] ${service} did not start · injected fault: ${service} · the core runs without it`)}const client = await LocalClient.connect(daemon)const agentId = await boundAgent(daemon, client, 'no-services')await turn(client, agentId, 'first, with no services')+ // With the recaps off a turn has no recap, and ends all the same.+ await new Promise((done) => setTimeout(done, 1_000))+ expect(client.frames.filter((frame) => frame.type === 'turn_summary')).toEqual([])// Off, never UNSUPPORTED: the apps read that as "update the CLI".expect(await client.request('session_search', { query: 'first' })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: false })for (const type of ['dsh_list', 'dsh_install', 'dsh_update', 'dsh_remove']) {@@ -261,7 +266,7 @@ describe('a failing service never takes the core down', () => {const d = daemononTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-80).join('\n')}`) })await d.start()- for (const service of ['usage', 'monitor', 'projects']) {+ for (const service of ['usage', 'monitor', 'projects', 'recaps']) {await until(`${service} to connect`, () => d.log().includes(`[services] ${service} connected`) || null, 30_000, 200)}expect(d.log()).toContain('[service workspaces] did not start · injected fault: workspaces')@@ -279,7 +284,7 @@ describe('a failing service never takes the core down', () => {})it('the monitor\'s readings failing on every call in the core leave the list its rows, then switch the monitor off; the core runs on', async () => {- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'monitor.resources,projects.fs_list_dir', ...IN_THE_CORE } })+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'monitor.resources,projects.fs_list_dir,recaps.lifecycle', ...IN_THE_CORE } })onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })await daemon.start()const client = await LocalClient.connect(daemon)@@ -295,6 +300,9 @@ describe('a failing service never takes the core down', () => {expect(await client.request('fs_list_dir', {})).toMatchObject({ error: 'SERVICE_FAILED', service: 'projects' })expect(await client.request('project_preview', { path: '/no/such/folder' })).not.toHaveProperty('service')await turn(client, agentId, 'with the monitor off')+ // The recaps failing on every turn event in the core: switched off by its guard, and the turns go on.+ await until('the recaps to be switched off', () => daemon?.log().includes('[services] recaps switched off after 5 failures') || null, 15_000, 250)+ await turn(client, agentId, 'with the recaps off')expect(daemon.coresStarted()).toBe(1)client.close()})diff --git a/cli/e2e/signedIn.e2e.ts b/cli/e2e/signedIn.e2e.tsindex 55eea1971..f35ec8a36 100644--- a/cli/e2e/signedIn.e2e.ts+++ b/cli/e2e/signedIn.e2e.ts@@ -15,7 +15,7 @@ import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'type Engine = 'claude' | 'codex'const MACHINE: FakeMachine = { machineId: 'c3'.repeat(16), computerId: 'e2e-computer-0000-0000-00000000000c', name: 'signed-in', token: 'e2e-token-signed-in' }/** Every service but the experiments, which start only once they are on (e2e/experiments.e2e.ts). */-const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects'] as const+const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'recaps'] as constconst row = async (client: LocalClient, agentId: string) =>((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 53f1098c8..fa26fc83e 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -311,7 +311,13 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// Then at 72,134 in 333, from 73,411 in 338: the updater left the core for a process the master runs// (services/updaterProcess.ts), and the core never downloads a build. The CLI's and hn's updaters// (lib/selfUpdate.ts, tui/update.ts, tui/install.ts) went, with the spawn lock they staged under.-const CORE_CLOSURE_BUDGET = 72_230+//+// Then at 71,244 in 332, from 72,134 in 333: the recaps (each turn's recap, the devices' turn cards and the+// notification a finished turn rings: lib/commander.ts and lib/agentNotifications.ts) run as a service, in+// the edge host by default (services/recaps.ts). The core keeps the turn lifecycle it tells them, a port+// that never waits (core/turns/recaps.ts, core/recapsLink.ts) and the reads of what they hold+// (lib/recapReads.ts).+const CORE_CLOSURE_BUDGET = 71_350/** 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[] = [@@ -325,6 +331,9 @@ const EDGE: RegExp[] = [/^lib\/(remoteRelay|terminalP2p|stunSelect|remoteViewerProxy|deviceRecentTrim|commanderReplay)\.ts$/,// The viewers' own: a viewer served to a client over its connection, and the stream it runs on./^lib\/(viewerForwarder|interactiveViewer|viewerWire)\.ts$/,+ // The recaps' own parts: the mirror that cuts each turn's recap and card, and the notification policy it+ // shares with the questions the core tells it of (services/recaps.ts).+ /^lib\/(commander|agentNotifications)\.ts$/,// The Store's and the viewers' parts of dsh; the launch path (installed, manifest, launch, runtime, …) is the core's./^dsh\/(catalog|install|update|updates|registry|wire|service|lock|builtins|viewer|viewerLedger|verdict|artifacts)\.ts$/,// Search's index; the readers of other engines' sessions (external.ts, externals/) are the core's, for adoption.diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex db9599c8f..922f911a7 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -44,7 +44,9 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGEframes, handed to the viewers, and refused at once while they are down. `workspacesLink.ts`: what the core tells workspaces intheirs. `teamsLink.ts`: every change to the teams' prompt scopes, kept until their process has it once Tabcollaboration is on, which of its deliveries may be written, and the scopes' own two questions.- `monitorLink.ts`: the monitor's port, asked of its process. `storeLink.ts`: what the Store in its+ `monitorLink.ts`: the monitor's port, asked of its process. `recapsLink.ts`: the recaps in their process,+ told each turn's lifecycle and never waited on, and read back from what they last said+ (`turns/recaps.ts` is the core's whole side of them). `storeLink.ts`: what the Store in itsprocess tells the core. `modelsLink.ts`: what the core keeps of models in its process for frames andkeystrokes, and how it asks it the rest. `agentQueries.ts`: what a service in its own process may ask of the agents;`accountQueries.ts`: of the account (a token, and the fleet's lane's sealing), so it holds no credential.diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.tsindex 39269570a..e24a28bcb 100644--- a/cli/src/core/agents/bind.ts+++ b/cli/src/core/agents/bind.ts@@ -12,7 +12,7 @@ import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilimport { findCursorTranscript } from '../../engines/cursor/discovery.js'import { cursorDataDir } from '../../engines/cursor/home.js'import { findGrokTranscript } from '../../engines/grok/session.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from '../turns/recaps.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import { isRecentlyDeleted } from '../../lib/deletedSessions.js'import { transcriptIsFirstTurn } from '../../lib/firstTurnReplay.js'@@ -53,7 +53,7 @@ export type RegisteredMeta = {export interface BindDeps {registry: Pick<typeof registry, 'inheritName' | 'unbindSession' | 'byAgent' | 'byProcess' | 'register' | 'has' | 'bySession'>- mirror: Pick<CommanderMirror, 'inheritSummary'>+ mirror: Pick<TurnRecaps, 'inheritSummary'>forgetSession: (id: string, opts?: { force?: boolean; keepAgent?: boolean; agentId?: string }) => void/** The app. */clients: { send(frame: { type: string; payload: Record<string, unknown> }): void }diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.tsindex dd44364ed..b34313d2a 100644--- a/cli/src/core/agents/forget.ts+++ b/cli/src/core/agents/forget.ts@@ -9,7 +9,7 @@ import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'import type { AutonomousDeviceInput } from '../deviceInput.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from '../turns/recaps.js'import { sid } from '../../lib/log.js'import type { registry } from '../../lib/registry.js'import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'@@ -40,7 +40,7 @@ export interface ForgetDeps {input: Pick<SessionInputController, 'forget'>deviceInput: Pick<AutonomousDeviceInput, 'forget'>detachDsh: (agentId: string) => void- mirror: Pick<CommanderMirror, 'forget'>+ mirror: Pick<TurnRecaps, 'forget'>/** The app (`send`) and the dial (`sendCommander`). */clients: { send(frame: Frame): void; sendCommander(frame: Frame): void }dataDir: stringdiff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.tsindex c4825b0f8..34ee159b6 100644--- a/cli/src/core/agents/fork.ts+++ b/cli/src/core/agents/fork.ts@@ -14,7 +14,7 @@ import { installedDsh } from '../../dsh/installed.js'import { harnessEnvToClear } from '../../dsh/launch.js'import { forkRuntimeKey, harnessLaunchOrRefusal, prepareHarnessLaunch } from '../../dsh/runtime.js'import { opencodeMajorVersion } from '../../engines/opencode/version.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from '../turns/recaps.js'import { createAndRegisterPane } from '../../lib/createAgentPane.js'import { enginePathOverride } from '../../lib/engineBin.js'import { engineInstallRecipe } from '../../lib/engineInstall.js'@@ -32,7 +32,7 @@ type ForkAgent = NonNullable<BackendSocket['onForkAgent']>export interface ForkAgentDeps {tmuxBackend: TmuxBackend | nullregistry: typeof registry- mirror: Pick<CommanderMirror, 'isBusy' | 'recentAsks' | 'recent' | 'lastFullText'>+ mirror: Pick<TurnRecaps, 'isBusy' | 'recentAsks' | 'recent' | 'lastFullText'>/** Forks whose session has not reported in yet, to the source session whose recap they inherit (bind.ts). */pendingForkInherit: Map<string, string>watchNewPane: ReturnType<typeof createPaneWatcher>diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 523095edc..ffc9ecdf1 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 { 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 { 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, RECAPS_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@@ -79,6 +79,9 @@ describe('the core API services stand on', () => {devicesChanged: vi.fn(),dialWatching: vi.fn(),wifi: WIFI_OFF,+ lastTurn: vi.fn(async () => null),+ turnCard: vi.fn(),+ turnSummary: vi.fn(),log: vi.fn(),})@@ -144,6 +147,41 @@ describe('the core API services stand on', () => {expect(core.clients.hasWindow).toBe(deps.hasWindow)expect(core.clients.devicesChanged).toBe(deps.devicesChanged)expect(core.clients.dialWatching).toBe(deps.dialWatching)+ expect(core.transcripts.lastTurn).toBe(deps.lastTurn)+ })++ it('lets the recaps send a turn\'s cards and recaps, and nothing else, down those doors', () => {+ const log = vi.fn()+ const turnCard = vi.fn()+ const turnSummary = vi.fn()+ const core = createCoreApi({ turnCard, turnSummary, log } as unknown as CoreApiDeps)+ const card = { type: 'commander_event' as const, agentId: 'a', dbSessionId: 's', payload: { kind: 'done' } }+ core.clients.turnCard(card)+ core.clients.turnSummary({ type: 'turn_summary', payload: {} })+ core.clients.turnSummary({ type: 'turn_summary_pending', payload: {} })+ expect(turnCard).toHaveBeenCalledWith(card)+ expect(turnSummary.mock.calls.map(([frame]) => frame.type)).toEqual(['turn_summary', 'turn_summary_pending'])+ // A frame that is not theirs is refused, and said: a recaps process speaks to the core as a service.+ core.clients.turnCard({ ...card, type: 'agents_list' } as never)+ core.clients.turnSummary({ type: 'commander_event' } as never)+ core.clients.turnSummary(undefined as never)+ expect(turnCard).toHaveBeenCalledTimes(1)+ expect(turnSummary).toHaveBeenCalledTimes(2)+ expect(log.mock.calls.map(([line]) => line)).toEqual([+ '[services] the recaps sent agents_list, which is not theirs to send',+ '[services] the recaps sent commander_event, which is not theirs to send',+ '[services] the recaps sent undefined, which is not theirs to send',+ ])+ // Said to the daemon's log unless told otherwise.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ createCoreApi({ turnCard, turnSummary } as unknown as CoreApiDeps).clients.turnCard({ type: 'nope' } as never)+ expect(warn).toHaveBeenCalledWith('[services] the recaps sent nope, which is not theirs to send')+ warn.mockRestore()+ })++ it('tells the recaps nothing, and reads no recap, when they fail', () => {+ expect(RECAPS_FALLBACKS).toMatchObject({ lifecycle: undefined, recaps: null })+ expect(readFallback(RECAPS_FALLBACKS.liveCards)).toEqual({ deferred: true, value: [] })})it('lets the devices put their own frames in front of the windows, and no other', () => {@@ -214,7 +252,7 @@ describe('the core API services stand on', () => {})it('starts with every port empty: a service fills its own when it starts', () => {- expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null })+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null })expect(emptyPorts()).not.toBe(emptyPorts())})diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 85853ebd2..fbcf1c867 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -25,7 +25,8 @@ import type { AgentGridTarget, GridAnnotation } from '../lib/gridAnnotation.js'import { GRID_FLEET_MAX_TIMEOUT_MS } from '../lib/gridFleetProtocol.js'import type { GridLaunchOverride } from '../lib/gridLaunch.js'import type { NewAgentModel } from '../lib/newAgentModel.js'-import type { LiveEvent } from '../lib/normalize.js'+import type { LastTurnText, LiveEvent } from '../lib/normalize.js'+import type { SessionRecaps } from '../lib/recapReads.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'@@ -181,6 +182,9 @@ export interface CoreApi {/** How to read a conversation its engine keeps in a database instead of a transcript file;* undefined for every other engine. */databaseHistory(session: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined+ /** A session's last turn as its engine recorded it: what was asked and the final answer; null when+ * there is none yet. Read from the end of its transcript, bounded (core/transcripts/lastTurn.ts). */+ lastTurn(sessionId: string): Promise<LastTurnText | null>}/** Conversations on this machine that Harness did not start, and which of them a process has open. */external: {@@ -256,6 +260,10 @@ export interface CoreApi {/** A dial on this computer is watching it, or no longer is: the core then makes the turn cards and* recaps for it, as for a device watching through the backend. */dialWatching(watching: boolean): void+ /** A turn's card for the devices (`commander_event`): its progress, and its recap once it ends. */+ turnCard(frame: TurnCardFrame): void+ /** A turn's recap for the apps (`turn_summary`, or `turn_summary_pending` while one is being cut). */+ turnSummary(frame: TurnSummaryFrame): void}/** How an agent's shell reaches this daemon: the command that runs this harness's CLI, the port the daemon* serves and the machine it serves as. An experiment writes them into the prompts of the agents it runs@@ -375,6 +383,20 @@ export const DELIVERIES_OFF: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery'onDelivery: () => () => {},}+/** A turn's card for the devices: the dial's and the Wi-Fi device's tiles and their notifications. */+export type TurnCardFrame = {+ type: 'commander_event'+ agentId: string+ dbSessionId: string+ name?: string+ payload: Record<string, unknown>+}+/** A turn's recap for the windows and the phone. */+export type TurnSummaryFrame = { type: 'turn_summary' | 'turn_summary_pending' } & Record<string, unknown>+/** The frame types `clients.turnCard` and `clients.turnSummary` carry: the core sends no other for them. */+export const TURN_CARD_TYPES: ReadonlySet<string> = new Set(['commander_event'])+export const TURN_SUMMARY_TYPES: ReadonlySet<string> = new Set(['turn_summary', 'turn_summary_pending'])+/** `agents.resolve` over a service process's own copy of the agents, as the registry answers it: by agent* id, then by engine session id (an agent with none yet is never found by an empty one). */export function resolveAgent(agents: readonly RegisteredSession[], id: string): RegisteredSession | undefined {@@ -552,6 +574,68 @@ export const SEARCH_FALLBACKS: PortFallbacks<SearchPort> = {touch: undefined, deleteHistory: undefined, session: undefined, stop: undefined,}+/*+ * Recaps (services/recaps.ts): each turn's recap, the devices' turn cards and the notifications a finished+ * turn rings, built from the turn's lifecycle. The core tells the recaps that lifecycle as it happens and+ * never waits on them: a session runs the same without them, and a turn they miss simply has no recap.+ */++/** A session as the core knows it when it tells the recaps something: what a card is addressed to. */+export interface RecapSession {+ sessionId: string+ /** The agent that owns it: a card is addressed to the agent, stable across a `/clear`. */+ agentId: string+ /** Its display name, which a summary card carries for a machine whose tile is not loaded. */+ name?: string+ /** Its transcript: a Claude sub-agent writes its own beside it, which a held turn end watches. */+ transcriptPath?: string+ /** An Orchestrator specialist's turn, or its director's while specialists are out: nobody's news. Said+ * where a turn ends, a cancel or a forget (reading it reads the orchestrator); absent, the recaps keep+ * what they were last told. */+ subagent?: boolean+}++/** Who watches this machine's turn cards: a device at all (through the backend or on the cable), and one+ * rendering this machine right now. */+export interface RecapWatchers { device: boolean; active: boolean }++/** The turn lifecycle, as the core tells the recaps. */+export type TurnLifecycle =+ /** A session's events (a turn started, its text, its tools and sub-agents, its end), as one batch. */+ | { kind: 'events'; session: RecapSession; events: LiveEvent[]; replay: boolean }+ /** The core's five-second turn heartbeat, and whether the turn is verifiably working right now. */+ | { kind: 'beat'; session: RecapSession; working: boolean }+ /** The turn was cancelled: no turn end comes. */+ | { kind: 'cancelled'; session: RecapSession }+ /** The session was unbound, or its agent removed; what is stored for it is kept for a resume. */+ | { kind: 'forgotten'; session: RecapSession }+ /** The engine's Stop hook: it stopped writing. */+ | { kind: 'stopped'; sessionId: string }+ /** The agent's conversation moved to a new session (a `/clear`, a fork's first turn): its recaps follow. */+ | { kind: 'rebound'; from: string; to: string }+ /** The conversation was purged: everything stored for it goes. */+ | { kind: 'purged'; sessionId: string }+ /** A question was put to the person, or answered: a turn waiting on one is not announced as done. */+ | { kind: 'asked' | 'answered'; sessionId: string; requestId: string }+ /** A device joined: every session's card is said again. `working`: the sessions whose turn is+ * verifiably working now, whose busy card is said with it. */+ | { kind: 'rejoined'; working: string[] }++/** The core's calls into the recaps: the lifecycle, and what they hold of a session, read in line. */+export interface RecapsPort {+ /** Something happened to a turn. A notice: the core never waits for it, and one the recaps miss costs+ * that turn its recap, nothing else. */+ lifecycle(event: TurnLifecycle, watchers: RecapWatchers): void+ /** A session's last turns and asks, and whether its card is busy; null when they hold nothing. */+ recaps(sessionId: string): SessionRecaps | null+ /** The cards of every turn still working or being recapped, for a dial that just attached: asked when it+ * attaches and sent when they come, never waited for in line. */+ liveCards(): Promise<TurnCardFrame[]>+}++/** What the core gets when the recaps fail: nothing told, no recap, and no live card. */+export const RECAPS_FALLBACKS: PortFallbacks<RecapsPort> = { lifecycle: undefined, recaps: null, liveCards: later([]) }+/** The core's calls into the DSH viewers: each harness agent's viewer server and verdict watch. */export interface ViewersPort {/** Start the agent's viewer and verdict watch when it has a DSH. Idempotent: called on every@@ -1166,10 +1250,11 @@ export interface CorePorts {monitor: MonitorPort | nullorchestrator: OrchestratorPort | nullsharing: SharingPort | null+ recaps: RecapsPort | null}export function emptyPorts(): CorePorts {- return { search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null }+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null }}export interface CoreApiDeps {@@ -1220,6 +1305,10 @@ export interface CoreApiDeps {dialWatching: CoreApi['clients']['dialWatching']/** The Wi-Fi device's doors (core/wifi.ts). */wifi: CoreApi['wifi']+ lastTurn: CoreApi['transcripts']['lastTurn']+ /** Where a turn's cards and recaps go: the devices, and the apps. Only their own frame types reach these. */+ turnCard: CoreApi['clients']['turnCard']+ turnSummary: CoreApi['clients']['turnSummary']log?: (line: string) => void}@@ -1227,13 +1316,16 @@ 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, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText,- signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, log = (line) => console.warn(line),+ signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, lastTurn, turnCard, turnSummary,+ log = (line) => console.warn(line),}: CoreApiDeps): CoreApi {// The devices reach the windows through these alone, and only with their own frames: a devices process// speaks to the core as a service, and what it may put in front of a person is decided here, not there.const windowFrames = new Set<string>(DEVICE_WINDOW_FRAMES)const bridgeFrames = new Set<string>(DEVICE_BRIDGE_FRAMES)const refused = (type: unknown): void => log(`[services] the devices sent a window ${String(type).slice(0, 40)}, which is not theirs to send`)+ // The recaps reach the devices and the apps through their own two doors, and only with their own frames.+ const refusedRecap = (type: unknown): void => log(`[services] the recaps sent ${String(type).slice(0, 40)}, which is not theirs to send`)return {dataDir,terminals,@@ -1258,7 +1350,7 @@ export function createCoreApi({},turns,questions,- transcripts: { databaseHistory },+ transcripts: { databaseHistory, lastTurn },external: { sessions: externalSessions, open: openSessions },account: { mintGridName, accessToken, lane, observerKey, privateGridName, machineName, backend, onNotice, signedIn, environment, machines },clients: {@@ -1275,6 +1367,8 @@ export function createCoreApi({refused(frame?.type)return false},+ turnCard: (frame) => { if (TURN_CARD_TYPES.has(frame?.type)) turnCard(frame); else refusedRecap(frame?.type) },+ turnSummary: (frame) => { if (TURN_SUMMARY_TYPES.has(frame?.type)) turnSummary(frame); else refusedRecap(frame?.type) },},daemon,wifi,diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 4eb8024aa..a612d3b7f 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -128,6 +128,8 @@ import { createWorkspacesLink } from './workspacesLink.js'import { createMonitorLink } from './monitorLink.js'import { createStoreLink } from './storeLink.js'import { createModelsLink } from './modelsLink.js'+import { createRecapsLink } from './recapsLink.js'+import { RECAPS_FALLBACKS } from './api.js'import { answerAgentQuery } from './agentQueries.js'import { createDeliveries } from './deliveries.js'import { createTerminalWatch } from './terminalWatch.js'@@ -622,6 +624,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend: (method, path, body) => proxyBackend(method, path, body),onNotice: (listener) => experimentHooks.onNotice(listener),dshInstallStatus: (status) => backendRef?.send({ type: 'dsh_install_status', payload: status }),+ // The recaps' cards and recaps (services/recaps.ts) down the doors they took from here, and a turn's final answer.+ turnCard: (frame) => backendRef?.sendCommander(frame), turnSummary: (frame) => backendRef?.send(frame), lastTurn: (sessionId) => readLastTurn(sessionId),// The backend mints and remembers the account's grid name; this CLI holds neither the account's// email nor its id. An older backend (no route) answers nothing, which the grid reconcile treats as// "no grid yet". Bounded so a stalled control-plane connection cannot hold the attempt open.@@ -665,7 +669,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// A dial attaching is shown what is still being asked and what is still working, as a device joining// through the backend is (onCommanderJoin): one whose devices' process restarted comes back to tiles// mid-turn, and to a question nobody has answered yet.- if (attached) for (const frame of [...openQuestions.values(), ...mirror.liveCards()]) ports.devices?.card(frame)+ // The working tiles are the recaps' to say: asked, and sent to the dial when they answer.+ if (attached) for (const frame of openQuestions.values()) ports.devices?.card(frame)+ if (attached) void mirror.liveCards().then((cards) => { for (const frame of cards) ports.devices?.card(frame) })},// What a device or another machine asks of an agent here: the SAME handlers the backend socket// drives, called directly — the slash-command adaptation and the turn and question plumbing live there.@@ -1033,7 +1039,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The monitor's readings, through its port (services/monitor.ts): none while it is off.harnessResourcesReader: () => (ports.monitor ?? MONITOR_OFF).resources(), harnessStorageReader: (agents, invalidate) => (ports.monitor ?? MONITOR_OFF).storage(agents, invalidate),}).agentsList- const agentNotifications = asking.agentNotificationsconst questionWatcher = asking.questionWatcher@@ -1043,22 +1048,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },hermesDb: (s) => hermesDbForSession(s),})- // Recaps: turn cards on the dial and the window, notifications on the phone (core/turns/recaps.ts).+ // Recaps: turn cards, notifications, cut by the recaps (services/recaps.ts) from the lifecycle the core tells (core/turns/recaps.ts).const recaps = createRecaps({- notifications: agentNotifications,- turnActivity,- clients: backend,- deviceIsWatching,- cableWatchingLocal,- bySession: (sessionId) => registry.bySession(sessionId),- resolve: (id) => registry.resolve(id),+ port: () => ports.recaps, turnActivity, clients: backend, deviceIsWatching, cableWatchingLocal, sessionTurnOpen,+ bySession: (sessionId) => registry.bySession(sessionId), resolve: (id) => registry.resolve(id), live: () => registry.list(),stopped: (agentId) => stoppedAgents.get(agentId),orchestratorRoleOf: (agentId) => ports.orchestrator?.roleOf(agentId) ?? null,- readLastTurn,- dataDir: env.ADAPTER_DATA_DIR,- recapForce: env.RECAP_FORCE,- recapWithoutDevice: () => env.RECAP_WITHOUT_DEVICE,})+ asking.hearQuestions(recaps.question) // a turn waiting on the person is not announced as doneconst isSubagentSession = recaps.isSubagentSessionconst mirror = recaps.mirror// Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap@@ -1131,6 +1128,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Its port from the start: its process connects as soon as the socket answers, before the rest of the// core is wired, and is resumed through this port then (core/wifi.ts `started`).if (outOfProcess.has('wifi')) ports.wifi = wifiLink.port+ // What the core tells the recaps in their own process, and reads back from what they said (core/recapsLink.ts).+ const recapsLink = createRecapsLink({ notify: (frame, opts) => serviceLinks.notify('recaps', frame, opts), buffered: () => serviceLinks.buffered('recaps'),+ call: (type, payload) => serviceLinks.call('recaps', type, payload), clients: coreApi.clients, lastTurn: coreApi.transcripts.lastTurn })const serviceLinks = createServiceLinks({token: serviceToken,owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),@@ -1150,10 +1150,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {: service === 'devices' ? devicesLink.answer(query, payload): service === 'wifi' ? wifiLink.answer(query, payload): service === 'handoff' ? answerConversationQuery(coreApi, query, payload)+ : service === 'recaps' ? recapsLink.answer(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.- notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload); else if (service === 'wifi') wifiLink.notice(payload); else if (service === 'viewers') viewersLink.notice(payload) },+ notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload); else if (service === 'wifi') wifiLink.notice(payload); else if (service === 'viewers') viewersLink.notice(payload); else if (service === 'recaps') recapsLink.notice(payload) },binary: (service, bytes) => { if (service === 'gateway') gatewayLink?.binary(bytes) },connected: (service) => {if (service === 'gateway') gatewayLink?.connected()@@ -1166,6 +1167,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (service === 'gateway') gatewayLink?.disconnected()if (service === 'devices') devicesLink.disconnected()if (service === 'wifi') wifiCore.stopped()+ if (service === 'recaps') recapsLink.disconnected()void terminalWatch.gone(service)},})@@ -1224,6 +1226,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {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)+ // The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.+ if (outOfProcess.has('recaps')) ports.recaps = recapsLink.port; else serviceHost.start('recaps', inline!.startRecaps, coreApi, RECAPS_FALLBACKS)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/questions.spec.ts b/cli/src/core/questions.spec.tsindex e17e25aa9..fea9256dc 100644--- a/cli/src/core/questions.spec.ts+++ b/cli/src/core/questions.spec.ts@@ -77,11 +77,21 @@ describe('questions', () => {const remember = vi.spyOn(asking.questions, 'remember')const log = vi.spyOn(console, 'log').mockImplementation(() => {})const shaped = [{ q: 'Ship it?', options: [] }]+ // Before the recaps hear questions, one is nobody else's news; after, they hear each.+ given(asking.questionWatcher).onQuestion('s1', 'r0', shaped)+ vi.mocked(deps.clients.sendCommander).mockClear()+ vi.mocked(deps.clients.sendLocal).mockClear()+ log.mockClear()+ const heard = vi.fn()+ asking.hearQuestions(heard)given(asking.questionWatcher).onQuestion('s1', 'r1', shaped)+ expect(heard).toHaveBeenCalledWith('asked', 's1', 'r1')expect(deps.deviceInput.setUserAction).toHaveBeenCalledWith('a1', true)expect(remember).toHaveBeenCalledWith('r1', 's1')const asked = vi.mocked(deps.clients.sendLocal).mock.calls[0][0]expect(asked).toMatchObject({ type: 'commander_question', agentId: 'a1', dbSessionId: 's1', payload: { requestId: 'r1', questions: shaped } })+ // A question is always news: the person is needed.+ expect(asked.payload.notification).toEqual({ id: 'r1', kind: 'needsYou' })expect(vi.mocked(deps.clients.sendCommander).mock.calls).toEqual([[waiting('s1', 'a1')], [asked]])expect(asking.openQuestions.get('s1')).toBe(asked)expect(log.mock.calls[0][0]).toContain('asking the user · "Ship it?" · req=r1')@@ -101,12 +111,19 @@ describe('questions', () => {it('closes a question answered elsewhere on every client it was shown on', () => {const { deps, asking } = setup()- const answered = vi.spyOn(asking.agentNotifications, 'answered')+ const answered = vi.fn()const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ // Before the recaps hear questions, an answer is closed all the same.+ given(asking.questionWatcher).onQuestionGone('s1', 'r0')+ vi.mocked(deps.clients.sendCommander).mockClear()+ vi.mocked(deps.clients.sendLocal).mockClear()+ vi.mocked(deps.deviceInput.setUserAction).mockClear()+ log.mockClear()+ asking.hearQuestions(answered)asking.openQuestions.set('s1', {})given(asking.questionWatcher).onQuestionGone('s1', 'r1')const closed = { type: 'commander_question_close', agentId: 'a1', dbSessionId: 's1', payload: { requestId: 'r1' } }- expect(answered).toHaveBeenCalledWith('s1', 'r1')+ expect(answered).toHaveBeenCalledWith('answered', 's1', 'r1')expect(deps.deviceInput.setUserAction).toHaveBeenCalledWith('a1', false)expect(deps.clients.sendCommander).toHaveBeenCalledWith(closed)expect(deps.clients.sendLocal).toHaveBeenCalledWith(closed)diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.tsindex 95cd658d9..dad6fbbec 100644--- a/cli/src/core/questions.ts+++ b/cli/src/core/questions.ts@@ -7,7 +7,6 @@* Moved verbatim out of `runForeground` (the core boundary, step 6: docs/design/2026-10-03-harnessd.md).* The socket's two handlers stay bound there: `answer` (question_response) and `monitorActivity`.*/-import { AgentNotifications } from '../lib/agentNotifications.js'import { AskQuestionController, QuestionWatcher, type QuestionAnswerPayload, type QuestionAnswerResult } from '../lib/askQuestion.js'import type { AutonomousDeviceInput } from './deviceInput.js'import { preview, sid } from '../lib/log.js'@@ -69,7 +68,10 @@ export function createQuestions({const openQuestions = new Map<string, Record<string, unknown>>()const monitorActivity = (sessionId: string): 'needsInput' | 'working' | 'idle' => openQuestions.has(sessionId)? 'needsInput' : sessionTurnOpen(sessionId) ? 'working' : 'idle'- const agentNotifications = new AgentNotifications()+ // Who hears that a question was asked or answered: the recaps, which do not announce a turn waiting on+ // the person as done (services/recaps.ts). Told once they exist; a question before then is nobody's news.+ let heard: ((kind: 'asked' | 'answered', sessionId: string, requestId: string) => void) | null = null+ const hearQuestions = (listener: typeof heard): void => { heard = listener }const questionWatcher = new QuestionWatcher({getSession: (id) => resolve(id),capture: captureTerminal,@@ -83,11 +85,14 @@ export function createQuestions({type: 'commander_question',agentId: agentIdFor(sessionId),dbSessionId: sessionId,- payload: { requestId, questions: shaped, notification: agentNotifications.asked(sessionId, requestId),+ // A question is always news: the person is needed (lib/agentNotifications.ts `asked`, which the+ // recaps keep to hold back the turn's own "done").+ payload: { requestId, questions: shaped, notification: { id: requestId, kind: 'needsYou' },// Robot clients need to distinguish a permission notice from an answerable question....(detail?.permission ? { permission: { dialog: detail.dialog, resolution: 'desktop' } } : {}),},}+ heard?.('asked', sessionId, requestId)clients.sendCommander(asked)// ...and to the window on this computer. `sendCommander` is `webEligible: false`, so until this// second call the app could not learn that an agent was blocked even though the question had@@ -108,7 +113,7 @@ export function createQuestions({// waiting, down the SAME path the question itself took, so the dial and the WiFi device cannot// disagree about whether a question is still open.onQuestionGone: (sessionId, requestId) => {- agentNotifications.answered(sessionId, requestId)+ heard?.('answered', sessionId, requestId)deviceInput.setUserAction(agentIdFor(sessionId), false)const closed = {type: 'commander_question_close',@@ -126,7 +131,7 @@ export function createQuestions({},})const questionResponse = createQuestionResponse(answer)- return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, monitorActivity, agentNotifications, questionWatcher }+ return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, monitorActivity, hearQuestions, questionWatcher }}/**diff --git a/cli/src/core/recapsLink.spec.ts b/cli/src/core/recapsLink.spec.tsnew file mode 100644index 000000000..0d7b944f4--- /dev/null+++ b/cli/src/core/recapsLink.spec.ts@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from 'vitest'+import { createRecapsLink, RECAPS_BUFFER_LIMIT } from './recapsLink.js'++const watchers = { device: true, active: false }+const s1 = { sessionId: 's1', agentId: 'a1' }++function setup() {+ let buffered = 0+ let clock = 1_000_000+ const deps = {+ notify: vi.fn(() => true),+ buffered: vi.fn(() => buffered),+ call: vi.fn(async (_type: string, _payload: Record<string, unknown>): Promise<Record<string, unknown>> => ({ cards: [] })),+ clients: { turnCard: vi.fn(), turnSummary: vi.fn() },+ lastTurn: vi.fn(async (sessionId: string) => (sessionId === 's1' ? { assistantText: 'done', userMessage: 'go' } : null)),+ log: vi.fn(),+ now: () => clock,+ }+ const link = createRecapsLink(deps)+ return { deps, link, back: (bytes: number) => { buffered = bytes }, later: (ms: number) => { clock += ms } }+}++describe('the recaps in their own process, as the core sees them', () => {+ it('tells each lifecycle event as a notification it never waits on, holding a purge and a rebound until heard', () => {+ const { deps, link } = setup()+ link.port.lifecycle({ kind: 'events', session: s1, events: [], replay: false }, watchers)+ link.port.lifecycle({ kind: 'purged', sessionId: 's1' }, watchers)+ link.port.lifecycle({ kind: 'rebound', from: 's1', to: 's2' }, watchers)+ expect(deps.notify.mock.calls).toEqual([+ [{ type: 'service_event', payload: { kind: 'lifecycle', event: { kind: 'events', session: s1, events: [], replay: false }, watchers } }, {}],+ [{ type: 'service_event', payload: { kind: 'lifecycle', event: { kind: 'purged', sessionId: 's1' }, watchers } }, { untilDelivered: true }],+ [{ type: 'service_event', payload: { kind: 'lifecycle', event: { kind: 'rebound', from: 's1', to: 's2' }, watchers } }, { untilDelivered: true }],+ ])+ })++ it('drops what would pile up on a process that reads nothing, says so once a minute, and never a purge', () => {+ const { deps, link, back, later } = setup()+ back(RECAPS_BUFFER_LIMIT + 1)+ for (let i = 0; i < 3; i++) link.port.lifecycle({ kind: 'beat', session: s1, working: true }, watchers)+ link.port.lifecycle({ kind: 'purged', sessionId: 's1' }, watchers)+ expect(deps.notify).toHaveBeenCalledTimes(1)+ expect(deps.log.mock.calls).toEqual([["[recaps] the recaps' process is not reading: 1 turn event(s) dropped; those turns have no recap"]])+ later(60_000)+ link.port.lifecycle({ kind: 'stopped', sessionId: 's1' }, watchers)+ expect(deps.log.mock.calls.at(-1)).toEqual(["[recaps] the recaps' process is not reading: 3 turn event(s) dropped; those turns have no recap"])+ back(0)+ link.port.lifecycle({ kind: 'stopped', sessionId: 's1' }, watchers)+ expect(deps.notify).toHaveBeenCalledTimes(2)+ })++ it('answers what the core reads from what the process last said of each session, and forgets a purge at once', () => {+ const { link } = setup()+ expect(link.port.recaps('s1')).toBeNull()+ link.notice({ kind: 'recaps', sessionId: 's1', recaps: { latest: 'r\n\nb', history: ['r\n\nb', 7], fullTexts: ['all of it'], asks: ['why?'], busy: true } })+ expect(link.port.recaps('s1')).toEqual({ latest: 'r\n\nb', history: ['r\n\nb'], fullTexts: ['all of it'], asks: ['why?'], busy: true })+ // Whatever is missing reads as nothing held.+ link.notice({ kind: 'recaps', sessionId: 's2', recaps: { history: 'no' } })+ expect(link.port.recaps('s2')).toEqual({ latest: null, history: [], fullTexts: [], asks: [], busy: false })+ link.notice({ kind: 'recaps', sessionId: 's2', recaps: null })+ expect(link.port.recaps('s2')).toBeNull()+ link.port.lifecycle({ kind: 'purged', sessionId: 's1' }, watchers)+ expect(link.port.recaps('s1')).toBeNull()+ // Not a session's recaps: ignored.+ link.notice({ kind: 'recaps', sessionId: 3, recaps: {} })+ expect(link.port.recaps('3')).toBeNull()+ })++ it('sends the process\'s cards and recaps on through the core API, which checks their types', () => {+ const { deps, link } = setup()+ const card = { type: 'commander_event', agentId: 'a1', dbSessionId: 's1', payload: { kind: 'done' } }+ link.notice({ kind: 'card', frame: card })+ link.notice({ kind: 'summary', frame: { type: 'turn_summary', payload: {} } })+ link.notice({ kind: 'card' })+ link.notice({ kind: 'summary', frame: 'x' })+ link.notice({ kind: 'other', frame: card })+ expect(deps.clients.turnCard.mock.calls).toEqual([[card]])+ expect(deps.clients.turnSummary.mock.calls).toEqual([[{ type: 'turn_summary', payload: {} }]])+ })++ it('reads a turn\'s final answer for the process, and answers nothing else', async () => {+ const { link } = setup()+ expect(await link.answer('lastTurn', { sessionId: 's1' })).toEqual({ turn: { assistantText: 'done', userMessage: 'go' } })+ expect(await link.answer('lastTurn', { sessionId: 's9' })).toEqual({ turn: null })+ expect(await link.answer('lastTurn', {})).toEqual({ error: 'UNKNOWN_QUERY' })+ expect(await link.answer('agents', {})).toEqual({ error: 'UNKNOWN_QUERY' })+ })++ it('asks the process for the cards of every turn still at work, and takes none it cannot read', async () => {+ const { deps, link } = setup()+ const card = { type: 'commander_event', agentId: 'a1', dbSessionId: 's1', payload: { kind: 'processing', text: 'Processing' } }+ deps.call.mockResolvedValueOnce({ cards: [card, null, 'x'] })+ expect(await link.port.liveCards()).toEqual([card])+ expect(deps.call).toHaveBeenCalledWith('liveCards', {})+ // Down, or answering something else: no card.+ deps.call.mockResolvedValueOnce({ error: 'SERVICE_UNAVAILABLE', service: 'recaps', retryable: true })+ expect(await link.port.liveCards()).toEqual([])+ })++ it('keeps no card busy once the process is gone', () => {+ const { link } = setup()+ link.notice({ kind: 'recaps', sessionId: 's1', recaps: { history: ['r'], busy: true } })+ link.notice({ kind: 'recaps', sessionId: 's2', recaps: { history: ['q'], busy: false } })+ link.disconnected()+ expect(link.port.recaps('s1')).toMatchObject({ history: ['r'], busy: false })+ expect(link.port.recaps('s2')).toMatchObject({ history: ['q'], busy: false })+ })++ it('says it to the daemon\'s log unless told otherwise', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const link = createRecapsLink({ notify: vi.fn(() => true), buffered: () => RECAPS_BUFFER_LIMIT + 1, call: vi.fn(), clients: { turnCard: vi.fn(), turnSummary: vi.fn() }, lastTurn: vi.fn() })+ link.port.lifecycle({ kind: 'stopped', sessionId: 's1' }, watchers)+ expect(warn).toHaveBeenCalledTimes(1)+ warn.mockRestore()+ })+})diff --git a/cli/src/core/recapsLink.ts b/cli/src/core/recapsLink.tsnew file mode 100644index 000000000..c8746191f--- /dev/null+++ b/cli/src/core/recapsLink.ts@@ -0,0 +1,112 @@+/**+ * The recaps in their own process, as the core sees them (services/recapsProcess.ts; in the edge host by+ * default).+ *+ * The core tells the process each turn's lifecycle as a notification (`service_event lifecycle`) and goes+ * on: it never waits for an answer, and one the process misses — down, hung, restarting — costs that turn+ * its recap and its card, nothing else. A hung process reads nothing, so what would pile up on the socket+ * to it is dropped past RECAPS_BUFFER_LIMIT and said once a minute, rather than kept in the core's memory.+ * Two notifications are held until the process hears them, as a purge's is for search: a purge's+ * forgetting, and a conversation's recaps moving to its new session.+ *+ * What the core reads back in line (an agent's last turns and asks, whether its card is busy) it answers+ * from what the process last said of each session (`service_notice recaps`), which the process says again+ * whole each time it connects. A purge forgets here at once, before the process hears it: a purged+ * conversation's recaps are never served again. The process gone, no card of it is busy.+ *+ * What the process would put in front of a person (a device's card, the apps' recap) it sends as a notice,+ * which goes through the core API's check of its type. A turn's final answer it asks of the core+ * (`service_query lastTurn`): the transcript is the core's to read.+ */+import type { CoreApi, RecapsPort, TurnCardFrame } from './api.js'+import type { SessionRecaps } from '../lib/recapReads.js'+import type { ServiceFrame } from './serviceLinks.js'++/** The most the core lets wait on the socket to a recaps process that reads nothing. */+export const RECAPS_BUFFER_LIMIT = 4 * 1024 * 1024++export interface RecapsLinkDeps {+ /** Tell the recaps' process something (core/serviceLinks.ts `notify`, for `recaps`). */+ notify(frame: ServiceFrame, opts?: { untilDelivered?: boolean }): boolean+ /** How many bytes wait on the socket to it. */+ buffered(): number+ /** Ask it something (core/serviceLinks.ts `call`, for `recaps`): its answer, or SERVICE_UNAVAILABLE. */+ call(type: string, payload: Record<string, unknown>): Promise<Record<string, unknown>>+ /** Where its cards and recaps go: the core API checks each frame's type. */+ clients: Pick<CoreApi['clients'], 'turnCard' | 'turnSummary'>+ lastTurn: CoreApi['transcripts']['lastTurn']+ log?: (line: string) => void+ now?: () => number+}++const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])++/** What the process said of a session, as the core keeps it; null when it said nothing is held. */+function recapsOf(value: unknown): SessionRecaps | null {+ if (!value || typeof value !== 'object') return null+ const said = value as Record<string, unknown>+ return {+ latest: typeof said.latest === 'string' ? said.latest : null,+ history: strings(said.history),+ fullTexts: strings(said.fullTexts),+ asks: strings(said.asks),+ busy: said.busy === true,+ }+}++export function createRecapsLink(deps: RecapsLinkDeps) {+ const log = deps.log ?? ((line: string) => console.warn(line))+ const now = deps.now ?? Date.now+ const known = new Map<string, SessionRecaps>()+ let dropped = 0+ let saidAt = -Infinity++ const port: RecapsPort = {+ lifecycle: (event, watchers) => {+ if (event.kind === 'purged') known.delete(event.sessionId)+ const held = event.kind === 'purged' || event.kind === 'rebound'+ if (!held && deps.buffered() > RECAPS_BUFFER_LIMIT) {+ dropped+++ if (now() - saidAt >= 60_000) {+ log(`[recaps] the recaps' process is not reading: ${dropped} turn event(s) dropped; those turns have no recap`)+ saidAt = now()+ dropped = 0+ }+ return+ }+ deps.notify({ type: 'service_event', payload: { kind: 'lifecycle', event, watchers } }, held ? { untilDelivered: true } : {})+ },+ recaps: (sessionId) => known.get(sessionId) ?? null,+ liveCards: async () => {+ const answer = await deps.call('liveCards', {})+ return Array.isArray(answer.cards) ? answer.cards.filter((card): card is TurnCardFrame => !!card && typeof card === 'object') : []+ },+ }++ return {+ port,+ /** What the process says without asking: a session's recaps, a card, a recap for the apps. */+ notice(payload: Record<string, unknown>): void {+ if (payload.kind === 'recaps' && typeof payload.sessionId === 'string') {+ const recaps = recapsOf(payload.recaps)+ if (recaps) known.set(payload.sessionId, recaps)+ else known.delete(payload.sessionId)+ } else if (payload.kind === 'card' && payload.frame && typeof payload.frame === 'object') {+ deps.clients.turnCard(payload.frame as Parameters<RecapsLinkDeps['clients']['turnCard']>[0])+ } else if (payload.kind === 'summary' && payload.frame && typeof payload.frame === 'object') {+ deps.clients.turnSummary(payload.frame as Parameters<RecapsLinkDeps['clients']['turnSummary']>[0])+ }+ },+ /** The core's answers to the process's questions (core/serviceLinks.ts `answer`, for `recaps`). */+ async answer(query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (query === 'lastTurn' && typeof payload.sessionId === 'string') return { turn: await deps.lastTurn(payload.sessionId) }+ return { error: 'UNKNOWN_QUERY' }+ },+ /** The process went: no card of it is busy any more, and the core's heartbeats stop with their turns. */+ disconnected(): void {+ for (const [sessionId, recaps] of known) if (recaps.busy) known.set(sessionId, { ...recaps, busy: false })+ },+ }+}++export type RecapsLink = ReturnType<typeof createRecapsLink>diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex faa61021d..996b42a6a 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -143,7 +143,7 @@ export function createAttach({const initialEvents: LiveEvent[] = []// Folding the transcript in below is deliberately silent — old turns must never replay live. But// when the history ENDS mid-turn the turn is still running, and dropping its `turn_started` costs- // the whole turn: CommanderMirror.onTurnEnded returns early while turnOpen is false, so the close+ // the whole turn: the recaps' mirror (lib/commander.ts onTurnEnded) returns early while turnOpen is false, so the close// that follows produces no recap and no `done`. Keep the last start and replay exactly that one.//// The exception is a transcript BORN AFTER its agent — the file is then the live first turn ratherdiff --git a/cli/src/core/turns/cancel.ts b/cli/src/core/turns/cancel.tsindex f56ea22db..0cb3d9010 100644--- a/cli/src/core/turns/cancel.ts+++ b/cli/src/core/turns/cancel.ts@@ -9,7 +9,7 @@ import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'import { correlateAgentEvent } from '../../lib/agentEvent.js'import type { QuestionWatcher } from '../../lib/askQuestion.js'import type { WifiFeed } from '../wifi.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from './recaps.js'import type { RegisteredSession } from '../../lib/registry.js'import type { SessionInputController } from '../../lib/sessionInput.js'import type { TurnActivity } from '../../lib/turnActivity.js'@@ -24,7 +24,7 @@ export interface CancelDeps {device: () => Pick<WifiFeed, 'turnEnded'> | undefinedstopHeartbeat: (sessionId: string) => voidquestionWatcher: Pick<QuestionWatcher, 'stop'>- mirror: Pick<CommanderMirror, 'cancel'>+ mirror: Pick<TurnRecaps, 'cancel'>turnActivity: Pick<TurnActivity, 'observe' | 'snapshot'>/** When each open turn started (the heartbeats'): the WiFi device reads an agent as running by it. */turnStartedAt: Map<string, number>diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsindex aea593df6..30f4d972d 100644--- a/cli/src/core/turns/funnel.ts+++ b/cli/src/core/turns/funnel.ts@@ -14,7 +14,7 @@ import { correlateAgentEvent } from '../../lib/agentEvent.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import { isDeviceInputBoundary } from '../deviceInput.js'import type { WifiFeed } from '../wifi.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from './recaps.js'import { deviceErrorText } from '../cardText.js'import { preview, sid } from '../../lib/log.js'import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'@@ -51,7 +51,7 @@ export interface FunnelDeps {device: () => Pick<WifiFeed, 'turnStarted' | 'turnEnded' | 'stream'> | undefinedstartHeartbeat: (sessionId: string) => voidquestionWatcher: Pick<QuestionWatcher, 'start' | 'noteTurnStart' | 'stop'>- mirror: Pick<CommanderMirror, 'ingest'>+ mirror: Pick<TurnRecaps, 'ingest'>/** How a consumer outside the core is called ([outsideConsumers]). */outside?: OutsideConsumers}@@ -160,9 +160,9 @@ export function funnelFor({// terminal sitting on a question the device never showed. Its watcher runs off the session, not// the turn — see the attach path — so leave it alone.if (bySession(sessionId)?.engine !== 'commandcode') questionWatcher.stop(sessionId)- // Do NOT stop the heartbeat here: the turn is closed but the device summarize is just starting- // (mirror sets summarizing=true in the mirror.ingest below). The timer keeps fanning "Summarizing…"- // to the device and self-cancels once mirror.heartbeat() reports idle (summary done).+ // Do NOT stop the heartbeat here: the turn is closed but its recap is just being cut (the recaps+ // hear the batch below and say its card is busy). The timer keeps beating for the device's card and+ // stops once mirror.heartbeat() reads it idle, which is at once while the recaps are off.}}mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })diff --git a/cli/src/core/turns/heartbeats.ts b/cli/src/core/turns/heartbeats.tsindex 0a35e2265..67059ecaf 100644--- a/cli/src/core/turns/heartbeats.ts+++ b/cli/src/core/turns/heartbeats.ts@@ -6,7 +6,7 @@* Moved verbatim out of `runForeground` (the core boundary, step 7: docs/design/2026-10-03-harnessd.md).*/import { correlateAgentEvent, turnHeartbeatFrame } from '../../lib/agentEvent.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from './recaps.js'import type { RegisteredSession } from '../../lib/registry.js'import type { RuntimeActivityReader } from '../../lib/runtimeActivity.js'import type { TurnActivity } from '../../lib/turnActivity.js'@@ -17,7 +17,7 @@ export interface HeartbeatDeps {agentIdFor: (sessionId: string) => stringruntimeActivity: Pick<RuntimeActivityReader, 'forget'>turnActivity: Pick<TurnActivity, 'check' | 'snapshot' | 'forget'>- mirror: Pick<CommanderMirror, 'heartbeat'>+ mirror: Pick<TurnRecaps, 'heartbeat'>/** The app. */clients: { send(frame: ReturnType<typeof correlateAgentEvent>): void }}diff --git a/cli/src/core/turns/recaps.spec.ts b/cli/src/core/turns/recaps.spec.tsindex d18a851fc..8e55d9d26 100644--- a/cli/src/core/turns/recaps.spec.ts+++ b/cli/src/core/turns/recaps.spec.ts@@ -1,49 +1,43 @@-import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'-import { AgentNotifications } from '../../lib/agentNotifications.js'-import { SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from '../../lib/commander.js'-import { deriveTurnSummary } from '../../lib/deviceRecap.js'+import type { LiveEvent } from '../../lib/normalize.js'+import type { SessionRecaps } from '../../lib/recapReads.js'import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'import type { ActivityFrame } from '../../lib/turnActivity.js'+import type { RecapsPort } from '../api.js'import { createRecaps, type RecapDeps } from './recaps.js'-const dirs: string[] = []-const temp = () => { const dir = mkdtempSync(join(tmpdir(), 'core-recaps-')); dirs.push(dir); return dir }-function setup(over: Partial<RecapDeps> = {}) {- const transcripts = temp()- const transcriptPath = join(transcripts, 'main.jsonl')- const live = { agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', transcriptPath } as RegisteredSession+ const live = { agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', transcriptPath: '/t/s1.jsonl' } as RegisteredSessionconst bare = { agentId: 'a2', sessionId: 's2', engine: 'claude', cwd: '/work/other' } as RegisteredSessionconst sessions = new Map([['s1', live], ['s2', bare]])+ const held = new Map<string, SessionRecaps>()+ const card = { type: 'commander_event' as const, agentId: 'a1', dbSessionId: 's1', payload: { kind: 'processing' } }+ const port = { lifecycle: vi.fn(), recaps: vi.fn((sessionId: string) => held.get(sessionId) ?? null), liveCards: vi.fn(async () => [card]) } satisfies RecapsPort+ let on: RecapsPort | null = portconst deps: RecapDeps = {- notifications: new AgentNotifications(),+ port: () => on,turnActivity: { snapshot: vi.fn(() => undefined) },- clients: { sendCommander: vi.fn(), send: vi.fn(), hasActiveCommander: vi.fn(() => false) },+ clients: { hasActiveCommander: vi.fn(() => false) },deviceIsWatching: vi.fn(() => true),cableWatchingLocal: vi.fn(() => false),bySession: (sessionId) => sessions.get(sessionId),resolve: (id) => id === 'a1' ? live : undefined,stopped: (agentId) => agentId === 'gone' ? ({ agentId: 'gone', sessionId: 'old-s' } as RegisteredSession) : null,+ live: () => [live, bare, { agentId: 'a3', sessionId: '' } as RegisteredSession],+ sessionTurnOpen: vi.fn((sessionId: string) => sessionId === 's1'),orchestratorRoleOf: vi.fn(() => null),- readLastTurn: vi.fn(async () => null),- dataDir: temp(),- recapForce: false,- recapWithoutDevice: () => true,...over,}const recaps = createRecaps(deps)- const opts = (recaps.mirror as unknown as { opts: CommanderMirrorOpts }).opts- return { deps, recaps, opts, live, transcriptPath }+ return { deps, recaps, port, held, live, off: () => { on = null } }}-describe('recaps', () => {- afterEach(() => {- vi.restoreAllMocks()- for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })- })+const watching = { device: true, active: false }+const started = { type: 'turn_started', payload: { userMessage: 'hi' } } as LiveEvent+const ended = { type: 'turn_ended', payload: {} } as LiveEvent++describe('recaps, as the core keeps them', () => {+ afterEach(() => { vi.restoreAllMocks() })it('counts a specialist\'s turn, or a director\'s while specialists are out, as a sub-agent\'s', () => {const { deps, recaps } = setup()@@ -65,53 +59,112 @@ describe('recaps', () => {expect(recaps.isSubagentSession('s1')).toBe(false)})- it('gives the mirror the clients, the device gates and an excerpt for a recap', async () => {- const { deps, opts } = setup()- vi.mocked(deps.turnActivity.snapshot).mockReturnValueOnce({ state: 'working' } as ActivityFrame).mockReturnValueOnce({ state: 'idle' } as ActivityFrame)- expect(opts.verifiedWorking!('s1')).toBe(true)- expect(opts.verifiedWorking!('s1')).toBe(false)- const frame = { type: 'commander_event', agentId: 'a1', dbSessionId: 's1', payload: {} } as Parameters<CommanderMirrorOpts['send']>[0]- opts.send(frame)- opts.sendWeb({ type: 'turn_summary' })- expect(deps.clients.sendCommander).toHaveBeenCalledWith(frame)- expect(deps.clients.send).toHaveBeenCalledWith({ type: 'turn_summary' })- expect(opts.hasDevice!()).toBe(true)- expect(opts.active!()).toBe(false)+ it('tells the recaps each batch, addressed as the core knows the session, and whether it is a sub-agent\'s only where a turn ends', () => {+ const { deps, recaps, port, live } = setup()+ recaps.mirror.ingest([started], 's1')+ vi.mocked(deps.orchestratorRoleOf).mockReturnValueOnce({ role: 'worker' })+ recaps.mirror.ingest([ended], 's1', { replay: true })+ recaps.mirror.ingest([started], 's2')+ recaps.mirror.ingest([started], 'unbound')+ const session = { sessionId: 's1', agentId: 'a1', name: projectDisplayName(live), transcriptPath: '/t/s1.jsonl' }+ expect(port.lifecycle.mock.calls).toEqual([+ [{ kind: 'events', session, events: [started], replay: false }, watching],+ [{ kind: 'events', session: { ...session, subagent: true }, events: [ended], replay: true }, watching],+ [{ kind: 'events', session: { sessionId: 's2', agentId: 'a2', name: projectDisplayName({ agentId: 'a2', sessionId: 's2', engine: 'claude', cwd: '/work/other' } as RegisteredSession) }, events: [started], replay: false }, watching],+ // A session the core no longer has is addressed by its own id, as the cards always were.+ [{ kind: 'events', session: { sessionId: 'unbound', agentId: 'unbound' }, events: [started], replay: false }, watching],+ ])+ expect(deps.orchestratorRoleOf).toHaveBeenCalledTimes(1)+ })++ it('says who watches: a device at all, and one rendering this machine (a plugged-in dial always is)', () => {+ const { deps, recaps, port } = setup()+ vi.mocked(deps.deviceIsWatching).mockReturnValue(false)+ recaps.mirror.noteEngineStopped('s1')vi.mocked(deps.cableWatchingLocal).mockReturnValueOnce(true)- expect(opts.active!()).toBe(true)+ recaps.mirror.noteEngineStopped('s1')vi.mocked(deps.clients.hasActiveCommander).mockReturnValueOnce(true)- expect(opts.active!()).toBe(true)- expect(await opts.summarize!('The fix is in. Tests pass.')).toEqual(await deriveTurnSummary('The fix is in. Tests pass.'))- expect(opts.summarizeIsLocal).toBe(true)- expect(opts.notifyWithoutDevice).toBe(true)- expect(opts.notifications).toBe(deps.notifications)- expect(opts.readLastTurn).toBe(deps.readLastTurn)- expect(opts.dataDir).toBe(deps.dataDir)- expect(opts.recapForce).toBe(false)- expect((opts.alwaysGenerate as () => boolean)()).toBe(true)+ recaps.mirror.noteEngineStopped('s1')+ expect(port.lifecycle.mock.calls.map(([, seen]) => seen)).toEqual([+ { device: false, active: false }, { device: false, active: true }, { device: false, active: true },+ ])+ })++ it('beats with whether the turn is verifiably working, and keeps beating while the recaps say its card is busy', () => {+ const { deps, recaps, port, held, off } = setup()+ vi.mocked(deps.turnActivity.snapshot).mockReturnValueOnce({ state: 'working' } as ActivityFrame)+ expect(recaps.mirror.heartbeat('s1')).toBe(false)+ held.set('s1', { latest: null, history: [], fullTexts: [], asks: [], busy: true })+ expect(recaps.mirror.heartbeat('s1')).toBe(true)+ expect(port.lifecycle.mock.calls.map(([event]) => event)).toMatchObject([+ { kind: 'beat', session: { sessionId: 's1' }, working: true },+ { kind: 'beat', session: { sessionId: 's1' }, working: false },+ ])+ // The recaps off: nothing is busy, and nothing is told.+ off()+ expect(recaps.mirror.heartbeat('s1')).toBe(false)+ expect(port.lifecycle).toHaveBeenCalledTimes(2)})- it('names agents and asks about sub-agents the way the rest of the core does', () => {- const { deps, opts, live } = setup()- expect(opts.nameFor!('s1')).toBe(projectDisplayName(live))- expect(opts.nameFor!('nobody')).toBeUndefined()- expect(opts.agentIdFor!('s1')).toBe('a1')- expect(opts.agentIdFor!('nobody')).toBeUndefined()+ it('tells a cancel, a forget, a purge, a rebound and a Stop hook, each in its own words', () => {+ const { deps, recaps, port } = setup()vi.mocked(deps.orchestratorRoleOf).mockReturnValueOnce({ role: 'worker' })- expect(opts.isSubagent!('s1')).toBe(true)+ recaps.mirror.cancel('s1')+ recaps.mirror.forget('s2')+ recaps.mirror.deleteHistory('s1')+ recaps.mirror.inheritSummary('s1', 's9')+ recaps.mirror.noteEngineStopped('s2')+ expect(port.lifecycle.mock.calls.map(([event]) => event)).toMatchObject([+ { kind: 'cancelled', session: { sessionId: 's1', subagent: true } },+ { kind: 'forgotten', session: { sessionId: 's2', subagent: false } },+ { kind: 'purged', sessionId: 's1' },+ { kind: 'rebound', from: 's1', to: 's9' },+ { kind: 'stopped', sessionId: 's2' },+ ])+ })++ it('says, as a device joins, which turns are verifiably working, so their busy cards go with it', () => {+ const { deps, recaps, port } = setup()+ vi.mocked(deps.turnActivity.snapshot).mockImplementation((sessionId) => (sessionId === 's2' ? { state: 'working' } as ActivityFrame : undefined))+ recaps.mirror.replayAll()+ expect(port.lifecycle).toHaveBeenCalledWith({ kind: 'rejoined', working: ['s2'] }, watching)+ })++ it('tells the recaps a question asked and answered', () => {+ const { recaps, port } = setup()+ recaps.question('asked', 's1', 'r1')+ recaps.question('answered', 's1', 'r1')+ expect(port.lifecycle.mock.calls.map(([event]) => event)).toEqual([+ { kind: 'asked', sessionId: 's1', requestId: 'r1' },+ { kind: 'answered', sessionId: 's1', requestId: 'r1' },+ ])+ })++ it('asks the recaps for the cards of turns still at work, and has none while they are off', async () => {+ const { recaps, off } = setup()+ expect(await recaps.mirror.liveCards()).toEqual([expect.objectContaining({ type: 'commander_event', dbSessionId: 's1' })])+ off()+ expect(await recaps.mirror.liveCards()).toEqual([])+ })++ it('reads a fork\'s "busy" from the core\'s own turn, not from the recaps', () => {+ const { recaps, port } = setup()+ expect(recaps.mirror.isBusy('s1')).toBe(true)+ expect(recaps.mirror.isBusy('s2')).toBe(false)+ expect(port.recaps).not.toHaveBeenCalled()})- it('counts a Claude Code sub-agent as at work while its own transcript is still growing', () => {- const { opts, transcriptPath } = setup()- expect(opts.subagentActive!('s2', 'x'), 'no transcript').toBe(false)- expect(opts.subagentActive!('s1', 'x'), 'no sub-agent file').toBe(false)- const file = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', 'agent-x.jsonl')- mkdirSync(join(file, '..'), { recursive: true })- writeFileSync(file, '{}\n')- expect(opts.subagentActive!('s1', 'x')).toBe(true)- const old = (Date.now() - SUBAGENT_IDLE_MS - 60_000) / 1000- utimesSync(file, old, old)- expect(opts.subagentActive!('s1', 'x')).toBe(false)+ it('reads a session\'s recaps from what the recaps hold, and none while they are off', () => {+ const { recaps, held, off } = setup()+ held.set('s1', { latest: 'old\n\nbody', history: ['r1\n\nb1', 'r0\n\nb0'], fullTexts: ['full one', 'full zero'], asks: ['why?', 'how?'], busy: false })+ expect(recaps.mirror.recent('s1', 1)).toEqual([{ kind: 'summary', text: 'b1', recap: 'r1', fullText: 'full one' }])+ expect(recaps.mirror.recentAsks('s1', 1)).toEqual(['why?'])+ expect(recaps.mirror.lastFullText('s1')).toBe('full one')+ expect(recaps.mirror.recent('nobody')).toEqual([])+ off()+ expect(recaps.mirror.recent('s1')).toEqual([])+ expect(recaps.mirror.recentAsks('s1')).toEqual([])+ expect(recaps.mirror.lastFullText('s1')).toBeUndefined()})it('looks recaps up under the engine session, asked for by agent, live or stopped', () => {diff --git a/cli/src/core/turns/recaps.ts b/cli/src/core/turns/recaps.tsindex f232226a0..f2733205c 100644--- a/cli/src/core/turns/recaps.ts+++ b/cli/src/core/turns/recaps.ts@@ -1,65 +1,75 @@/**- * Recaps: the dial's and the window's turn cards and the phone's notifications, through the commander- * mirror. A recap is an excerpt of the answer, cut as the turn ends; a sub-agent's turn end is not- * announced; recaps are stored under the engine session and asked for by agent.+ * Recaps, as the core keeps them: only the turn's lifecycle, told to the recaps service as it happens+ * (services/recaps.ts, through `RecapsPort`), and what it holds of a session, read back in line. The cards+ * on the dial and in the window, the notifications on the phone and the recap files are the service's.*- * Moved verbatim out of `runForeground` (the core boundary, step 7: docs/design/2026-10-03-harnessd.md).+ * The core never waits on it. Each call below is a notice the service may miss, or a read of what it last+ * said (in its own process, core/recapsLink.ts), or none while it is off: then a turn has no recap and+ * no card, and nothing else changes. A recap is stored under the engine session and asked for by agent.+ *+ * `mirror` keeps the calls the rest of the core made into the commander mirror when it ran here, so the+ * funnel, the heartbeats, cancel, fork, binding and purge each say what happened in their own words.*/-import { statSync } from 'node:fs'-import { join } from 'node:path'-import type { AgentNotifications } from '../../lib/agentNotifications.js'-import { CommanderMirror, SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from '../../lib/commander.js'-import { deriveTurnSummary } from '../../lib/deviceRecap.js'-import type { LastTurnText } from '../../lib/normalize.js'+import type { LiveEvent } from '../../lib/normalize.js'+import { lastFullText, recentAsks, recentRecaps, type RecentRecap, type SessionRecaps } from '../../lib/recapReads.js'import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'import type { TurnActivity } from '../../lib/turnActivity.js'import type { OrchestratorService } from '../../orchestrator/service.js'--type CommanderFrame = Parameters<CommanderMirrorOpts['send']>[0]-type WebFrame = Parameters<CommanderMirrorOpts['sendWeb']>[0]+import type { RecapSession, RecapsPort, RecapWatchers, TurnCardFrame, TurnLifecycle } from '../api.js'export interface RecapDeps {- notifications: AgentNotifications+ /** The recaps service's port, or null while it is off. */+ port: () => RecapsPort | nullturnActivity: Pick<TurnActivity, 'snapshot'>- /** The dial (`sendCommander`, `hasActiveCommander`) and the app (`send`). */- clients: { sendCommander(frame: CommanderFrame): void; send(frame: WebFrame): void; hasActiveCommander(): boolean }+ /** Whether a device actively renders this machine through the backend. */+ clients: { hasActiveCommander(): boolean }deviceIsWatching: () => booleancableWatchingLocal: () => booleanbySession: (sessionId: string) => RegisteredSession | undefinedresolve: (id: string) => RegisteredSession | undefined/** A stopped agent's archived record (stoppedAgents.get). */stopped: (agentId: string) => RegisteredSession | null+ /** The live agents: which of them are verifiably working, when a device joins. */+ live: () => RegisteredSession[]+ /** Whether a turn is open on the session: the core's own word, from its transcript. */+ sessionTurnOpen: (sessionId: string) => boolean/** The orchestrator's role for an agent: a specialist, or the director. */orchestratorRoleOf: OrchestratorService['roleOf']- readLastTurn: (sessionId: string) => Promise<LastTurnText | null>- dataDir: string- recapForce: boolean- recapWithoutDevice: () => boolean+}++/** The calls the core makes about a turn's recap. */+export interface TurnRecaps {+ /** A session's events, as one batch. */+ ingest(events: LiveEvent[], sessionId: string, options?: { replay?: boolean }): void+ /** The turn heartbeat: whether the devices' card for it is still busy, as the recaps last said. */+ heartbeat(sessionId: string): boolean+ cancel(sessionId: string): void+ forget(sessionId: string): void+ deleteHistory(sessionId: string): void+ inheritSummary(fromSessionId: string, toSessionId: string): void+ noteEngineStopped(sessionId: string): void+ replayAll(): void+ /** A turn is open on the session right now: a fork waits for it to end. */+ isBusy(sessionId: string): boolean+ recent(sessionId: string, n?: number): RecentRecap[]+ recentAsks(sessionId: string, n?: number): string[]+ lastFullText(sessionId: string): string | undefined+ /** The cards of every turn still at work, for a dial that just attached; none while the recaps are off. */+ liveCards(): Promise<TurnCardFrame[]>}export function createRecaps({- notifications, turnActivity, clients, deviceIsWatching, cableWatchingLocal, bySession, resolve, stopped,- orchestratorRoleOf, readLastTurn, dataDir, recapForce, recapWithoutDevice,+ port, turnActivity, clients, deviceIsWatching, cableWatchingLocal, bySession, resolve, stopped, live, sessionTurnOpen,+ orchestratorRoleOf,}: RecapDeps) {- // The recap is an excerpt of the answer, cut the moment the turn ends — no model in the loop. The- // window, the phone and the dial show it beside the whole answer, so a model's rewrite (which cost- // about 9 s of every turn) said again what the screen already showed.- const summarizer: Pick<CommanderMirrorOpts, 'summarize' | 'summarizeIsLocal'> = {- summarize: async (text) => deriveTurnSummary(text),- summarizeIsLocal: true,- }/*** A turn that belongs to a SUB-AGENT: an Orchestrator specialist, or its Director while specialists* are still out.*- * Hoisted out of the commander's options because the dial is no longer the only screen that has to- * know. The cable learns it as `silent` on the summary card; the window and the phone learn it as- * `subagent` on `turn_ended` (see emitSessionEvents) — the phone notifies on neither. One rule, asked twice — the two surfaces used to disagree+ * The dial is not the only screen that has to know. The recaps learn it with the turn's end and put it+ * on the summary card as `silent`; the window and the phone learn it as `subagent` on `turn_ended` (see+ * the funnel) — the phone notifies on neither. One rule, asked twice — the two surfaces used to disagree* here, and a four-specialist project put ONE row on the dial and FIVE marks in the window.- *- * ⚠️ The commander ORs this with its own `abandoned` state — a held turn released because a- * sub-agent went silent — which lives inside it and is not reachable from here. That case is rare- * (a killed or crashed sub-agent) and costs the window one extra mark, not five.*/const isSubagentSession = (sessionId: string): boolean => {const agentId = bySession(sessionId)?.agentId@@ -70,43 +80,54 @@ export function createRecaps({try { role = orchestratorRoleOf(agentId) } catch { return false }return role?.role === 'worker' || (role?.role === 'director' && role.busy)}- const mirror = new CommanderMirror({- notifications,- notifyWithoutDevice: true,- verifiedWorking: sessionId => turnActivity.snapshot(sessionId)?.state === 'working',- send: (frame) => clients.sendCommander(frame),- sendWeb: (frame) => clients.send(frame), // turn_summary_pending / turn_summary → web indicator- hasDevice: () => deviceIsWatching(), // device-gate the LLM recap (mirror node)- // Live cards stream to whatever is actually rendering. The dial has one screen and it is always the- // one in front of the user, so a cable session counts as active by construction.- active: () => clients.hasActiveCommander() || cableWatchingLocal(),- ...summarizer,- nameFor: (sessionId) => { const s = bySession(sessionId); return s ? projectDisplayName(s) : undefined },- agentIdFor: (sessionId) => bySession(sessionId)?.agentId,- // An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not- // announced: the person asked to hear from the main agent once, not from every sub-agent.- isSubagent: (sessionId: string) => isSubagentSession(sessionId),- // A claude sub-agent still at work is one whose transcript is still growing:- // `<session>/subagents/agent-<id>.jsonl` beside the parent's (the same file enrichSubagentStats- // reads). Written in the last SUBAGENT_IDLE_MS = alive; the held turn end waits for it.- subagentActive: (sessionId, agentId) => {- const transcriptPath = bySession(sessionId)?.transcriptPath- if (!transcriptPath) return false- try {- const at = statSync(join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', `agent-${agentId}.jsonl`)).mtimeMs- return Date.now() - at < SUBAGENT_IDLE_MS- } catch { return false }+ /** Who watches the cards now: the recaps read it as they emit one. A plugged-in dial is always watching. */+ const watchers = (): RecapWatchers => ({ device: deviceIsWatching(), active: clients.hasActiveCommander() || cableWatchingLocal() })+ /** A session as the recaps address its cards. Whether it is a sub-agent's is asked only where a turn+ * ends (it reads the orchestrator); elsewhere the recaps keep what they were last told. */+ const session = (sessionId: string, subagent?: boolean): RecapSession => {+ const known = bySession(sessionId)+ return {+ sessionId,+ agentId: known?.agentId ?? sessionId,+ ...(known ? { name: projectDisplayName(known) } : {}),+ ...(known?.transcriptPath ? { transcriptPath: known.transcriptPath } : {}),+ ...(subagent === undefined ? {} : { subagent }),+ }+ }+ const tell = (event: TurnLifecycle): void => { port()?.lifecycle(event, watchers()) }+ const read = (sessionId: string): SessionRecaps | null => port()?.recaps(sessionId) ?? null++ const mirror: TurnRecaps = {+ ingest: (events, sessionId, options) => {+ const ends = events.some((event) => event.type === 'turn_ended')+ tell({ kind: 'events', session: session(sessionId, ends ? isSubagentSession(sessionId) : undefined), events, replay: !!options?.replay })+ },+ heartbeat: (sessionId) => {+ tell({ kind: 'beat', session: session(sessionId), working: turnActivity.snapshot(sessionId)?.state === 'working' })+ return read(sessionId)?.busy ?? false},- readLastTurn,- dataDir,- recapForce,- alwaysGenerate: () => recapWithoutDevice(),- })+ cancel: (sessionId) => { tell({ kind: 'cancelled', session: session(sessionId, isSubagentSession(sessionId)) }) },+ forget: (sessionId) => { tell({ kind: 'forgotten', session: session(sessionId, isSubagentSession(sessionId)) }) },+ deleteHistory: (sessionId) => { tell({ kind: 'purged', sessionId }) },+ inheritSummary: (from, to) => { tell({ kind: 'rebound', from, to }) },+ noteEngineStopped: (sessionId) => { tell({ kind: 'stopped', sessionId }) },+ replayAll: () => {+ const working = live().map((s) => s.sessionId).filter((sessionId) => !!sessionId && turnActivity.snapshot(sessionId)?.state === 'working')+ tell({ kind: 'rejoined', working })+ },+ isBusy: (sessionId) => sessionTurnOpen(sessionId),+ recent: (sessionId, n) => recentRecaps(read(sessionId), n),+ recentAsks: (sessionId, n) => recentAsks(read(sessionId), n),+ lastFullText: (sessionId) => lastFullText(read(sessionId)),+ liveCards: () => port()?.liveCards() ?? Promise.resolve([]),+ }+ /** A question put to the person, or answered: a turn waiting on one is not announced as done. */+ const question = (kind: 'asked' | 'answered', sessionId: string, requestId: string): void => { tell({ kind, sessionId, requestId }) }// Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device// and the voice router know. Resolve across the two, or every tile restores empty.const recent = (id: string, n: number) => mirror.recent(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)- const recentAsks = (id: string, n?: number) => mirror.recentAsks(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)+ const recentAsksOf = (id: string, n?: number) => mirror.recentAsks(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)/*** The reply to `agent_recent`: an agent's last turn summaries and the person's last questions. Asked* by a device restoring its tiles at boot, so it holds only what was summarized (recap and body),@@ -124,10 +145,10 @@ export function createRecaps({// are different lengths on any machine where a turn ended without one, so a reply that folds// the questions into the event rows loses exactly the newest ones — and a REMOTE agent then// reaches the router with nothing but its name.- const asks = recentAsks(projectId, n)+ const asks = recentAsksOf(projectId, n)return { agentId: projectId, events, asks }}- return { mirror, isSubagentSession, recent, recentAsks, agentRecent }+ return { mirror, isSubagentSession, question, recent, recentAsks: recentAsksOf, agentRecent }}export type Recaps = ReturnType<typeof createRecaps>diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.tsindex 5c23bb083..8ca435f5f 100644--- a/cli/src/core/turns/turnHooks.ts+++ b/cli/src/core/turns/turnHooks.ts@@ -10,7 +10,7 @@import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'-import type { CommanderMirror } from '../../lib/commander.js'+import type { TurnRecaps } from './recaps.js'import { sid } from '../../lib/log.js'import type { LiveEvent, TurnState } from '../../lib/normalize.js'import type { RegisteredSession } from '../../lib/registry.js'@@ -35,7 +35,7 @@ export interface TurnHookDeps {announceTurnAborted: (sessionId: string, engine: string, message: string) => voidarmAgyIdleWatch: (sessionId: string) => voidclearAgyIdleWatch: (sessionId: string) => void- mirror: Pick<CommanderMirror, 'noteEngineStopped'>+ mirror: Pick<TurnRecaps, 'noteEngineStopped'>dataDir: string}diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex 2269c38b3..1d5b5f3f3 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -412,7 +412,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', 'handoff'])+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps'])})})@@ -428,7 +428,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,handoff', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff' })+ expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps' })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 42065ae6f..f556c02db 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -358,8 +358,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// The git work (workspaces, the project readers) runs in git's own processes, and the monitor's// 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', 'handoff'], heapLimitMiB: 384, rssLimitMiB: 768 },+ // than workspaces alone had. The recaps hold each session's last three recaps, answers (8 KiB each at+ // most) and asks, as the core did while they ran in it, and a few timers per open turn.+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps'], 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/commander.spec.ts b/cli/src/lib/commander.spec.tsindex 3d8629c07..b5a947d1c 100644--- a/cli/src/lib/commander.spec.ts+++ b/cli/src/lib/commander.spec.ts@@ -783,3 +783,55 @@ describe('CommanderMirror keeps the complete final answer beside the clipped oneexpect(Buffer.from(full, 'utf8').toString('utf8')).toBe(full)})})++describe('what the mirror holds, as its process tells the core', () => {+ let dir = ''+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'adapter-commander-held-')) })+ afterEach(() => { vi.restoreAllMocks(); rmSync(dir, { recursive: true, force: true }) })++ it('says each change to a session\'s card or recaps, counts what was stored, and lists every session it holds', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const changed = vi.fn()+ const mirror = new CommanderMirror({ send: () => {}, sendWeb: () => {}, hasDevice: () => true, summarize: async () => 'Recap\n\nBody', dataDir: dir, changed })+ expect(mirror.snapshot('s1')).toBeNull()+ expect(mirror.busy('s1')).toBe(false)+ expect(mirror.revision('s1')).toBe(0)+ mirror.ingest([{ type: 'turn_started', payload: { userMessage: 'why?' } }] as LiveEvent[], 's1')+ expect(mirror.busy('s1')).toBe(true)+ expect(mirror.revision('s1')).toBe(1)+ expect(mirror.snapshot('s1')).toEqual({ latest: null, history: [], fullTexts: [], asks: ['why?'], busy: true })+ mirror.ingest([{ type: 'text_delta', payload: { content: 'Because.' } }, { type: 'turn_ended', payload: {} }] as LiveEvent[], 's1')+ await vi.waitFor(() => expect(mirror.revision('s1')).toBe(2))+ expect(mirror.snapshot('s1')).toEqual({ latest: 'Recap\n\nBody', history: ['Recap\n\nBody'], fullTexts: ['Because.'], asks: ['why?'], busy: false })+ expect(changed.mock.calls.every(([sessionId]) => sessionId === 's1')).toBe(true)+ const said = changed.mock.calls.length+ mirror.cancel('s1')+ mirror.forget('s1')+ mirror.inheritSummary('s1', 's2')+ expect(changed.mock.calls.slice(said).map(([sessionId]) => sessionId)).toEqual(['s1', 's1', 's2'])+ expect(mirror.sessions().sort()).toEqual(['s1', 's2'])+ mirror.deleteHistory('s1')+ expect(mirror.snapshot('s1')).toBeNull()+ expect(mirror.sessions()).toEqual(['s2'])+ })++ it('says a turn that ends with nothing to recap, and one whose recap failed or came back empty', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ const changed = vi.fn()+ const summarize = vi.fn(async (): Promise<string | null> => null)+ const mirror = new CommanderMirror({ send: () => {}, sendWeb: () => {}, hasDevice: () => true, summarize, dataDir: dir, changed })+ const turn = (text: string) => mirror.ingest([+ { type: 'turn_started', payload: { userMessage: 'go' } },+ ...(text ? [{ type: 'text_delta', payload: { content: text } }] : []),+ { type: 'turn_ended', payload: {} },+ ] as LiveEvent[], 's1')+ for (const [text, fail] of [['', false], ['an answer', false], ['an answer', true]] as const) {+ if (fail) summarize.mockRejectedValueOnce(new Error('no'))+ changed.mockClear()+ turn(text)+ await vi.waitFor(() => expect(mirror.busy('s1')).toBe(false))+ expect(changed).toHaveBeenLastCalledWith('s1')+ }+ })+})diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex 3f0f2e12e..36782f051 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -23,6 +23,7 @@ import { join } from 'path'import type { LastTurnText, LiveEvent } from './normalize.js'import { AgentNotifications } from './agentNotifications.js'import { deriveTurnSummary } from './deviceRecap.js'+import { RECENT_TURNS, lastFullText, recentAsks, recentRecaps, splitSummary, type RecentRecap, type SessionRecaps } from './recapReads.js'import { atomicWriteJson } from './registry.js'export type CommanderFrame = {@@ -86,6 +87,11 @@ export interface CommanderMirrorOpts {recapForce?: boolean/** A function when the setting can change while the daemon runs. */alwaysGenerate?: boolean | (() => boolean)+ /**+ * What this session's recaps hold, or whether its card is busy, may have changed: the recaps' process+ * tells the core what it now holds (services/recapsProcess.ts), which answers from it in line.+ */+ changed?: (sessionId: string) => void}interface SessionState {@@ -117,7 +123,6 @@ interface TodoInput {todos?: Array<{ content?: string; subject?: string; status?: string }>}-const MAX_PART = 2000// Stable per-tool colors (device renders the tool name in this color); hash fallback for others.const TOOL_COLORS: Record<string, string> = {@@ -231,17 +236,6 @@ function holdsTurn(a: SessionState['agents'][number]): boolean {return a.doneMs === null && !a.carried}-/** Split a persisted "recap\n\nbody" into its parts (mirror websocket.ts:540 / getRecentEvents). */-function splitSummary(summary: string): { recap: string; body: string } {- const nl = summary.indexOf('\n\n')- const recap = (nl >= 0 ? summary.slice(0, nl) : summary).replace(/\s+/g, ' ').trim().slice(0, MAX_PART)- const body = (nl >= 0 ? summary.slice(nl + 2) : summary).replace(/\s+/g, ' ').trim().slice(0, MAX_PART)- return { recap, body }-}--/** How many turn summaries are kept per session. Three is what the voice router reads: enough to tell one- * agent's subject from another's, few enough that one chatty agent cannot crowd the others out. */-const RECENT_TURNS = 3/*** The cap on ONE stored final answer, in bytes of UTF-8.@@ -323,6 +317,7 @@ export class CommanderMirror {* of. The question carries the topic; the answer usually does not.*/private asks = new Map<string, string[]>()+ private revisions = new Map<string, number>()private file: stringprivate historyFile: stringprivate fullTextFile: string@@ -403,6 +398,7 @@ export class CommanderMirror {// The question is a fact about the TURN, not about the recap, so it is kept on its own list// and no longer has to wait for, or stay in step with, anything else.this.rememberAsk(sessionId, e.payload.userMessage || '')+ this.stored(sessionId)st.turnOpen = truest.everOpened = truest.abandoned = false@@ -509,6 +505,7 @@ export class CommanderMirror {break // thinking/user_message — web-only}}+ this.opts.changed?.(sessionId)}private clearEndTimers(st: SessionState): void {@@ -651,6 +648,7 @@ export class CommanderMirror {const ac = new AbortController()st.abort = acst.summarizing = true+ this.opts.changed?.(sessionId)const t0 = Date.now()void this.resolveTurnText(sessionId, fallbackText, fallbackUserMessage)@@ -704,6 +702,7 @@ export class CommanderMirror {// messages), or a tools/thinking-only turn ended with no final text. Graceful: clear busy, no recap.const ask = userMessage.replace(/\s+/g, ' ').trim().slice(0, 60)st.summarizing = false+ this.opts.changed?.(sessionId)this.trace(sessionId, `${sid} turn-end · empty assistant text → done · source=${source}${ask ? ` · ask="${ask}"` : ' · (no user prompt captured this turn)'}`)this.emit(sessionId, { kind: 'done', text: 'done' })return@@ -739,6 +738,7 @@ export class CommanderMirror {// Recorded in the SAME branch as the summary, so the two arrays cannot drift out of step —// a turn that produced no summary produces no row in either.this.rememberFullText(sessionId, text)+ this.stored(sessionId)this.saveSoon()const { recap, body } = splitSummary(summary)const notification = this.notifications.completed(sessionId, body || recap,@@ -752,6 +752,7 @@ export class CommanderMirror {this.opts.sendWeb({ type: 'turn_summary', agentId: this.opts.agentIdFor?.(sessionId) ?? sessionId,dbSessionId: sessionId, payload: { summary, sessionId, notification } })} else {+ this.opts.changed?.(sessionId)this.trace(sessionId, `${sid} summarizer returned NULL after ${ms}ms → done`)this.emit(sessionId, { kind: 'done', text: 'done' })if (!local) {@@ -763,6 +764,7 @@ export class CommanderMirror {const ms = Date.now() - t0if (ac.signal.aborted) returnst.summarizing = false+ this.opts.changed?.(sessionId)this.trace(sessionId, `${sid} FAILED after ${ms}ms: ${err instanceof Error ? err.message : String(err)}`, true)this.emit(sessionId, { kind: 'done', text: 'done' })this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId, done: true } })@@ -841,30 +843,10 @@ export class CommanderMirror {** `n` is honoured now. It used to be ignored and this always returned one, which made every caller* asking for more a promise nobody kept: the router in particular was told it had three turns of- * context and was given one.- *- * Falls back to the single latest summary when the history is empty, so the recaps already on disk from- * before this existed are usable on the first run rather than after three more turns.+ * context and was given one. The rule is lib/recapReads.ts's, which the core reads with too.*/- recent(sessionId: string, n = 2): Array<{ kind: string; text: string; recap?: string; fullText?: string }> {- const want = Math.max(1, n)- const stored = this.history.get(sessionId) ?? []- const latest = this.summaries.get(sessionId)- // The latest lives in both places once a turn has run under this build; dedupe so it is not read twice.- const usingHistory = stored.length > 0- const all = usingHistory ? stored : latest ? [latest] : []- const fulls = this.fullTexts.get(sessionId) ?? []- return all- .slice(0, want)- // PAIRED BEFORE FILTERING, not after. The filter below drops empty summaries, and dropping them- // from one array while reading the other by position is how a turn ends up carrying the previous- // turn's answer — wrong in the one way nobody would think to check.- .map((summary, at) => ({ summary, full: fulls[usingHistory ? at : 0] }))- .filter(({ summary }) => summary && summary.trim())- .map(({ summary, full }) => {- const { recap, body } = splitSummary(summary)- return { kind: 'summary', text: body || recap, recap, ...(full ? { fullText: full } : {}) }- })+ recent(sessionId: string, n = 2): RecentRecap[] {+ return recentRecaps(this.snapshot(sessionId), n)}/**@@ -876,12 +858,45 @@ export class CommanderMirror {* one belongs — every time a turn ended without a summary.*/recentAsks(sessionId: string, n = RECENT_TURNS): string[] {- return (this.asks.get(sessionId) ?? []).filter(Boolean).slice(0, Math.max(1, n))+ return recentAsks(this.snapshot(sessionId), n)}/** The newest turn's complete final answer, for a consumer that reads rather than glances. */lastFullText(sessionId: string): string | undefined {- return this.fullTexts.get(sessionId)?.[0]+ return lastFullText(this.snapshot(sessionId))+ }++ /** A turn is open on this session, or its recap is being cut: the devices' card for it is busy. */+ busy(sessionId: string): boolean {+ const st = this.states.get(sessionId)+ return !!st && (st.turnOpen || st.summarizing)+ }++ /** Bumped whenever what is stored for a session changes, so a reader can tell cheaply that it did. */+ revision(sessionId: string): number {+ return this.revisions.get(sessionId) ?? 0+ }++ /** What is held for one session; null when nothing is, stored or live. */+ snapshot(sessionId: string): SessionRecaps | null {+ const busy = this.busy(sessionId)+ const latest = this.summaries.get(sessionId) ?? null+ const history = this.history.get(sessionId) ?? []+ const fullTexts = this.fullTexts.get(sessionId) ?? []+ const asks = this.asks.get(sessionId) ?? []+ if (!busy && latest === null && !history.length && !fullTexts.length && !asks.length) return null+ return { latest, history, fullTexts, asks, busy }+ }++ /** Every session anything is held for, stored or live. */+ sessions(): string[] {+ return [...new Set([...this.states.keys(), ...this.summaries.keys(), ...this.history.keys(), ...this.fullTexts.keys(), ...this.asks.keys()])]+ }++ /** What is stored for this session changed: counted, and said. */+ private stored(sessionId: string): void {+ this.revisions.set(sessionId, this.revision(sessionId) + 1)+ this.opts.changed?.(sessionId)}/** The user's own words for a turn, clipped — the topic signal the recap cannot carry. */@@ -920,6 +935,7 @@ export class CommanderMirror {// A cancel outranks a held turn-end: the user threw the turn away, sub-agents and all.this.clearEndTimers(st)st.endPending = false+ this.opts.changed?.(sessionId)this.emit(sessionId, { kind: 'done', text: 'done' })}@@ -942,6 +958,7 @@ export class CommanderMirror {const pastFull = this.fullTexts.get(fromSessionId)if (pastFull?.length && !this.fullTexts.get(toSessionId)?.length) this.fullTexts.set(toSessionId, pastFull)this.save()+ this.stored(toSessionId)}/** Session metadata was unbound or its process agent was removed: abort any in-flight recap and drop@@ -956,6 +973,7 @@ export class CommanderMirror {if (st) this.clearEndTimers(st)this.states.delete(sessionId)// NB: intentionally do NOT delete this.summaries[sessionId] — reuse it on the next resume.+ this.opts.changed?.(sessionId)this.emit(sessionId, { kind: 'done', text: 'done' })}@@ -969,6 +987,7 @@ export class CommanderMirror {this.fullTexts.delete(sessionId)this.asks.delete(sessionId)this.save(true)+ this.stored(sessionId)}private load(): void {@@ -1028,3 +1047,4 @@ export class CommanderMirror {// Used by other modules only for potential reuse — kept exported.export { splitSummary }+export type { SessionRecaps }diff --git a/cli/src/lib/handoffDiscovery.ts b/cli/src/lib/handoffDiscovery.tsindex 50d16d1b0..37f72671c 100644--- a/cli/src/lib/handoffDiscovery.ts+++ b/cli/src/lib/handoffDiscovery.ts@@ -5,7 +5,7 @@import type { AgentEngine } from '../engines/types.js'import type { HandoffDeps } from './agentHandoff.js'import { isSubagentTranscript } from './subagentTranscript.js'-import type { CommanderMirror } from './commander.js'+import type { RecentRecap } from './recapReads.js'import type { RegisteredSession } from './registry.js'import type { RepairedSession } from './sessionRepair.js'import type { TurnSource } from './sessionSearch/sessionTurns.js'@@ -99,7 +99,12 @@ export interface HandoffWiring {bySession(sessionId: string): { agentId: string } | null | undefined}stopped: { get(id: string): RegisteredSession | null; ids(): string[] }- mirror: Pick<CommanderMirror, 'recentAsks' | 'lastFullText' | 'recent'>+ /** The recaps, as the core reads them back (core/turns/recaps.ts). */+ mirror: {+ recentAsks(sessionId: string, n?: number): string[]+ lastFullText(sessionId: string): string | undefined+ recent(sessionId: string, n?: number): RecentRecap[]+ }databaseHistory: HandoffDeps['readHistory']findLiveSession: DiscoveryDeps['findLiveSession']claudeProcessSession: DiscoveryDeps['claudeProcessSession']diff --git a/cli/src/lib/recapReads.spec.ts b/cli/src/lib/recapReads.spec.tsnew file mode 100644index 000000000..c49d7d11c--- /dev/null+++ b/cli/src/lib/recapReads.spec.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest'+import { lastFullText, recentAsks, recentRecaps, splitSummary, type SessionRecaps } from './recapReads.js'++const held = (over: Partial<SessionRecaps> = {}): SessionRecaps => ({ latest: null, history: [], fullTexts: [], asks: [], busy: false, ...over })++describe('reading a session\'s recaps', () => {+ it('splits a stored recap from its body, each flattened and bounded', () => {+ expect(splitSummary('The recap\n\nThe body\nnext')).toEqual({ recap: 'The recap', body: 'The body next' })+ expect(splitSummary('only one')).toEqual({ recap: 'only one', body: 'only one' })+ expect(splitSummary('x'.repeat(3000)).recap).toHaveLength(2000)+ })++ it('reads the last turns newest first, each with its own answer, falling back to the latest alone', () => {+ expect(recentRecaps(null)).toEqual([])+ expect(recentRecaps(held())).toEqual([])+ expect(recentRecaps(held({ latest: 'old\n\nbody', fullTexts: ['the answer'] }), 3)).toEqual([{ kind: 'summary', text: 'body', recap: 'old', fullText: 'the answer' }])+ const two = held({ history: ['r1\n\nb1', ' ', 'r0'], fullTexts: ['one', 'blank', 'zero'] })+ // Paired before the empty one is dropped: each row keeps its own answer.+ expect(recentRecaps(two, 3)).toEqual([+ { kind: 'summary', text: 'b1', recap: 'r1', fullText: 'one' },+ { kind: 'summary', text: 'r0', recap: 'r0', fullText: 'zero' },+ ])+ expect(recentRecaps(two, 0)).toHaveLength(1)+ expect(recentRecaps(held({ history: ['r'] }))).toEqual([{ kind: 'summary', text: 'r', recap: 'r' }])+ })++ it('reads the person\'s last questions and the newest answer', () => {+ expect(recentAsks(null)).toEqual([])+ expect(recentAsks(held({ asks: ['a', '', 'b', 'c'] }))).toEqual(['a', 'b', 'c'])+ expect(recentAsks(held({ asks: ['a', 'b'] }), 0)).toEqual(['a'])+ expect(lastFullText(null)).toBeUndefined()+ expect(lastFullText(held({ fullTexts: ['newest', 'older'] }))).toBe('newest')+ })+})diff --git a/cli/src/lib/recapReads.ts b/cli/src/lib/recapReads.tsnew file mode 100644index 000000000..35020c11d--- /dev/null+++ b/cli/src/lib/recapReads.ts@@ -0,0 +1,81 @@+/**+ * Reading a session's stored recaps: its last turns' summaries and answers, and the person's last+ * questions. Pure functions of what the recaps hold (`SessionRecaps`), so that the recaps service+ * (lib/commander.ts, in its process) and the core, which answers from what that service last reported+ * (core/recapsLink.ts), read them with one rule and cannot drift apart.+ */++/** What the recaps hold of one session, newest first. */+export interface SessionRecaps {+ /** The latest turn's stored "recap\n\nbody" (summaries.json), which a session from before the history+ * has alone. */+ latest: string | null+ /** The last few turns' "recap\n\nbody". */+ history: string[]+ /** The same turns' complete final answers, index-aligned with `history`. */+ fullTexts: string[]+ /** What the person asked on each of the last few turns. */+ asks: string[]+ /** Whether the devices' card for it is still busy: a turn open, or its recap being cut. */+ busy: boolean+}++/** One stored turn, as a device restoring its tile and the router read it. */+export interface RecentRecap {+ kind: string+ text: string+ recap?: string+ fullText?: string+}++export const MAX_PART = 2000++/** How many turn summaries are kept per session. Three is what the voice router reads: enough to tell one+ * agent's subject from another's, few enough that one chatty agent cannot crowd the others out. */+export const RECENT_TURNS = 3++/** Split a persisted "recap\n\nbody" into its parts (mirror websocket.ts:540 / getRecentEvents). */+export function splitSummary(summary: string): { recap: string; body: string } {+ const nl = summary.indexOf('\n\n')+ const recap = (nl >= 0 ? summary.slice(0, nl) : summary).replace(/\s+/g, ' ').trim().slice(0, MAX_PART)+ const body = (nl >= 0 ? summary.slice(nl + 2) : summary).replace(/\s+/g, ' ').trim().slice(0, MAX_PART)+ return { recap, body }+}++/**+ * The session's last `n` turn summaries, newest first — for a device restoring its tile at boot and for+ * the voice router deciding which agent a spoken sentence belongs to.+ *+ * Falls back to the single latest summary when the history is empty, so the recaps already on disk from+ * before the history existed are usable on the first run rather than after three more turns.+ */+export function recentRecaps(recaps: SessionRecaps | null, n = 2): RecentRecap[] {+ if (!recaps) return []+ const want = Math.max(1, n)+ const stored = recaps.history+ // The latest lives in both places once a turn has run under this build; dedupe so it is not read twice.+ const usingHistory = stored.length > 0+ const all = usingHistory ? stored : recaps.latest ? [recaps.latest] : []+ const fulls = recaps.fullTexts+ return all+ .slice(0, want)+ // PAIRED BEFORE FILTERING, not after. The filter below drops empty summaries, and dropping them+ // from one array while reading the other by position is how a turn ends up carrying the previous+ // turn's answer — wrong in the one way nobody would think to check.+ .map((summary, at) => ({ summary, full: fulls[usingHistory ? at : 0] }))+ .filter(({ summary }) => summary && summary.trim())+ .map(({ summary, full }) => {+ const { recap, body } = splitSummary(summary)+ return { kind: 'summary', text: body || recap, recap, ...(full ? { fullText: full } : {}) }+ })+}++/** The person's own last questions to this agent, newest first. */+export function recentAsks(recaps: SessionRecaps | null, n = RECENT_TURNS): string[] {+ return (recaps?.asks ?? []).filter(Boolean).slice(0, Math.max(1, n))+}++/** The newest turn's complete final answer, for a consumer that reads rather than glances. */+export function lastFullText(recaps: SessionRecaps | null): string | undefined {+ return recaps?.fullTexts[0]+}diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 732f7d784..326dd2abb 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -32,6 +32,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['monitor', async () => (await import('./services/monitorProcess.js')).runMonitorService],['projects', async () => (await import('./services/projectsProcess.js')).runProjectsService],['handoff', async () => (await import('./services/handoffProcess.js')).runHandoffService],+ ['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],['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/AGENTS.md b/cli/src/services/AGENTS.mdindex 2042265b1..0db846fc9 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -50,8 +50,8 @@ A service that can crash natively, hang or leak should run in a process of its othat process. A process per risk, not per feature: search (native `node:sqlite`), the viewers (theirservers) with the Store (its minutes-long installs), each experiment (below), models (grid's installs,downloads and commands), the devices (the dials' serial ports, the fleet's lane, the voice router's-worker, and the Wi-Fi device), and the edge host, one process for the light services that only answer requests-(workspaces, usage, the monitor, the project readers). A fault in one of the edge host's services can+worker, and the Wi-Fi device), and the edge host, one process for the light services+(workspaces, usage, the monitor, the project readers, the recaps). A fault in one of the edge host's services cancost the others in it, never the core. Every service in `KNOWN_SERVICES` runs out of the core's processby default, unless `HARNESSD_SERVICES` names a subset, by service (`search,usage`) or by process(`edge`), and `HARNESSD_SERVICES=none` runs them all inside the core's process (for debugging or a quick@@ -134,6 +134,13 @@ way back).Their process runs only once there is a device (`onDemand`, asked for since protocol 4): a dial's port in/dev, a paired Wi-Fi device or its session, or a request for them (src/core/devicesWake.ts);what a Wi-Fi device sends while it starts is held by the core. `e2e/devicesOnDemand.e2e.ts` proves it.+- A service the core tells what happens and never waits on: the recaps (`src/services/recapsProcess.ts`,+ `src/core/recapsLink.ts`) hear each turn's lifecycle as a notification, and one they miss costs that+ turn its recap, nothing else; what would pile up on a hung process is dropped. What they put in front+ of a person goes back as a notice the core checks the type of (`clients.turnCard`, `turnSummary`), and+ what the core reads back in line it reads from what they last said of each session.+ `e2e/recapsProcess.e2e.ts` proves turns end on time with them killed, hung or slow, and+ `e2e/recapsCompat.e2e.ts` that the dial and the windows hear the same cards and recaps as before.- State built from every change must get every change exactly once. The teams show how(`src/services/teamsProcess.ts`, `src/core/teamsLink.ts`): the core numbers each change and keeps ituntil the process acknowledges it; on each connection the process says what it applied and getsdiff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex e6cbbc79d..19bd5c1e5 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -9,6 +9,7 @@ import { startTeamsInCore } from './collaboration.js'import { startMonitor } from './monitor.js'import { startOrchestrator } from './orchestrator.js'import { startProjects } from './projects.js'+import { startRecaps } from './recaps.js'import { startSearch } from './search.js'import { startSharing } from './sharing.js'import { startStore } from './store.js'@@ -19,6 +20,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, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })+ expect({ ...inline }).toEqual({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 51ab52aa7..98f9b28e2 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -21,6 +21,7 @@ export { startTeamsInCore } from './collaboration.js'export { startMonitor } from './monitor.js'export { startOrchestrator } from './orchestrator.js'export { startProjects } from './projects.js'+export { startRecaps } from './recaps.js'export { startSearch } from './search.js'export { startSharing } from './sharing.js'export { startStore } from './store.js'diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.tsindex 82f622f20..5194f0cc1 100644--- a/cli/src/services/modelsProcess.spec.ts+++ b/cli/src/services/modelsProcess.spec.ts@@ -240,6 +240,7 @@ describe('the core API models runs on in its own process', () => {api.questions.answer('a1', 'r', {})expect(await api.questions.answerReviewed({} as never)).toBe(false)expect(api.transcripts.databaseHistory({} as never)).toBeUndefined()+ expect(await api.transcripts.lastTurn('s1')).toBeNull()expect(api.external.sessions.list()).toEqual([])expect(await api.external.sessions.scan()).toEqual([])expect(api.external.open.known()).toEqual(new Map())@@ -249,6 +250,8 @@ describe('the core API models runs on in its own process', () => {api.clients.dshInstallStatus({})api.clients.windows({ type: 'orchestrator_changed', payload: {} })expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)+ api.clients.turnCard({ type: 'commander_event', agentId: 'a', dbSessionId: 's', payload: {} })+ api.clients.turnSummary({ type: 'turn_summary' })expect(ask).not.toHaveBeenCalled()})})diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex 6b38455ce..3b274d149 100644--- a/cli/src/services/modelsProcess.ts+++ b/cli/src/services/modelsProcess.ts@@ -81,7 +81,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa},turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },- transcripts: { databaseHistory: () => undefined },+ transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },external: {sessions: { list: () => [], scan: async () => [] },open: { known: () => new Map(), fresh: async () => new Map() },diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex e03239f00..0092d1cb3 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -39,6 +39,7 @@ describe('the core API a light service runs on in its own process', () => {api.questions.answer('a1', 'q', {})await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)expect(api.transcripts.databaseHistory(agent('a1'))).toBeUndefined()+ expect(await api.transcripts.lastTurn('s1')).toBeNull()expect(api.external.sessions.list()).toEqual([])await expect(api.external.sessions.scan()).resolves.toEqual([])expect(api.external.open.known().size).toBe(0)@@ -64,6 +65,10 @@ describe('the core API a light service runs on in its own process', () => {expect(api.clients.hasWindow()).toBe(false)api.clients.devicesChanged({})api.clients.dialWatching(true)+ // What only the recaps ask (services/recaps.ts): nothing, from every other service.+ api.clients.turnCard({ type: 'commander_event', agentId: 'a', dbSessionId: 's', payload: {} })+ api.clients.turnSummary({ type: 'turn_summary' })+ expect(await api.transcripts.lastTurn('s1')).toBeNull()// With no way to ask the core, it acts on nothing: no agent made, no turn, no window told.await expect(api.agents.create({ engine: 'claude', cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false })).resolves.toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex e4f6061f8..4649be5d6 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -70,14 +70,17 @@ export const UNASKED = {machine: { id: () => '', computerId: () => '', name: () => '' },activityText: async (): Promise<string | null> => null,account: { signedIn: () => false, environment: () => '', machines: async () => ({ status: 503, body: {} }) },- clients: { sendLocal: () => {}, sendToWindow: () => false, hasWindow: () => false, devicesChanged: () => {}, dialWatching: () => {} },+ clients: { sendLocal: () => {}, sendToWindow: () => false, hasWindow: () => false, devicesChanged: () => {}, dialWatching: () => {}, turnCard: () => {}, turnSummary: () => {} },wifi: WIFI_OFF,+ /** What only the recaps ask (services/recapsProcess.ts): a turn's final answer. */+ lastTurn: async () => null,} satisfies {machine: CoreApi['machine']activityText: CoreApi['agents']['activityText']account: Pick<CoreApi['account'], 'signedIn' | 'environment' | 'machines'>- clients: Pick<CoreApi['clients'], 'sendLocal' | 'sendToWindow' | 'hasWindow' | 'devicesChanged' | 'dialWatching'>+ clients: Pick<CoreApi['clients'], 'sendLocal' | 'sendToWindow' | 'hasWindow' | 'devicesChanged' | 'dialWatching' | 'turnCard' | 'turnSummary'>wifi: CoreApi['wifi']+ lastTurn: CoreApi['transcripts']['lastTurn']}export function processCoreApi(dataDir: string, service: string, view: AgentsView = {}): CoreApi {@@ -122,7 +125,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie...(view.deliveries?.turns ?? DELIVERIES_OFF),},questions: { answer: () => {}, answerReviewed: async () => false },- transcripts: { databaseHistory: () => undefined },+ transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },external: {sessions: { list: () => [], scan: async () => [] },open: { known: () => new Map(), fresh: async () => new Map() },diff --git a/cli/src/services/recaps.spec.ts b/cli/src/services/recaps.spec.tsnew file mode 100644index 000000000..86cbb4ef9--- /dev/null+++ b/cli/src/services/recaps.spec.ts@@ -0,0 +1,211 @@+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { emptyPorts, type RecapSession, type TurnLifecycle } from '../core/api.js'+import { SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from '../lib/commander.js'+import { deriveTurnSummary } from '../lib/deviceRecap.js'+import type { LiveEvent } from '../lib/normalize.js'+import { fakeCore } from '../testing/fakeCore.js'+import { createRecaps, startRecaps } from './recaps.js'++const dirs: string[] = []+const temp = () => { const dir = mkdtempSync(join(tmpdir(), 'recaps-')); dirs.push(dir); return dir }+const watching = { device: true, active: true }+const nobody = { device: false, active: false }+const s1: RecapSession = { sessionId: 's1', agentId: 'a1', name: 'app', subagent: false }+const started = (userMessage = 'what is the fix?') => ({ type: 'turn_started', payload: { userMessage } }) as LiveEvent+const ended = { type: 'turn_ended', payload: {} } as LiveEvent+const flush = () => new Promise((done) => setTimeout(done, 0))++function setup(over: Parameters<typeof createRecaps>[1] = {}) {+ const core = fakeCore({ dataDir: temp() })+ vi.mocked(core.transcripts.lastTurn).mockResolvedValue({ assistantText: 'The fix is in. Tests pass.', userMessage: 'what is the fix?' } as never)+ const recaps = createRecaps(core, { recapForce: false, recapWithoutDevice: () => true, ...over })+ const opts = (recaps.mirror as unknown as { opts: CommanderMirrorOpts }).opts+ const tell = (event: TurnLifecycle, seen = watching) => recaps.port.lifecycle(event, seen)+ return { core, recaps, opts, tell }+}++describe('the recaps', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ })++ it('starts in the core\'s process behind its port', () => {+ const ports = emptyPorts()+ startRecaps(fakeCore({ dataDir: temp() }), ports)+ expect(ports.recaps?.recaps('nobody')).toBeNull()+ })++ it('cuts a turn\'s recap from its final answer, sends the card and the apps\' recap, and keeps it for the core to read', async () => {+ const { core, recaps, tell } = setup()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ expect(recaps.port.recaps('s1')).toMatchObject({ asks: ['what is the fix?'], busy: true })+ tell({ kind: 'events', session: s1, events: [ended], replay: false })+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())+ const summary = await deriveTurnSummary('The fix is in. Tests pass.')+ expect(core.transcripts.lastTurn).toHaveBeenCalledWith('s1')+ expect(vi.mocked(core.clients.turnSummary).mock.calls[0][0]).toMatchObject({ type: 'turn_summary', agentId: 'a1', dbSessionId: 's1', payload: { summary, sessionId: 's1' } })+ const cards = vi.mocked(core.clients.turnCard).mock.calls.map(([frame]) => frame)+ expect(cards.map((frame) => frame.payload.kind)).toEqual(['processing', 'done', 'summary'])+ // The summary card carries the agent's name for a machine whose tile is not loaded.+ expect(cards[2]).toMatchObject({ type: 'commander_event', agentId: 'a1', dbSessionId: 's1', name: 'app' })+ expect(recaps.port.recaps('s1')).toMatchObject({ busy: false, history: [summary], fullTexts: ['The fix is in. Tests pass.'] })+ })++ it('streams no card with no device watching, and still cuts the recap for the apps', async () => {+ const { core, tell } = setup()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ tell({ kind: 'events', session: s1, events: [started()], replay: false }, nobody)+ tell({ kind: 'events', session: s1, events: [ended], replay: false }, nobody)+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())+ expect(core.clients.turnCard).not.toHaveBeenCalled()+ })++ it('beats a busy card only while the core says the turn is verifiably working', () => {+ const { core, tell } = setup()+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ vi.mocked(core.clients.turnCard).mockClear()+ tell({ kind: 'beat', session: s1, working: false })+ expect(core.clients.turnCard).not.toHaveBeenCalled()+ tell({ kind: 'beat', session: s1, working: true })+ expect(vi.mocked(core.clients.turnCard).mock.calls.map(([frame]) => frame.payload)).toEqual([{ kind: 'processing', text: 'Processing' }])+ })++ it('clears the card on a cancel and a forget, keeping what is stored for a resume', () => {+ const { core, recaps, tell } = setup()+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ vi.mocked(core.clients.turnCard).mockClear()+ tell({ kind: 'cancelled', session: s1 })+ expect(recaps.port.recaps('s1')?.busy).toBe(false)+ tell({ kind: 'forgotten', session: { ...s1, subagent: true } })+ expect(vi.mocked(core.clients.turnCard).mock.calls.map(([frame]) => frame.payload)).toEqual([+ { kind: 'done', text: 'done' }, { kind: 'done', text: 'done', subagent: true },+ ])+ expect(recaps.port.recaps('s1')?.asks).toEqual(['what is the fix?'])+ })++ it('keeps what it was last told of whether a session is a sub-agent\'s, when an event does not say', () => {+ const { core, tell } = setup()+ tell({ kind: 'events', session: { ...s1, subagent: true }, events: [started()], replay: false })+ vi.mocked(core.clients.turnCard).mockClear()+ tell({ kind: 'cancelled', session: { sessionId: 's1', agentId: 'a1' } })+ expect(vi.mocked(core.clients.turnCard).mock.calls[0][0].payload).toEqual({ kind: 'done', text: 'done', subagent: true })+ // A session never told of is anyone's.+ tell({ kind: 'cancelled', session: { sessionId: 's2', agentId: 'a2' } })+ expect(core.clients.turnCard).toHaveBeenCalledTimes(1)+ })++ it('moves a conversation\'s recaps to its new session, and forgets a purged one', async () => {+ const { core, recaps, tell } = setup()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ tell({ kind: 'events', session: s1, events: [ended], replay: false })+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalled())+ tell({ kind: 'rebound', from: 's1', to: 's9' })+ expect(recaps.port.recaps('s9')?.history).toEqual(recaps.port.recaps('s1')?.history)+ tell({ kind: 'purged', sessionId: 's1' })+ expect(recaps.port.recaps('s1')).toBeNull()+ })++ it('holds a turn\'s "done" notification while a question waits on the person, and lets it go once answered', async () => {+ const { core, tell } = setup()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ tell({ kind: 'asked', sessionId: 's1', requestId: 'r1' })+ tell({ kind: 'events', session: s1, events: [ended], replay: false })+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalledTimes(1))+ expect(vi.mocked(core.clients.turnSummary).mock.calls[0][0].payload).toMatchObject({ notification: null })+ tell({ kind: 'answered', sessionId: 's1', requestId: 'r1' })+ tell({ kind: 'events', session: s1, events: [started('and now?')], replay: false })+ tell({ kind: 'events', session: s1, events: [ended], replay: false })+ await vi.waitFor(() => expect(core.clients.turnSummary).toHaveBeenCalledTimes(2))+ expect(vi.mocked(core.clients.turnSummary).mock.calls[1][0].payload).toMatchObject({ notification: { kind: 'done' } })+ })++ it('says every card again as a device joins, busy only where the core says the turn is working', () => {+ const { core, tell } = setup()+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ tell({ kind: 'events', session: { ...s1, sessionId: 's2', agentId: 'a2' }, events: [started()], replay: false })+ tell({ kind: 'beat', session: s1, working: true })+ vi.mocked(core.clients.turnCard).mockClear()+ tell({ kind: 'rejoined', working: ['s2'] })+ expect(vi.mocked(core.clients.turnCard).mock.calls.map(([frame]) => [frame.dbSessionId, frame.payload.kind])).toEqual([['s2', 'processing']])+ })++ it('says the cards of every turn still at work, for a dial that just attached', async () => {+ const { recaps, tell } = setup()+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ tell({ kind: 'beat', session: s1, working: true })+ expect(await recaps.port.liveCards()).toEqual([{ type: 'commander_event', agentId: 'a1', dbSessionId: 's1', payload: { kind: 'processing', text: 'Processing' } }])+ })++ it('lets a held turn end go on the engine\'s Stop hook', () => {+ const { recaps, tell } = setup()+ const stopped = vi.spyOn(recaps.mirror, 'noteEngineStopped')+ tell({ kind: 'stopped', sessionId: 's1' })+ expect(stopped).toHaveBeenCalledWith('s1')+ })++ it('gives the mirror the core\'s doors, the device gates as told, and an excerpt for a recap', async () => {+ const { core, opts, tell } = setup({ changed: vi.fn() })+ const frame = { type: 'commander_event' as const, agentId: 'a1', dbSessionId: 's1', payload: {} }+ opts.send(frame)+ opts.sendWeb({ type: 'turn_summary' })+ expect(core.clients.turnCard).toHaveBeenCalledWith(frame)+ expect(core.clients.turnSummary).toHaveBeenCalledWith({ type: 'turn_summary' })+ tell({ kind: 'stopped', sessionId: 's1' }, { device: true, active: false })+ expect(opts.hasDevice()).toBe(true)+ expect(opts.active!()).toBe(false)+ expect(await opts.summarize('The fix is in. Tests pass.')).toEqual(await deriveTurnSummary('The fix is in. Tests pass.'))+ expect(opts.summarizeIsLocal).toBe(true)+ expect(opts.notifyWithoutDevice).toBe(true)+ expect(opts.dataDir).toBe(core.dataDir)+ expect(opts.recapForce).toBe(false)+ expect((opts.alwaysGenerate as () => boolean)()).toBe(true)+ expect(opts.nameFor!('nobody')).toBeUndefined()+ expect(opts.agentIdFor!('nobody')).toBeUndefined()+ expect(opts.isSubagent!('nobody')).toBe(false)+ expect(opts.changed).toBeTypeOf('function')+ })++ it('reads the recap settings from the daemon\'s environment unless told', () => {+ const recaps = createRecaps(fakeCore({ dataDir: temp() }))+ const opts = (recaps.mirror as unknown as { opts: CommanderMirrorOpts }).opts+ expect(typeof opts.recapForce).toBe('boolean')+ expect(typeof (opts.alwaysGenerate as () => boolean)()).toBe('boolean')+ })++ it('counts a Claude Code sub-agent as at work while its own transcript is still growing', () => {+ const { opts, tell } = setup()+ const transcripts = temp()+ const transcriptPath = join(transcripts, 'main.jsonl')+ tell({ kind: 'stopped', sessionId: 's1' })+ tell({ kind: 'cancelled', session: { ...s1, transcriptPath } })+ tell({ kind: 'cancelled', session: { sessionId: 's2', agentId: 'a2' } })+ expect(opts.subagentActive!('s2', 'x'), 'no transcript').toBe(false)+ expect(opts.subagentActive!('s1', 'x'), 'no sub-agent file').toBe(false)+ const file = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', 'agent-x.jsonl')+ mkdirSync(join(file, '..'), { recursive: true })+ writeFileSync(file, '{}\n')+ expect(opts.subagentActive!('s1', 'x')).toBe(true)+ const old = (Date.now() - SUBAGENT_IDLE_MS - 60_000) / 1000+ utimesSync(file, old, old)+ expect(opts.subagentActive!('s1', 'x')).toBe(false)+ })++ it('cuts no recap from a turn whose final answer the core cannot read', async () => {+ const { core, tell } = setup()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.mocked(core.transcripts.lastTurn).mockResolvedValue(null)+ tell({ kind: 'events', session: s1, events: [started()], replay: false })+ tell({ kind: 'events', session: s1, events: [ended], replay: false })+ await flush()+ await flush()+ expect(core.clients.turnSummary).not.toHaveBeenCalled()+ expect(vi.mocked(core.clients.turnCard).mock.calls.at(-1)?.[0].payload).toEqual({ kind: 'done', text: 'done' })+ })+})diff --git a/cli/src/services/recaps.ts b/cli/src/services/recaps.tsnew file mode 100644index 000000000..e7818a945--- /dev/null+++ b/cli/src/services/recaps.ts@@ -0,0 +1,139 @@+/**+ * Recaps: each turn's recap, the devices' turn cards and the notification a finished turn rings+ * (lib/commander.ts), built from the turn lifecycle the core tells this service as it happens+ * (`RecapsPort.lifecycle`, core/api.ts).+ *+ * A session runs the same without it. The core never waits on it: it tells it what happened and goes on,+ * so a recaps service that is down, slow or failing costs a turn its recap and its card, never its end.+ * What the core reads back (an agent's last turns and asks, for a device restoring its tiles, the router,+ * a fork and the handoff) it reads from this service's port, in its process, or from what this service+ * last reported, in its own (core/recapsLink.ts, services/recapsProcess.ts). The recaps it keeps are its+ * own files in the data folder (`summaries*.json`), as they were when this ran inside the core.+ *+ * What the mirror used to read from the core in line (who an engine session belongs to, its name, whether+ * a device watches, whether a turn is verifiably working) comes with each event instead, as the core knew+ * it when it said it, so that the same code runs whichever process it is in.+ */+import { statSync } from 'node:fs'+import { join } from 'node:path'+import { env } from '../config/env.js'+import type { CoreApi, CorePorts, RecapSession, RecapsPort, RecapWatchers, TurnCardFrame, TurnLifecycle } from '../core/api.js'+import { AgentNotifications } from '../lib/agentNotifications.js'+import { CommanderMirror, SUBAGENT_IDLE_MS } from '../lib/commander.js'+import { deriveTurnSummary } from '../lib/deviceRecap.js'++export interface RecapsOptions {+ /** What a session's recaps hold, or whether its card is busy, may have changed: the recaps' own process+ * tells the core (services/recapsProcess.ts). */+ changed?: (sessionId: string) => void+ /** The test override that streams every card with no device there (`RECAP_FORCE`). */+ recapForce?: boolean+ /** Whether a recap is cut for every turn, a device watching or not (`RECAP_WITHOUT_DEVICE`). */+ recapWithoutDevice?: () => boolean+}++/** The service: its port, and the mirror itself for its process's own reads (services/recapsProcess.ts). */+export interface Recaps {+ port: RecapsPort+ mirror: CommanderMirror+}++/** Start the recaps in the core's process: its port is the core's way in. */+export function startRecaps(core: CoreApi, ports: CorePorts): void {+ ports.recaps = createRecaps(core).port+}++export function createRecaps(core: CoreApi, options: RecapsOptions = {}): Recaps {+ /** Each session as the core last described it. */+ const sessions = new Map<string, RecapSession>()+ /** Whether each session's turn was verifiably working at the core's last heartbeat. */+ const working = new Map<string, boolean>()+ let watchers: RecapWatchers = { device: false, active: false }+ // Shared by the turns' ends and the questions put to the person: a turn waiting on an answer is not+ // announced as done (lib/agentNotifications.ts). The core tells this service both.+ const notifications = new AgentNotifications()+ const mirror = new CommanderMirror({+ notifications,+ notifyWithoutDevice: true,+ // Presentation lease only: the heartbeat's own reading of the turn, as the core said it with the beat.+ verifiedWorking: (sessionId) => working.get(sessionId) === true,+ send: (frame) => core.clients.turnCard(frame),+ // turn_summary_pending / turn_summary → the web indicator.+ sendWeb: (frame) => core.clients.turnSummary(frame as Parameters<CoreApi['clients']['turnSummary']>[0]),+ hasDevice: () => watchers.device,+ // Live cards stream to whatever is actually rendering. The dial has one screen and it is always the+ // one in front of the user, so the core counts a cable session as active by construction.+ active: () => watchers.active,+ // The recap is an excerpt of the answer, cut the moment the turn ends — no model in the loop. The+ // window, the phone and the dial show it beside the whole answer, so a model's rewrite (which cost+ // about 9 s of every turn) said again what the screen already showed.+ summarize: async (text) => deriveTurnSummary(text),+ summarizeIsLocal: true,+ nameFor: (sessionId) => sessions.get(sessionId)?.name,+ agentIdFor: (sessionId) => sessions.get(sessionId)?.agentId,+ // An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not+ // announced: the person asked to hear from the main agent once, not from every sub-agent.+ isSubagent: (sessionId) => sessions.get(sessionId)?.subagent ?? false,+ // A claude sub-agent still at work is one whose transcript is still growing:+ // `<session>/subagents/agent-<id>.jsonl` beside the parent's. Written in the last SUBAGENT_IDLE_MS =+ // alive; the held turn end waits for it.+ subagentActive: (sessionId, agentId) => {+ const transcriptPath = sessions.get(sessionId)?.transcriptPath+ if (!transcriptPath) return false+ try {+ const at = statSync(join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', `agent-${agentId}.jsonl`)).mtimeMs+ return Date.now() - at < SUBAGENT_IDLE_MS+ } catch { return false }+ },+ readLastTurn: (sessionId) => core.transcripts.lastTurn(sessionId),+ dataDir: core.dataDir,+ recapForce: options.recapForce ?? env.RECAP_FORCE,+ alwaysGenerate: () => options.recapWithoutDevice?.() ?? env.RECAP_WITHOUT_DEVICE,+ changed: options.changed,+ })++ const know = (session: RecapSession): string => {+ const subagent = session.subagent ?? sessions.get(session.sessionId)?.subagent ?? false+ sessions.set(session.sessionId, { ...session, subagent })+ return session.sessionId+ }++ const lifecycle = (event: TurnLifecycle, seen: RecapWatchers): void => {+ watchers = seen+ switch (event.kind) {+ case 'events': mirror.ingest(event.events, know(event.session), { replay: event.replay }); return+ case 'beat': {+ const sessionId = know(event.session)+ working.set(sessionId, event.working)+ mirror.heartbeat(sessionId)+ return+ }+ case 'cancelled': mirror.cancel(know(event.session)); return+ case 'forgotten': mirror.forget(know(event.session)); return+ case 'stopped': mirror.noteEngineStopped(event.sessionId); return+ case 'rebound': mirror.inheritSummary(event.from, event.to); return+ case 'purged':+ sessions.delete(event.sessionId)+ working.delete(event.sessionId)+ mirror.deleteHistory(event.sessionId)+ return+ case 'asked': notifications.asked(event.sessionId, event.requestId); return+ case 'answered': notifications.answered(event.sessionId, event.requestId); return+ case 'rejoined': {+ const now = new Set(event.working)+ for (const sessionId of new Set([...working.keys(), ...now])) working.set(sessionId, now.has(sessionId))+ mirror.replayAll()+ return+ }+ }+ }++ return {+ port: {+ lifecycle,+ recaps: (sessionId) => mirror.snapshot(sessionId),+ liveCards: async () => mirror.liveCards() as TurnCardFrame[],+ },+ mirror,+ }+}diff --git a/cli/src/services/recapsProcess.spec.ts b/cli/src/services/recapsProcess.spec.tsnew file mode 100644index 000000000..a15680531--- /dev/null+++ b/cli/src/services/recapsProcess.spec.ts@@ -0,0 +1,138 @@+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { CoreApi, TurnLifecycle } from '../core/api.js'+import type { LiveEvent } from '../lib/normalize.js'+import type { CoreConnection, ServiceProcessOptions } from './process.js'+import { createRecaps } from './recaps.js'+import { recapsCoreApi, runRecapsService } from './recapsProcess.js'++// The real default reaches a real socket and this process's own channel: never in a test.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))++const dirs: string[] = []+const temp = () => { const dir = mkdtempSync(join(tmpdir(), 'recaps-process-')); dirs.push(dir); return dir }+const watching = { device: true, active: true }+const s1 = { sessionId: 's1', agentId: 'a1', subagent: false }+const started = { type: 'turn_started', payload: { userMessage: 'what is the fix?' } } as LiveEvent+const ended = { type: 'turn_ended', payload: {} } as LiveEvent+const lifecycle = (event: TurnLifecycle) => ({ kind: 'lifecycle', event, watchers: watching })++/** A connection to the core that records what it is told and answers `lastTurn` with `turn`. */+function connection(turn: unknown = { assistantText: 'The fix is in.', userMessage: 'what is the fix?' }) {+ const notice = vi.fn()+ const query = vi.fn(async (_name: string, _payload?: Record<string, unknown>) => ({ turn }) as Record<string, unknown>)+ const said = (kind: string) => notice.mock.calls.filter(([k]) => k === kind).map(([, payload]) => payload)+ return { core: { query, notice } satisfies CoreConnection, notice, query, said }+}++describe('the recaps in their own process', () => {+ afterEach(() => {+ vi.clearAllMocks()+ vi.restoreAllMocks()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ })++ const setup = (over: Partial<Parameters<typeof runRecapsService>[0]> = {}) => {+ let options: ServiceProcessOptions | null = null+ let api: CoreApi | null = null+ const service = { stop: vi.fn() }+ const handle = runRecapsService({+ dataDir: temp(), socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (given) => { options = given; return service },+ create: (core, opts) => { api = core; return createRecaps(core, { recapForce: false, recapWithoutDevice: () => true, ...opts }) },+ ...over,+ })+ return { options: options!, api: api!, service, handle }+ }++ it('reaches the core as `recaps`, through the socket and token it was given, and answers the apps nothing', () => {+ const { options, handle, service } = setup()+ expect(options).toMatchObject({ name: 'recaps', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(Object.keys(options.requests)).toEqual(['liveCards'])+ expect(handle).toBe(service)+ })++ it('cuts a turn\'s recap, sends its cards and recap as notices, and says what it now holds of the session', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { options } = setup()+ const core = connection()+ options.onConnected!(core.core)+ options.onEvent!(lifecycle({ kind: 'events', session: s1, events: [started], replay: false }))+ expect(core.said('recaps').at(-1)).toMatchObject({ sessionId: 's1', recaps: { asks: ['what is the fix?'], busy: true } })+ options.onEvent!(lifecycle({ kind: 'events', session: s1, events: [ended], replay: false }))+ await vi.waitFor(() => expect(core.said('summary')).toHaveLength(1))+ expect(core.query).toHaveBeenCalledWith('lastTurn', { sessionId: 's1' })+ expect(core.said('summary')[0]).toMatchObject({ frame: { type: 'turn_summary', agentId: 'a1', dbSessionId: 's1' } })+ expect(core.said('card').map(({ frame }) => frame.payload.kind)).toEqual(['processing', 'done', 'summary'])+ expect(core.said('recaps').at(-1)).toMatchObject({ sessionId: 's1', recaps: { busy: false, history: [expect.any(String)] } })+ // A change is said once: a beat that changes nothing says nothing more.+ const before = core.said('recaps').length+ options.onEvent!(lifecycle({ kind: 'beat', session: s1, working: false }))+ expect(core.said('recaps')).toHaveLength(before)+ })++ it('tells a core that connects everything it holds, and a new connection everything again', () => {+ const { options } = setup()+ options.onEvent!(lifecycle({ kind: 'events', session: s1, events: [started], replay: false }))+ const first = connection()+ options.onConnected!(first.core)+ expect(first.said('recaps')).toMatchObject([{ sessionId: 's1', recaps: { busy: true } }])+ options.onDisconnected!()+ // While no core listens, nothing is said, and the change waits for the next connection.+ options.onEvent!(lifecycle({ kind: 'cancelled', session: s1 }))+ expect(first.said('recaps')).toHaveLength(1)+ const second = connection()+ options.onConnected!(second.core)+ expect(second.said('recaps')).toMatchObject([{ sessionId: 's1', recaps: { busy: false } }])+ })++ it('cuts no recap when the core is not there to read the turn, or reads none', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { api } = setup()+ expect(await api.transcripts.lastTurn('s1')).toBeNull()+ const { options, api: connected } = setup()+ options.onConnected!(connection('not a turn').core)+ expect(await connected.transcripts.lastTurn('s1')).toBeNull()+ })++ it('answers the core\'s one question: the cards of every turn still at work', async () => {+ const { options } = setup()+ options.onEvent!(lifecycle({ kind: 'events', session: s1, events: [started], replay: false }))+ options.onEvent!(lifecycle({ kind: 'beat', session: s1, working: true }))+ expect(await options.requests.liveCards({}, { local: true, owner: true })).toMatchObject({ cards: [{ dbSessionId: 's1', payload: { kind: 'processing' } }] })+ })++ it('takes only what reads as a lifecycle event', () => {+ const { options } = setup()+ const core = connection()+ options.onConnected!(core.core)+ for (const payload of [{ kind: 'lifecycle' }, { kind: 'lifecycle', event: { kind: 'stopped', sessionId: 's1' } }, { kind: 'other', event: { kind: 'rejoined', working: [] }, watchers: watching }, { kind: 'lifecycle', event: 'x', watchers: watching }, { kind: 'lifecycle', event: {}, watchers: watching }]) {+ options.onEvent!(payload as Record<string, unknown>)+ }+ expect(core.notice).not.toHaveBeenCalled()+ })++ it('drops a card or a recap said while no core is connected', () => {+ const { api } = setup()+ expect(() => api.clients.turnCard({ type: 'commander_event', agentId: 'a', dbSessionId: 's', payload: {} })).not.toThrow()+ expect(() => api.clients.turnSummary({ type: 'turn_summary' })).not.toThrow()+ })++ it('runs on a core API that reaches the core only through these three ways, and holds no credential', async () => {+ const ways = { turnCard: vi.fn(), turnSummary: vi.fn(), lastTurn: vi.fn(async () => null) }+ const api = recapsCoreApi('/data', ways)+ expect(api.dataDir).toBe('/data')+ expect(api.transcripts.lastTurn).toBe(ways.lastTurn)+ expect(api.clients.turnCard).toBe(ways.turnCard)+ expect(api.clients.turnSummary).toBe(ways.turnSummary)+ await expect(api.account.accessToken()).rejects.toThrow('recaps holds no credential')+ })++ it('runs on the real service process unless told otherwise', async () => {+ const { runServiceProcess } = await import('./process.js')+ runRecapsService({ dataDir: temp(), socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'recaps' }))+ })+})diff --git a/cli/src/services/recapsProcess.ts b/cli/src/services/recapsProcess.tsnew file mode 100644index 000000000..5f75bfcd9--- /dev/null+++ b/cli/src/services/recapsProcess.ts@@ -0,0 +1,101 @@+/**+ * The recaps in their own process: the edge host's, by default (`harness __service recaps`, harnessd's+ * `SERVICE_HOSTS`).+ *+ * The same recaps as in the core's process (services/recaps.ts), on a core API built here. The core tells+ * this process each turn's lifecycle (`service_event lifecycle`) and never waits for it; a turn it misses+ * while this process is down, hung or slow simply has no recap. What the recaps would put in front of a+ * person (a device's turn card, the apps' recap) goes back to the core as a notice, which the core sends on+ * after checking its type. A turn's final answer, which the recap is cut from, is asked of the core+ * (`service_query lastTurn`): the transcript is the core's to read.+ *+ * What the core reads back in line (an agent's last turns and asks, and whether its card is busy) it reads+ * from what this process last told it (`service_notice recaps`), whenever a session's changes, and all of+ * them each time it connects: a core that restarted holds nothing until then (core/recapsLink.ts).+ */+import type { CoreApi, TurnCardFrame, TurnLifecycle, TurnSummaryFrame, RecapWatchers } from '../core/api.js'+import type { LastTurnText } from '../lib/normalize.js'+import { processCoreApi } from './processCoreApi.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { createRecaps } from './recaps.js'++export interface RecapsServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+ /** Swapped in tests. */+ create?: typeof createRecaps+}++/** What the recaps ask of the core in their own process; the rest of the core API answers as nothing. */+export interface RecapsCoreWays {+ turnCard(frame: TurnCardFrame): void+ turnSummary(frame: TurnSummaryFrame): void+ lastTurn(sessionId: string): Promise<LastTurnText | null>+}++/** The core API the recaps run on in their own process: the light services' (processCoreApi.ts), with+ * the three ways the recaps reach the core. */+export function recapsCoreApi(dataDir: string, ways: RecapsCoreWays): CoreApi {+ const api = processCoreApi(dataDir, 'recaps')+ return {+ ...api,+ transcripts: { ...api.transcripts, lastTurn: ways.lastTurn },+ clients: { ...api.clients, turnCard: ways.turnCard, turnSummary: ways.turnSummary },+ }+}++/** Whether what the core sent reads as a lifecycle event: its kind, and the watchers beside it. */+const isLifecycle = (payload: Record<string, unknown>): payload is { event: TurnLifecycle; watchers: RecapWatchers } =>+ !!payload.event && typeof payload.event === 'object' && typeof (payload.event as { kind?: unknown }).kind === 'string'+ && !!payload.watchers && typeof payload.watchers === 'object'++export function runRecapsService(options: RecapsServiceOptions): ServiceProcess {+ let core: CoreConnection | null = null+ /** What the current connection was last told of each session: whether its card was busy, and which of+ * its stored recaps' revisions. A change is said once; a new connection is told everything. */+ const told = new Map<string, string>()++ const tell = (sessionId: string): void => {+ if (!core) return+ const said = `${recaps.mirror.busy(sessionId)}:${recaps.mirror.revision(sessionId)}`+ if (told.get(sessionId) === said) return+ told.set(sessionId, said)+ core.notice?.('recaps', { sessionId, recaps: recaps.port.recaps(sessionId) })+ }++ const recaps = (options.create ?? createRecaps)(recapsCoreApi(options.dataDir, {+ // Lost with the connection, as a card to a device that went away is: the next turn's card follows.+ turnCard: (frame) => { core?.notice?.('card', { frame }) },+ turnSummary: (frame) => { core?.notice?.('summary', { frame }) },+ // Asked of the core, which reads the transcript; no answer without one (the recap then is none).+ lastTurn: async (sessionId) => {+ if (!core) return null+ const answer = await core.query('lastTurn', { sessionId })+ return answer.turn && typeof answer.turn === 'object' ? answer.turn as LastTurnText : null+ },+ }), { changed: tell })++ const run = options.run ?? runServiceProcess+ return run({+ name: 'recaps',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ // The apps ask the recaps nothing: the core answers them from what this process tells it. The core+ // itself asks one thing, when a dial attaches: the cards of every turn still at work.+ requests: { liveCards: async () => ({ cards: await recaps.port.liveCards() }) },+ onEvent: (payload) => {+ if (payload.kind === 'lifecycle' && isLifecycle(payload)) recaps.port.lifecycle(payload.event, payload.watchers)+ },+ onConnected: (connection) => {+ core = connection+ told.clear()+ for (const sessionId of recaps.mirror.sessions()) tell(sessionId)+ },+ onDisconnected: () => { core = null },+ })+}diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.tsindex a4b62f16c..825ed100f 100644--- a/cli/src/services/searchProcess.spec.ts+++ b/cli/src/services/searchProcess.spec.ts@@ -133,6 +133,7 @@ describe('search in its own process', () => {api.questions.answer('live', 'q', {})await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)expect(api.transcripts.databaseHistory({ engine: 'claude' } as never)).toBeUndefined()+ expect(await api.transcripts.lastTurn('s1')).toBeNull()expect(api.external.sessions.list()).toEqual([])await expect(api.account.mintGridName()).resolves.toBeNull()await expect(api.account.accessToken()).rejects.toThrow('search holds no credential')@@ -145,6 +146,8 @@ describe('search in its own process', () => {api.clients.dshInstallStatus({ phase: 'clone' })api.clients.windows({ type: 'orchestrator_changed', payload: {} })expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)+ api.clients.turnCard({ type: 'commander_event', agentId: 'a', dbSessionId: 's', payload: {} })+ api.clients.turnSummary({ type: 'turn_summary' })})it('runs as a real service process, over the conversations this machine has, by default', () => {diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex eae94456d..5bc32998d 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -63,7 +63,7 @@ export function searchCoreApi(// Search drives no agent: these are never asked of it.turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },- transcripts: { databaseHistory },+ transcripts: { databaseHistory, lastTurn: UNASKED.lastTurn },external: {sessions: new ExternalSessions({ providers, excluded: [dataDir], log: console.warn }),open: new OpenSessions({ providers, log: console.warn }),diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.tsindex 915e4c8ec..661bb202d 100644--- a/cli/src/services/viewersProcess.spec.ts+++ b/cli/src/services/viewersProcess.spec.ts@@ -262,6 +262,7 @@ describe('the viewers in their own process', () => {api.clients.viewerChanged('a1')expect(tell.mock.calls).toEqual([['a1'], ['a1']])expect(api.transcripts.databaseHistory(agent())).toBeUndefined()+ expect(await api.transcripts.lastTurn('s1')).toBeNull()expect(api.external.sessions.list()).toEqual([])await expect(api.external.sessions.scan()).resolves.toEqual([])expect(api.external.open.known().size).toBe(0)@@ -287,6 +288,8 @@ describe('the viewers in their own process', () => {expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)// Built on its own, it reaches no client.expect(api.clients.viewerFrame('c1', 'viewer_data', {})).toBe(false)+ api.clients.turnCard({ type: 'commander_event', agentId: 'a', dbSessionId: 's', payload: {} })+ api.clients.turnSummary({ type: 'turn_summary' })})it('runs as a real service by default: its viewers, on its own link to the core', async () => {diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex 92f7568cf..5d23991a4 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -81,7 +81,7 @@ export function viewersCoreApi(// The viewers drive no agent: these are never asked of them.turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },- transcripts: { databaseHistory: () => undefined },+ transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },external: {sessions: { list: () => [], scan: async () => [] },open: { known: () => new Map(), fresh: async () => new Map() },diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.tsindex 6754fb531..f2a9a6459 100644--- a/cli/src/services/workspacesProcess.spec.ts+++ b/cli/src/services/workspacesProcess.spec.ts@@ -159,6 +159,7 @@ describe('workspaces in their own process', () => {api.agents.sync(agent('a1'))expect(renamed).toHaveBeenCalledWith('a1')expect(api.transcripts.databaseHistory(agent())).toBeUndefined()+ expect(await api.transcripts.lastTurn('s1')).toBeNull()expect(api.external.sessions.list()).toEqual([])await expect(api.external.sessions.scan()).resolves.toEqual([])expect(api.external.open.known().size).toBe(0)@@ -184,6 +185,8 @@ describe('workspaces in their own process', () => {api.clients.dshInstallStatus({ phase: 'clone' })api.clients.windows({ type: 'orchestrator_changed', payload: {} })expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)+ api.clients.turnCard({ type: 'commander_event', agentId: 'a', dbSessionId: 's', payload: {} })+ api.clients.turnSummary({ type: 'turn_summary' })})it('runs as a real service process, with the real workspaces, by default', () => {diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex 1de26a860..218566a0d 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -72,7 +72,7 @@ export function workspacesCoreApi(// The workspaces drive no agent: these are never asked of them.turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },- transcripts: { databaseHistory: () => undefined },+ transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },external: {sessions: { list: () => [], scan: async () => [] },open: { known: () => new Map(), fresh: async () => new Map() },diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 66dfccfea..43011cc14 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -42,7 +42,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {...over.turns,},questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => false), ...over.questions },- transcripts: { databaseHistory: vi.fn(() => undefined), ...over.transcripts },+ transcripts: { databaseHistory: vi.fn(() => undefined), lastTurn: vi.fn(async () => null), ...over.transcripts },external: {sessions: { list: vi.fn(() => []), scan: vi.fn(async () => []) },open: { known: vi.fn(() => new Map()), fresh: vi.fn(async () => new Map()) },@@ -72,6 +72,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {clients: {viewerChanged: vi.fn(), viewerFrame: vi.fn(() => false), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), observer: vi.fn(() => true),sendLocal: vi.fn(), sendToWindow: vi.fn(() => true), hasWindow: vi.fn(() => true), devicesChanged: vi.fn(), dialWatching: vi.fn(),+ turnCard: vi.fn(), turnSummary: vi.fn(),...over.clients,},daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', autonomousEnv: 'prod', ...over.daemon },diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.tsindex bad847817..5ddcc1bce 100644--- a/cli/src/testing/teamFixture.ts+++ b/cli/src/testing/teamFixture.ts@@ -58,7 +58,7 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixtureonDelivery: (listener) => { listeners.add(listener); return () => { listeners.delete(listener) } },},questions: { answer: () => {}, answerReviewed: async () => false },- transcripts: { databaseHistory: () => undefined },+ transcripts: { databaseHistory: () => undefined, lastTurn: async () => null },external: { sessions: { list: () => [], scan: async () => [] }, open: { known: () => new Map(), fresh: async () => new Map() } },account: {mintGridName: async () => null, accessToken: () => Promise.reject(new Error('no credential')), lane: LANE_OFF,