Skip to content

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

Fix Device follow-up results in the existing summary flow (#336)

Leod732a2e52da4
diff --git a/cli/README.md b/cli/README.md
index fc33c51f4..e7e712ca7 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -315,5 +315,4 @@ automatically. Revoke closes only the selected device connection. Existing Harne
requirements remain unchanged; the running daemon's direct device transport works offline from
its backend. Browser/dial behavior and Buddy are unchanged.
-See [the contract](../docs/autonomous-device-integration.md) and
-[Vietnamese guide](../docs/vi/autonomous-device-integration_vi.md).
+See [the contract](../docs/autonomous-device-integration.md).
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index f1993fb15..b0ca57204 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -225,6 +225,7 @@ import { probeGridAssignment, sameGridAssignment } from './lib/gridAssignment.js
import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { SessionInputController } from './lib/sessionInput.js'
+import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'
import { AutonomousDeviceInput, isDeviceInputBoundary } from './lib/autonomous-device/input.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfile.js'
@@ -2155,6 +2156,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
|| (session.engine === 'cursor' && replayCursorFromStart)
const historyEvents: LiveEvent[] = []
let historyTurnOpen = false
+ if (autonomousDeviceService?.needsTranscript(session.agentId, session.sessionId, session.engine)) {
+ for (const line of lines) autonomousDeviceService.observeTranscript(session.agentId, session.sessionId, session.engine, line)
+ }
runtimeProfiles.hydrate(session, lines)
await runtimeProfiles.ingestConfig(session, true)
// Returns `turnOpen` rather than assigning it: every engine folds exactly once, and a second call
@@ -2403,6 +2407,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
legacySubmit: (id, text, deliveryId) => input.submit(id, text, deliveryId),
legacyCancel: id => input.cancelDelivery(id),
onDelivery: event => autonomousDeviceService?.delivery(event),
+ onDispatch: (id, deliveryId, text) => autonomousDeviceService?.inputDispatched(id, deliveryId, text, registry.byAgent(id)?.sessionId),
onInputStatus: event => autonomousDeviceService?.inputStatus(event),
onForget: id => autonomousDeviceService?.agentGone(id),
})
@@ -4167,6 +4172,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const session = registry.bySession(evt.sessionId)
if (!session || session.engine !== evt.engine) return null
agentTokenUsage.changed(session)
+ if (autonomousDeviceService?.needsTranscript(session.agentId, evt.sessionId, session.engine)) {
+ autonomousDeviceService.observeTranscript(session.agentId, evt.sessionId, session.engine, evt.text)
+ }
runtimeProfiles.ingest(session, evt.text)
let events
if (session.engine === 'codex') {
@@ -5820,6 +5828,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
deviceStore.startUiDelivery()
autonomousDeviceService = new AutonomousDeviceService({
store: deviceStore,
+ resultJournal: new DeviceResultJournal(join(env.ADAPTER_DATA_DIR, 'device-results.json')),
+ inputConsumed: (id, text) => deviceInput.onTurnStarted(id, text),
machineId: backend.machineId,
requestAppFocus: (agentId, expiresAt, focusRevision) => backend.sendFirstLocal({
type: 'device_focus', payload: { machineId: backend.machineId, agentId, expiresAt, focusRevision },
diff --git a/cli/src/lib/autonomous-device/input.spec.ts b/cli/src/lib/autonomous-device/input.spec.ts
index 35c188fc9..8273a5792 100644
--- a/cli/src/lib/autonomous-device/input.spec.ts
+++ b/cli/src/lib/autonomous-device/input.spec.ts
@@ -79,11 +79,12 @@ describe('in-flight input through the Autonomous Device contract', () => {
expect(await f.send('B', 'Make the roof red', revision)).toMatchObject({ status: 'duplicate', receipt: { deliveryId: before } })
expect(f.inject).toHaveBeenCalledTimes(2)
f.end()
- expect(f.receipt('A').state).toBe('completed')
+ // A session end without engine result evidence cannot complete a native input.
+ expect(f.receipt('A').state).toBe('unknown')
expect(f.receipt('B').state).toBe('delivered')
f.start('Make the roof red')
f.end()
- expect(f.receipt('B').state).toBe('completed')
+ expect(f.receipt('B').state).toBe('unknown')
expect(f.receipt('B').turnId).not.toBe(f.receipt('A').turnId)
f.controller.forget('agent')
})
@@ -124,10 +125,10 @@ describe('in-flight input through the Autonomous Device contract', () => {
expect(f.receipt('B').state).toBe('delivered')
expect(f.receipt('C').state).toBe('delivered')
f.start('B'); f.end()
- expect(f.receipt('B').state).toBe('completed')
+ expect(f.receipt('B').state).toBe('unknown')
expect(f.receipt('C').state).toBe('delivered')
f.start('C'); f.end()
- expect(f.receipt('C').state).toBe('completed')
+ expect(f.receipt('C').state).toBe('unknown')
f.controller.forget('agent')
})
@@ -138,8 +139,8 @@ describe('in-flight input through the Autonomous Device contract', () => {
await f.send('B'); await vi.advanceTimersByTimeAsync(0); f.start('B')
f.end()
f.service.commander({ type: 'commander_event', agentId: 'agent', payload: { kind: 'summary', text: 'A answer' } })
- expect(f.receipt('A')).toMatchObject({ state: 'unknown', error: { code: 'OVERLAPPING_INPUTS' } })
- expect(f.receipt('B')).toMatchObject({ state: 'unknown', error: { code: 'OVERLAPPING_INPUTS' } })
+ expect(f.receipt('A')).toMatchObject({ state: 'unknown', error: { code: 'RESULT_EVIDENCE_MISSING' } })
+ expect(f.receipt('B')).toMatchObject({ state: 'unknown', error: { code: 'RESULT_EVIDENCE_MISSING' } })
expect(f.events.findLast(event => event.kind === 'turn.done')).toMatchObject({ payload: {} })
expect(await f.send('B')).toMatchObject({ status: 'duplicate' })
expect(f.inject).toHaveBeenCalledTimes(2)
@@ -259,7 +260,8 @@ describe('native input write evidence', () => {
expect(await f.send('A')).toMatchObject({ status: 'duplicate' })
expect(f.inject).toHaveBeenCalledTimes(1)
f.end()
- expect(f.receipt('A').state).toBe('completed')
+ // A session end without engine result evidence cannot complete a native input.
+ expect(f.receipt('A').state).toBe('unknown')
f.controller.forget('agent')
})
@@ -270,6 +272,7 @@ describe('native input write evidence', () => {
f.gone()
expect(f.receipt('A')).toMatchObject({ state: 'unknown', error: { code: 'AGENT_GONE' } })
f.end()
+ // A session end without engine result evidence cannot complete a native input.
expect(f.receipt('A').state).toBe('unknown')
})
@@ -334,8 +337,8 @@ it.each(['codex', 'claude'] as const)('%s Device filter rejects an inferred comp
expect(inputEvents.map(event => event.type)).toEqual(['turn_ended', 'turn_started'])
if (engine === 'claude') expect(claude.pendingTools.has('running-tool')).toBe(false) // unchanged shared normalizer
observe(inputEvents)
- expect(f.receipt('A').state).toBe('unknown')
- expect(f.receipt('B').state).toBe('unknown')
+ expect(f.receipt('A').state).toBe('started')
+ expect(f.receipt('B').state).toBe('started')
const endEvents = engine === 'codex'
? codex.ingest(JSON.stringify({ type: 'event_msg', payload: { type: 'task_complete' } }))
: (() => {
diff --git a/cli/src/lib/autonomous-device/input.ts b/cli/src/lib/autonomous-device/input.ts
index 6f391fd76..4f7641b01 100644
--- a/cli/src/lib/autonomous-device/input.ts
+++ b/cli/src/lib/autonomous-device/input.ts
@@ -51,6 +51,7 @@ export interface DeviceInputDeps {
acquireControl: (id: string) => (() => void) | null
legacySubmit: (id: string, text: string, deliveryId: string) => void
legacyCancel: (deliveryId: string) => boolean
+ onDispatch?: (id: string, deliveryId: string, text: string) => void
onDelivery: (event: SessionInputDelivery) => void
onInputStatus: (event: DeviceInputStatus) => void
onForget?: (id: string) => void
@@ -185,6 +186,7 @@ export class AutonomousDeviceInput {
const version = session.cliVersion?.match(/(\d+)\.(\d+)\.(\d+)/)
item.mode = !state.busy ? 'direct' : session.engine === 'claude' ? 'native_queue'
: version && (Number(version[1]) > 0 || Number(version[2]) >= 106) ? 'steering' : 'native_input'
+ this.deps.onDispatch?.(id, item.deliveryId, item.content)
item.dispatched = true
state.pending.push(item)
const result = await this.deps.inject(session.agentId, item.content)
diff --git a/cli/src/lib/autonomous-device/relay.spec.ts b/cli/src/lib/autonomous-device/relay.spec.ts
index c6c531dd0..9d1b77327 100644
--- a/cli/src/lib/autonomous-device/relay.spec.ts
+++ b/cli/src/lib/autonomous-device/relay.spec.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from 'node:fs'
import { describe, expect, it, vi } from 'vitest'
import { AutonomousDeviceRelay } from './relay.js'
import { AutonomousDeviceService } from './service.js'
@@ -8,11 +9,11 @@ function fixture(store?: import('./store.js').AutonomousDeviceStore) {
const crypto = { sessionRole: () => role as 'device' | 'web', sessionIdentity: () => identity,
unwrapDown: (_c: string, frame: Record<string, unknown>) => ({ ...frame, payload: (frame.payload as { __e2e: unknown }).__e2e }),
wrapTarget: (_c: string, type: string, payload: Record<string, unknown>) => ({ type, payload: { __e2e: payload } }) }
- const service = new AutonomousDeviceService({ store, machineId: 'machine', agents: () => [{ agentId: 'agent', name: 'Agent', engine: 'codex', state: 'idle' }], submit, cancelDelivery: cancel, stop: async () => true, answer: async () => true, recent: () => [] })
+ const service = new AutonomousDeviceService({ store, now: () => 0, machineId: 'machine', agents: () => [{ agentId: 'agent', name: 'Agent', engine: 'codex', state: 'idle' }], submit, cancelDelivery: cancel, stop: async () => true, answer: async () => true, recent: () => [] })
const remoteRevoke = vi.fn()
const relay = new AutonomousDeviceRelay(crypto, send, service, 'machine', undefined, remoteRevoke)
const request = (payload: Record<string, unknown>) => relay.handle('conn', { type: 'autonomous_device_request', payload: { __e2e: payload } })
- return { relay, request, send, submit, service, cancel, remoteRevoke, setRole: (r: string) => { role = r }, revoke: () => { identity = null } }
+ return { relay, request, send, submit, service, cancel, remoteRevoke, setRole: (r: string) => { role = r }, setIdentity: (id: string) => { identity = id }, revoke: () => { identity = null } }
}
describe('Autonomous device existing E2EE relay seam', () => {
it('requires existing device-role trust and encrypted payload before calling the service', async () => {
@@ -84,3 +85,28 @@ it('Store uses the same device-only encrypted hello gate and never exposes gener
expect(f.send.mock.calls.at(-1)?.[1]).toMatchObject({ payload: { __e2e: { error: { code: 'UNSUPPORTED_CAPABILITY' } } } })
expect(call).toHaveBeenCalledOnce()
})
+
+
+it('delivers correlated summaries by default only to the originating identity, including replay', async () => {
+ const f = fixture()
+ const capture = JSON.parse(readFileSync(new URL('../../../../docs/contracts/autonomous-device-summary-correlation/codex-steering.json', import.meta.url), 'utf8'))
+ await f.request({ type: 'hello', proto: 1, requestId: randomUUID() }) // unchanged application hello
+ for (const [i, text] of capture.inputs.entries()) {
+ await f.request({ type: 'turn.send', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', idempotencyKey: `key-${i}`, text })
+ f.service.inputDispatched('agent', f.service.receipt('trusted-device', `key-${i}`)!.deliveryId, text)
+ }
+ for (const row of capture.records) f.service.observeTranscript('agent', 'session', 'codex', JSON.stringify(row))
+ const frames: any[] = []
+ f.service.replay(undefined, e => frames.push(e))
+ const result = frames.find(e => e.kind === 'turn.summary')
+ expect(result).toBeDefined()
+ const results = () => f.send.mock.calls.map(([, frame]) => frame.payload.__e2e).filter(e => e.kind === 'turn.summary')
+ f.send.mockClear(); f.relay.emit(result)
+ expect(results()).toHaveLength(1)
+ f.send.mockClear()
+ await f.request({ type: 'hello', proto: 1, requestId: randomUUID() })
+ expect(results()).toHaveLength(1)
+ f.send.mockClear(); f.setIdentity('other-device')
+ await f.request({ type: 'hello', proto: 1, requestId: randomUUID() })
+ f.relay.emit(result); expect(results()).toHaveLength(0)
+})
diff --git a/cli/src/lib/autonomous-device/relay.ts b/cli/src/lib/autonomous-device/relay.ts
index 554195280..546adfe9a 100644
--- a/cli/src/lib/autonomous-device/relay.ts
+++ b/cli/src/lib/autonomous-device/relay.ts
@@ -57,6 +57,10 @@ export class AutonomousDeviceRelay {
}
private sendEvent(connId: string, identity: string, event: AutonomousDeviceFrame): void {
const p = event.payload as Frame | undefined
+ if (event.kind === 'turn.summary' && p?.resultId !== undefined) {
+ if (this.service.canSendResult(identity, event)) this.sendTo(connId, identity, 'autonomous_device_event', event)
+ return
+ }
if (typeof p?.idempotencyKey === 'string') {
const own = this.service.receipt(identity, p.idempotencyKey)
const receipt = p.receipt as Frame | undefined
diff --git a/cli/src/lib/autonomous-device/resultContract.ts b/cli/src/lib/autonomous-device/resultContract.ts
new file mode 100644
index 000000000..52df8ea7c
--- /dev/null
+++ b/cli/src/lib/autonomous-device/resultContract.ts
@@ -0,0 +1,18 @@
+import { z } from 'zod'
+const id = z.string().min(1)
+const member = z.strictObject({ deliveryId: id, idempotencyKey: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/) })
+const correlation = z.discriminatedUnion('scope', [
+ z.strictObject({ scope: z.literal('input'), inputs: z.array(member).length(1), engineTurnId: id.optional() }),
+ z.strictObject({ scope: z.literal('group'), inputs: z.array(member).min(2).max(64), engineTurnId: id.optional() }),
+])
+export const DeviceResultPayloadSchema = z.strictObject({
+ serverInstanceId: id, resultId: id, correlation,
+ outcome: z.enum(['completed', 'failed', 'cancelled']), fullText: z.string().min(1),
+ kind: z.literal('summary').optional(), text: z.string().optional(), recap: z.string().optional(),
+ idempotencyKey: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(), turnId: id.nullable().optional(),
+})
+export const DeviceResultSchema = z.strictObject({
+ type: z.literal('event'), kind: z.literal('turn.summary'), agentId: id,
+ serverInstanceId: id.optional(), machineId: id.optional(), eventId: z.number().int().positive().optional(),
+ payload: DeviceResultPayloadSchema,
+})
diff --git a/cli/src/lib/autonomous-device/resultEvidence.ts b/cli/src/lib/autonomous-device/resultEvidence.ts
new file mode 100644
index 000000000..9aecc61ff
--- /dev/null
+++ b/cli/src/lib/autonomous-device/resultEvidence.ts
@@ -0,0 +1,99 @@
+import { createHash } from 'node:crypto'
+
+export const inputHash = (text: string): string => createHash('sha256').update(text.replace(/\r\n/g, '\n').trim()).digest('hex')
+export interface ResultEvidence {
+ evidenceId: string
+ engineTurnId?: string
+ inputs: string[] // matched delivery IDs, never session-wide outstanding inputs
+ outcome: 'completed' | 'failed' | 'cancelled'
+ fullText: string
+}
+type Json = Record<string, any>
+interface Node { parent?: string; input?: string | null; root: boolean; text?: string; messageId?: string }
+interface State { nodes: Map<string, Node>; seen: Set<string>; turns: Map<string, Array<string | null>> }
+/** Device-only transcript observer. Neither scheduling nor shared normalizers are changed.
+ * Claude: walk the final answer's parentUuid chain to its human root, including queued_command
+ * attachments on that exact branch. Codex: use explicit per-message engine turn IDs only.
+ */
+export class DeviceResultEvidence {
+ private sessions = new Map<string, State>()
+ constructor(private readonly consume: (agentId: string, text: string, timestamp: number) => string | null,
+ private readonly result: (agentId: string, evidence: ResultEvidence) => void,
+ private readonly uncertain: (agentId: string, inputs: string[]) => void) {}
+ forget(agentId: string): void { this.sessions.delete(agentId) }
+ ingest(agentId: string, engine: string, line: string): void {
+ if (engine !== 'claude' && engine !== 'codex') return
+ let row: Json
+ try { row = JSON.parse(line) } catch { return }
+ if (!row || typeof row !== 'object' || row.isSidechain === true) return
+ let s = this.sessions.get(agentId)
+ if (!s) { s = { nodes: new Map(), seen: new Set(), turns: new Map() }; this.sessions.set(agentId, s) }
+ if (engine === 'claude') this.claude(agentId, s, row)
+ else this.codex(agentId, s, row)
+ }
+ private claude(agent: string, s: State, row: Json): void {
+ if (typeof row.uuid !== 'string' || !row.uuid || s.nodes.has(row.uuid)) return
+ const message = row.message
+ const attachment = row.attachment
+ const blocks: Json[] = Array.isArray(message?.content) ? message.content : []
+ const text = typeof message?.content === 'string' ? message.content
+ : blocks.filter(b => b?.type === 'text' && typeof b.text === 'string').map(b => b.text).join('\n')
+ const root = row.type === 'user' && row.isMeta !== true && !!text && !blocks.some(b => b?.type === 'tool_result')
+ const queued = row.type === 'attachment' && attachment?.type === 'queued_command'
+ && attachment.commandMode === 'prompt' && attachment.origin?.kind === 'human' && typeof attachment.prompt === 'string'
+ const node: Node = { parent: typeof row.parentUuid === 'string' ? row.parentUuid : undefined, root }
+ if (root || queued) node.input = this.consume(agent, root ? text : attachment.prompt, Date.parse(row.timestamp))
+ if (row.type === 'assistant') { node.text = text; node.messageId = message?.id }
+ s.nodes.set(row.uuid, node)
+ // Missing ancestry after eviction fails closed, never infers membership from time/session.
+ if (s.nodes.size > 8192) s.nodes.delete(s.nodes.keys().next().value!)
+ if (row.type !== 'assistant' || message?.stop_reason !== 'end_turn' || blocks.some(b => b?.type === 'tool_use')) return
+ const members: Array<string | null> = []
+ const final: string[] = []
+ let cursor: Node | undefined = node, complete = false
+ const visited = new Set<Node>()
+ while (cursor && !visited.has(cursor)) {
+ visited.add(cursor)
+ if ('input' in cursor) members.unshift(cursor.input ?? null)
+ if (cursor.messageId && cursor.messageId === node.messageId && cursor.text) final.unshift(cursor.text)
+ if (cursor.root) { complete = true; break }
+ cursor = cursor.parent ? s.nodes.get(cursor.parent) : undefined
+ }
+ const ids = members.filter((id): id is string => id !== null)
+ const fullText = final.join('\n\n')
+ if (!complete || members.includes(null) || !ids.length || !fullText.trim()) { this.uncertain(agent, ids); return }
+ this.result(agent, { evidenceId: `claude:${row.uuid}`, inputs: [...new Set(ids)], outcome: 'completed', fullText })
+ }
+ private codex(agent: string, s: State, row: Json): void {
+ const p = row.payload
+ if (!p || typeof p !== 'object') return
+ const key = typeof row.ordinal === 'number' ? `ordinal:${row.ordinal}` : typeof p.id === 'string' ? `item:${p.id}`
+ : p.type === 'task_complete' && typeof p.turn_id === 'string' ? `complete:${p.turn_id}` : undefined
+ if (!key || s.seen.has(key)) return
+ s.seen.add(key)
+ if (s.seen.size > 16384) s.seen.delete(s.seen.values().next().value!)
+ if (row.type === 'response_item' && p.type === 'message' && p.role === 'user') {
+ const metadata = p.internal_chat_message_metadata_passthrough
+ const turn = metadata?.turn_id
+ // Older rollouts lacking explicit message-to-turn mapping are deliberately unsupported.
+ if (typeof turn !== 'string' || !turn) return
+ const kinds = metadata.content_item_kinds
+ if (!Array.isArray(kinds) || !kinds.includes('user.text')) return // environment/AGENTS context is not an input
+ const blocks: Json[] = Array.isArray(p.content) ? p.content.filter((_: unknown, i: number) => kinds[i] === 'user.text') : []
+ const text = blocks.filter(b => b?.type === 'input_text' && typeof b.text === 'string').map(b => b.text).join('\n')
+ const member = this.consume(agent, text, Date.parse(row.timestamp))
+ const inputs = s.turns.get(turn) ?? []
+ inputs.push(member); s.turns.set(turn, inputs)
+ if (s.turns.size > 256) { const first = s.turns.keys().next().value!; this.uncertain(agent, (s.turns.get(first) ?? []).filter((id): id is string => id !== null)); s.turns.delete(first) }
+ }
+ if (row.type !== 'event_msg' || !['task_complete', 'turn_aborted'].includes(p.type) || typeof p.turn_id !== 'string') return
+ const members = s.turns.get(p.turn_id) ?? []
+ s.turns.delete(p.turn_id)
+ const ids = members.filter((id): id is string => id !== null)
+ const fullText = p.last_agent_message
+ if (members.includes(null) || !ids.length || typeof fullText !== 'string' || !fullText.trim() || p.type === 'turn_aborted' || p.error) {
+ this.uncertain(agent, ids); return
+ }
+ this.result(agent, { evidenceId: `codex:${p.turn_id}`, engineTurnId: p.turn_id, inputs: [...new Set(ids)], outcome: 'completed', fullText })
+ }
+}
diff --git a/cli/src/lib/autonomous-device/resultJournal.ts b/cli/src/lib/autonomous-device/resultJournal.ts
new file mode 100644
index 000000000..80856ed25
--- /dev/null
+++ b/cli/src/lib/autonomous-device/resultJournal.ts
@@ -0,0 +1,30 @@
+import { closeSync, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from '../secureState.js'
+const MAX_BYTES = 32 * 1024 * 1024
+/** Atomic local transaction: reservations and immutable results survive together.
+ * Never log content. Corrupt/unwritable state fails closed instead of losing dedupe.
+ */
+export class DeviceResultJournal {
+ constructor(private readonly path: string) {}
+ load(): unknown {
+ secureStateDirectory(dirname(this.path))
+ if (!hardenPrivateStateFileIfPresent(this.path, MAX_BYTES)) return undefined
+ return JSON.parse(readPrivateStateFile(this.path, MAX_BYTES))
+ }
+ save(value: unknown): void {
+ secureStateDirectory(dirname(this.path))
+ hardenPrivateStateFileIfPresent(this.path, MAX_BYTES)
+ const data = JSON.stringify(value)
+ if (Buffer.byteLength(data) > MAX_BYTES) throw new Error('Device result journal capacity exceeded')
+ const temporary = `${this.path}.${randomUUID()}.tmp`
+ try {
+ const fd = openSync(temporary, 'wx', 0o600)
+ try { writeFileSync(fd, data); fsyncSync(fd) } finally { closeSync(fd) }
+ renameSync(temporary, this.path)
+ const directory = openSync(dirname(this.path), 'r')
+ try { fsyncSync(directory) } finally { closeSync(directory) }
+ } finally { rmSync(temporary, { force: true }) }
+ }
+}
diff --git a/cli/src/lib/autonomous-device/results.spec.ts b/cli/src/lib/autonomous-device/results.spec.ts
new file mode 100644
index 000000000..8167fdfd1
--- /dev/null
+++ b/cli/src/lib/autonomous-device/results.spec.ts
@@ -0,0 +1,326 @@
+import { z } from 'zod'
+import { DeviceResultSchema } from './resultContract.js'
+import { readFileSync, mkdtempSync, rmSync, statSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { AutonomousDeviceService, type AutonomousDeviceServiceOptions } from './service.js'
+import { DeviceResultJournal } from './resultJournal.js'
+import { DeviceResultEvidence } from './resultEvidence.js'
+
+const fixture = (name: string) => JSON.parse(readFileSync(new URL(`../../../../docs/contracts/autonomous-device-summary-correlation/${name}.json`, import.meta.url), 'utf8'))
+const claude = fixture('claude-native-queue'), codex = fixture('codex-steering')
+const dirs: string[] = []
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+function setup(engine = 'claude', overrides: Partial<AutonomousDeviceServiceOptions> = {}) {
+ const events: any[] = [], submit = vi.fn()
+ const service = new AutonomousDeviceService({ machineId: 'machine', serverInstanceId: 'instance',
+ now: () => Date.parse('2026-09-24T00:00:00Z'),
+ agents: () => [{ agentId: 'agent', engine, name: 'Agent', state: 'working' }], submit,
+ cancelDelivery: () => true, stop: async () => true, answer: async () => true, recent: () => [],
+ emit: event => events.push(event), ...overrides })
+ const send = async (key: string, text: string, owner = 'owner') => {
+ const response = await service.request(owner, { type: 'turn.send', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', idempotencyKey: key, text })
+ const receipt = service.receipt(owner, key)!
+ if (response.status === 'accepted') {
+ service.inputDispatched('agent', receipt.deliveryId, text)
+ service.delivery({ deliveryId: receipt.deliveryId, sessionId: 'agent', state: 'delivered' })
+ }
+ return receipt
+ }
+ const ingest = (row: unknown) => service.observeTranscript('agent', 'session', engine, JSON.stringify(row))
+ const results = () => events.filter(e => e.kind === 'turn.summary')
+ return { service, send, ingest, results, events, submit }
+}
+
+describe('Device result membership from captured engine evidence', () => {
+ it('only parses transcripts for dispatched Device work in its bound session', async () => {
+ const spy = vi.spyOn(DeviceResultEvidence.prototype, 'ingest')
+ try {
+ const f = setup()
+ f.ingest(claude.records[0])
+ expect(spy).not.toHaveBeenCalled()
+ await f.service.request('owner', { type: 'turn.send', requestId: randomUUID(), machineId: 'machine',
+ agentId: 'agent', idempotencyKey: 'A', text: claude.inputs[0] })
+ f.ingest(claude.records[0]) // reserved/daemon queued is not dispatched
+ expect(spy).not.toHaveBeenCalled()
+ f.service.inputDispatched('agent', f.service.receipt('owner', 'A')!.deliveryId, claude.inputs[0], 'session')
+ f.service.observeTranscript('other-agent', 'session', 'claude', JSON.stringify(claude.records[0]))
+ f.service.observeTranscript('agent', 'other-session', 'claude', JSON.stringify(claude.records[0]))
+ expect(spy).not.toHaveBeenCalled()
+ f.ingest(claude.records[0])
+ expect(spy).toHaveBeenCalledTimes(1)
+ f.ingest({ type: 'assistant', uuid: 'scoped-final', parentUuid: claude.records[0].uuid,
+ message: { id: 'scoped-message', stop_reason: 'end_turn', content: [{ type: 'text', text: 'A done' }] } })
+ expect(f.service.receipt('owner', 'A')?.state).toBe('completed')
+ spy.mockClear()
+ f.ingest(claude.records[0])
+ expect(spy).not.toHaveBeenCalled()
+ await f.send('B', claude.inputs[1])
+ expect(f.service.needsTranscript('agent', 'session', 'claude')).toBe(true)
+ f.service.revoke('owner')
+ f.ingest(claude.records[0])
+ expect(spy).not.toHaveBeenCalled()
+ } finally { spy.mockRestore() }
+ })
+
+ it.each(['claude', 'codex'])('%s produces one immutable result for consumed A/B, never queued C', async engine => {
+ const capture = engine === 'claude' ? claude : codex
+ const f = setup(engine)
+ const a = await f.send('A', capture.inputs[0]), b = await f.send('B', capture.inputs[1])
+ await f.send('C', 'Still queued, not consumed')
+ for (const row of capture.records) f.ingest(row)
+ expect(f.results()).toHaveLength(1)
+ expect(f.results()[0].payload).toMatchObject({ serverInstanceId: 'instance', outcome: 'completed', correlation: {
+ scope: 'group', inputs: [{ deliveryId: a.deliveryId, idempotencyKey: 'A' }, { deliveryId: b.deliveryId, idempotencyKey: 'B' }],
+ } })
+ expect(f.service.receipt('owner', 'A')?.state).toBe('completed')
+ expect(f.service.receipt('owner', 'B')?.state).toBe('completed')
+ expect(f.service.receipt('owner', 'C')?.state).toBe('delivered')
+ DeviceResultSchema.parse(f.results()[0])
+ const original = structuredClone(f.results()[0])
+ for (const row of capture.records) f.ingest(row)
+ f.service.turnEnded('agent')
+ f.service.commander({ type: 'commander_event', agentId: 'agent', payload: { kind: 'summary', text: 'unrelated latest recap' } })
+ expect(f.results()).toEqual([original])
+ const replay: any[] = []
+ f.service.replay({ serverInstanceId: 'instance', cursor: 0 }, e => replay.push(e))
+ expect(replay.find(e => e.kind === 'turn.summary')).toEqual(original)
+ await f.send('B', capture.inputs[1]) // lost RPC acknowledgment
+ expect(f.submit).toHaveBeenCalledTimes(3)
+ })
+
+ it('Claude enqueue/remove alone cannot complete B; A can finish separately', async () => {
+ const f = setup()
+ await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1])
+ f.ingest(claude.records[0])
+ for (const row of claude.records.filter((r: any) => r.type === 'queue-operation')) f.ingest(row)
+ f.ingest({ type: 'assistant', uuid: 'final-A', parentUuid: claude.records[0].uuid,
+ message: { id: 'message-A', stop_reason: 'end_turn', content: [{ type: 'text', text: 'A done' }] } })
+ expect(f.results()[0].payload.correlation.scope).toBe('input')
+ expect(f.results()[0].payload.correlation.inputs.map((i: any) => i.idempotencyKey)).toEqual(['A'])
+ expect(f.service.receipt('owner', 'B')?.state).toBe('delivered')
+ f.ingest({ ...claude.records[0], uuid: 'root-B', message: { content: claude.inputs[1] } })
+ f.ingest({ type: 'assistant', uuid: 'final-B', parentUuid: 'root-B', message: { id: 'message-B', stop_reason: 'end_turn', content: [{ type: 'text', text: 'B done' }] } })
+ expect(f.results().map(e => e.payload.correlation.inputs.map((i: any) => i.idempotencyKey))).toEqual([['A'], ['B']])
+ })
+
+ it('does not use a queued attachment from a sibling transcript branch', async () => {
+ const f = setup(); await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1])
+ f.ingest(claude.records[0])
+ const queued = claude.records.find((r: any) => r.attachment?.type === 'queued_command')
+ f.ingest({ ...queued, parentUuid: claude.records[0].uuid })
+ f.ingest({ type: 'assistant', uuid: 'other-branch-final', parentUuid: claude.records[0].uuid,
+ message: { id: 'final', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Only A' }] } })
+ f.service.turnEnded('agent')
+ expect(f.results()[0].payload.correlation.inputs.map((i: any) => i.idempotencyKey)).toEqual(['A'])
+ expect(f.service.receipt('owner', 'B')?.state).toBe('unknown')
+ })
+
+ it.each(['missing-parent', 'different-owner', 'identical-prompts'])('fails closed for %s', async variant => {
+ const f = setup()
+ await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1], variant === 'different-owner' ? 'other' : 'owner')
+ if (variant === 'identical-prompts') await f.send('duplicate-text', claude.inputs[1])
+ for (const row of claude.records) f.ingest(variant === 'missing-parent' && row.message?.stop_reason === 'end_turn' ? { ...row, parentUuid: 'missing' } : row)
+ f.service.turnEnded('agent')
+ expect(f.results()).toHaveLength(0)
+ expect(f.service.receipt('owner', 'A')?.state).toBe('unknown')
+ expect(f.service.receipt(variant === 'different-owner' ? 'other' : 'owner', 'B')?.state).not.toBe('completed')
+ })
+
+ it('Codex requires explicit per-input turn identity, not the currently busy turn', async () => {
+ const f = setup('codex'); await f.send('A', codex.inputs[0]); await f.send('B', codex.inputs[1])
+ for (const row of codex.records) {
+ const copy = structuredClone(row)
+ if (copy.type === 'response_item') delete copy.payload.internal_chat_message_metadata_passthrough
+ f.ingest(copy)
+ }
+ f.service.turnEnded('agent')
+ expect(f.results()).toHaveLength(0)
+ expect(f.service.receipt('owner', 'B')?.state).toBe('delivered')
+ })
+
+ it('session gone and bare turn.done never fabricate completion', async () => {
+ const f = setup(); const a = await f.send('A', 'A')
+ f.service.delivery({ deliveryId: a.deliveryId, sessionId: 'agent', state: 'started' })
+ f.service.turnEnded('agent')
+ expect(f.service.receipt('owner', 'A')).toMatchObject({ state: 'unknown', error: { code: 'RESULT_EVIDENCE_MISSING' } })
+ f.service.agentGone('agent'); expect(f.results()).toHaveLength(0)
+ })
+})
+
+describe('result persistence, opt-in and authorization', () => {
+ it('persists before dispatch, restores receipts without resending, replays stable results after restart', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'device-results-')); dirs.push(dir)
+ const journal = new DeviceResultJournal(join(dir, 'journal.json'))
+ const f = setup('claude', { resultJournal: journal })
+ await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1]); await f.send('C', 'unresolved')
+ for (const row of claude.records) f.ingest(row)
+ const payload = structuredClone(f.results()[0].payload)
+ expect(statSync(join(dir, 'journal.json')).mode & 0o777).toBe(0o600)
+ const restarted = setup('claude', { resultJournal: journal, serverInstanceId: 'new-instance' })
+ expect(restarted.service.receipt('owner', 'C')).toMatchObject({ state: 'unknown', error: { code: 'DAEMON_RESTART' } })
+ await restarted.send('C', 'unresolved')
+ expect(restarted.submit).not.toHaveBeenCalled()
+ const replay: any[] = []
+ restarted.service.replay({ serverInstanceId: 'instance', cursor: 0 }, e => replay.push(e))
+ expect(replay[0]).toMatchObject({ type: 'resync', reason: 'instance_changed' })
+ expect(replay.find(e => e.kind === 'turn.summary')).toMatchObject({ serverInstanceId: 'new-instance', payload })
+ const event = replay.find(e => e.kind === 'turn.summary')
+ expect(restarted.service.canSendResult('owner', event)).toBe(true)
+ expect(restarted.service.canSendResult('other', event)).toBe(false)
+ restarted.service.revoke('owner')
+ expect(restarted.service.canSendResult('owner', event)).toBe(false)
+ expect(setup('claude', { resultJournal: journal }).service.receipt('owner', 'A')).toBeNull()
+ })
+
+ it('does not dispatch if durable reservation fails', async () => {
+ const f = setup('claude', { resultJournal: { load: () => undefined, save: () => { throw new Error('disk full') } } })
+ const response = await f.service.request('owner', { type: 'turn.send', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', idempotencyKey: 'A', text: 'A' })
+ expect(response.receipt).toMatchObject({ state: 'unknown' })
+ expect(f.submit).not.toHaveBeenCalled()
+ })
+
+ it('expires result access after the documented retention period', async () => {
+ let now = Date.parse('2026-09-24T00:00:00Z')
+ const f = setup('claude', { now: () => now }); await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1])
+ for (const row of claude.records) f.ingest(row)
+ const event = f.results()[0]
+ now += 30 * 60_000 + 1
+ expect(f.service.canSendResult('owner', event)).toBe(false)
+ expect(f.service.receipt('owner', 'A')).toBeNull()
+ })
+})
+
+
+it('publishes the exact runtime result schema and valid shared OS fixtures', () => {
+ expect(fixture('result.schema')).toEqual(z.toJSONSchema(DeviceResultSchema))
+ DeviceResultSchema.parse(fixture('group-result'))
+ DeviceResultSchema.parse(fixture('input-result'))
+ for (const step of fixture('os-replay-cases').steps) if (step.event.kind === 'turn.summary') DeviceResultSchema.parse(step.event)
+ const invalid = fixture('group-result')
+ invalid.payload.correlation.scope = 'input'
+ expect(DeviceResultSchema.safeParse(invalid).success).toBe(false)
+})
+
+it('does not complete a result when journal commit fails and does not trust unwritten/history input', async () => {
+ let failWrites = false
+ const f = setup('claude', { resultJournal: { load: () => undefined, save: () => { if (failWrites) throw new Error('disk full') } } })
+ await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1])
+ for (const row of claude.records.slice(0, -1)) f.ingest(row)
+ failWrites = true
+ expect(() => f.ingest(claude.records.at(-1))).toThrow('disk full')
+ expect(f.results()).toHaveLength(0)
+ expect(f.service.receipt('owner', 'A')?.state).not.toBe('completed')
+ expect(f.service.receipt('owner', 'B')?.state).not.toBe('completed')
+ const unwritten = setup()
+ await unwritten.service.request('owner', { type: 'turn.send', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', idempotencyKey: 'A', text: claude.inputs[0] })
+ for (const row of claude.records) unwritten.ingest(row)
+ expect(unwritten.results()).toHaveLength(0)
+ expect(unwritten.service.receipt('owner', 'A')?.state).toBe('queued')
+})
+
+it('keeps reordered Codex completions separate and rejects mismatched completion IDs', async () => {
+ const f = setup('codex'); await f.send('A', codex.inputs[0]); await f.send('B', codex.inputs[1])
+ const users = codex.records.filter((r: any) => r.type === 'response_item' && r.payload.internal_chat_message_metadata_passthrough.content_item_kinds.includes('user.text'))
+ f.ingest(users[0])
+ f.ingest({ ...users[1], payload: { ...users[1].payload, internal_chat_message_metadata_passthrough: { ...users[1].payload.internal_chat_message_metadata_passthrough, turn_id: 'turn-B' } } })
+ const completion = codex.records.at(-1)
+ f.ingest({ ...completion, ordinal: 900, payload: { ...completion.payload, turn_id: 'wrong-turn' } })
+ expect(f.results()).toHaveLength(0)
+ f.ingest({ ...completion, ordinal: 901, payload: { ...completion.payload, turn_id: 'turn-B' } })
+ expect(f.results()[0].payload.correlation.inputs.map((i: any) => i.idempotencyKey)).toEqual(['B'])
+ expect(f.service.receipt('owner', 'A')?.state).toBe('started')
+ f.ingest(completion)
+ expect(f.results()[1].payload.correlation.inputs.map((i: any) => i.idempotencyKey)).toEqual(['A'])
+})
+
+it('rejects oversize results without truncating or announcing completion', async () => {
+ const f = setup(); await f.send('A', claude.inputs[0])
+ f.ingest(claude.records[0])
+ f.ingest({ type: 'assistant', uuid: 'large-final', parentUuid: claude.records[0].uuid,
+ message: { id: 'large-message', stop_reason: 'end_turn', content: [{ type: 'text', text: 'x'.repeat(33 * 1024) }] } })
+ expect(f.results()).toHaveLength(0)
+ expect(f.service.receipt('owner', 'A')?.state).toBe('unknown')
+})
+
+it('retains the committed result when transport emission loses its acknowledgment', async () => {
+ const f = setup('claude', { emit: event => { if (event.kind === 'turn.summary') throw new Error('socket closed') } })
+ await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1])
+ for (const row of claude.records.slice(0, -1)) f.ingest(row)
+ const before = f.service.resume().cursor
+ expect(() => f.ingest(claude.records.at(-1))).toThrow('socket closed')
+ const replay: any[] = []
+ f.service.replay({ serverInstanceId: 'instance', cursor: before }, e => replay.push(e))
+ expect(replay.filter(e => e.kind === 'turn.summary')).toHaveLength(1)
+ expect(f.service.receipt('owner', 'B')?.state).toBe('completed')
+})
+
+it('cannot match a dispatched input against a different engine session after rebind', async () => {
+ const f = setup()
+ await f.service.request('owner', { type: 'turn.send', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', idempotencyKey: 'A', text: claude.inputs[0] })
+ f.service.inputDispatched('agent', f.service.receipt('owner', 'A')!.deliveryId, claude.inputs[0], 'old-session')
+ for (const row of claude.records) f.ingest(row) // fixture ingests into session, not old-session
+ expect(f.results()).toHaveLength(0)
+ expect(f.service.receipt('owner', 'A')?.state).not.toBe('completed')
+})
+
+it('keeps a single task compatible and suppresses late mirror recaps after final/restart', async () => {
+ let snapshot: any
+ const journal = { load: () => snapshot, save: (value: unknown) => { snapshot = structuredClone(value) } }
+ const f = setup('claude', { resultJournal: journal })
+ const a = await f.send('A', claude.inputs[0])
+ f.ingest(claude.records[0])
+ f.ingest({ type: 'assistant', uuid: 'single-final', parentUuid: claude.records[0].uuid,
+ message: { id: 'single-answer', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Single answer.' }] } })
+ expect(f.results()[0].payload).toMatchObject({ idempotencyKey: 'A', fullText: 'Single answer.', text: 'Single answer.',
+ correlation: { scope: 'input', inputs: [{ deliveryId: a.deliveryId, idempotencyKey: 'A' }] } })
+ f.service.commander({ type: 'commander_event', agentId: 'agent', payload: { kind: 'summary', text: 'Delayed recap' } })
+ expect(f.results()).toHaveLength(1)
+ const restarted = setup('claude', { resultJournal: journal, serverInstanceId: 'new' })
+ restarted.service.commander({ type: 'commander_event', agentId: 'agent', payload: { kind: 'summary', text: 'Replayed old recap' } })
+ expect(restarted.results()).toHaveLength(0)
+})
+
+it('preserves structured question/answer RPCs without treating an answer acknowledgment as task completion', async () => {
+ const answer = vi.fn(async () => true)
+ const f = setup('claude', { answer })
+ await f.send('A', claude.inputs[0]); f.ingest(claude.records[0])
+ f.service.commander({ type: 'commander_question', agentId: 'agent', payload: { requestId: 'question', questions: [{ question: 'Which two?' }] } })
+ expect(f.events.find(e => e.kind === 'question.open').payload).toMatchObject({ questionRequestId: 'question', idempotencyKey: 'A' })
+ const req = { type: 'question.answer', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', idempotencyKey: 'answer-key', questionRequestId: 'question', answers: { planes: 'Outer' } }
+ expect((await f.service.request('owner', req)).receipt).toMatchObject({ state: 'completed' })
+ await f.service.request('owner', { ...req, requestId: randomUUID() })
+ expect(answer).toHaveBeenCalledTimes(1)
+ expect(f.service.receipt('owner', 'A')?.state).toBe('started')
+ expect(f.results()).toHaveLength(0)
+ f.ingest({ type: 'assistant', uuid: 'answered-final', parentUuid: claude.records[0].uuid,
+ message: { id: 'answered-message', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Done after answering.' }] } })
+ expect(f.results()[0].payload.correlation.inputs.map((i: any) => i.idempotencyKey)).toEqual(['A'])
+})
+
+it('keeps legacy engine task and question summaries on their existing path', async () => {
+ const f = setup('commandcode', { fullText: () => 'Complete legacy answer' })
+ const a = await f.send('A', 'Legacy task')
+ f.service.delivery({ deliveryId: a.deliveryId, sessionId: 'agent', state: 'started' })
+ f.service.turnStarted('agent')
+ f.service.turnEnded('agent')
+ f.service.commander({ type: 'commander_event', agentId: 'agent', payload: { kind: 'summary', text: 'Legacy preview' } })
+ expect(f.service.receipt('owner', 'A')?.state).toBe('completed')
+ expect(f.results()[0].payload).toEqual({ kind: 'summary', text: 'Legacy preview', fullText: 'Complete legacy answer' })
+})
+
+it('rejects tampered agent, key, delivery and owner on a retained summary', async () => {
+ const f = setup(); await f.send('A', claude.inputs[0]); await f.send('B', claude.inputs[1])
+ for (const row of claude.records) f.ingest(row)
+ const event = f.results()[0]
+ expect(event.payload).not.toHaveProperty('idempotencyKey')
+ expect(event.payload).not.toHaveProperty('turnId')
+ expect(f.service.canSendResult('wrong-owner', event)).toBe(false)
+ expect(f.service.canSendResult('owner', { ...event, agentId: 'wrong-agent' })).toBe(false)
+ for (const field of ['deliveryId', 'idempotencyKey']) {
+ const altered = structuredClone(event); altered.payload.correlation.inputs[0][field] = 'wrong'
+ expect(f.service.canSendResult('owner', altered)).toBe(false)
+ }
+})
diff --git a/cli/src/lib/autonomous-device/service.spec.ts b/cli/src/lib/autonomous-device/service.spec.ts
index cc7825477..7be1cf644 100644
--- a/cli/src/lib/autonomous-device/service.spec.ts
+++ b/cli/src/lib/autonomous-device/service.spec.ts
@@ -2,10 +2,11 @@ import { describe, expect, it, vi } from 'vitest'
import { randomUUID } from 'node:crypto'
import { AUTONOMOUS_DEVICE_CAPABILITIES, AutonomousDeviceService, type AutonomousDeviceFrame } from './service.js'
+// Legacy-engine fixture retains the original lifecycle contract; native evidence has its own results suite.
function fixture(now?: () => number, fullAnswer?: string) {
const submit = vi.fn(), stop = vi.fn(async () => true), answer = vi.fn(async () => true)
const events: AutonomousDeviceFrame[] = []
- const service = new AutonomousDeviceService({ now, machineId: 'machine', agents: () => [{ agentId: 'agent', name: 'Project', engine: 'claude', state: 'idle' }],
+ const service = new AutonomousDeviceService({ now, machineId: 'machine', agents: () => [{ agentId: 'agent', name: 'Project', engine: 'commandcode', state: 'idle' }],
submit, stop, answer, cancelDelivery: vi.fn(() => true), recent: () => [], fullText: () => fullAnswer, emit: f => events.push(f) })
const send = (fields: Record<string, unknown> = {}) => ({ type: 'turn.send', requestId: randomUUID(), machineId: 'machine', agentId: 'agent', text: 'hello', idempotencyKey: 'intent1', ...fields })
return { service, submit, stop, answer, events, send }
diff --git a/cli/src/lib/autonomous-device/service.ts b/cli/src/lib/autonomous-device/service.ts
index 6d9f0bfd5..aee328e36 100644
--- a/cli/src/lib/autonomous-device/service.ts
+++ b/cli/src/lib/autonomous-device/service.ts
@@ -1,3 +1,6 @@
+import { DeviceResultPayloadSchema } from './resultContract.js'
+import { DeviceResultEvidence, inputHash, type ResultEvidence } from './resultEvidence.js'
+import type { DeviceResultJournal } from './resultJournal.js'
import type { DeviceInputStatus } from './input.js'
import type { AutonomousDeviceStore } from './store.js'
import { DEVICE_STORE_CAPABILITIES, DeviceStoreError } from './storeContract.js'
@@ -16,6 +19,8 @@ export interface AutonomousDeviceAgent { agentId: string; name: string; engine:
const AGENT_RECAP_MAX_CHARS = 200
export interface AutonomousDeviceDelivery { deliveryId: string; sessionId: string; state: ReceiptState; reason?: string }
export interface AutonomousDeviceServiceOptions {
+ resultJournal?: Pick<DeviceResultJournal, 'load' | 'save'>
+ inputConsumed?: (agentId: string, text: string) => void
store?: AutonomousDeviceStore
machineId: string; serverInstanceId?: string; now?: () => number
agents: () => AutonomousDeviceAgent[]
@@ -48,7 +53,10 @@ export interface AutonomousDeviceServiceOptions {
fullText?: (agentId: string) => string | undefined
emit?: (frame: AutonomousDeviceFrame) => void
}
-interface Entry { deviceId: string; digest: string; receipt: AutonomousDeviceReceipt }
+interface Entry { deviceId: string; digest: string; receipt: AutonomousDeviceReceipt
+ promptHash?: string; reservedAt?: number; dispatchedAt?: number; sessionId?: string; evidenceManaged?: boolean; consumed?: boolean
+}
+interface ResultRecord { deviceId: string; evidenceId: string; at: number; agentId: string; payload: Record<string, unknown> }
const CAPABILITIES = ['focus.get', 'focus.ensure', 'focus.step', 'scroll', 'agents.list', 'turn.send', 'turn.stop', 'status', 'recap', 'question.answer', 'receipt.get'] as const
export const AUTONOMOUS_DEVICE_CAPABILITIES: string[] = [...CAPABILITIES]
const MUTATIONS = new Set(['turn.send', 'turn.stop', 'question.answer'])
@@ -85,6 +93,118 @@ export class AutonomousDeviceService {
private readonly questions = new Map<string, { requestId: string; questions: unknown }>()
private events: AutonomousDeviceFrame[] = []
private sequence = 0
+ private readonly results = new Map<string, ResultRecord>()
+ private readonly transcriptSessions = new Map<string, string>()
+ private readonly transcriptAgents = new Set<string>()
+ private readonly evidence = new DeviceResultEvidence(
+ (agent, text, at) => this.consumeInput(agent, text, at),
+ (agent, evidence) => this.recordResult(agent, evidence),
+ (agent, ids) => this.evidenceUnknown(agent, ids),
+ )
+ /** Cheap no-op for ordinary app/orchestrator agents; only dispatched Device work opts in. */
+ needsTranscript(agentId: string, sessionId: string, engine: string): boolean {
+ if (!this.transcriptAgents.has(agentId) || !['claude', 'codex'].includes(engine)) return false
+ let pending = false
+ for (const entry of this.deliveries.values()) {
+ if (!entry.evidenceManaged || entry.receipt.agentId !== agentId
+ || entry.receipt.serverInstanceId !== this.serverInstanceId || entry.dispatchedAt === undefined
+ || ['completed', 'rejected'].includes(entry.receipt.state)) continue
+ pending = true
+ if (!entry.sessionId || entry.sessionId === sessionId) return true
+ }
+ if (!pending) {
+ this.transcriptAgents.delete(agentId)
+ this.transcriptSessions.delete(agentId)
+ this.evidence.forget(agentId)
+ }
+ return false
+ }
+ observeTranscript(agentId: string, sessionId: string, engine: string, line: string): void {
+ if (!this.needsTranscript(agentId, sessionId, engine)) return
+ if (this.transcriptSessions.get(agentId) !== sessionId) {
+ this.evidence.forget(agentId)
+ this.transcriptSessions.set(agentId, sessionId)
+ }
+ this.evidence.ingest(agentId, engine, line)
+ }
+ inputDispatched(agentId: string, deliveryId: string, text: string, sessionId?: string): void {
+ const entry = this.deliveries.get(deliveryId)
+ if (!entry?.evidenceManaged || entry.receipt.agentId !== agentId || entry.receipt.serverInstanceId !== this.serverInstanceId || entry.dispatchedAt !== undefined) return
+ entry.promptHash = inputHash(text) // exact engine input after slash-command adaptation
+ entry.dispatchedAt = this.now()
+ entry.sessionId = sessionId || this.transcriptSessions.get(agentId)
+ this.persist()
+ this.transcriptAgents.add(agentId)
+ }
+ private consumeInput(agentId: string, text: string, timestamp: number): string | null {
+ if (!Number.isFinite(timestamp)) return null
+ const hash = inputHash(text)
+ const candidates = [...this.entries.values()].filter(e => e.evidenceManaged && !e.consumed
+ && (!e.sessionId || e.sessionId === this.transcriptSessions.get(agentId))
+ && e.receipt.agentId === agentId && e.receipt.serverInstanceId === this.serverInstanceId
+ && !['completed', 'rejected'].includes(e.receipt.state) && e.promptHash === hash && timestamp >= (e.dispatchedAt ?? Infinity))
+ // Identical unresolved text cannot be disambiguated using a transcript timestamp alone.
+ if (candidates.length !== 1) { this.evidenceUnknown(agentId, candidates.map(e => e.receipt.deliveryId)); return null }
+ const entry = candidates[0]
+ entry.consumed = true
+ this.options.inputConsumed?.(agentId, text)
+ this.update(entry, 'started')
+ return entry.receipt.deliveryId
+ }
+ private evidenceUnknown(agentId: string, ids: string[]): void {
+ for (const id of ids) {
+ const entry = this.deliveries.get(id)
+ if (entry?.receipt.agentId === agentId) this.update(entry, 'unknown', 'RESULT_EVIDENCE_MISSING')
+ }
+ }
+ private recordResult(agentId: string, evidence: ResultEvidence): void {
+ const evidenceId = `${agentId}:${this.transcriptSessions.get(agentId)}:${evidence.evidenceId}`
+ if (this.results.has(evidenceId)) return
+ const entries = evidence.inputs.map(id => this.deliveries.get(id))
+ const first = entries[0]
+ if (!first || entries.some(e => !e || !e.consumed || e.receipt.agentId !== agentId
+ || e.deviceId !== first.deviceId || e.receipt.serverInstanceId !== this.serverInstanceId
+ || ['completed', 'rejected'].includes(e.receipt.state))) {
+ this.evidenceUnknown(agentId, evidence.inputs); return
+ }
+ this.prune()
+ if (entries.length > 64 || this.results.size >= 512 || Buffer.byteLength(evidence.fullText) > 128 * 1024) {
+ this.evidenceUnknown(agentId, evidence.inputs); return
+ }
+ const payload = DeviceResultPayloadSchema.parse({ serverInstanceId: this.serverInstanceId, resultId: randomUUID(),
+ correlation: { scope: entries.length === 1 ? 'input' : 'group',
+ inputs: entries.map(e => ({ deliveryId: e!.receipt.deliveryId, idempotencyKey: e!.receipt.idempotencyKey })),
+ ...(evidence.engineTurnId ? { engineTurnId: evidence.engineTurnId } : {}) },
+ outcome: evidence.outcome, fullText: evidence.fullText, kind: 'summary',
+ text: evidence.fullText.replace(/\s+/g, ' ').trim().slice(0, AGENT_RECAP_MAX_CHARS),
+ ...(entries.length === 1 ? { idempotencyKey: first.receipt.idempotencyKey, turnId: first.receipt.turnId } : {}) })
+ if (Buffer.byteLength(JSON.stringify(payload)) > 32 * 1024) { this.evidenceUnknown(agentId, evidence.inputs); return }
+ this.results.set(evidenceId, { deviceId: first.deviceId, evidenceId, agentId, at: this.now(), payload })
+ // Commit the immutable result and all its proven receipts together before publishing anything.
+ const previous = entries.map(e => structuredClone(e!.receipt))
+ for (const entry of entries) {
+ entry!.receipt.state = evidence.outcome === 'completed' ? 'completed' : 'unknown'
+ entry!.receipt.error = evidence.outcome === 'completed' ? null : { code: 'RESULT_NOT_COMPLETED', message: evidence.outcome }
+ entry!.receipt.at = this.now()
+ }
+ try { this.persist() } catch (error) {
+ this.results.delete(evidenceId)
+ entries.forEach((entry, i) => { entry!.receipt = previous[i] })
+ throw error
+ }
+ // Retain the result envelope before any network callback can fail.
+ this.event('turn.summary', agentId, payload)
+ for (const entry of entries) this.event('receipt.updated', agentId, { receipt: structuredClone(entry!.receipt), idempotencyKey: entry!.receipt.idempotencyKey })
+ }
+ canSendResult(deviceId: string, frame: AutonomousDeviceFrame): boolean {
+ const payload = frame.payload as Record<string, unknown> | undefined
+ return [...this.results.values()].some(r => r.deviceId === deviceId && r.agentId === frame.agentId
+ && r.payload.resultId === payload?.resultId && canonical(r.payload) === canonical(payload) && r.at >= this.now() - TTL)
+ }
+ private persist(): void {
+ this.options.resultJournal?.save({ version: 1, machineId: this.options.machineId,
+ entries: [...this.entries.values()], results: [...this.results.values()] })
+ }
private focusOwner: string | undefined
private focused: { machineId: string; agentId: string } | null = null
private focusCounter = 0
@@ -187,6 +307,27 @@ export class AutonomousDeviceService {
constructor(private readonly options: AutonomousDeviceServiceOptions) {
this.serverInstanceId = options.serverInstanceId ?? randomUUID()
this.now = options.now ?? Date.now
+ const snapshot = options.resultJournal?.load()
+ if (snapshot !== undefined) {
+ if (!object(snapshot) || snapshot.version !== 1 || snapshot.machineId !== options.machineId
+ || !Array.isArray(snapshot.entries) || !Array.isArray(snapshot.results)) throw new Error('Invalid Device result journal; refusing to lose delivery dedupe')
+ for (const entry of snapshot.entries as Entry[]) {
+ if (!entry.deviceId || !entry.digest || !entry.receipt?.deliveryId || !entry.receipt.idempotencyKey) throw new Error('Invalid Device receipt journal')
+ if (!['completed', 'rejected'].includes(entry.receipt.state)) {
+ entry.receipt.state = 'unknown'; entry.receipt.error = { code: 'DAEMON_RESTART', message: 'Reconcile original delivery; never resend automatically' }
+ }
+ this.entries.set(this.key(entry.deviceId, entry.receipt.idempotencyKey), entry)
+ this.deliveries.set(entry.receipt.deliveryId, entry)
+ }
+ for (const record of snapshot.results as ResultRecord[]) {
+ if (!record.deviceId || !record.evidenceId || !record.payload?.resultId) throw new Error('Invalid Device result journal')
+ this.results.set(record.evidenceId, record)
+ }
+ this.prune()
+ this.persist()
+ // New transport instance/sequence; immutable payload retains its originating instance.
+ for (const record of this.results.values()) this.retainEvent('turn.summary', record.agentId, record.payload)
+ }
}
private key(deviceId: string, key: string): string { return `${deviceId}:${key}` }
/** The newest `recap` turn's headline for an agent, or undefined when no turn has been summarised. */
@@ -201,6 +342,7 @@ export class AutonomousDeviceService {
return value ? structuredClone(value) : null
}
private prune(): void {
+ for (const [key, result] of this.results) if (this.now() - result.at > TTL) this.results.delete(key)
for (const [key, entry] of this.entries) {
if (['completed', 'rejected'].includes(entry.receipt.state) && this.now() - entry.receipt.at > TTL) {
this.entries.delete(key); this.deliveries.delete(entry.receipt.deliveryId)
@@ -224,8 +366,8 @@ export class AutonomousDeviceService {
entry.receipt.state = state
entry.receipt.at = this.now()
entry.receipt.error = code ? { code, message: code === 'NOT_CONFIRMED' ? 'Delivery could not be confirmed; inspect the agent before retrying.' : code } : null
- if (state === 'started') {
- entry.receipt.turnId ??= randomUUID()
+ if (state === 'started') entry.receipt.turnId ??= randomUUID()
+ if (state === 'started' && !entry.evidenceManaged) {
const agentId = entry.receipt.agentId
const previous = this.turns.get(agentId)
if (this.openTurns.has(agentId) || this.ambiguousTurns.has(agentId) || (previous && previous !== entry)) {
@@ -241,6 +383,9 @@ export class AutonomousDeviceService {
this.event('receipt.updated', entry.receipt.agentId, { receipt: structuredClone(entry.receipt), idempotencyKey: entry.receipt.idempotencyKey })
}
agentGone(agentId: string): void {
+ this.transcriptAgents.delete(agentId)
+ this.evidence.forget(agentId)
+ this.transcriptSessions.delete(agentId)
this.turns.delete(agentId)
this.openTurns.delete(agentId)
this.pendingStarts.delete(agentId)
@@ -271,15 +416,22 @@ export class AutonomousDeviceService {
this.entries.delete(key)
}
for (const [key, step] of this.steps) if (step.deviceId === deviceId) this.steps.delete(key)
+ for (const [key, result] of this.results) if (result.deviceId === deviceId) this.results.delete(key)
+ this.persist()
// A newly paired identity cannot replay the previous device's request receipts.
this.events = []
}
- event(kind: string, agentId: string | undefined, payload: Record<string, unknown>): void {
+ private retainEvent(kind: string, agentId: string | undefined, payload: Record<string, unknown>): AutonomousDeviceFrame {
const frame: AutonomousDeviceFrame = { type: 'event', eventId: ++this.sequence, serverInstanceId: this.serverInstanceId,
- machineId: this.options.machineId, ...(agentId ? { agentId } : {}), kind, payload }
+ machineId: this.options.machineId, ...(agentId ? { agentId } : {}), kind, payload: structuredClone(payload) }
this.events.push(frame)
if (this.events.length > 500) this.events.shift()
- this.options.emit?.(frame)
+ return frame
+ }
+ event(kind: string, agentId: string | undefined, payload: Record<string, unknown>): void {
+ if (kind === 'receipt.updated') this.persist()
+ const frame = this.retainEvent(kind, agentId, payload)
+ this.options.emit?.(structuredClone(frame))
}
resume(resume?: { serverInstanceId?: unknown; cursor?: unknown }): { resumed: boolean; cursor: number } {
const cursor = resume?.cursor
@@ -290,9 +442,11 @@ export class AutonomousDeviceService {
replay(resume: { serverInstanceId?: unknown; cursor?: unknown } | undefined, send: (frame: AutonomousDeviceFrame) => unknown): void {
if (!this.resume(resume).resumed) {
send({ type: 'resync', reason: resume?.serverInstanceId === this.serverInstanceId ? 'cursor_too_old' : 'instance_changed', serverInstanceId: this.serverInstanceId, cursor: this.sequence })
+ // Reconcile immutable retained results even when the ordinary event cursor expired.
+ for (const record of this.results.values()) if (record.at >= this.now() - TTL) send(this.retainEvent('turn.summary', record.agentId, structuredClone(record.payload)))
return
}
- for (const event of this.events) if (Number(event.eventId) > Number(resume?.cursor)) send(event)
+ for (const event of this.events) if (Number(event.eventId) > Number(resume?.cursor)) send(structuredClone(event))
}
turnStarted(agentId: string): void {
this.openTurns.add(agentId)
@@ -308,6 +462,9 @@ export class AutonomousDeviceService {
this.event('turn.started', agentId, entry ? { turnId: entry.receipt.turnId, idempotencyKey: entry.receipt.idempotencyKey } : {})
}
turnEnded(agentId: string, aborted = false): void {
+ // Session-wide close is not evidence for Device native inputs. Raw engine evidence owns completion.
+ for (const entry of this.entries.values()) if (entry.evidenceManaged && entry.receipt.agentId === agentId
+ && entry.receipt.state === 'started') this.update(entry, 'unknown', aborted ? 'TURN_INTERRUPTED' : 'RESULT_EVIDENCE_MISSING')
this.ambiguousTurns.delete(agentId)
this.openTurns.delete(agentId)
this.pendingStarts.delete(agentId)
@@ -323,11 +480,22 @@ export class AutonomousDeviceService {
const p = object(frame.payload) ? frame.payload : {}
if (frame.type === 'commander_question' && agentId && typeof p.requestId === 'string') {
this.questions.set(agentId, { requestId: p.requestId, questions: p.questions })
- this.event('question.open', agentId, { questionRequestId: p.requestId, questions: p.questions })
+ const candidates = [...this.entries.values()].filter(e => e.receipt.agentId === agentId && e.consumed
+ && e.receipt.serverInstanceId === this.serverInstanceId
+ && !['completed', 'rejected'].includes(e.receipt.state))
+ const single = candidates.length === 1 ? candidates[0] : this.turns.get(agentId)
+ this.event('question.open', agentId, { questionRequestId: p.requestId, questions: p.questions,
+ ...(single ? { idempotencyKey: single.receipt.idempotencyKey, turnId: single.receipt.turnId } : {}) })
} else if (frame.type === 'commander_question_close' && agentId) {
if (this.questions.get(agentId)?.requestId === p.requestId) this.questions.delete(agentId)
this.event('question.close', agentId, { questionRequestId: p.requestId })
} else if (frame.type === 'commander_event' && agentId && ['summary', 'tool', 'error'].includes(String(p.kind))) {
+ // Device native results already use turn.summary with exact engine evidence. The
+ // legacy mirror's asynchronous/latest recap must never emit a second final reply.
+ // Other engines and sessions without native Device reservations keep their path.
+ this.prune()
+ if (p.kind === 'summary' && ([...this.entries.values()].some(e => e.evidenceManaged && e.receipt.agentId === agentId)
+ || [...this.results.values()].some(r => r.agentId === agentId))) return
const full = p.kind === 'summary' ? this.options.fullText?.(agentId) : undefined
this.event(p.kind === 'summary' ? 'turn.summary' : p.kind === 'tool' ? 'turn.tool' : 'agent.error', agentId, full ? { ...p, fullText: full } : p)
}
@@ -391,9 +559,10 @@ export class AutonomousDeviceService {
}
if (type === 'question.answer' && this.questions.get(agentId)?.requestId !== req.questionRequestId) fail('QUESTION_STALE', 'Question is no longer open')
this.reserveCapacity()
- const entry: Entry = { deviceId, digest, receipt: { idempotencyKey: String(req.idempotencyKey), deliveryId: randomUUID(), operation: type,
+ const entry: Entry = { deviceId, digest, ...(type === 'turn.send' && ['claude', 'codex'].includes(agent.engine) ? { promptHash: inputHash(String(req.text)), reservedAt: this.now(), evidenceManaged: true } : {}), receipt: { idempotencyKey: String(req.idempotencyKey), deliveryId: randomUUID(), operation: type,
machineId: this.options.machineId, agentId, state: 'queued', turnId: null, serverInstanceId: this.serverInstanceId, error: null, at: this.now() } }
this.entries.set(key, entry); this.deliveries.set(entry.receipt.deliveryId, entry); reserved = entry
+ this.persist() // durable reservation MUST precede any engine write
try {
if (type === 'turn.send') this.options.submit(agentId, String(req.text), entry.receipt.deliveryId)
else {
diff --git a/docs/autonomous-device-integration.md b/docs/autonomous-device-integration.md
index 517e74d2d..1feef3a05 100644
--- a/docs/autonomous-device-integration.md
+++ b/docs/autonomous-device-integration.md
@@ -195,9 +195,12 @@ completed/rejected receipt is evicted, even if younger than 30 minutes; retentio
both capacity and TTL. Outstanding/unknown entries are never silently evicted: if all 512 are
unresolved, new mutations receive `BACKPRESSURE`. Evicting these entries would permit a duplicate
live prompt; this explicit exception takes precedence over unconditional oldest-entry eviction.
-A retired key may be treated as new, so never auto-resend after `receipt:null`. All receipts/events are
-RAM-only. Every daemon start has a new UUID `serverInstanceId`; no mutation auto-replay is safe
-across restart. Revoke clears the old device's receipts and event replay history.
+A retired key may be treated as new, so never auto-resend after `receipt:null`. The CLI now persists
+reservations, receipts and proven native Device results atomically in `device-results.json`.
+Each daemon start has a new transport `serverInstanceId`; restored in-flight receipts are unknown,
+not redispatched. Immutable results retain their originating payload instance. Revoke clears the
+old device's receipts, retained results and event replay history. See
+[summary correlation and recovery](autonomous-device-result-correlation.md).
Events are encrypted full objects:
@@ -208,8 +211,12 @@ Events are encrypted full objects:
Kinds include `receipt.updated`, `turn.started`, `turn.done`, `turn.error`, `turn.summary`,
`turn.tool`, `agent.error`, `question.open`, `question.close`.
-`turn.summary` payload and `recap` turn entries carry three views of one answer, and a consumer should
-prefer `turns[].fullText`, then `turn.summary.fullText`, then `text`:
+For an enriched `turn.summary` with resultId/correlation, use that event's fullText exclusively;
+never fetch latest recap to identify its result. The [summary contract](autonomous-device-result-correlation.md)
+defines membership, dedupe, stable replay and a 32 KiB serialized payload bound without truncation.
+The following recap/preview rules describe the unchanged **legacy** summary path:
+
+`turn.summary` payload and `recap` turn entries carry three views of one answer:
| Field | Limit | What it is |
|---|---|---|
@@ -231,11 +238,13 @@ is UTF-8 safe and marked with a trailing `…`. `text` and `recap` are unchanged
shared `commander_event` card is not widened — the USB dial's encoder throws above an 8 KiB frame, so the
field is added only to the events this service emits. Question-open payload is
`{questionRequestId,questions}`. Status uses `openQuestion.requestId` for that same identifier.
-Only device-origin turns with known correlation include `idempotencyKey`/`turnId`.
+Only single-input device-origin turns with known correlation include singular `idempotencyKey`/`turnId`.
+A group uses `payload.correlation.inputs` and never selects one arbitrary member key.
Ring capacity 500; cursor is `(serverInstanceId,eventId)`. Matching retained cursor replays newer
events. Changed instance or stale cursor returns encrypted `{type:"resync",reason:
"instance_changed"|"cursor_too_old",serverInstanceId,cursor}`. First connect also requests resync.
-OS re-reads agents/status and reconciles outstanding keys using receipt.get. Queued means wait;
+After resync, retained enriched summaries are replayed with fresh transport event IDs; dedupe by
+originating payload instance/resultId. OS re-reads agents/status and reconciles outstanding keys using receipt.get. Queued means wait;
delivered/started/completed means adopt; rejected means report; unknown/null means inspect and ask
before resending. Never automatically replay mutations on reconnect.
diff --git a/docs/autonomous-device-result-correlation.md b/docs/autonomous-device-result-correlation.md
index db238d9aa..3cbfd9ae9 100644
--- a/docs/autonomous-device-result-correlation.md
+++ b/docs/autonomous-device-result-correlation.md
@@ -1,118 +1,203 @@
-# Autonomous Device grouped results — turn.correlation.v2
+# Correlation on existing Autonomous Device summaries
-Status: Harness-side contract decision for OS coordination, 2026-09-24.
-**Not implemented or advertised by PR #294.** Both sides must implement and test this
-contract before enabling it. PR #294 delivers follow-up input; it does not complete the
-merged-result → Lamp flow. Existing single-input fields keep their meaning.
+Agreed with OS on 2026-09-25. This fixes the existing Device return path. It is enabled
+by default and uses the existing `turn.summary` event and ordinary application hello.
+There is no separate result event, version, feature flag, or capability negotiation.
+Both sides must update before grouped results can be routed to Lamp correctly.
-## Decision
+## Wire contract
-One engine result may cover several inputs. Publish one result with explicit membership,
-not one copy per input. Never select an arbitrary request key for a merged summary.
-Input acceptance, result membership, and task completion are separate facts.
-
-Negotiate `turn.correlation.v2` as a capability on both peers. Send a new
-`turn.result` event only to an opted-in peer. Do not overload `turn.summary`, `turnId`,
-`runId`, or receipt states. Older peers continue to receive existing session events;
-uncorrelated overlapping results cannot complete or speak a pending run.
+`turn.summary` is the final user-facing result. Keep its existing `fullText` (complete
+answer), `text` (compact preview), and optional `kind`/`recap` meanings. Add result identity,
+originating instance, explicit input membership, and outcome inside `payload`:
```json
{
"type": "event",
- "kind": "turn.result",
+ "kind": "turn.summary",
"agentId": "agent-123",
+ "machineId": "machine-123",
+ "serverInstanceId": "current-transport-instance",
+ "eventId": 42,
"payload": {
- "serverInstanceId": "instance-123",
- "resultId": "result-456",
+ "serverInstanceId": "originating-receipt-instance",
+ "resultId": "stable-result-id",
"correlation": {
"scope": "group",
"inputs": [
- { "deliveryId": "delivery-A", "idempotencyKey": "original-key-A" },
- { "deliveryId": "delivery-B", "idempotencyKey": "original-key-B" }
- ],
- "engineTurnId": "optional-engine-native-id"
+ {"deliveryId": "delivery-A", "idempotencyKey": "original-key-A"},
+ {"deliveryId": "delivery-B", "idempotencyKey": "original-key-B"}
+ ]
},
"outcome": "completed",
- "fullText": "Created the house with a garden and a red roof."
+ "kind": "summary",
+ "text": "Finished: two red planes and two blue planes.",
+ "fullText": "Finished: two red planes and two blue planes."
}
}
```
-Required: agentId, serverInstanceId, resultId, correlation.scope, correlation.inputs,
-outcome, fullText. Scope is `input` (exactly one member) or `group` (two or more).
-Each member contains both original idempotencyKey and deliveryId, with no duplicates.
-Outcome is `completed`, `failed`, or `cancelled`. fullText is the complete immutable result
-for this membership, never a pointer to latest recap. engineTurnId is optional evidence,
-not the DEVICE run ID. Do not put a singular runId/idempotencyKey on a group event.
-The existing transport sequence/replay envelope still applies.
-
-## Harness responsibilities
-
-1. Preserve each request reservation and receipt independently. Include only inputs whose
- consumption and association with this result are established by engine evidence.
- A clear composer, native queue insertion, proximity in time, or a session end alone
- cannot establish result membership. Queued but unconsumed inputs stay pending.
-2. Build the immutable result at an actual engine completion boundary. Generate resultId
- once; replay and reconnect reuse the same ID, text and membership. Never emit a result
- when only input acceptance is known. Missing evidence retains `unknown` receipts and
- session-scoped information; it does not produce a guessed group.
-3. Only proven members may transition to completed (for outcome completed). Failed or
- cancelled work must not be labelled completed; existing receipt states remain unchanged
- until a separately negotiated receipt outcome extension exists. Do not close other runs.
-4. Partition delivery to the authenticated originating device. Do not disclose another
- device's request keys or private result through a shared agent subscription. Grouping
- across owners requires separate authorization and is outside this contract.
-5. Retain result records alongside receipt/replay retention and publish retention limits.
- Instance change is reconciliation, never permission to resubmit automatically.
-
-This requires Device-specific engine evidence extraction; synthetic group IDs do not
-solve missing evidence. Shared chat/orchestrator normalizers need not change for this PR.
-
-## OS responsibilities
-
-1. Register original request key, deliveryId, serverInstanceId, agentId and local DEVICE
- run ID before routing a result. Resolve every member to the same authenticated device,
- instance and agent. Any explicit mismatch or unresolved member prevents application
- of the whole event; reconcile receipts, without agent/latest-run fallback.
-2. Atomically store result and membership, then resolve exactly the listed runs with the
- stated outcome. Pending runs not listed remain pending. Store a reference to the one
- shared result rather than copying it into independent per-input responses.
-3. Deduplicate by (device identity, serverInstanceId, resultId). An identical replay is a
- no-op. Same ID with different content/membership is a protocol error, never a new result.
-4. Enqueue a single Lamp utterance per result, using fullText from this event. Do not speak
- once per member or again on turn.done/summary/receipt.updated. Suppress results belonging
- to expired voice targets or incompatible reply routes; retain the result for retrieval.
- A group spanning distinct reply destinations must not choose the latest destination.
-5. Persist the TTS outbox and its dedupe identity before playback. If playback acknowledgment
- is lost, retain an uncertain playback state and avoid automatic replay: exactly-once
- audible playback cannot be guaranteed by network dedupe alone.
-6. Reconnect replays results and reconciles original receipts/keys; it never resends input
- with a new key. Consume receipt.input separately for steering/native/daemon queue UI.
-
-## Current OS compatibility
-
-The OS patch supplied on base `30e034f84` supports one event → one input/run, using
-agentId + original idempotencyKey (top-level, payload, or payload.receipt), or DEVICE
-runId/run_id. If both exist they must match the same route. Explicit mismatch does not
-fall back; overlapping runs do not use agent-only/latest recap inference. fullText in the
-event is preferred. This is compatible with proven single-input summaries, **not groups**.
-
-OS does not yet consume this capability, group membership, result dedupe, or receipt.input.
-Do not send the example above to today's OS or duplicate a merged summary under every key.
-No Autonomous OS source is changed by this PR.
-
-## Joint acceptance tests before enablement
-
-- A then steering B: one proven merged result resolves A/B and speaks once.
-- Claude queues B but result covers only A: B remains pending until consumed and completed.
-- A/B/C with B included and C not consumed: only A/B resolve.
-- Unknown membership: no fabricated key, completion or voice response.
-- Duplicate/reordered events, lost acknowledgment, reconnect, and restart: no duplicate input
- or TTS enqueue; changed instance is reconciled explicitly.
-- Wrong key, deliveryId, agent, owner, or instance: no partial application or fallback.
-- Mixed voice destinations, cancelled runs, expired routes and failed results: no wrong Lamp
- response; outcomes remain distinct from input acceptance.
-
-Rollout order: OS parser/storage/outbox and Harness evidence/result producer behind the
-capability; shared fixtures for the cases above; real engine + physical Lamp test; then
-mutual enablement. Until then PR #294 is an input-delivery fix only.
+Scope is `input` for exactly one member, `group` for two or more. Inputs contain the
+original deliveryId and idempotencyKey, unique by both fields. Optional engineTurnId
+belongs inside correlation and is an engine-native ID, never an OS DEVICE run ID.
+Outcome is `completed`, `failed`, or `cancelled`; this producer currently proves successful
+completion only. It leaves interrupted/failed work unknown instead of inventing a result.
+
+A proven single-input summary also retains singular payload.idempotencyKey and turnId
+for existing clients. They identify that same member and retain their existing meaning.
+**Group summaries never contain a singular key/runId/turnId selected from the members.**
+One shared result is not copied into several independent replies. A queued but unconsumed
+input is not included. Receipt input acceptance is not task completion.
+
+The exact [runtime-generated schema](contracts/autonomous-device-summary-correlation/result.schema.json),
+[single summary](contracts/autonomous-device-summary-correlation/input-result.json),
+[group summary](contracts/autonomous-device-summary-correlation/group-result.json), and
+[OS replay expectations](contracts/autonomous-device-summary-correlation/os-replay-cases.json) are the
+shared fixtures. The schema describes enriched summaries; older legacy summaries remain
+valid on the existing protocol. Ownership, uniqueness by each member field, and matching
+singular fields require semantic checks in addition to JSON schema validation.
+
+## OS application rules
+
+1. Register each outgoing request's device identity, agentId, receipt instance, deliveryId,
+ original key, local run and reply destination. Match **every** member of an enriched
+ summary to that registry. Explicit owner/agent/instance/key/delivery mismatch or unknown
+ membership prevents application of the entire result; reconcile, never guess by latest
+ run, recap, agent alone or nearby timestamps.
+2. Store the immutable result and membership atomically. Close exactly the listed runs for
+ the stated outcome. C remains pending when only A/B are listed. Retain one shared result
+ reference rather than manufacture a separate answer for A and B.
+3. Dedupe by `(device identity, payload.serverInstanceId, payload.resultId)` across live,
+ replay, reconnect, process restart and reordered envelopes. Same identity with different
+ content/membership is a protocol error. A new transport eventId does not make a new result.
+4. TTS uses fullText from this summary **once per result**. Enqueue the durable TTS outbox
+ entry with the result dedupe identity. Do not speak again on turn.done or receipt.updated:
+ these are lifecycle updates, not another final reply. Do not query latest recap to fill
+ in a missing correlated result. Unknown or invalid results must be visibly unresolved.
+5. Do not select the latest voice destination for a group spanning incompatible destinations.
+ Retain it for retrieval instead. Lost playback acknowledgment remains uncertain; network
+ dedupe cannot guarantee exactly-once audible playback. Do not automatically replay it.
+6. Preserve a task's result route across a structured question. question.open and successful
+ question.answer acknowledgment are not completion of that task. An answer operation's
+ receipt describes delivery of the answer; it is not a new text input in the final result
+ membership. Bind the answer UI/voice route back to the original task. The unchanged
+ questionRequestId and answer shape remain authoritative for submitting answers.
+
+## Engine consumption evidence
+
+The Device observer reads raw transcript records only while that agent has dispatched,
+unresolved native Device input in the matching engine session. Both history and live hooks
+check this boundary before forwarding records. Ordinary app/orchestrator agents bypass
+Device transcript parsing and evidence allocation; queued-but-not-dispatched requests do
+not enable it. Completed/rejected or revoked work stops observation, and agent removal
+clears it. Restored receipts do not activate observation or resend input after restart.
+This does not change shared chat/orchestrator scheduling. A reservation is durably saved before
+engine dispatch. Matching requires one exact normalized input hash, a dispatch marker,
+a record timestamp at or after dispatch, and the same bound engine session. Duplicate
+unresolved identical text is ambiguous and is not guessed FIFO. Slash commands use the
+adapted text actually sent to the engine. Historical and still-unwritten inputs cannot
+acquire membership.
+
+**Claude:** in the original Lamp failure (Code 2.1.263), B was enqueued at 09:22:26.
+The next tool boundary wrote remove/absorbed_mid_turn and a human `queued_command`
+attachment with commandMode prompt. That attachment lies on the parentUuid branch of the
+final assistant message at 09:23:26 with stop_reason end_turn. The previous observer only
+saw ordinary user starts and missed B. The fix walks that final answer's exact parent
+branch to its human root and includes consumed Device inputs on that branch. Enqueue or
+remove alone is not consumption; a sibling-branch attachment is excluded. fullText comes
+from the final assistant message, not a recap. No synthetic engineTurnId is claimed.
+
+**Codex:** existing 0.156.1 transcript records contain per-message
+internal_chat_message_metadata_passthrough.turn_id and content_item_kinds. Only user.text
+blocks establish membership; project/environment instructions do not. The matching
+explicit task_complete.turn_id and last_agent_message supply the result. Same engine turn
+can cover A/B; distinct turn IDs yield separate summaries. Merely being in the same session
+or following task_started is insufficient.
+
+Evidence establishes that inputs were in the engine context producing that final answer;
+it does not independently verify the requested edits. Missing lineage/completion produces
+`unknown / RESULT_EVIDENCE_MISSING` for consumed inputs. Unconsumed queued inputs remain
+pending. A session-wide turn end alone cannot complete native Device inputs.
+
+Redacted structural captures:
+[Claude](contracts/autonomous-device-summary-correlation/claude-native-queue.json),
+[Codex](contracts/autonomous-device-summary-correlation/codex-steering.json).
+
+## One return path and compatibility
+
+- Native Device results are emitted once through turn.summary. Device forwarding suppresses
+ mirror-generated asynchronous summaries for agents with retained native Device reservations
+ or results. A late or restarted recap cannot create a second final answer. App, USB dial
+ and orchestrator mirror behavior is unchanged; suppression is only in the Device facade.
+- Task A alone receives the same final event, fullText/preview and its original singular key.
+ It additionally gets stable result metadata. Existing clients can ignore additive fields.
+- Unsupported **engines** retain their original lifecycle, question, done and summary paths.
+ They do not acquire fabricated membership or result identity. Their pre-existing limitations
+ are not presented as durable correlated-result guarantees.
+- Unsupported **native transcript formats** (for example Codex without explicit input/turn
+ mapping), truncated/compacted Claude ancestry, ambiguous identical prompts, mixed owners,
+ or untracked inputs fail closed with unknown receipts. No latest-recap fallback silently
+ attributes their text to a Device task. Consumers must display the unresolved receipt/error.
+- Structured question and answer RPCs are unchanged. A question with one known originating
+ input carries its existing key/turnId. Multi-input questions have no arbitrary singular
+ key; exact grouped question-to-voice routing is not added by this change. Status/answer by
+ questionRequestId remains available and group question routing needs separate coordination.
+- Older OS versions that route only one key per event **cannot correctly resolve a group**.
+ They still receive the one summary with complete text; versions that reject uncorrelated
+ overlap will leave those routes unresolved and may not speak. This is an explicit upgrade
+ requirement, not a claimed compatibility success: update OS to this contract before testing
+ grouped TTS. There is no hidden switch or second disabled return path to enable afterward.
+- Old-client restart/TTS dedupe is not guaranteed. Updated OS must store result identities
+ and process the recovery behavior below; ordinary single-task wire compatibility cannot
+ substitute for implementing group or durable replay semantics.
+
+## Persistence, restart and replay
+
+`device-results.json` in the private CLI data directory atomically stores reservations,
+receipts and immutable result payloads, with file and directory fsync. It stores prompt
+hashes rather than prompt bodies, plus final answer text. A failed reservation write prevents
+dispatch. Receipt completion and its result are committed together before publication;
+failed commits do not publish completion. Corrupt state fails closed, never drops dedupe.
+
+A result retains resultId, content, outcome, membership and payload.serverInstanceId across
+replay/restart. Top-level serverInstanceId identifies the **current transport**, while
+payload.serverInstanceId identifies the **original receipt/result instance**. OS matches the
+payload instance to original pending runs. engineTurnId and Device run IDs never replace it.
+
+- Ordinary event replay retains 500 events. A valid cursor replays their stored envelopes.
+ Missing/expired/old-instance cursor gets resync followed by retained final summaries with
+ fresh increasing transport event IDs. OS must consume these reconciliation summaries and
+ dedupe by result identity. It must not discard them merely because the transport restarted.
+- Restored in-flight receipts become `unknown / DAEMON_RESTART`. The daemon does not resend
+ their input or guess unfinished consumption. Same-key retries return the original record.
+ A previously committed result is replayable even if its send or acknowledgment was lost.
+- At most 512 receipts and 512 results. Results expire after 30 minutes; completed/rejected
+ receipts keep the existing 30-minute TTL and capacity eviction policy. Unresolved receipts
+ remain reserved across restart and apply backpressure. No automatic replay after expiry.
+- At most 64 members and 32 KiB serialized payload per result, fitting the encrypted transport
+ budget. Oversized results remain unknown rather than being truncated and marked complete.
+ The snapshot is bounded at 32 MiB. Evidence is bounded to 8,192 Claude nodes and 256 active
+ Codex turns; evicted/missing evidence fails closed.
+- Live and replay delivery both verify the authenticated originating Device against immutable
+ stored membership. Same-owner groups only. Revocation removes its receipts and results.
+ A result with changed owner/agent/key/delivery/content cannot pass this check.
+
+## Validation and remaining work
+
+Mock/component coverage includes A, A/B grouped with C pending, A/B separate, native queue
+versus consumption, sibling branches, missing evidence, session rebinding, duplicate/mismatched
+results, reconnect, daemon restart, lost acknowledgments, journal failure, legacy engines,
+structured question/answer, and unchanged shared controller/normalizer/orchestrator behavior.
+Schema and fixtures are checked against the runtime validator.
+
+Read-only replay of the original unredacted Claude Lamp transcript produces one A/B summary,
+completes both receipts and preserves the exact 332-character final answer. Existing Codex
+smoke transcript replay produces one A/B summary with GARDEN_RED. These are **transcript
+replays**, not new engine tasks or end-to-end Lamp verification. No task with a fee, deployment
+or CLI restart is performed by this change.
+
+Still unsupported: automatic recovery of in-flight consumption after daemon restart, failed/
+cancelled result production, missing native evidence formats, mixed-owner/untracked groups,
+and grouped question-to-voice routing. OS must implement result routing, persistent dedupe,
+TTS outbox and question-route retention. The HAL spoken-history issue is separate. Do not
+claim app → OS → TTS fixed until both implementations pass a real end-to-end test.
diff --git a/docs/autonomous-device-store.md b/docs/autonomous-device-store.md
index 3167bd08e..8ddf4b336 100644
--- a/docs/autonomous-device-store.md
+++ b/docs/autonomous-device-store.md
@@ -2,8 +2,7 @@
This is the shared implementation contract for Autonomous OS (`harness-use` → OS loopback API →
existing direct encrypted device connection → Harness CLI). It adds Store discovery and **agent
-preparation**, not task delivery. English and [Vietnamese](vi/autonomous-device-store_vi.md) describe
-the same contract. The machine-readable authority is
+preparation**, not task delivery. The machine-readable authority is
[`contracts/autonomous-device-store-v1/`](contracts/autonomous-device-store-v1/).
**Status:** implemented in this checkout; not installed, released, or deployed by this change.
diff --git a/docs/contracts/autonomous-device-store-v1/README.md b/docs/contracts/autonomous-device-store-v1/README.md
index fda7080f9..b80d7d17e 100644
--- a/docs/contracts/autonomous-device-store-v1/README.md
+++ b/docs/contracts/autonomous-device-store-v1/README.md
@@ -1,7 +1,6 @@
# Shared OS contract: Autonomous device Store v1
-Start with [English](../../autonomous-device-store.md) or
-[Tiếng Việt](../../vi/autonomous-device-store_vi.md).
+Start with [the Store contract](../../autonomous-device-store.md).
- `request.schema.json`: decrypted request payloads, including optional input defaults.
- `response.schema.json`: successful responses and errors for the four new operations.
diff --git a/docs/contracts/autonomous-device-summary-correlation/claude-native-queue.json b/docs/contracts/autonomous-device-summary-correlation/claude-native-queue.json
new file mode 100644
index 000000000..4ab4689c6
--- /dev/null
+++ b/docs/contracts/autonomous-device-summary-correlation/claude-native-queue.json
@@ -0,0 +1,346 @@
+{
+ "description": "Redacted structural capture of Claude Code 2.1.263 Lamp failure, 2026-09-25. No new engine task. Node IDs, content and tool payloads anonymized; parent chain and record kinds preserved.",
+ "inputs": [
+ "Paint four planes red.",
+ "Correction: only paint two planes red."
+ ],
+ "records": [
+ {
+ "type": "user",
+ "timestamp": "2026-09-25T02:22:08.844Z",
+ "isSidechain": false,
+ "uuid": "node-0",
+ "parentUuid": "previous-turn",
+ "message": {
+ "role": "user",
+ "content": "Paint four planes red."
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:22:08.844Z",
+ "isSidechain": false,
+ "uuid": "node-1",
+ "parentUuid": "node-0",
+ "attachment": {
+ "type": "total_tokens_reminder"
+ }
+ },
+ {
+ "type": "assistant",
+ "timestamp": "2026-09-25T02:22:13.997Z",
+ "isSidechain": false,
+ "uuid": "node-2",
+ "parentUuid": "node-1",
+ "message": {
+ "id": "msg_011CfPMsRDDeQeLM3HWEK6nX",
+ "role": "assistant",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "tool-redacted",
+ "name": "Bash",
+ "input": {}
+ }
+ ]
+ }
+ },
+ {
+ "type": "queue-operation",
+ "timestamp": "2026-09-25T02:22:26.743Z",
+ "operation": "enqueue",
+ "content": "Correction: only paint two planes red."
+ },
+ {
+ "type": "queue-operation",
+ "timestamp": "2026-09-25T02:22:42.479Z",
+ "operation": "remove",
+ "content": "Correction: only paint two planes red.",
+ "reason": "absorbed_mid_turn"
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:22:14.034Z",
+ "isSidechain": false,
+ "uuid": "node-5",
+ "parentUuid": "node-2",
+ "attachment": {
+ "type": "hook_success"
+ }
+ },
+ {
+ "type": "user",
+ "timestamp": "2026-09-25T02:22:42.473Z",
+ "isSidechain": false,
+ "uuid": "node-6",
+ "parentUuid": "node-2",
+ "message": {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tool-redacted",
+ "content": "Tool completed."
+ }
+ ]
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:22:42.466Z",
+ "isSidechain": false,
+ "uuid": "node-7",
+ "parentUuid": "node-6",
+ "attachment": {
+ "type": "hook_success"
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:22:26.743Z",
+ "isSidechain": false,
+ "uuid": "node-8",
+ "parentUuid": "node-7",
+ "attachment": {
+ "type": "queued_command",
+ "prompt": "Correction: only paint two planes red.",
+ "commandMode": "prompt",
+ "origin": {
+ "kind": "human"
+ },
+ "source_uuid": "queued-source-B"
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:22:42.479Z",
+ "isSidechain": false,
+ "uuid": "node-9",
+ "parentUuid": "node-8",
+ "attachment": {
+ "type": "total_tokens_reminder"
+ }
+ },
+ {
+ "type": "assistant",
+ "timestamp": "2026-09-25T02:22:45.427Z",
+ "isSidechain": false,
+ "uuid": "node-10",
+ "parentUuid": "node-9",
+ "message": {
+ "id": "msg_011CfPMusfEtFVd5aR9gbJ51",
+ "role": "assistant",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "text",
+ "text": "Applying correction."
+ }
+ ]
+ }
+ },
+ {
+ "type": "assistant",
+ "timestamp": "2026-09-25T02:22:50.170Z",
+ "isSidechain": false,
+ "uuid": "node-11",
+ "parentUuid": "node-10",
+ "message": {
+ "id": "msg_011CfPMusfEtFVd5aR9gbJ51",
+ "role": "assistant",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "tool-redacted",
+ "name": "Bash",
+ "input": {}
+ }
+ ]
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:22:50.228Z",
+ "isSidechain": false,
+ "uuid": "node-12",
+ "parentUuid": "node-11",
+ "attachment": {
+ "type": "hook_success"
+ }
+ },
+ {
+ "type": "user",
+ "timestamp": "2026-09-25T02:23:18.525Z",
+ "isSidechain": false,
+ "uuid": "node-13",
+ "parentUuid": "node-11",
+ "message": {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tool-redacted",
+ "content": "Tool completed."
+ }
+ ]
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:18.517Z",
+ "isSidechain": false,
+ "uuid": "node-14",
+ "parentUuid": "node-13",
+ "attachment": {
+ "type": "hook_success"
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:18.530Z",
+ "isSidechain": false,
+ "uuid": "node-15",
+ "parentUuid": "node-14",
+ "attachment": {
+ "type": "total_tokens_reminder"
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:18.531Z",
+ "isSidechain": false,
+ "uuid": "node-16",
+ "parentUuid": "node-15",
+ "attachment": {
+ "type": "batching_reminder_sent"
+ }
+ },
+ {
+ "type": "last-prompt"
+ },
+ {
+ "type": "ai-title"
+ },
+ {
+ "type": "mode"
+ },
+ {
+ "type": "permission-mode"
+ },
+ {
+ "type": "atis-latch"
+ },
+ {
+ "type": "assistant",
+ "timestamp": "2026-09-25T02:23:21.461Z",
+ "isSidechain": false,
+ "uuid": "node-22",
+ "parentUuid": "node-16",
+ "message": {
+ "id": "msg_011CfPMxZskCY97NtvfmVPc2",
+ "role": "assistant",
+ "stop_reason": "tool_use",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "tool-redacted",
+ "name": "Bash",
+ "input": {}
+ }
+ ]
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:21.506Z",
+ "isSidechain": false,
+ "uuid": "node-23",
+ "parentUuid": "node-22",
+ "attachment": {
+ "type": "hook_success"
+ }
+ },
+ {
+ "type": "user",
+ "timestamp": "2026-09-25T02:23:21.583Z",
+ "isSidechain": false,
+ "uuid": "node-24",
+ "parentUuid": "node-22",
+ "message": {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tool-redacted",
+ "content": "Tool completed."
+ }
+ ]
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:21.582Z",
+ "isSidechain": false,
+ "uuid": "node-25",
+ "parentUuid": "node-24",
+ "attachment": {
+ "type": "hook_success"
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:21.594Z",
+ "isSidechain": false,
+ "uuid": "node-26",
+ "parentUuid": "node-25",
+ "attachment": {
+ "type": "total_tokens_reminder"
+ }
+ },
+ {
+ "type": "attachment",
+ "timestamp": "2026-09-25T02:23:21.597Z",
+ "isSidechain": false,
+ "uuid": "node-27",
+ "parentUuid": "node-26",
+ "attachment": {
+ "type": "batching_reminder_sent"
+ }
+ },
+ {
+ "type": "last-prompt"
+ },
+ {
+ "type": "ai-title"
+ },
+ {
+ "type": "mode"
+ },
+ {
+ "type": "permission-mode"
+ },
+ {
+ "type": "atis-latch"
+ },
+ {
+ "type": "assistant",
+ "timestamp": "2026-09-25T02:23:26.780Z",
+ "isSidechain": false,
+ "uuid": "node-33",
+ "parentUuid": "node-27",
+ "message": {
+ "id": "msg_011CfPMxmyWjnS5SWf5KYDht",
+ "role": "assistant",
+ "stop_reason": "end_turn",
+ "content": [
+ {
+ "type": "text",
+ "text": "Finished: two red planes and two blue planes."
+ }
+ ]
+ }
+ }
+ ]
+}
diff --git a/docs/contracts/autonomous-device-summary-correlation/codex-steering.json b/docs/contracts/autonomous-device-summary-correlation/codex-steering.json
new file mode 100644
index 000000000..c5bf64d67
--- /dev/null
+++ b/docs/contracts/autonomous-device-summary-correlation/codex-steering.json
@@ -0,0 +1,110 @@
+{
+ "description": "Redacted Codex 0.156.1 existing smoke transcript, 2026-09-24. Explicit per-input turn metadata retained. No new engine task.",
+ "inputs": [
+ "Use the shell tool to execute sleep 20, then reply HOUSE_READY. This is an input delivery test. Do not modify files.",
+ "For this text-only test, revise the response to say GARDEN_RED. Do not create or modify files."
+ ],
+ "records": [
+ {
+ "timestamp": "2026-09-24T06:04:09.800Z",
+ "ordinal": 1,
+ "type": "event_msg",
+ "payload": {
+ "type": "task_started",
+ "turn_id": "engine-turn-1",
+ "root_turn_id": "engine-turn-1",
+ "started_at": 1790229849,
+ "model_context_window": 258400,
+ "collaboration_mode_kind": "default"
+ }
+ },
+ {
+ "timestamp": "2026-09-24T06:04:12.561Z",
+ "ordinal": 5,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "input-5",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "Project instructions (redacted)."
+ },
+ {
+ "type": "input_text",
+ "text": "Environment context (redacted)."
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "engine-turn-1",
+ "create_time": 1790229852.561252,
+ "content_item_kinds": [
+ "agents_md.instructions",
+ "environments.environment_context"
+ ]
+ }
+ }
+ },
+ {
+ "timestamp": "2026-09-24T06:04:13.379Z",
+ "ordinal": 8,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "input-8",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "Use the shell tool to execute sleep 20, then reply HOUSE_READY. This is an input delivery test. Do not modify files."
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "engine-turn-1",
+ "create_time": 1790229853.379667,
+ "content_item_kinds": [
+ "user.text"
+ ]
+ }
+ }
+ },
+ {
+ "timestamp": "2026-09-24T06:04:18.692Z",
+ "ordinal": 16,
+ "type": "response_item",
+ "payload": {
+ "type": "message",
+ "id": "input-16",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_text",
+ "text": "For this text-only test, revise the response to say GARDEN_RED. Do not create or modify files."
+ }
+ ],
+ "internal_chat_message_metadata_passthrough": {
+ "turn_id": "engine-turn-1",
+ "create_time": 1790229858.692509,
+ "content_item_kinds": [
+ "user.text"
+ ]
+ }
+ }
+ },
+ {
+ "timestamp": "2026-09-24T06:04:41.433Z",
+ "ordinal": 27,
+ "type": "event_msg",
+ "payload": {
+ "type": "task_complete",
+ "turn_id": "engine-turn-1",
+ "last_agent_message": "GARDEN_RED",
+ "started_at": 1790229849,
+ "completed_at": 1790229881,
+ "duration_ms": 31634,
+ "time_to_first_token_ms": 5597
+ }
+ }
+ ]
+}
diff --git a/docs/contracts/autonomous-device-summary-correlation/group-result.json b/docs/contracts/autonomous-device-summary-correlation/group-result.json
new file mode 100644
index 000000000..f2d2c459e
--- /dev/null
+++ b/docs/contracts/autonomous-device-summary-correlation/group-result.json
@@ -0,0 +1,29 @@
+{
+ "type": "event",
+ "kind": "turn.summary",
+ "agentId": "agent-fixture",
+ "serverInstanceId": "transport-instance",
+ "eventId": 42,
+ "machineId": "machine-fixture",
+ "payload": {
+ "serverInstanceId": "originating-instance",
+ "resultId": "stable-result-id",
+ "correlation": {
+ "scope": "group",
+ "inputs": [
+ {
+ "deliveryId": "delivery-A",
+ "idempotencyKey": "key-A"
+ },
+ {
+ "deliveryId": "delivery-B",
+ "idempotencyKey": "key-B"
+ }
+ ]
+ },
+ "outcome": "completed",
+ "fullText": "Finished: two red planes and two blue planes.",
+ "kind": "summary",
+ "text": "Finished: two red planes and two blue planes."
+ }
+}
diff --git a/docs/contracts/autonomous-device-summary-correlation/input-result.json b/docs/contracts/autonomous-device-summary-correlation/input-result.json
new file mode 100644
index 000000000..7ca3675ae
--- /dev/null
+++ b/docs/contracts/autonomous-device-summary-correlation/input-result.json
@@ -0,0 +1,27 @@
+{
+ "type": "event",
+ "kind": "turn.summary",
+ "agentId": "agent-fixture",
+ "serverInstanceId": "transport-instance",
+ "eventId": 43,
+ "machineId": "machine-fixture",
+ "payload": {
+ "serverInstanceId": "originating-instance",
+ "resultId": "single-result-C",
+ "correlation": {
+ "scope": "input",
+ "inputs": [
+ {
+ "deliveryId": "delivery-C",
+ "idempotencyKey": "key-C"
+ }
+ ]
+ },
+ "outcome": "completed",
+ "fullText": "C completed separately.",
+ "kind": "summary",
+ "text": "C completed separately.",
+ "idempotencyKey": "key-C",
+ "turnId": "receipt-turn-C"
+ }
+}
diff --git a/docs/contracts/autonomous-device-summary-correlation/os-replay-cases.json b/docs/contracts/autonomous-device-summary-correlation/os-replay-cases.json
new file mode 100644
index 000000000..a66b79244
--- /dev/null
+++ b/docs/contracts/autonomous-device-summary-correlation/os-replay-cases.json
@@ -0,0 +1,184 @@
+{
+ "description": "OS receive-side expectations. Input identifiers are example reservations; no new requests are created by events. Schema alone cannot verify ownership or duplicate IDs.",
+ "pending": [
+ {
+ "deliveryId": "delivery-A",
+ "idempotencyKey": "key-A"
+ },
+ {
+ "deliveryId": "delivery-B",
+ "idempotencyKey": "key-B"
+ },
+ {
+ "deliveryId": "delivery-C",
+ "idempotencyKey": "key-C"
+ }
+ ],
+ "originatingServerInstanceId": "originating-instance",
+ "steps": [
+ {
+ "event": {
+ "type": "event",
+ "kind": "turn.summary",
+ "agentId": "agent-fixture",
+ "serverInstanceId": "transport-instance",
+ "eventId": 42,
+ "machineId": "machine-fixture",
+ "payload": {
+ "serverInstanceId": "originating-instance",
+ "resultId": "stable-result-id",
+ "correlation": {
+ "scope": "group",
+ "inputs": [
+ {
+ "deliveryId": "delivery-A",
+ "idempotencyKey": "key-A"
+ },
+ {
+ "deliveryId": "delivery-B",
+ "idempotencyKey": "key-B"
+ }
+ ]
+ },
+ "outcome": "completed",
+ "fullText": "Finished: two red planes and two blue planes.",
+ "kind": "summary",
+ "text": "Finished: two red planes and two blue planes."
+ }
+ },
+ "expected": {
+ "resolve": [
+ "delivery-A",
+ "delivery-B"
+ ],
+ "pending": [
+ "delivery-C"
+ ],
+ "ttsEnqueueCount": 1
+ }
+ },
+ {
+ "event": {
+ "type": "event",
+ "kind": "turn.summary",
+ "agentId": "agent-fixture",
+ "serverInstanceId": "transport-instance",
+ "eventId": 42,
+ "machineId": "machine-fixture",
+ "payload": {
+ "serverInstanceId": "originating-instance",
+ "resultId": "stable-result-id",
+ "correlation": {
+ "scope": "group",
+ "inputs": [
+ {
+ "deliveryId": "delivery-A",
+ "idempotencyKey": "key-A"
+ },
+ {
+ "deliveryId": "delivery-B",
+ "idempotencyKey": "key-B"
+ }
+ ]
+ },
+ "outcome": "completed",
+ "fullText": "Finished: two red planes and two blue planes.",
+ "kind": "summary",
+ "text": "Finished: two red planes and two blue planes."
+ }
+ },
+ "expected": {
+ "resolve": [],
+ "pending": [
+ "delivery-C"
+ ],
+ "ttsEnqueueCount": 0
+ }
+ },
+ {
+ "event": {
+ "type": "resync",
+ "reason": "instance_changed",
+ "serverInstanceId": "new-transport-instance",
+ "cursor": 1
+ },
+ "expected": {
+ "resendInput": false
+ }
+ },
+ {
+ "event": {
+ "type": "event",
+ "kind": "turn.summary",
+ "agentId": "agent-fixture",
+ "serverInstanceId": "new-transport-instance",
+ "eventId": 2,
+ "machineId": "machine-fixture",
+ "payload": {
+ "serverInstanceId": "originating-instance",
+ "resultId": "stable-result-id",
+ "correlation": {
+ "scope": "group",
+ "inputs": [
+ {
+ "deliveryId": "delivery-A",
+ "idempotencyKey": "key-A"
+ },
+ {
+ "deliveryId": "delivery-B",
+ "idempotencyKey": "key-B"
+ }
+ ]
+ },
+ "outcome": "completed",
+ "fullText": "Finished: two red planes and two blue planes.",
+ "kind": "summary",
+ "text": "Finished: two red planes and two blue planes."
+ }
+ },
+ "expected": {
+ "resolve": [],
+ "pending": [
+ "delivery-C"
+ ],
+ "ttsEnqueueCount": 0
+ }
+ },
+ {
+ "event": {
+ "type": "event",
+ "kind": "turn.summary",
+ "agentId": "agent-fixture",
+ "serverInstanceId": "new-transport-instance",
+ "eventId": 3,
+ "machineId": "machine-fixture",
+ "payload": {
+ "serverInstanceId": "originating-instance",
+ "resultId": "single-result-C",
+ "correlation": {
+ "scope": "input",
+ "inputs": [
+ {
+ "deliveryId": "delivery-C",
+ "idempotencyKey": "key-C"
+ }
+ ]
+ },
+ "outcome": "completed",
+ "fullText": "C completed separately.",
+ "kind": "summary",
+ "text": "C completed separately.",
+ "idempotencyKey": "key-C",
+ "turnId": "receipt-turn-C"
+ }
+ },
+ "expected": {
+ "resolve": [
+ "delivery-C"
+ ],
+ "pending": [],
+ "ttsEnqueueCount": 1
+ }
+ }
+ ]
+}
diff --git a/docs/contracts/autonomous-device-summary-correlation/result.schema.json b/docs/contracts/autonomous-device-summary-correlation/result.schema.json
new file mode 100644
index 000000000..a64b67b2f
--- /dev/null
+++ b/docs/contracts/autonomous-device-summary-correlation/result.schema.json
@@ -0,0 +1,182 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "event"
+ },
+ "kind": {
+ "type": "string",
+ "const": "turn.summary"
+ },
+ "agentId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "serverInstanceId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "machineId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "eventId": {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991
+ },
+ "payload": {
+ "type": "object",
+ "properties": {
+ "serverInstanceId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "resultId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "correlation": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "const": "input"
+ },
+ "inputs": {
+ "minItems": 1,
+ "maxItems": 1,
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "deliveryId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "idempotencyKey": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
+ }
+ },
+ "required": [
+ "deliveryId",
+ "idempotencyKey"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "engineTurnId": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": [
+ "scope",
+ "inputs"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "const": "group"
+ },
+ "inputs": {
+ "minItems": 2,
+ "maxItems": 64,
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "deliveryId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "idempotencyKey": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
+ }
+ },
+ "required": [
+ "deliveryId",
+ "idempotencyKey"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "engineTurnId": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "required": [
+ "scope",
+ "inputs"
+ ],
+ "additionalProperties": false
+ }
+ ]
+ },
+ "outcome": {
+ "type": "string",
+ "enum": [
+ "completed",
+ "failed",
+ "cancelled"
+ ]
+ },
+ "fullText": {
+ "type": "string",
+ "minLength": 1
+ },
+ "kind": {
+ "type": "string",
+ "const": "summary"
+ },
+ "text": {
+ "type": "string"
+ },
+ "recap": {
+ "type": "string"
+ },
+ "idempotencyKey": {
+ "type": "string",
+ "pattern": "^[A-Za-z0-9_-]{1,64}$"
+ },
+ "turnId": {
+ "anyOf": [
+ {
+ "type": "string",
+ "minLength": 1
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "serverInstanceId",
+ "resultId",
+ "correlation",
+ "outcome",
+ "fullText"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "type",
+ "kind",
+ "agentId",
+ "payload"
+ ],
+ "additionalProperties": false
+}
diff --git a/docs/in-flight-agent-input.md b/docs/in-flight-agent-input.md
index 3d9d207db..2f4146d4f 100644
--- a/docs/in-flight-agent-input.md
+++ b/docs/in-flight-agent-input.md
@@ -98,11 +98,11 @@ uses its original voice request key and focus revision. The supplied OS patch on
`30e034f84` adds single-input correlation and avoids agent/latest recap fallback after
overlap. It does not support merged results or consume receipt.input yet.
-The concrete handoff is [Grouped result contract: turn.correlation.v2](autonomous-device-result-correlation.md).
-It defines the event schema, evidence requirements, run closure, result/TTS dedupe,
-compatibility and joint rollout tests. This is the Harness-side contract decision, not an
-implemented or advertised capability. No OS repository changes are included. PR #294 fixes
-input delivery; the complete overlapping-result → Lamp flow remains follow-up work.
+The current handoff is [Device summary correlation](autonomous-device-result-correlation.md).
+It adds explicit membership and durable result identity to the existing turn.summary path,
+by default. It specifies dedupe, replay, restart and compatibility; no separate result
+protocol or opt-in remains. OS must implement the metadata before grouped Lamp TTS can be
+validated. No OS repository changes are included.
## Validation (2026-09-24)
diff --git a/docs/vi/autonomous-device-integration_vi.md b/docs/vi/autonomous-device-integration_vi.md
deleted file mode 100644
index caa195790..000000000
--- a/docs/vi/autonomous-device-integration_vi.md
+++ /dev/null
@@ -1,191 +0,0 @@
-# Autonomous device ↔ Mac trực tiếp
-
-## Khám phá Store và chuẩn bị agent (v1)
-
-Robot đã pair có thể negotiate capability Store và chuẩn bị agent, tách biệt với giao task. Xem [contract chung cho phía OS](autonomous-device-store_vi.md), gồm JSON schemas, recovery và ví dụ Blender. Các operation cũ giữ tương thích.
-
-
-Mac tự tìm Autonomous OS qua service Avahi `_autonomous._tcp` đang có, dùng bonjour-service
-browse ba giây. Không nhập IP, không backend relay hoặc credential cloud trên thiết bị. Giữ
-login/start của Harness Mac như cũ; daemon đang chạy vẫn pair/điều khiển khi backend offline.
-Buddy không dùng và không sửa.
-
-```sh
-harness autonomous-device discover --json
-harness autonomous-device pair --device '<discovery-id>' --code-stdin
-harness autonomous-device status --json
-harness autonomous-device list --json
-harness autonomous-device revoke '<full fingerprint>'
-```
-
-Thiết bị sinh/hiển thị mã; Desktop chọn thiết bị tìm thấy rồi ghi mã vào stdin của CLI, không argv/log.
-Discovery trả `{devices:[{id,name,host,port}]}`. CLI dial trực tiếp
-`ws://<host>:<SRV-port>/api/harness/ws`, dùng đúng port quảng bá (có thể80), nginx chuyển Upgrade
-cho route đó. Không hardcode5000, không thêm Avahi/script. Frame đầu machine_select payload
-machineId/label; OS trả machine_selected và e2e_pair_intent nếu đang pair. Sau mã nhập đúng, chạy
-PAKE và e2e_hello/welcome gốc; CLI chờ session đúng identity trước báo paired.
-
-Không listener Mac mới, custom handshake/trust store, role mới hay backend onboarding. Inbound
-trực tiếp chỉ nhận PAKE/cancel/hello/status cần thiết và app RPC; không setup token/remote password,
-terminal/admin. Intent/PAKE chỉ được nhận trong lần pair chủ động. Backend offline không xóa
-direct session hoặc cho phép pair nhầm browser slot.
-
-Metadata `${ADAPTER_DATA_DIR}/autonomous-device-connections.json` chỉ lưu discoveryId/fingerprint;
-key/pin vẫn ở E2eeManager/paired.json gốc. Mỗi15giây tìm lại thiết bị đã lưu và reconnect. Publickey
-reconnect phải đúng fingerprint association; mDNS không cấp quyền. Revoke đóng socket và bỏ
-association, không ảnh hưởng browser/dial khác. Sai mã đóng attempt để lần sau có socket/intent mới.
-Chỉ app hello đã xác thực mới bật recap/notification.
-
-Facade loopback có credential: GET discover; POST pair/start `{code,device}`; GET pair/status;
-GET status (transport direct); GET list (id là fingerprint, khác discoveryId); POST revoke `{id}`;
-GET receipt query deviceId canonical publickey và idempotencyKey. Không listen/address/replace/all.
-
-Khi device tự revoke trust cục bộ, nó gửi application request đã xác thực
-`{type:"pair.revoke",requestId}` và đợi `pair.revoke_result` trước khi đóng socket. CLI sẽ xóa đúng
-identity đó cùng metadata reconnect. Socket chỉ đóng mà không có request này vẫn là `offline`, không
-được hiểu là revoke, để lỗi mạng thoáng qua không unpair device.
-
-Revoke là hai chiều. Khi app gỡ device (`harness unpair`, `harness unpair --all`,
-`harness autonomous-device revoke`, hoặc dashboard) trong lúc session direct của device đang mở, CLI
-seal `{type:"pair.revoke",machineId:<machineId của máy này>}` dưới dạng `autonomous_device_event` trên
-chính session E2EE đó, rồi đóng socket nhẹ nhàng và xóa trust local. Best-effort: gửi lỗi không chặn
-việc gỡ local. Device đang offline lúc đó sẽ biết khi reconnect: `e2e_hello` với pin cũ bị trả
-`e2e_denied` (`unpaired`).
-
-Wire dùng nguyên e2e_* gốc role device, CI b:device. App outer autonomous_device_request/result/event
-vẫn pairwise encrypted với empty dbSessionId AAD; helper relay.ts chỉ là adapter ứng dụng dùng chung
-crypto, không kết nối backend. Request agents.list/status/recap/turn.send/turn.stop/question.answer/
-receipt.get giữ target rõ và receipt/dedupe. Không replay mutation khi mất kết nối; unknown không
-có nghĩa chưa gửi. Cache512/ring500 và schema đầy đủ ở [bản EN](../autonomous-device-integration.md).
-
-## Focus của app cho voice
-
-CLI quảng bá capability `focus.get`; request `{type:"focus.get",requestId}` trả
-`{type:"focus.get_result",requestId,focus:null|{machineId,agentId,name?},focusRevision}`.
-Event `focus.changed` có payload `{focus,focusRevision}` cùng schema. Monitor Pairing hiển thị
-snapshot này; OS có thể poll để phục hồi khi bỏ lỡ event.
-
-Nguồn focus là frame local tường minh `app_focus {agentId}` từ Desktop, không phải `terminal_open`.
-Ban đầu focus là null. `app_focus {agentId:null}` hoặc đóng socket đang sở hữu focus sẽ xóa focus;
-socket cũ không được xóa focus của socket mới. Mỗi thay đổi focus đổi revision, kể cả A→B→A; thông báo lại cùng target giữ nguyên revision
-nhưng chuyển quyền sở hữu sang socket thông báo;
-revision là chuỗi opaque có server instance ID nên khác sau restart. Khi đọc snapshot, agent local
-đã bị xóa làm focus thành null và đổi revision. Focus máy remote giữ đúng machine ID remote;
-facade device chỉ hỗ trợ máy đã pair, không thay bằng agent local hoặc tự relay task.
-
-`turn.send` và `question.answer` nhận `focusRevision` tùy chọn bên cạnh target ID tường minh.
-Sau bước kiểm tra receipt trùng, service kiểm tra đồng bộ revision và target trước khi reserve/gửi.
-Sai revision hoặc target trả `FOCUS_CHANGED` không receipt: request đó chưa dispatch. Request trùng
-đã reserve vẫn trả receipt cũ dù focus đổi. Client cũ không truyền revision vẫn dùng target tường minh
-như trước. `turn.stop` không nhận trường này, tiếp tục nhắm target của lượt đang chạy.
-
-`turn.summary` và mỗi phần tử `recap.turns[]` mang ba mức của cùng một câu trả lời; bên tiêu thụ nên
-ưu tiên `turns[].fullText`, rồi `turn.summary.fullText`, rồi `text`:
-
-| Trường | Giới hạn | Là gì |
-|---|---|---|
-| `recap` | 60 ký tự | câu văn xuôi đầu tiên — tiêu đề ô tile |
-| `text` | 250 ký tự | câu trả lời bị làm phẳng một dòng rồi cắt — để liếc |
-| `fullText` | 8192 byte UTF-8 | tin nhắn cuối của agent đúng như hiện trên màn hình, giữ markdown và xuống dòng |
-
-`fullText` là tuỳ chọn, vắng mặt khi chưa ghi được câu trả lời nào, nên phải đọc phòng thủ. Nó chỉ chứa
-phản hồi cuối hướng tới người dùng — không có transcript tool, suy luận ẩn hay output terminal — và
-không tốn thêm lần gọi model: đó chính là văn bản mà bộ tóm tắt cục bộ vốn đã nhận.
-
-Trần 8192 byte là phép tính chứ không phải khẩu vị: socket direct nhận 65536 byte, `recap` có thể trả
-năm lượt một lần, và payload đã seal phình khoảng 37% qua AEAD và base64. Cắt vượt trần là cắt an toàn
-UTF-8, kèm `…` ở cuối. `text` và `recap` giữ nguyên từng byte, và card `commander_event` dùng chung
-không bị nới — encoder của dial USB ném lỗi khi frame vượt 8 KiB, nên trường này chỉ thêm vào event do
-service này phát ra.
-
-Typecheck/focused test đã đạt gồm chỉ chọn discovery, retry socket mới, chờ authenticated identity
-và từ chối reconnect giả mạo. Real mDNS/direct Go OS ↔ CLI đã đạt khi backend chưa từng kết nối: discovery SRV, sai mã/retry,
-PAKE/session, encrypted list/send/dedupe, restart/reconnect và revoke/unpair. Status chỉ đếm direct
-session đã xác thực và app-ready, không đếm socket thô. Full CLI đã đạt với
-`npm test -- --maxWorkers=1 --testTimeout=30000 --hookTimeout=30000`: 144 file / 1.871 test pass,
-5 file / 50 test skip; `npm run typecheck` đạt. Lần chạy deadline mặc định 5 giây bị timeout ở
-các test password/scrypt sẵn có khi máy chịu tải. Chỉ đổi deadline qua lệnh chạy serial, không
-sửa test hoặc cấu hình để né lỗi. Không deploy hoặc pair thiết bị thật.
-
-### Agent mặc định khi bật mode
-
-Capability tùy chọn `focus.ensure` nhận `{type:"focus.ensure",requestId}` và trả cùng snapshot
-`{focus,focusRevision}` như `focus.get`. Nếu app đã có focus thì giữ nguyên, kể cả máy remote;
-OS vẫn từ chối target remote chưa được hỗ trợ. Nếu chưa có focus, CLI yêu cầu một cửa sổ Desktop
-local chọn agent đầu tiên theo thứ tự `agents.list`, dùng flow chọn pane hiện có. Desktop đang có
-lựa chọn sẽ gửi lại focus đó thay vì thay đổi. Chỉ xác nhận `app_focus` mới thiết lập target chính thức;
-không gửi task hay tự đặt target khi không có app.
-Các request đồng thời dùng chung lần chờ tối đa hai giây. Không có agent trả `NO_AGENTS`; không có
-cửa sổ hoặc không nhận xác nhận trả `FOCUS_UNAVAILABLE`. Frame local `device_focus` có thời hạn để
-request đến trễ không mở pane sau khi hết thời gian chờ. Chỉ gọi khi bật voice mode, không gọi giữa
-utterance để tự đổi target. CLI cũ chưa có capability cần chọn agent trong app. Pairing, đọc focus,
-event và dispatch task thông thường giữ nguyên.
-Xác nhận focus tự động mang revision ban đầu; CLI bỏ qua nếu user đã chọn focus mới trong lúc request đang truyền.
-
-### Chuyển focus từng bước
-
-`focus.step` là một nấc xoay của carousel trên dial USB, nhưng do thiết bị đã pair yêu cầu thay vì ngón tay:
-
-```json
-{"type":"focus.step","requestId":"<uuid>","idempotencyKey":"<uuid mỗi gesture>","direction":"next","focusRevision":"<từ focus.get>"}
-```
-
-`direction` là `next` hoặc `previous`; `idempotencyKey` khớp `[A-Za-z0-9_-]{1,64}`; `focusRevision`
-bắt buộc. Thành công trả đúng snapshot `{focus,focusRevision}` như `focus.get`, đọc **sau khi** Desktop
-xác nhận lựa chọn mới qua frame `app_focus` thông thường; event `focus.changed` mang cùng snapshot như
-mọi lần đổi focus khác. Không tự đặt target khi không có app.
-
-Thứ tự đi là của dial: các tile đang mở trong cửa sổ Desktop theo thứ tự tile (không có cửa sổ thì
-mọi agent theo thứ tự rail — máy này trước, rồi các máy khác theo thứ tự wheel), xoay vòng ở cả hai
-đầu. Agent không có tile không bao giờ được bước tới. Chưa có focus thì `next` bắt đầu ở tile đầu,
-`previous` ở tile cuối. Chỉ có một agent thì trả ngay snapshot hiện tại, không chuyển gì. Bước chuyển
-dùng đúng forward `dial_focus` của dial cáp, nên app quyết định ý nghĩa của việc chọn y như với dial.
-
-Thứ tự kiểm tra: kết quả đã lưu cho `(deviceId,idempotencyKey)` được trả trước, dù thành công hay lỗi,
-nên gesture retry là một nấc chứ không phải hai (cùng key nhưng khác `direction` hoặc `focusRevision`
-→ `IDEMPOTENCY_CONFLICT`). Chỉ key mới mới được so với revision hiện tại: `focusRevision` cũ trả
-`FOCUS_CHANGED` và không chuyển. Kết quả lưu chỉ trong RAM, tối đa 512 mỗi daemon, xoá cũ nhất trước,
-và bị xoá khi revoke như receipt.
-
-Lỗi: `NO_AGENTS` khi không có gì để bước tới; `FOCUS_UNAVAILABLE` khi không có cửa sổ Desktop hoặc
-app không xác nhận trong hai giây (daemon không retry — đọc `focus.get` trước khi gửi lại);
-`INVALID_REQUEST` khi direction, key hoặc revision sai.
-
-Giới hạn target giữ nguyên. Bước chuyển có thể rơi vào tile thuộc máy khác vì cửa sổ có thể đang mở
-tile đó; daemon local khi đó báo focus của app rời máy này (`focus:null` với revision mới, hoặc
-target remote nếu Desktop công bố ở đây), và `turn.send` tới target đó vẫn trả `MACHINE_MISMATCH`.
-OS vẫn chịu trách nhiệm hiển thị rằng target remote chưa được hỗ trợ dispatch. Pairing, transport,
-credential và flow gửi task không đổi; CLI cũ không liệt kê `focus.step` trong capabilities của hello.
-
-### Cuộn terminal đang focus
-
-`scroll` là một lần báo ngón tay trên mặt kính của thiết bị đã pair, chuyển thẳng tới terminal mà
-Desktop đang mở trước mặt — đúng frame `dial_scroll` mà dial USB gửi, nên app xử lý hai bên như nhau:
-
-```json
-{"type":"scroll","requestId":"<uuid>","phase":"move","dy":-24}
-{"type":"scroll","requestId":"<uuid>","phase":"up","dy":-3,"velocity":-900}
-```
-
-Ở đây thiết bị là một touchpad: nó báo **quãng di chuyển**, không phải vị trí, vì nó không biết
-terminal cao bao nhiêu; terminal giữ scrollback và tự tính. Một vuốt gửi thành nhiều mảnh — `down`
-khi ngón tay chạm (cửa sổ dừng mọi quán tính đang chạy), các `move` mang `dy` pixel thiết bị đã đi
-kể từ lần báo trước (dương = xuống dưới mặt kính), và `up` khi nhấc tay, với `velocity` (px/s của
-thiết bị, cùng dấu với `dy`) trở thành cú fling. `dy` và `velocity` mặc định 0, phải là số nguyên
-trong ±4096 và ±100000. Mỗi `down` phải có `up`: vuốt không đóng sẽ giữ trạng thái kéo bên app cho
-tới `down` kế tiếp.
-
-Một vuốt là stream, không phải mutation: không `idempotencyKey`, không receipt, không lưu gì, và
-không có gì để retry — mất một `move` chỉ là cuộn ngắn hơn. Thành công trả `scroll_result` rỗng.
-Chỉ terminal Desktop đang focus mới cuộn; pane viewer thì không. Lỗi: `FOCUS_UNAVAILABLE` khi không
-có cửa sổ Desktop; `INVALID_REQUEST` khi phase sai, giá trị không phải số nguyên hoặc ngoài khoảng,
-hoặc có field lạ. CLI cũ không liệt kê `scroll` trong capabilities của hello.
-
-## Input bổ sung khi agent đang chạy
-
-`turn.send` tới Claude/Codex dùng input native ngay khi agent đang làm việc; chỉ serialize thao
-tác ghi terminal. Capability `input.status.v1` bổ sung `receipt.input` để phân biệt steering,
-native queue, daemon queue và trạng thái xác nhận input. Không đổi nghĩa receipt cũ: input đã
-nhận không có nghĩa task hoàn tất. Các lượt chồng nhau thiếu correlation phải giữ `unknown`.
-Xem [chi tiết engine, kiểm thử và phần OS cần phối hợp](../in-flight-agent-input.md). OS cần lưu
-nhiều delivery và không gán summary/recap theo session cho câu bổ sung mới nhất.
diff --git a/docs/vi/autonomous-device-store_vi.md b/docs/vi/autonomous-device-store_vi.md
deleted file mode 100644
index 213bb7d03..000000000
--- a/docs/vi/autonomous-device-store_vi.md
+++ /dev/null
@@ -1,255 +0,0 @@
-# Contract Autonomous robot → Harness Store, v1
-
-Đây là tài liệu tích hợp chung cho phía Autonomous OS và OpenHarness. Luồng giữ nguyên:
-`harness-use → OS loopback API → direct encrypted device connection → Harness CLI`.
-[Bản English](../autonomous-device-store.md) mô tả cùng contract; nguồn máy đọc được là
-[JSON schemas và fixture Blender](../contracts/autonomous-device-store-v1/).
-
-**Trạng thái:** đã triển khai trong checkout này, chưa cài vào daemon đang chạy, chưa release hay
-triển khai lên robot. OS phải kiểm tra capabilities khi hello, không suy đoán từ số phiên bản.
-Sau bàn giao, mọi thay đổi contract phải được thông báo cho phía OS và cập nhật đồng bộ schemas,
-fixtures, tests và hai bản tài liệu. Không âm thầm đổi nghĩa field/operation v1.
-
-## Kết nối, capability và quyền
-
-Giữ `proto:1`, pairing, PAKE, identity pin và E2EE của integration hiện có. JSON dưới đây là
-**payload sau giải mã**, không gửi plaintext trên LAN. Mỗi RPC có `requestId` UUIDv4 mới; response
-là `<type>_result`, echo đúng requestId.
-
-OS chỉ bật tự động chuẩn bị khi `hello_result.capabilities` có đủ:
-
-```json
-["store.list", "store.inspect", "agent.prepare", "operation.get"]
-```
-
-CLI cũ/chưa nối service trả `UNSUPPORTED_CAPABILITY`; báo cần cập nhật CLI trên máy đã pair.
-Không dùng `dsh_install`, `agent_create` hoặc generic dispatcher để lách capability. OS cũ vẫn hoạt
-động như trước. Chỉ xử lý máy đã pair; vẫn cần role-device đã xác thực, ciphertext và application
-hello. Rate limit/concurrency limit của interface cũ giữ nguyên.
-
-Device có thể yêu cầu cài package chính thức và dependency chính thức đã được nhận diện trong Store.
-Setup thực thi thật dưới quyền tài khoản trên máy, không phải sandbox. Package/dependency cộng đồng
-chưa cài yêu cầu chủ máy review/cài qua Desktop. Package đã được chủ máy cài có thể dùng.
-Không nhận URL/ref tùy ý, lệnh shell, engine override, bypass quyền, update/remove hay admin RPC.
-Agent mới dùng permission bypass **tắt**, không có first prompt.
-
-## 1. Khám phá và kiểm tra thông tin
-
-```json
-{"type":"store.list","requestId":"11111111-1111-4111-8111-111111111111","query":"Blender","offset":0,"limit":5}
-```
-
-Response: `{type,requestId,machineId,packages:[Package],nextOffset:number|null}`.
-`query` tùy chọn, tối đa 200 ký tự; tìm tất cả từ trong ID/name/description/category. `offset` mặc định
-0 (0–25000), `limit` mặc định 10 (1–10). Lặp với nextOffset đến null; catalog có thể đổi giữa các trang.
-Viewer là dependency, không phải agent để chọn. Package đã cài nhưng bị unlist vẫn xuất hiện.
-
-```json
-{"type":"store.inspect","requestId":"22222222-2222-4222-8222-222222222222","packageId":"autonomous/blender"}
-```
-
-Response: `{type,requestId,machineId,package:Package,candidates:[Agent],candidatesTruncated:boolean}`.
-Tối đa 5 candidate; dùng `agents.list` nếu cần xem thêm. Chỉ ghép candidate theo package identity được
-lưu trong registry, không đoán theo tên hoặc recap. OS/người dùng quyết định session có đúng project
-hay không; inspect/prepare không tự chiếm session.
-
-| Field của Package | Ý nghĩa |
-|---|---|
-| `packageId,name,description,category,engine` | Dữ kiện từ catalog/manifest đã cài |
-| `catalog,installed` | Hai boolean độc lập: có trên Store không đồng nghĩa đã cài |
-| `verified,installAllowed` | Nhận diện nguồn chính thức và quyền cài tự động; không chứng minh tool chạy được |
-| `viewerPackageId` | Shared viewer đã biết hoặc null |
-| `version,broken` | Tree/commit đã cài nếu biết; lỗi package hoặc null |
-| `capabilities` | `{source:"package_metadata",description,category}`: mô tả công bố, không phải capability đã test |
-| `requirements` | `{engine,viewerPackageId,applications:null,note}`: manifest hiện chưa có danh sách dependency ứng dụng chuẩn hóa |
-| `installation` | `not_installed / installed / installing / broken`; installing phản ánh install đang chạy trong service này |
-| `readiness` | `{state,scope:"package_doctor",engineAuthentication:"unknown",taskSuccess:"unknown",checkedAt?,version?,lines?}` |
-| `lastPreparation` | `{state,phase,error,updatedAt}` mới nhất trong bộ nhớ, hoặc null; lịch sử bền vững xem operation.get |
-
-Readiness: `not_installed / unknown / passed / failed`. List/inspect không chạy scripts. Prepare chạy
-doctor của package và viewer, lưu tối đa 10 dòng, mỗi dòng 400 ký tự, timestamp và version. Đổi version
-hoặc restart daemon làm cache check mất hiệu lực. Không có doctor thì phạm vi kiểm tra là unknown.
-Doctor pass là bằng chứng tại thời điểm kiểm tra, không chứng minh login/license/GPU, mọi tính năng
-hay task cụ thể đều sẵn sàng. Install từ luồng khác được phản ánh khi installed index thay đổi.
-
-Agent candidate có `{agentId,machineId,packageId,engine,workspace,state,runtime,error?}`.
-`runtime` là `starting / ready / unavailable`; workspace là đường dẫn tuyệt đối canonical nếu biết.
-`agents.list` cũng thêm các field tùy chọn `packageId,workspace,runtime`. Package null/absent nghĩa là
-không biết, không được suy từ recap. Runtime ready cần terminal sống và engine process được launch watcher xác nhận (`launch.state=ready`),
-hoặc native conversation đã bind đối với agent được discovery. Agent mới không bắt buộc có native
-session ID: một số engine chỉ tạo ID sau task đầu tiên. Terminal thường là ngoại lệ. Xác thực engine chưa được kiểm chứng độc lập.
-
-## 2. Chuẩn bị agent, không giao task
-
-```json
-{
- "type":"agent.prepare",
- "requestId":"33333333-3333-4333-8333-333333333333",
- "machineId":"mac-example",
- "packageId":"autonomous/blender",
- "idempotencyKey":"prepare-airplane-001",
- "workspace":{"kind":"new","name":"airplane"}
-}
-```
-
-Workspace bắt buộc, chọn đúng một dạng:
-
-- `{"kind":"new","name":"airplane"}`: tạo trong `~/harnesses/` theo convention hiện có. Name tùy
- chọn, 1–100 ký tự ASCII chữ/số/`_`/`-`, bắt đầu bằng chữ/số. Bỏ name thì dùng tên package/thời gian.
- Nếu tên đã tồn tại, báo lỗi; không tự dùng lại folder.
-- `{"kind":"existing","path":"/Users/example/harnesses/airplane"}`: thư mục tuyệt đối đã tồn tại,
- tối đa 4096 ký tự, không control characters. Resolve symlink trước khi kiểm tra. Chủ máy chọn rõ
- project này; materialize áp dụng template/instructions theo package. Nếu agent khác đang dùng
- workspace thì từ chối, không đổi project của session đó. Các request device cùng workspace được
- chặn tranh chấp trước bước tạo agent.
-
-Không nhận `text`/`prompt`; không tự update package đã cài. Dùng lại Store install/setup/doctor,
-`prepareProjectFolder`, `onCreateAgent`, `AgentCreationReceipts`. Package đã cài bỏ qua install/setup
-nhưng chạy lại doctor. Dependency thiếu/doctor fail trả hướng dẫn. Package hỏng không tự ghi đè.
-
-Response ngay sau khi ghi reservation bền vững:
-`{type:"agent.prepare_result",requestId,status:"accepted",operation:Operation}`.
-Retry cùng key/tham số, requestId mới → `status:"duplicate"`, cùng operation. Đổi tham số dưới cùng
-key → `IDEMPOTENCY_CONFLICT`. Xem JSON đầy đủ khớp implementation trong
-[blender.fixture.json](../contracts/autonomous-device-store-v1/blender.fixture.json).
-
-Operation có:
-`operationId` (64 ký tự hex thường), `machineId`, `packageId`, `state`, `phase`, `createdAt`,
-`updatedAt` (Unix milliseconds), `agentId`, `workspace`, `error:{code,message}|null`, `guidance|null`,
-`doctor:[]`, `taskDispatched:false`, `engineAuthentication:"unknown"`.
-Các field chưa có giá trị như agentId/workspace dùng null. Lưu operationId được trả về, không tự tính.
-
-## 3. Lifecycle, polling và phục hồi
-
-```json
-{"type":"operation.get","requestId":"44444444-4444-4444-8444-444444444444","operationId":"<64 ký tự hex nhận từ prepare>"}
-```
-
-Response `{type:"operation.get_result",requestId,operation:Operation}`. Chỉ identity đã tạo operation
-được đọc nó; ID không tồn tại/thuộc device khác đều trả `OPERATION_NOT_FOUND`.
-Poll khoảng 2 giây/lần, backoff khi rate limited. **V1 không thêm progress event**; polling là nguồn
-trạng thái chuẩn. Sau reconnect hoặc resync, poll lại operation IDs đã lưu. Event replay/cursor và
-serverInstanceId hiện có vẫn áp dụng cho task/turn.
-
-| State | OS cần làm |
-|---|---|
-| `accepted` | Đã lưu ý định, chưa kết luận install/create xảy ra |
-| `running` | Tiếp tục poll operation hiện tại |
-| `ready` | Đã chuẩn bị package và terminal và engine launch; **chưa giao task** |
-| `failed` | Lỗi xác định như không có package; kiểm tra trước khi tạo ý định mới |
-| `needs_user_action` | Hiển thị error.message + guidance; có thể cần dependency/login/workspace hoặc kết quả thực thi chưa rõ |
-
-Phases: `accepted → install / clone / setup → doctor → workspace → create → launch → complete`.
-Có thể bỏ qua hoặc lặp các phase khi package đã cài/shared dependencies. AgentId có thể đã có dù chưa
-ready hoặc đang cần thao tác: mở agent đó để xử lý, không tạo thêm.
-
-Ready chỉ xác nhận bước chuẩn bị. Không chứng minh đã dựng máy bay, đã đăng nhập hay model thành công.
-Nếu engine chưa launch thành công sau 10 phút, polling trả `ENGINE_ACTION_REQUIRED`; lỗi launch đã
-biết báo sớm hơn. Hoàn tất prompt engine rồi poll lại có thể đưa cùng operation về ready. Agent biến
-mất/đổi workspace khiến operation previously-ready trở thành cần thao tác.
-
-Quy tắc retry/recovery:
-
-- Key theo `(paired identity,idempotencyKey)` trên máy; 1–64 chữ/số ASCII/`_`/`-`.
-- Ghi private journal trước side effect; creation receipt bảo vệ riêng bước spawn. Không tự hết hạn
- journal/receipt; giữ dữ liệu trong ADAPTER_DATA_DIR.
-- Tối đa 4 preparation jobs đang chạy. Request device cùng package chia sẻ install; lock Store hiện
- có bao phủ Desktop/CLI. `DSH_BUSY` không cho phép chạy setup song song.
-- Timeout/disconnect không hủy công việc đã accepted. Retry cùng prepare key/tham số để lấy lại ID
- hoặc poll ID cũ. Timeout không nghĩa là chưa thực thi.
-- Restart: nếu creation receipt xác nhận created thì lấy lại agentId, kiểm tra registry/package/
- workspace/runtime; không spawn lại.
-- Nếu journal bị ngắt mà chưa có creation xác nhận, trả `RECOVERY_REQUIRED`. Không tự chạy lại
- install/setup/tạo folder/spawn. Chủ máy kiểm tra side effects trước khi chủ động dùng key mới.
-- Revoke pairing chặn bước tiếp theo ở boundary; setup/doctor/spawn đang chạy có thể đã tạo side
- effects và không luôn hủy được. Không tự xóa file/agent của người dùng. Transport bị revoke không
- được tiếp tục gửi/đọc.
-- `receipt.get` hiện có dành cho turn/stop/answer, không đọc preparation. Dedupe delivery của nó còn
- trong bộ nhớ; thay đổi này **không** làm `turn.send` bền vững qua restart. Nếu task mất xác nhận
- qua restart, kiểm tra serverInstanceId và kết quả agent; không tự gửi lại vì receipt cũ biến mất.
-
-## Lỗi
-
-Trước accepted: `{type,requestId,error:{code,message}}`, không có operation.
-Sau accepted: đọc `operation.error` và `guidance`, kể cả response duplicate.
-
-| Code | Xử lý |
-|---|---|
-| `UNSUPPORTED_CAPABILITY`, `PROTO_UNSUPPORTED` | Cập nhật CLI, không gọi generic dispatcher |
-| `HELLO_REQUIRED`, `RATE_LIMITED`, `BACKPRESSURE` | Hello/backoff, giữ nguyên key |
-| `INVALID_REQUEST`, `MACHINE_MISMATCH` | Sửa payload/target, field lạ bị từ chối |
-| `PACKAGE_NOT_FOUND`, `PACKAGE_REVIEW_REQUIRED` | Chọn package hợp lệ hoặc chủ máy review/cài |
-| `PACKAGE_BROKEN`, `DEPENDENCY_NOT_READY` | Đọc doctor/broken evidence, sửa trên máy |
-| `INVALID_WORKSPACE`, `WORKSPACE_IN_USE` | Chọn project khác hoặc chọn rõ candidate hiện có |
-| `IDEMPOTENCY_CONFLICT` | Đối chiếu state caller, không dùng cùng key cho ý định khác |
-| `OPERATION_NOT_FOUND`, `STORAGE_FAILED` | Kiểm tra identity/ID/storage; không suy ra chưa chạy |
-| `INSTALL_UNCONFIRMED`, `CREATION_UNCONFIRMED`, `PREPARATION_UNCONFIRMED`, `RECOVERY_REQUIRED` | Side effects có thể tồn tại, kiểm tra trước retry mới |
-| `ENGINE_ACTION_REQUIRED`, `AGENT_UNAVAILABLE` | Mở agent được trả về, xử lý login/trust/launch/target |
-| `REVOKED`, `INTERNAL` | Dừng/đối chiếu, không tự tạo intent mới |
-
-Lỗi Store/creator gốc cũng được chuyển tiếp: `CLONE_FAILED`, `SETUP_FAILED`, `DOCTOR_FAILED`,
-`DSH_BUSY`, `TMUX_UNAVAILABLE`, `CWD_NOT_FOUND`, `TMUX_TOO_OLD_FOR_DSH`, `PROJECT_EXISTS`,
-`PROJECT_PREPARATION_FAILED`... OS phải hiển thị code/message/guidance chưa biết, không coi là success.
-
-## Luồng Blender hoàn chỉnh và phần Autonomous OS cần làm
-
-1. Lưu user intent “I want to use Blender to draw an airplane for me”; kiểm tra đủ capabilities.
-2. `store.list(query:"Blender")` → `store.inspect(packageId:"autonomous/blender")`. Dựa trên package
- identity/readiness/candidate, không recap. Nếu người dùng chọn session phù hợp đã có thì dùng ID
- đó và bỏ qua prepare.
-3. Nếu cần agent mới, lưu `prepare-airplane-001` + workspace rồi gọi prepare. Lưu operationId, poll,
- thông báo tiến độ hoặc hướng dẫn cần thao tác. Không yêu cầu OS biết cách setup riêng Blender.
-4. Khi ready, lưu machineId/agentId, tạo key task riêng **`task-airplane-001`**, rồi gửi đúng một lần:
-
- ```json
- {"type":"turn.send","requestId":"55555555-5555-4555-8555-555555555555","machineId":"mac-example","agentId":"agent-example","idempotencyKey":"task-airplane-001","text":"Use Blender to draw an airplane for me."}
- ```
-
- Không đưa task vào prepare/name/setup/first prompt. Dùng target vừa nhận, không ràng buộc với
- app focus không liên quan.
-5. Lưu delivery receipt/serverInstanceId; theo dõi receipt/status/events/questions/recap. Permission
- prompt phải xử lý trên Desktop; `question.answer` không duyệt tool permissions. Chỉ báo dựng xong
- khi có kết quả công việc, không khi prepare ready.
-6. OS cần: capability fallback, journal intent/keys, polling/reconnect, chọn candidate và UI/voice cho
- needs_user_action. Không cần credential hay script Blender mới.
-
-## Kiểm thử và giới hạn
-
-Tests bao phủ metadata/installed/readiness, install dùng chung, dependency lỗi, setup/doctor/
-materialize **thật với package fixture local**, arguments tạo agent không bypass quyền, dedupe/
-timeout/reconnect, restart và khoảng trống spawn/journal, symlink/workspace collision, revoke,
-capability/role/encryption boundaries và schema/fixture khớp implementation.
-
-Engine/model creation trong tests là mock. Dòng doctor Blender trong fixture là ví dụ tổng hợp.
-Lượt triển khai này chưa cài Blender, chạy robot thật, gọi model có phí hay render máy bay. Cần một
-lượt acceptance phối hợp Lamp → CLI mới → Blender thật sau khi cả hai phía tích hợp.
-
-```sh
-cd cli
-npx tsx scripts/device-store-contract.ts --check
-npx vitest run src/lib/autonomous-device --maxWorkers=1
-```
-
-## Tự mở Desktop sau khi chuẩn bị agent
-
-Ngay khi có `agentId`, trước readiness, CLI lưu yêu cầu mở/reveal agent trên một Desktop local.
-Desktop tái sử dụng tab đã có hoặc mở một tab, rồi dùng cơ chế viewer chung của package, kể cả khi
-viewer URL/lỗi đến sau. Terminal cho phép người dùng xử lý login/trust; mở UI không tự trả lời,
-không bypass quyền và không gửi task. Áp dụng mọi Store package.
-
-Event loopback nội bộ `device_prepare_open` mang `{operationId,machineId,agentId}`. Desktop xác nhận
-bằng `device_prepare_opened` với `{operationId,agentId}` khi đã có terminal pane. Đây không phải
-operation device hay capability LAN mới. CLI retry mỗi hai giây đến khi nhận xác nhận, lưu xác nhận
-vào journal và khôi phục yêu cầu còn chờ sau daemon restart. Các lần mở đồng thời được gộp theo
-machine/agent; cùng operation không tạo tab trùng hoặc liên tục giành focus. Nếu mất xác nhận rồi
-Desktop restart, có thể reveal lại tab cũ nhưng không tạo terminal thứ hai. Tab đã xác nhận rồi
-được người dùng đóng sẽ không tự mở lại.
-
-Desktop tương thích phải đang chạy và đăng nhập. Nếu app chưa mở, quá cũ hoặc đang reconnect,
-yêu cầu UI tiếp tục chờ; cơ chế này không cài hay khởi chạy ứng dụng Desktop. Readiness độc lập với
-xác nhận mở UI; cả hai không chứng minh engine đã login hoặc task thành công. JSON schemas và tên
-capability/operation phía OS không đổi.
-
-**Cập nhật bàn giao OS:** `ready` chấp nhận engine launch đã xác nhận mà không chờ native session ID.
-Không gửi prompt mồi để lấy ID. OS vẫn gửi task thật đúng một lần qua `turn.send`, với idempotency key
-riêng. Event mở UI không giao task.
diff --git a/docs/vi/worktree-pull-requests_vi.md b/docs/vi/worktree-pull-requests_vi.md
deleted file mode 100644
index 588218b87..000000000
--- a/docs/vi/worktree-pull-requests_vi.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# PR bên cạnh branch
-
-Header terminal đủ rộng có link riêng `PR #123 · Draft / Open / Merged / Closed`, giữ nguyên màu
-branch. Nhãn PR và thông tin branch cùng ẩn khi hover để chỉ hiện các nút điều khiển. Header hẹp dùng nhãn gọn `#123 · Draft`, ưu tiên chỗ cho trạng thái PR trước tên branch.
-Chỉ header rất nhỏ (dưới 360 logical pixel ở cỡ chữ bình thường) mới ẩn nhãn.
-Click mở GitHub; không merge, checkout hay xoá worktree.
-
-CLI đọc branch và remote `origin` tại thư mục của agent, kể cả linked worktree, rồi dùng `gh` và
-phiên đăng nhập GitHub trên máy đó. Đây là truy vấn chỉ đọc, có timeout, không tự mở login. Request
-và response được mã hoá khi chuyển tới máy remote.
-
-Chỉ hiện nhãn khi có kết quả PR hợp lệ. Đang tải, không có PR hoặc không tra cứu được đều ẩn nhãn.
-API vẫn phân biệt lỗi tra cứu với tra cứu thành công nhưng không có PR. Refresh mỗi phút, cache CLI 60 giây có giới
-hạn, bỏ kết quả cũ khi đổi agent/branch. Ưu tiên PR đang mở; nếu không có, lấy PR cập nhật gần nhất.
-
-Phạm vi ban đầu: repo github.com trong `origin`, khớp cả branch lẫn repository nguồn. Chưa tìm PR từ
-fork sang upstream hay GitHub Enterprise. Đã merge không có nghĩa worktree sạch hoặc có thể xoá.