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.

Launch and resume failures: count them right, keep the reason (#1777)

Jacob Pham567599daa73b
diff --git a/backend/src/analytics/productHealth.test.ts b/backend/src/analytics/productHealth.test.ts
index 37263dd03..cf0af7d49 100644
--- a/backend/src/analytics/productHealth.test.ts
+++ b/backend/src/analytics/productHealth.test.ts
@@ -1,6 +1,6 @@
import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
-import { cleanUsageContext, HEALTH_MEASURES, HEALTH_FLOWS } from '../types/productHealthContract.js'
+import { cleanUsageContext, HEALTH_MEASURES, HEALTH_FLOWS, PRODUCT_HEALTH_METRICS } from '../types/productHealthContract.js'
import { PRODUCT_USAGE_ADD_PHONE_OPENINGS, PRODUCT_USAGE_DESKTOP_FLOWS } from '../types/productUsage.js'
import { dailyProductHealth, healthBreakdowns } from './productHealth.js'
@@ -96,3 +96,8 @@ it('reports first-run activation only against its own observed episode denominat
expect(dailyProductHealth([row('collector_days', 5)], new Date('2026-10-23')).daily[0].firstRun.responsePercent).toBeNull()
expect(dailyProductHealth([row('first_run_started', 1), row('first_run_response', 2)], new Date('2026-10-23')).daily[0].firstRun.responsePercent).toBeNull()
})
+
+it('names each resume preparation kind per source', () => {
+ for (const kind of ['invalid_json', 'foreign_session', 'not_owned_file', 'changed_during', 'other'])
+ expect((PRODUCT_HEALTH_METRICS as readonly string[]).includes(`request_app_resume_preparation_${kind}`), kind).toBe(true)
+})
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index 80217601c..1383b26a8 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -92,6 +92,12 @@ it('keeps the client and server vocabulary identical', () => {
.toBe(readFileSync(new URL('../types/productUsage.ts', import.meta.url), 'utf8'))
})
+it('names launch refusals and agent-started launches', () => {
+ const metrics = new Set<string>(PRODUCT_USAGE_METRICS)
+ for (const m of ['launch_refused', 'launch_agent_started', 'launch_agent_created', 'launch_agent_failed', 'launch_agent_refused',
+ 'launch_refused_code_session_in_harness', 'launch_refused_code_invalid_request']) expect(metrics.has(m), m).toBe(true)
+})
+
it('names every launch code in each of its families, once, as a fixed word that can carry no message', () => {
const metrics = new Set<string>(PRODUCT_USAGE_METRICS)
expect(metrics.size).toBe(PRODUCT_USAGE_METRICS.length)
diff --git a/backend/src/types/productHealthContract.ts b/backend/src/types/productHealthContract.ts
index d902c6b2c..b54c01d5a 100644
--- a/backend/src/types/productHealthContract.ts
+++ b/backend/src/types/productHealthContract.ts
@@ -45,10 +45,15 @@ export type CliReportFailure = typeof CLI_REPORT_FAILURES[number]
export const RESUME_REASONS = ['runtime_unavailable', 'saved_state_missing', 'project_missing', 'harness_missing',
'credentials_missing', 'busy', 'changed', 'unconfirmed', 'preparation_failed', 'launch_failed', 'invalid', 'other'] as const
export type ResumeReason = typeof RESUME_REASONS[number]
+/** Which check refused a resume's history preparation (cli/src/engines/kit/resumeRepair.ts): on 2026-10-26, 10 of
+ * 17 failed resumes were `preparation_failed` and nothing said why. Counted beside `resume_reason_preparation_failed`. */
+export const RESUME_PREPARATION_KINDS = ['invalid_json', 'foreign_session', 'not_owned_file', 'changed_during', 'other'] as const
+export type ResumePreparationKind = typeof RESUME_PREPARATION_KINDS[number]
export const PRODUCT_HEALTH_METRICS = [
...CLI_REPORT_FAILURES.map(reason => `health_cli_report_failure_${reason}` as const),
...CLI_REPORT_FAILURES.map(reason => `health_desktop_report_failure_${reason}` as const),
...HEALTH_SOURCES.flatMap(source => RESUME_REASONS.map(reason => `request_${source}_resume_reason_${reason}` as const)),
+ ...HEALTH_SOURCES.flatMap(source => RESUME_PREPARATION_KINDS.map(kind => `request_${source}_resume_preparation_${kind}` as const)),
// hn's (`tui`) come through its daemon's queue, under that daemon's context, never one of their own.
...(['cli', 'desktop', 'tui'] as const).flatMap(surface => HEALTH_MEASURES.map(m => `health_${surface}_${m}` as const)),
// The phone reports only its coverage (the threshold its breakdowns need) and late deliveries.
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index 3f47c79f1..7f1303c23 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -171,10 +171,11 @@ export type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]
* and resume requests' `other` refusals, and every delete and restart refusal — from any client, and again,
* apart, those the phone asked for (`phone_`), which a daemon's report otherwise carries mixed with the
* Desktop's, the TUI's and tools'. Setup reasons have their own families, adding up to `launch_failed_setup`,
- * `create_error_setup` and `request_phone_create_error_setup`; existing `other` families keep their meaning. */
+ * `create_error_setup` and `request_phone_create_error_setup`; existing `other` families keep their meaning.
+ * `launch_refused_code` names which correct refusal a `launch_refused` was (cli/src/lib/productUsageSignals.ts). */
export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code',
'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code',
- 'launch_failed_setup_code', 'create_error_setup_code', 'phone_create_error_setup_code'] as const
+ 'launch_failed_setup_code', 'create_error_setup_code', 'phone_create_error_setup_code', 'launch_refused_code'] as const
/** The engine an installation's first launch asked for; any other engine is `other`. */
export const PRODUCT_USAGE_LAUNCH_ENGINES = ['opencode', 'claude', 'codex', 'other'] as const
export type ProductUsageLaunchEngine = typeof PRODUCT_USAGE_LAUNCH_ENGINES[number]
@@ -200,6 +201,11 @@ export const PRODUCT_USAGE_METRICS = [
'launch_started', 'launch_created', 'launch_failed', 'launch_cancelled', 'launch_unconfirmed', 'launch_unobserved',
// A created launch whose engine then did not start: one of the launch_created, never also a launch_failed.
'launch_late_failed',
+ // A create turned down because the request was wrong, not because Harness failed (the Oct 26 report counted
+ // opening a conversation that is already a harness, and a cloud agent with no task, as failures): never also
+ // a launch_failed. The agent twins count the launches an agent or a Swarm started (the create's `startedBy`),
+ // so a person's own launches are the total less those.
+ 'launch_refused', 'launch_agent_started', 'launch_agent_created', 'launch_agent_failed', 'launch_agent_refused',
'launch_wait_install', 'launch_wait_model', 'launch_wait_native', 'launch_wait_other',
'launch_failed_setup', 'launch_failed_auth', 'launch_failed_unavailable', 'launch_failed_invalid', 'launch_failed_other',
'launch_under_10s', 'launch_10s_to_1m', 'launch_1m_to_5m', 'launch_over_5m',
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 33386e4cd..60452563a 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2058,6 +2058,27 @@ describe('BackendSocket outbound queue', () => {
}
})
+ it('tells the gateway a launch an agent started, apart from a person\'s', async () => {
+ const socket = relaySocket('token')
+ bindLaunchRequests(socket)
+ const signals: Array<Record<string, unknown>> = []
+ vi.spyOn(gatewayOf(socket), 'usageLaunch').mockImplementation((signal) => { signals.push(signal as never) })
+ socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'SPAWN_FAILED' }))
+ socket.registerLocalClient('local:started-by', { sendFrame: () => true, sendBinary: () => true })
+ try {
+ const agentId = randomUUID(), personId = randomUUID()
+ socket.handleLocalFrame('local:started-by', { type: 'agent_create', payload: { requestId: 'agent', creationId: agentId, engine: 'codex',
+ cwd: '/tmp/work', startedBy: 'agent', parentAgentId: 'parent-agent' } })
+ socket.handleLocalFrame('local:started-by', { type: 'agent_create', payload: { requestId: 'person', creationId: personId, engine: 'codex', cwd: '/tmp/work' } })
+ await vi.waitFor(() => expect(signals.filter(signal => signal.phase === 'start')).toHaveLength(2))
+ expect(signals).toContainEqual({ id: agentId, phase: 'start', engine: 'codex', agentStarted: true })
+ expect(signals).toContainEqual({ id: personId, phase: 'start', engine: 'codex' })
+ } finally {
+ await socket.unregisterLocalClient('local:started-by')
+ await socket.stop()
+ }
+ })
+
it('tells the gateway a launch\'s engine and the agent it created, and then that agent\'s start failing', async () => {
// A create whose engine then did not start was counted as a launch that worked: the reply had said created
// (core/agents/newPane.ts; production counters, 2026-10-16). Only fixed names and the agent's id leave here.
@@ -2982,6 +3003,19 @@ describe('agent_restart RPC', () => {
await socket.unregisterLocalClient('local:restart'); await socket.stop()
})
+ it.each([false, true])('counts which check refused a resume\'s preparation (receipt: %s)', async withReceipt => {
+ const { socket } = localSocket()
+ const counted: string[] = []
+ vi.spyOn(gatewayOf(socket), 'usageCounter').mockImplementation(metric => { counted.push(metric) })
+ bindLaunchRequests(socket, { resume: vi.fn(async () => ({ ok: false as const, error: 'RESUME_PREPARATION_FAILED', reason: 'changed_during', detail: 'PRIVATE' })) })
+ socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId: 'prepare', agentId: 'agent-1',
+ ...(withReceipt ? { creationId: `resume-${randomUUID()}` } : {}) } })
+ await vi.waitFor(() => expect(counted).toContain('request_app_resume_preparation_changed_during'))
+ expect(counted).toContain('request_app_resume_reason_preparation_failed')
+ expect(JSON.stringify(counted)).not.toContain('PRIVATE')
+ await socket.unregisterLocalClient('local:restart'); await socket.stop()
+ })
+
it('delegates a resume-only intent and retains its original receipt', async () => {
const { socket, frames } = localSocket()
const creationId = `resume-${randomUUID()}`
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 668a2e536..e63404cfb 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -937,7 +937,8 @@ export class BackendSocket {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const launchMeasured = productUsageLaunch(type, (frame.payload as { creationId?: unknown } | undefined)?.creationId,
- signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)), (frame.payload as { engine?: unknown } | undefined)?.engine)
+ signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)), (frame.payload as { engine?: unknown } | undefined)?.engine,
+ (frame.payload as { startedBy?: unknown } | undefined)?.startedBy === 'agent')
const usageSource = productUsageSource(local, !!connId && this.toolClients.has(connId), role, frame.payload)
const measured = productUsageRequest(type, (metric) => this.toGateway('usage', (gateway) => gateway.usageCounter?.(metric)), Date.now, usageSource,
(frame.payload as { userAction?: unknown } | undefined)?.userAction === true)
@@ -946,7 +947,8 @@ export class BackendSocket {
signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)))
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => {
if (t === type) {
- measured(p.error ?? (p.failure as { code?: unknown } | undefined)?.code, p.state, !!p.agent, p.ok)
+ const failure = p.failure as { code?: unknown; reason?: unknown } | undefined
+ measured(p.error ?? failure?.code, p.state, !!p.agent, p.ok, undefined, p.reason ?? failure?.reason)
// The agent frame itself: a created launch's agent is watched until it starts (gateway/productUsage.ts).
launchMeasured(p.error ?? (p.failure as { code?: unknown } | undefined)?.code, p.state, p.agent, (p.held as { service?: unknown } | undefined)?.service)
}
diff --git a/cli/src/cloud/service.spec.ts b/cli/src/cloud/service.spec.ts
index f3537219f..3db03b391 100644
--- a/cli/src/cloud/service.spec.ts
+++ b/cli/src/cloud/service.spec.ts
@@ -8,7 +8,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CloudCore } from '../core/api.js'
import type { CloudHarness } from '../lib/cloudAgents.js'
import type { Bridge } from './bridge.js'
-import { nameFor, repositoryOf, startCloudService } from './service.js'
+import { repositoryOf } from '../lib/cloudAgents.js'
+import { nameFor, startCloudService } from './service.js'
import { CloudError, type CloudAdapter, type CloudUpdate } from './types.js'
const owner = { local: true, owner: true }
diff --git a/cli/src/cloud/service.ts b/cli/src/cloud/service.ts
index 3ff23b56e..62027672a 100644
--- a/cli/src/cloud/service.ts
+++ b/cli/src/cloud/service.ts
@@ -14,7 +14,7 @@ import { randomBytes } from 'node:crypto'
import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import type { CloudCore, CloudPort, CloudResult, ServiceRequests } from '../core/api.js'
-import { CLOUD_AGENT_IDS, CLOUD_AGENTS, SAID_MAX, cloudAgentFrame, isCloudAgent, type CloudAgentId, type CloudAgentInfo, type CloudHarness } from '../lib/cloudAgents.js'
+import { CLOUD_AGENT_IDS, CLOUD_AGENTS, SAID_MAX, cloudAgentFrame, cloudRequestRefusal, isCloudAgent, repositoryOf, type CloudAgentId, type CloudHarness } from '../lib/cloudAgents.js'
import { connectionFor, connectionsBridge, type Bridge } from './bridge.js'
import { cursorAdapter } from './cursor.js'
import { devinAdapter } from './devin.js'
@@ -59,13 +59,6 @@ const QUIET_MS = 24 * 60 * 60_000
const LOOK_MIN_MS = 5_000
const TRANSCRIPT_MAX = 500
-/** `owner/name` from a GitHub address or the pair itself, or null. */
-export function repositoryOf(value: unknown): string | null {
- if (typeof value !== 'string') return null
- const match = /^(?:https:\/\/github\.com\/|git@github\.com:)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(value.trim())
- return match ? `${match[1]}/${match[2]}` : null
-}
-
/** A harness's name from its task: its first line, short. */
export function nameFor(task: string, agent: CloudAgentId): string {
const line = task.split('\n').map((part) => part.trim()).find(Boolean) ?? ''
@@ -245,12 +238,9 @@ export function startCloudService(options: CloudServiceOptions) {
const agent = request.engine
if (!isCloudAgent(agent)) return { ok: false, error: 'INVALID_ENGINE', detail: 'That is not a cloud agent.' }
const task = typeof request.prompt === 'string' ? request.prompt.trim() : ''
- if (!task) return { ok: false, error: 'INVALID_REQUEST', detail: `Tell ${CLOUD_AGENTS[agent].name} what to do.` }
+ const refusal = cloudRequestRefusal(agent, task, [request.repositoryUrl, request.repository])
+ if (refusal) return { ok: false, error: 'INVALID_REQUEST', detail: refusal }
const repository = repositoryOf(request.repositoryUrl) ?? repositoryOf(request.repository)
- // A repository given but not read (a GitLab address, a typo) is refused: started without it, the agent would work blind.
- if (!repository && (request.repositoryUrl || request.repository)) return { ok: false, error: 'INVALID_REQUEST', detail: 'That is not a GitHub repository: give owner/name or https://github.com/owner/name.' }
- const info: CloudAgentInfo = CLOUD_AGENTS[agent]
- if (info.kind === 'coding' && !info.repositoryOptional && !repository) return { ok: false, error: 'INVALID_REQUEST', detail: `Choose a GitHub repository for ${CLOUD_AGENTS[agent].name}.` }
const acuLimit = typeof request.acuLimit === 'number' && Number.isInteger(request.acuLimit) && request.acuLimit > 0 && request.acuLimit <= 1000 ? request.acuLimit : undefined
const model = typeof request.model === 'string' && request.model ? request.model.slice(0, 120) : undefined
let started: Awaited<ReturnType<CloudAdapter['start']>>
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index e5cabff33..55308ea64 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -1024,6 +1024,17 @@ describe('agent_resume and agent_restart', () => {
expect(await bare.relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'AGENT_NOT_FOUND' })
})
+ // Which check refused a resume's history (lib/resumeAgentService.ts) reaches the reply, so its counter can name it.
+ it('pass a refusal\'s reason on, directly and through a receipt', async () => {
+ const refused = { ok: false as const, error: 'RESUME_PREPARATION_FAILED', reason: 'invalid_json', detail: 'Could not prepare the saved conversation.' }
+ const direct = setup({}, { resume: vi.fn(async () => refused) })
+ expect(await direct.relaunch('agent_resume', { agentId: 'a1' })).toStrictEqual({ error: 'RESUME_PREPARATION_FAILED', reason: 'invalid_json', detail: 'Could not prepare the saved conversation.' })
+ const kept = setup({}, { resume: vi.fn(async () => refused) })
+ await kept.relaunch('agent_resume', { agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(kept.replies).toStrictEqual([{ creationId: CREATION, state: 'failed',
+ failure: { code: 'RESUME_PREPARATION_FAILED', reason: 'invalid_json', detail: 'Could not prepare the saved conversation.' } }]))
+ })
+
it('keep a receipt: one relaunch per creation id, an unobserved one unconfirmed, a refusal failed and cut short', async () => {
const { relaunch, replies, resume } = setup()
await relaunch('agent_resume', { agentId: 'a1', creationId: CREATION, permissionMode: 'auto' })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 2085c7de8..85df23634 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -48,7 +48,7 @@ export type ForkAgent = NonNullable<BackendSocket['onForkAgent']>
* actually resumed the prior conversation or had to fall back to a fresh one (core/agents/restart.ts). */
export type RestartAgent = (agentId: string) => Promise<
{ ok: true; session: RegisteredSession; resumed: boolean }
- | { ok: false; error: string; detail?: string }
+ | { ok: false; error: string; detail?: string; reason?: string }
>
/** Resumes stopped work directly, or attaches if it is already running. Never replaces a live process
* and never falls back to a fresh conversation (core/agents/lifecycle.ts). */
@@ -259,7 +259,8 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// so clients can distinguish "safe to correct the choices" from "outcome still unknown".
if (status.state === 'failed') {
return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error,
- ...(status.detail ? { detail: status.detail } : {}), ...(status.existingFolder ? { existingFolder: status.existingFolder } : {}) } }
+ ...(status.reason ? { reason: status.reason } : {}), ...(status.detail ? { detail: status.detail } : {}),
+ ...(status.existingFolder ? { existingFolder: status.existingFolder } : {}) } }
}
return status
}
@@ -575,7 +576,8 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// RESTART_FAILED can follow an unobserved relaunch. Never silently
// replace that process again when a caller checks this intent.
if (result.error === 'RESTART_FAILED' || result.error === 'RESUME_UNCONFIRMED') return { state: 'unconfirmed' }
- return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ return { state: 'failed', error: result.error, ...(result.reason ? { reason: result.reason } : {}),
+ ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
}).then(async (status) => {
reply({ creationId, ...await creationStatusPayload(status) })
}).catch(() => reply({ error: 'INTERNAL' }))
@@ -586,7 +588,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
}
const result = await invoke()
if (!result.ok) {
- reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
+ reply({ error: result.error, ...(result.reason ? { reason: result.reason } : {}), ...(result.detail ? { detail: result.detail } : {}) })
return
}
reply({ agent: await toProject(result.session), resumed: result.resumed })
diff --git a/cli/src/engines/kit/resumeRepair.spec.ts b/cli/src/engines/kit/resumeRepair.spec.ts
index 0e7a45dc3..fdfcdd269 100644
--- a/cli/src/engines/kit/resumeRepair.spec.ts
+++ b/cli/src/engines/kit/resumeRepair.spec.ts
@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { launch as codex } from '../codex/launch.js'
import { prepareResume as prepareCodexResume } from '../launchPrep.js'
-import { repairHistoryText } from './resumeRepair.js'
+import { repairHistoryText, ResumePreparationError } from './resumeRepair.js'
// The former engines/codex/portableHistory.spec.ts, its cases unchanged, against Codex's declared repair
// (`resumeRepair` in codex/launch.ts) applied by the kit, through the composition the resume calls.
@@ -26,6 +26,14 @@ const badReasoning = () => ({ type: 'reasoning', id: BAD_ID, summary, content: [
const message = { type: 'message', id: BAD_ID, role: 'assistant', content: [{ type: 'output_text', text: 'Hello.' }] }
const history = (...items: unknown[]) => [meta, ...items.map(item => record('response_item', item)), ''].join('\n')
const payloads = (value: string) => value.trim().split('\n').slice(1).map(line => JSON.parse(line).payload)
+/** The typed refusal `run` throws: its kind says which check refused, for the resume reply and its counters. */
+function refusal(run: () => unknown): ResumePreparationError {
+ try { run() } catch (error) {
+ expect(error).toBeInstanceOf(ResumePreparationError)
+ return error as ResumePreparationError
+ }
+ throw new Error('expected a refusal')
+}
describe('Codex reasoning history portability', () => {
it('repairs the screenshot pair without changing the answer, its id, or the reasoning summary', () => {
@@ -72,6 +80,19 @@ describe('Codex reasoning history portability', () => {
})
})
+describe('a half-written last line in history text', () => {
+ it('passes it through and repairs the lines before it', () => {
+ const tail = '{"type":"respo'
+ const result = portableCodexHistory(history(badReasoning()) + tail, SESSION)
+ expect(result.repairedItems).toBe(1)
+ expect(result.history.endsWith('\n' + tail)).toBe(true)
+ })
+
+ it('still refuses it once a newline follows', () => {
+ expect(() => portableCodexHistory(history(badReasoning()) + '{"type":"respo\n', SESSION)).toThrow(ResumePreparationError)
+ })
+})
+
describe('preparing a stopped Codex session for resume', () => {
let profile: string
let file: string
@@ -162,7 +183,7 @@ describe('preparing a stopped Codex session for resume', () => {
if (!changed) { changed = true; writeFileSync(file, appended, { flag: 'a' }) }
return read
})
- expect(() => prepareCodexResume(source())).toThrow('changed during resume preparation')
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'changed_during', message: expect.stringContaining('changed during resume preparation') })
expect(readFileSync(file, 'utf8')).toBe(history(badReasoning()) + appended)
expect(readdirSync(join(profile, 'sessions', '2026', '09', '15'))).toHaveLength(1)
})
@@ -178,14 +199,63 @@ describe('preparing a stopped Codex session for resume', () => {
expect(payloads(readFileSync(file, 'utf8'))[0]).not.toHaveProperty('id')
})
- it.each(['invalid JSON', '{"type":"response_item","payload":'])('does not rewrite or back up a partial or invalid rollout (%s)', (invalid) => {
- const original = history(badReasoning()) + invalid
+ // A broken record that ends in a newline was finished that way: not what an interrupted writer leaves.
+ it.each(['invalid JSON', '{"type":"response_item","payload":'])('does not rewrite or back up a rollout with a broken complete line (%s)', (invalid) => {
+ const original = history(badReasoning()) + invalid + '\n'
writeFileSync(file, original)
- expect(() => prepareCodexResume(source())).toThrow()
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'invalid_json', message: `invalid JSON in Codex rollout at line 3` })
expect(readFileSync(file, 'utf8')).toBe(original)
expect(readdirSync(join(profile, 'sessions', '2026', '09', '15'))).toHaveLength(1)
})
+ it('refuses invalid JSON in the middle of a rollout, whatever its end', () => {
+ const original = [meta, 'not json', record('response_item', badReasoning()), '{"type":"respo'].join('\n')
+ writeFileSync(file, original)
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'invalid_json', message: 'invalid JSON in Codex rollout at line 2' })
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ })
+
+ // An interrupted Codex leaves its last record half written; that refused the whole conversation (Oct 26 report).
+ it('keeps a half-written last line as it is and repairs the rest', () => {
+ const tail = '{"type":"respo'
+ const original = history(badReasoning(), message) + tail
+ writeFileSync(file, original)
+ const logged = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const result = prepareCodexResume(source())
+ expect(result.repairedItems).toBe(1)
+ const repaired = readFileSync(file, 'utf8')
+ expect(repaired.endsWith('\n' + tail)).toBe(true)
+ expect(payloads(repaired.slice(0, -tail.length))).toEqual([{ type: 'reasoning', summary, content: [] }, message])
+ expect(readFileSync(result.backupPath!, 'utf8')).toBe(original)
+ expect(logged.mock.calls.map(call => String(call[0]))).toEqual(['[resume] Codex rollout ended in a partial line; kept as is'])
+ })
+
+ it('keeps a half-written last line of a rollout that needs no repair, without rewriting it', () => {
+ const original = history(message) + '{"type":"response_item","payload":{"type":"message","content":"secret'
+ writeFileSync(file, original)
+ const logged = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const before = statSync(file)
+ expect(prepareCodexResume(source())).toEqual({ repairedItems: 0 })
+ expect(statSync(file).ino).toBe(before.ino)
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ // The log names the file, never the conversation's text.
+ expect(logged.mock.calls.flat().join(' ')).not.toContain('secret')
+ })
+
+ it('leaves a complete last record without a newline alone', () => {
+ const original = history(message).trimEnd()
+ writeFileSync(file, original)
+ const logged = vi.spyOn(console, 'log').mockImplementation(() => {})
+ expect(prepareCodexResume(source())).toEqual({ repairedItems: 0 })
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ expect(logged).not.toHaveBeenCalled()
+ })
+
+ it('still refuses a rollout whose only line is half written: it has no session record', () => {
+ writeFileSync(file, '{"timestamp":"2026-09-15T06:43:10.580Z","type":"session_me')
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'foreign_session', message: 'Codex rollout has no session metadata' })
+ })
+
// A person who moved CODEX_HOME in their shell profile keeps their rollouts there, and an agent of theirs
// names no profile of its own. The rollout was held to the daemon's own CODEX_HOME, refused as "outside the
// session profile", and every restart or reopen of that agent failed after its engine had been stopped.
@@ -215,7 +285,7 @@ describe('preparing a stopped Codex session for resume', () => {
it('refuses a different session instead of modifying the wrong history', () => {
const original = history(badReasoning())
writeFileSync(file, original)
- expect(() => prepareCodexResume({ ...source(), sessionId: 'another-session' })).toThrow('does not belong')
+ expect(refusal(() => prepareCodexResume({ ...source(), sessionId: 'another-session' }))).toMatchObject({ kind: 'foreign_session', message: 'Codex rollout does not belong to the session being resumed' })
expect(readFileSync(file, 'utf8')).toBe(original)
})
@@ -224,11 +294,30 @@ describe('preparing a stopped Codex session for resume', () => {
const original = history(badReasoning())
writeFileSync(outside, original)
symlinkSync(outside, file)
- expect(() => prepareCodexResume(source())).toThrow('outside the session profile')
- expect(() => prepareCodexResume({ ...source(), transcriptPath: outside })).toThrow('outside the session profile')
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'not_owned_file', message: expect.stringContaining('outside the session profile') })
+ expect(refusal(() => prepareCodexResume({ ...source(), transcriptPath: outside }))).toMatchObject({ kind: 'not_owned_file' })
expect(readFileSync(outside, 'utf8')).toBe(original)
})
+ it('refuses a rollout whose first record is not its session record', () => {
+ writeFileSync(file, [record('response_item', message), meta, ''].join('\n'))
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'foreign_session' })
+ })
+
+ it('refuses a record that is JSON but not an object', () => {
+ writeFileSync(file, [meta, '[1,2]', ''].join('\n'))
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'invalid_json', message: 'invalid Codex rollout record' })
+ })
+
+ it('names a failed write as another kind of refusal, and keeps the original', () => {
+ const original = history(badReasoning())
+ writeFileSync(file, original)
+ vi.spyOn(fs, 'writeSync').mockReturnValue(0)
+ expect(refusal(() => prepareCodexResume(source()))).toMatchObject({ kind: 'other', message: 'Could not write the prepared Codex history' })
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ expect(readdirSync(join(profile, 'sessions', '2026', '09', '15'))).toHaveLength(1)
+ })
+
it('leaves other engines, fresh sessions, and missing histories to the existing launch path', () => {
expect(prepareCodexResume({ ...source(), engine: 'claude' })).toEqual({ repairedItems: 0 })
expect(prepareCodexResume({ ...source(), sessionId: '' })).toEqual({ repairedItems: 0 })
diff --git a/cli/src/engines/kit/resumeRepair.ts b/cli/src/engines/kit/resumeRepair.ts
index 62a91b823..9f3cca32a 100644
--- a/cli/src/engines/kit/resumeRepair.ts
+++ b/cli/src/engines/kit/resumeRepair.ts
@@ -9,6 +9,7 @@ import { createHash, randomUUID } from 'node:crypto'
import { closeSync, constants, fsyncSync, fstatSync, lstatSync, openSync, readSync, realpathSync, renameSync, rmSync, writeSync, type Stats } from 'node:fs'
import { isAbsolute, join, relative } from 'node:path'
import type { ResumeRepairContract } from '../facets/launch.js'
+import type { ResumePreparationKind } from '../../lib/productHealthContract.js'
import { findSessionFile } from './sessionRecords.js'
type JsonObject = Record<string, unknown>
@@ -51,6 +52,18 @@ function valueAt(record: JsonObject, path: readonly string[]): unknown {
return value
}
+/**
+ * Why a history could not be prepared, by which check refused it: the resume reply and its counters carry the kind
+ * (lib/resumeAgentService.ts). On 2026-10-26, 10 of 17 failed resumes were a preparation failure and nothing said
+ * which. The message names the file and a line number only, never conversation text.
+ */
+export class ResumePreparationError extends Error {
+ constructor(readonly kind: ResumePreparationKind, message: string) {
+ super(message)
+ this.name = 'ResumePreparationError'
+ }
+}
+
/** Shared by the string helper and the file reader, which retains only one record at a time. */
function historyRepair(contract: ResumeRepairContract, sessionId: string) {
const repair = REPAIRS[contract.repair]
@@ -58,19 +71,24 @@ function historyRepair(contract: ResumeRepairContract, sessionId: string) {
let sawFirst = false
let repairedItems = 0
let lineNumber = 0
- const line = (line: string): string => {
+ let partialTail = false
+ /** `last`: the final line, with no newline after it. */
+ const line = (line: string, last = false): string => {
lineNumber++
if (!line.trim()) return line
let record: unknown
try { record = JSON.parse(line) } catch {
+ // An interrupted engine leaves its last record half written, and refusing it refused the whole
+ // conversation (Oct 26 report). It is kept byte for byte: the engine reads its own file as it left it.
+ if (last) { partialTail = true; return line }
// JSON.parse's own error can quote conversation text; keep it out of daemon logs.
- throw new Error(`invalid JSON in ${file} at line ${lineNumber}`)
+ throw new ResumePreparationError('invalid_json', `invalid JSON in ${file} at line ${lineNumber}`)
}
- if (!object(record)) throw new Error(`invalid ${file} record`)
+ if (!object(record)) throw new ResumePreparationError('invalid_json', `invalid ${file} record`)
if (!sawFirst) {
// The id is never empty (the caller returns before), so a record with no such field never matches.
if (record.type !== contract.first.type || valueAt(record, contract.first.id) !== sessionId) {
- throw new Error(`${file} does not belong to the session being resumed`)
+ throw new ResumePreparationError('foreign_session', `${file} does not belong to the session being resumed`)
}
sawFirst = true
}
@@ -83,22 +101,24 @@ function historyRepair(contract: ResumeRepairContract, sessionId: string) {
}
return changed ? JSON.stringify(record) + (line.endsWith('\r') ? '\r' : '') : line
}
- return { line, finish: () => {
- if (!sawFirst) throw new Error(`${file} has no session metadata`)
+ return { line, partialTail: () => partialTail, finish: () => {
+ if (!sawFirst) throw new ResumePreparationError('foreign_session', `${file} has no session metadata`)
return repairedItems
} }
}
/** Only replayed items are repaired. Other records (including readable event history) and unchanged lines
- * retain their exact bytes. Invalid JSON aborts the whole repair. */
+ * retain their exact bytes. Invalid JSON aborts the whole repair, except in a final line with no newline. */
export function repairHistoryText(contract: ResumeRepairContract, history: string, sessionId: string): { history: string; repairedItems: number } {
const repair = historyRepair(contract, sessionId)
- const lines = history.split('\n').map(repair.line)
+ const parts = history.split('\n')
+ const lines = parts.map((line, index) => repair.line(line, index === parts.length - 1))
return { history: lines.join('\n'), repairedItems: repair.finish() }
}
const READ_BYTES = 64 * 1024
-const changedDuring = (contract: ResumeRepairContract) => new Error(`${contract.names.file} changed during resume preparation; retry after its writer stops`)
+const changedDuring = (contract: ResumeRepairContract) =>
+ new ResumePreparationError('changed_during', `${contract.names.file} changed during resume preparation; retry after its writer stops`)
function sameFile(a: Stats, b: Stats): boolean {
return b.isFile() && a.ino === b.ino && a.dev === b.dev && a.size === b.size
@@ -118,7 +138,7 @@ function scanHistory(contract: ResumeRepairContract, fd: number, size: number, s
const line = (bytes: Buffer) => {
const newline = bytes.at(-1) === 10
const original = bytes.subarray(0, bytes.length - (newline ? 1 : 0)).toString('utf8')
- const repaired = repair.line(original)
+ const repaired = repair.line(original, !newline)
const output = repaired === original ? bytes : Buffer.from(repaired + (newline ? '\n' : ''))
repairedBytes += output.length
emit?.(bytes, output)
@@ -144,14 +164,14 @@ function scanHistory(contract: ResumeRepairContract, fd: number, size: number, s
if (start < count) fragments.push(Buffer.from(chunk.subarray(start, count)))
}
if (fragments.length) line(Buffer.concat(fragments))
- return { repairedItems: repair.finish(), repairedBytes, digest: hash.digest('hex') }
+ return { repairedItems: repair.finish(), repairedBytes, digest: hash.digest('hex'), partialTail: repair.partialTail() }
}
function writeAll(contract: ResumeRepairContract, fd: number, bytes: Buffer): void {
let written = 0
while (written < bytes.length) {
const count = writeSync(fd, bytes, written, bytes.length - written)
- if (!count) throw new Error(`Could not write the prepared ${contract.names.history}`)
+ if (!count) throw new ResumePreparationError('other', `Could not write the prepared ${contract.names.history}`)
written += count
}
}
@@ -188,7 +208,7 @@ export function repairHistory(contract: ResumeRepairContract, sessionId: string,
})
if (!before.isFile() || before.isSymbolicLink() || !inside
|| (typeof process.getuid === 'function' && before.uid !== process.getuid())) {
- throw new Error(`${contract.names.file} is outside the session profile or is not an owned regular file`)
+ throw new ResumePreparationError('not_owned_file', `${contract.names.file} is outside the session profile or is not an owned regular file`)
}
const input = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW)
try {
@@ -198,6 +218,7 @@ export function repairHistory(contract: ResumeRepairContract, sessionId: string,
unchanged()
const inspected = scanHistory(contract, input, before.size, sessionId)
unchanged()
+ if (inspected.partialTail) console.log(`[resume] ${contract.names.file} ended in a partial line; kept as is`)
if (!inspected.repairedItems) return { repairedItems: 0 }
const suffix = randomUUID()
diff --git a/cli/src/gateway/productUsage.spec.ts b/cli/src/gateway/productUsage.spec.ts
index 0fa72490b..75a931f75 100644
--- a/cli/src/gateway/productUsage.spec.ts
+++ b/cli/src/gateway/productUsage.spec.ts
@@ -462,6 +462,28 @@ it('names the code of an `other` launch failure, so the codes add up to launch_f
expect(JSON.stringify(sent)).not.toContain('PRIVATE_CANARY')
})
+it('counts correct refusals and agents\' launches apart from people\'s failures', async () => {
+ await usage.sync()
+ usage.launch({ id: 'fixture-agent-refused', phase: 'start', agentStarted: true })
+ for (let poll = 0; poll < 2; poll++) usage.launch({ id: 'fixture-agent-refused', phase: 'refused', code: 'session_in_harness' })
+ usage.launch({ id: 'fixture-person-failed', phase: 'start' })
+ usage.launch({ id: 'fixture-person-failed', phase: 'failed', failure: 'setup', code: 'spawn_failed' })
+ usage.launch({ id: 'fixture-agent-created', phase: 'start', agentStarted: true })
+ usage.launch({ id: 'fixture-agent-created', phase: 'created' })
+ usage.launch({ id: 'fixture-agent-failed-1', phase: 'start', agentStarted: true })
+ usage.launch({ id: 'fixture-agent-failed-1', phase: 'failed', failure: 'other', code: 'internal' })
+ usage.launch({ id: 'fixture-person-refused', phase: 'start' })
+ usage.launch({ id: 'fixture-person-refused', phase: 'refused', code: 'PRIVATE_CANARY' as never })
+ await flush()
+ const t = totals()
+ expect(t).toMatchObject({ launch_started: 5, launch_agent_started: 3, launch_refused: 2, launch_agent_refused: 1,
+ launch_refused_code_session_in_harness: 1, launch_refused_code_unlisted: 1, launch_failed: 2, launch_agent_failed: 1,
+ launch_created: 1, launch_agent_created: 1 })
+ // A refusal is no failure of either kind, and the failure kinds still add up to launch_failed.
+ expect(t.launch_failed_setup + t.launch_failed_other).toBe(t.launch_failed)
+ expect(JSON.stringify(sent)).not.toContain('PRIVATE_CANARY')
+})
+
it('counts a setup launch reason once across polls, separately from other failures and without retaining identifiers', async () => {
await usage.sync()
for (const [index, code] of ['tmux_unavailable', 'native_launch_held', 'PRIVATE_CANARY' as never].entries()) {
diff --git a/cli/src/gateway/productUsage.ts b/cli/src/gateway/productUsage.ts
index b5245538c..85151ff12 100644
--- a/cli/src/gateway/productUsage.ts
+++ b/cli/src/gateway/productUsage.ts
@@ -117,7 +117,7 @@ export function createProductUsage(deps: ProductUsageDeps) {
let choiceKnown = false, tuiHeld: ProductUsageMetric[] = [], tuiRefusedDay: string | null = null
const tuiRefused = (): boolean => tuiRefusedDay === key(now())
const running = new Map<string, { started: number; response: boolean; error: boolean; waited: boolean }>()
- const launches = new Map<string, { started: number; done: boolean; waits: Set<string> }>()
+ const launches = new Map<string, { started: number; done: boolean; waits: Set<string>; agent: boolean }>()
/** The agents of created launches still starting, by agent id (RAM only), with when each was created. */
const starting = new Map<string, number>()
const forget = (): void => { running.clear(); launches.clear(); starting.clear() }
@@ -440,7 +440,10 @@ export function createProductUsage(deps: ProductUsageDeps) {
if (!launches.get(oldest)!.done) add('launch_unobserved')
launches.delete(oldest)
}
- launches.set(signal.id, { started: now(), done: false, waits: new Set() }); add('launch_started'); return
+ const agent = signal.agentStarted === true
+ launches.set(signal.id, { started: now(), done: false, waits: new Set(), agent }); add('launch_started')
+ if (agent) add('launch_agent_started')
+ return
}
const launch = launches.get(signal.id)
if (!launch || launch.done) return
@@ -449,9 +452,13 @@ export function createProductUsage(deps: ProductUsageDeps) {
if (!launch.waits.has(wait)) { launch.waits.add(wait); add(`launch_wait_${wait}` as ProductUsageMetric) }
return
}
- if (!['created', 'failed', 'cancelled', 'unconfirmed'].includes(signal.phase)) return
+ if (!['created', 'failed', 'refused', 'cancelled', 'unconfirmed'].includes(signal.phase)) return
launch.done = true
add(`launch_${signal.phase}` as ProductUsageMetric)
+ // Agents' and Swarms' launches, counted again: since Oct 21 there are many more of them, and they moved a rate
+ // people read as a person's. A person's own are the total less these.
+ if (launch.agent && ['created', 'failed', 'refused'].includes(signal.phase)) add(`launch_agent_${signal.phase}` as ProductUsageMetric)
+ if (signal.phase === 'refused') add(`launch_refused_code_${listed(signal.code)}`)
if (signal.phase === 'failed') {
const kind = ['setup', 'auth', 'unavailable', 'invalid'].includes(signal.failure ?? '') ? signal.failure! : 'other'
add(`launch_failed_${kind}` as ProductUsageMetric)
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index 61059b411..12fe923c6 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -7,7 +7,8 @@ import type { LaunchModel } from './launchModel.js'
export type AgentCreationOutcome =
| { state: 'created'; agentId: string; level?: 'native' | 'handoff'; resumed?: boolean }
- | { state: 'failed'; error: string; detail?: string; preparedFolder?: string; existingFolder?: string }
+ // `reason`: which check a refusal failed, where its code has several (a resume's RESUME_PREPARATION_FAILED).
+ | { state: 'failed'; error: string; detail?: string; reason?: string; preparedFolder?: string; existingFolder?: string }
| { state: 'unconfirmed' }
export type AgentCreationStatus = AgentCreationOutcome
diff --git a/cli/src/lib/cloudAgents.ts b/cli/src/lib/cloudAgents.ts
index d2d551573..0b3b7dae9 100644
--- a/cli/src/lib/cloudAgents.ts
+++ b/cli/src/lib/cloudAgents.ts
@@ -47,6 +47,29 @@ export function isCloudAgent(id: unknown): id is CloudAgentId {
return typeof id === 'string' && Object.hasOwn(CLOUD_AGENTS, id)
}
+/** `owner/name` from a GitHub address or the pair itself, or null. */
+export function repositoryOf(value: unknown): string | null {
+ if (typeof value !== 'string') return null
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(value.trim())
+ return match ? `${match[1]}/${match[2]}` : null
+}
+
+/**
+ * Why a cloud agent cannot start this task, in the words a person reads, or null when it can. The cloud service
+ * answers with it (cloud/service.ts) and `harness new` refuses with it before sending (lib/newCommand.ts): a typo
+ * there reached the service and came back a counted launch failure (Oct 26 report). [repositories] are the ways a
+ * request names one, the first that reads winning.
+ */
+export function cloudRequestRefusal(agent: CloudAgentId, task: string, repositories: readonly unknown[]): string | null {
+ const info: CloudAgentInfo = CLOUD_AGENTS[agent]
+ if (!task.trim()) return `Tell ${info.name} what to do.`
+ const repository = repositories.map(repositoryOf).find(Boolean)
+ // A repository given but not read (a GitLab address, a typo) is refused: started without it, the agent would work blind.
+ if (!repository && repositories.some(Boolean)) return 'That is not a GitHub repository: give owner/name or https://github.com/owner/name.'
+ if (info.kind === 'coding' && !info.repositoryOptional && !repository) return `Choose a GitHub repository for ${info.name}.`
+ return null
+}
+
/** Where a cloud harness is: working, waiting on the person, done with its turn, failed, or stopped. */
export type CloudState = 'starting' | 'working' | 'needs_input' | 'idle' | 'failed' | 'stopped'
export const CLOUD_STATES: readonly CloudState[] = ['starting', 'working', 'needs_input', 'idle', 'failed', 'stopped']
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index a9de19faf..c1e553cc2 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -312,6 +312,29 @@ describe('harness new: the daemon', () => {
expect(here.out.at(-1)).toBe('Open it in Harness with ⌘O.')
})
+ // A typo used to reach the cloud service and come back a counted launch failure (Oct 26 report): refused here, in
+ // the service's own words, before anything is sent.
+ it.each([
+ [['cursor-cloud'], 'Tell Cursor Cloud what to do.'],
+ [['cursor-cloud', '--', ' '], 'Tell Cursor Cloud what to do.'],
+ [['cursor-cloud', '--repo', 'gitlab.com/a/b', '--', 'x'], 'That is not a GitHub repository: give owner/name or https://github.com/owner/name.'],
+ [['cursor-cloud', '--', 'x'], 'Choose a GitHub repository for Cursor Cloud.'],
+ [['fo'], 'Tell Fo what to do.'],
+ ])('refuses a cloud request the service would refuse, sending nothing: %j', async (argv, words) => {
+ expect(() => parseNewArgs(argv, env)).toThrow(new NewUsageError(words))
+ const socket = new FakeSocket(() => null)
+ const refused = deps(argv, socket)
+ expect(await newCommand(refused)).toBe(2)
+ expect(refused.err[0]).toBe(words)
+ expect(socket.sent).toEqual([])
+ })
+
+ it('lets Devin Cloud start without a repository, and a cloud agent with one', () => {
+ expect(parseNewArgs(['devin-cloud', '--', 'x'], env)).toMatchObject({ agent: 'devin-cloud', prompt: 'x', repo: null })
+ expect(parseNewArgs(['cursor-cloud', '--repo', 'https://github.com/acme/api', '--', 'x'], env)).toMatchObject({ repo: 'https://github.com/acme/api' })
+ expect(parseNewArgs(['fo', '--task', 'book a table'], env)).toMatchObject({ agent: 'fo', prompt: 'book a table' })
+ })
+
it('refuses the old @machine before asking anything of a machine, and says what to type', async () => {
const socket = new FakeSocket(() => null)
const old = deps(['claude', '@office', 'lamp-first-task', '--', 'What is 2+2?'], socket)
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 3430bb935..1950d5384 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -7,7 +7,7 @@ import { formatNext, type NextStep } from '../agentClient/next.js'
import { folderTrust } from '../engines/launchPrep.js'
import { ENGINES, type AgentEngine } from '../engines/types.js'
import { engineName } from '../messages/model.js'
-import { isCloudAgent } from './cloudAgents.js'
+import { cloudRequestRefusal, isCloudAgent } from './cloudAgents.js'
import { projectFolderSlug } from './agentNames.js'
import { permissionModeFlags } from './engineLaunch.js'
import { projectsRoot } from './projectFolder.js'
@@ -171,6 +171,9 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string; p
if ((repo !== null || acuLimit !== null) && !isCloudAgent(words[0])) {
throw new NewUsageError(`${repo !== null ? '--repo' : '--acu-limit'} is for a cloud agent: harness new devin-cloud ${repo !== null ? '--repo owner/name' : '--acu-limit 10'} -- <task>`)
}
+ // What the cloud service would refuse, refused before anything is sent, in its words.
+ const cloudRefusal = isCloudAgent(words[0]) ? cloudRequestRefusal(words[0], prompt ?? '', [repo]) : null
+ if (cloudRefusal) throw new NewUsageError(cloudRefusal)
if (!MODES.has(mode)) throw new NewUsageError(`--mode is one of ${[...MODES].join(', ')}.`)
if (words.length > 2) throw new NewUsageError(`Too many words: ${words.slice(2).join(' ')}.`)
if (words[1] !== undefined) {
diff --git a/cli/src/lib/productHealthContract.ts b/cli/src/lib/productHealthContract.ts
index d902c6b2c..b54c01d5a 100644
--- a/cli/src/lib/productHealthContract.ts
+++ b/cli/src/lib/productHealthContract.ts
@@ -45,10 +45,15 @@ export type CliReportFailure = typeof CLI_REPORT_FAILURES[number]
export const RESUME_REASONS = ['runtime_unavailable', 'saved_state_missing', 'project_missing', 'harness_missing',
'credentials_missing', 'busy', 'changed', 'unconfirmed', 'preparation_failed', 'launch_failed', 'invalid', 'other'] as const
export type ResumeReason = typeof RESUME_REASONS[number]
+/** Which check refused a resume's history preparation (cli/src/engines/kit/resumeRepair.ts): on 2026-10-26, 10 of
+ * 17 failed resumes were `preparation_failed` and nothing said why. Counted beside `resume_reason_preparation_failed`. */
+export const RESUME_PREPARATION_KINDS = ['invalid_json', 'foreign_session', 'not_owned_file', 'changed_during', 'other'] as const
+export type ResumePreparationKind = typeof RESUME_PREPARATION_KINDS[number]
export const PRODUCT_HEALTH_METRICS = [
...CLI_REPORT_FAILURES.map(reason => `health_cli_report_failure_${reason}` as const),
...CLI_REPORT_FAILURES.map(reason => `health_desktop_report_failure_${reason}` as const),
...HEALTH_SOURCES.flatMap(source => RESUME_REASONS.map(reason => `request_${source}_resume_reason_${reason}` as const)),
+ ...HEALTH_SOURCES.flatMap(source => RESUME_PREPARATION_KINDS.map(kind => `request_${source}_resume_preparation_${kind}` as const)),
// hn's (`tui`) come through its daemon's queue, under that daemon's context, never one of their own.
...(['cli', 'desktop', 'tui'] as const).flatMap(surface => HEALTH_MEASURES.map(m => `health_${surface}_${m}` as const)),
// The phone reports only its coverage (the threshold its breakdowns need) and late deliveries.
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index 3f47c79f1..7f1303c23 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -171,10 +171,11 @@ export type LaunchErrorCode = typeof LAUNCH_ERROR_CODES[number]
* and resume requests' `other` refusals, and every delete and restart refusal — from any client, and again,
* apart, those the phone asked for (`phone_`), which a daemon's report otherwise carries mixed with the
* Desktop's, the TUI's and tools'. Setup reasons have their own families, adding up to `launch_failed_setup`,
- * `create_error_setup` and `request_phone_create_error_setup`; existing `other` families keep their meaning. */
+ * `create_error_setup` and `request_phone_create_error_setup`; existing `other` families keep their meaning.
+ * `launch_refused_code` names which correct refusal a `launch_refused` was (cli/src/lib/productUsageSignals.ts). */
export const LAUNCH_ERROR_FAMILIES = ['launch_failed_code', 'launch_late_failed_code', 'create_error_code', 'resume_error_code',
'delete_error_code', 'restart_error_code', 'phone_delete_error_code', 'phone_restart_error_code',
- 'launch_failed_setup_code', 'create_error_setup_code', 'phone_create_error_setup_code'] as const
+ 'launch_failed_setup_code', 'create_error_setup_code', 'phone_create_error_setup_code', 'launch_refused_code'] as const
/** The engine an installation's first launch asked for; any other engine is `other`. */
export const PRODUCT_USAGE_LAUNCH_ENGINES = ['opencode', 'claude', 'codex', 'other'] as const
export type ProductUsageLaunchEngine = typeof PRODUCT_USAGE_LAUNCH_ENGINES[number]
@@ -200,6 +201,11 @@ export const PRODUCT_USAGE_METRICS = [
'launch_started', 'launch_created', 'launch_failed', 'launch_cancelled', 'launch_unconfirmed', 'launch_unobserved',
// A created launch whose engine then did not start: one of the launch_created, never also a launch_failed.
'launch_late_failed',
+ // A create turned down because the request was wrong, not because Harness failed (the Oct 26 report counted
+ // opening a conversation that is already a harness, and a cloud agent with no task, as failures): never also
+ // a launch_failed. The agent twins count the launches an agent or a Swarm started (the create's `startedBy`),
+ // so a person's own launches are the total less those.
+ 'launch_refused', 'launch_agent_started', 'launch_agent_created', 'launch_agent_failed', 'launch_agent_refused',
'launch_wait_install', 'launch_wait_model', 'launch_wait_native', 'launch_wait_other',
'launch_failed_setup', 'launch_failed_auth', 'launch_failed_unavailable', 'launch_failed_invalid', 'launch_failed_other',
'launch_under_10s', 'launch_10s_to_1m', 'launch_1m_to_5m', 'launch_over_5m',
diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.ts
index d34f8efef..64f3ae266 100644
--- a/cli/src/lib/productUsageSignals.spec.ts
+++ b/cli/src/lib/productUsageSignals.spec.ts
@@ -81,6 +81,8 @@ it('ignores arbitrary RPC names and status polling and survives unavailable repo
expect(() => productUsageRequest('agent_create', () => { throw Error('offline') })(undefined, 'created', true)).not.toThrow()
})
+const ID = 'fixture-creation-one'
+
it('reduces durable launch statuses to fixed categories without forwarding error or hold text', () => {
const emit = vi.fn(), id = 'fixture-creation-one'
productUsageLaunch('agent_create', id, emit)(undefined, 'pending', false, 'install')
@@ -105,6 +107,28 @@ it.each(['ENGINE_LAUNCH_REFUSED', 'PTY_HOST_UNAVAILABLE', 'GIT_PROJECT_UNAVAILAB
'INVALID_BRANCH', 'BRANCH_SWITCH_FAILED', 'BRANCH_IN_USE', 'WORKTREE_FAILED'])('names the launch helper refusal %s', code => {
expect(launchErrorCode(code)).toBe(code.toLowerCase())
})
+// Opening a conversation that is already a harness, or a cloud agent with no task, is the request turned down, not
+// Harness failing: the Oct 26 report counted them as launch failures.
+it.each(['SESSION_IN_HARNESS', 'SESSION_OPEN_ELSEWHERE', 'SESSION_OPEN_IN_TERMINAL', 'SESSION_BUSY_IN_TERMINAL', 'INVALID_REQUEST'])(
+ 'counts the correct refusal %s as refused, not as a launch failure', error => {
+ const emit = vi.fn()
+ productUsageLaunch('agent_create', ID, emit)(error, undefined, false, undefined)
+ productUsageLaunch('agent_create_status', ID, emit)(error, 'failed', false, undefined)
+ const refused = { id: ID, phase: 'refused', code: error.toLowerCase() }
+ expect(emit.mock.calls.flat().slice(1)).toEqual([refused, refused])
+ })
+it('still counts a failure that is no refusal as failed', () => {
+ const emit = vi.fn()
+ productUsageLaunch('agent_create_status', ID, emit)('SPAWN_FAILED', 'failed', false, undefined)
+ expect(emit).toHaveBeenCalledWith({ id: ID, phase: 'failed', failure: 'setup', code: 'spawn_failed' })
+})
+it('marks a launch an agent started, and only that one', () => {
+ const emit = vi.fn()
+ productUsageLaunch('agent_create', ID, emit, 'claude', true)
+ productUsageLaunch('agent_create', ID, emit, 'claude')
+ expect(emit.mock.calls.flat()).toEqual([{ id: ID, phase: 'start', engine: 'claude', agentStarted: true }, { id: ID, phase: 'start', engine: 'claude' }])
+})
+
it('keeps a setup refusal\'s fixed code for the separate setup diagnostic, leaving other kinds alone', () => {
const emit = vi.fn()
productUsageLaunch('agent_create_status', 'fixture-creation-one', emit)('TMUX_UNAVAILABLE', 'failed', false, undefined)
@@ -351,6 +375,21 @@ it.each([
for (const name of names) expect(PRODUCT_USAGE_METRICS).toContain(name)
expect(JSON.stringify(names)).not.toContain(error)
})
+it('counts which check refused a resume\'s preparation, once, by a fixed name', () => {
+ const counted = (preparation?: unknown) => {
+ const emit = vi.fn(), done = productUsageRequest('agent_resume', emit, () => 0, 'app')
+ done('RESUME_PREPARATION_FAILED', undefined, false, false, undefined, preparation)
+ done('RESUME_PREPARATION_FAILED', undefined, false, false, undefined, preparation)
+ return emit.mock.calls.flat().filter(name => String(name).startsWith('request_app_resume_preparation_') || name === 'request_app_resume_reason_preparation_failed')
+ }
+ expect(counted('invalid_json')).toEqual(['request_app_resume_reason_preparation_failed', 'request_app_resume_preparation_invalid_json'])
+ expect(counted('/PRIVATE/path')).toEqual(['request_app_resume_reason_preparation_failed', 'request_app_resume_preparation_other'])
+ expect(counted()).toEqual(['request_app_resume_reason_preparation_failed'])
+ // Only a preparation failure names a kind: another refusal's reason is not one.
+ const emit = vi.fn()
+ productUsageRequest('agent_resume', emit, () => 0, 'app')('AGENT_BUSY', undefined, false, false, undefined, 'invalid_json')
+ expect(emit.mock.calls.flat().filter(name => String(name).includes('_preparation_'))).toEqual([])
+})
it.each([
['RESUME_UNCONFIRMED', undefined, 'unconfirmed', 'unknown'],
[undefined, 'unconfirmed', 'unconfirmed', 'unknown'],
diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.ts
index ae8a0d326..2469ffb90 100644
--- a/cli/src/lib/productUsageSignals.ts
+++ b/cli/src/lib/productUsageSignals.ts
@@ -1,4 +1,4 @@
-import { AUTOMATIC_POLL_ACTIONS, HEALTH_FAILURES, HEALTH_MEASURES, type HealthSource, type ResumeReason } from './productHealthContract.js'
+import { AUTOMATIC_POLL_ACTIONS, HEALTH_FAILURES, HEALTH_MEASURES, RESUME_PREPARATION_KINDS, type HealthSource, type ResumeReason } from './productHealthContract.js'
import type { MessageOutcome, MessageReceipt } from './sessionInput.js'
import { LAUNCH_ERROR_CODES, PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_LAUNCH_ENGINES, PRODUCT_USAGE_USER_OPENED_ACTIONS,
type LaunchErrorCode, type ProductUsageLaunchEngine, type ProductUsageMetric } from './productUsageContract.js'
@@ -55,13 +55,20 @@ export function launchErrorCode(error: unknown): LaunchErrorCode {
export function launchEngine(engine: unknown): ProductUsageLaunchEngine {
return (PRODUCT_USAGE_LAUNCH_ENGINES as readonly unknown[]).includes(engine) ? engine as ProductUsageLaunchEngine : 'other'
}
+/** A create turned down because the request was wrong, not because Harness failed: opening a conversation that is
+ * already a harness or open elsewhere (core/agents/adopt.ts), a cloud agent with no task or repository
+ * (cloud/service.ts). The Oct 26 report counted them as launch failures. */
+export const LAUNCH_REFUSALS: ReadonlySet<string> = new Set(['SESSION_IN_HARNESS', 'SESSION_OPEN_ELSEWHERE', 'SESSION_OPEN_IN_TERMINAL',
+ 'SESSION_BUSY_IN_TERMINAL', 'INVALID_REQUEST'])
export interface ProductUsageLaunchSignal {
/** Local RAM only, discarded on stop/choice change; never part of a report or persisted queue. */
id: string
- phase: 'start' | 'pending' | 'created' | 'failed' | 'cancelled' | 'unconfirmed' | 'work_requested'
+ phase: 'start' | 'pending' | 'created' | 'failed' | 'refused' | 'cancelled' | 'unconfirmed' | 'work_requested'
+ /** On `start`: an agent or a Swarm asked for this launch (the create's `startedBy`), not a person. */
+ agentStarted?: true
origin?: 'interactive' | 'tool'
failure?: Failure
- /** The listed code of an `other` or setup failure, or of a created launch's late one (`late`). */
+ /** The listed code of an `other` or setup failure, of a refusal, or of a created launch's late one (`late`). */
code?: LaunchErrorCode
wait?: 'install' | 'model' | 'native' | 'other'
/** The engine a new launch asked for (`start`), as a fixed name: an installation's first launch counts it. */
@@ -84,17 +91,19 @@ function createdSignal(agent: unknown): Omit<ProductUsageLaunchSignal, 'id'> {
}
/** Observe an actual new-harness receipt through subsequent status polls. Polling adds no attempts.
- * [engine] is the request's `engine`; the reply's [agent] is its agent frame, or whether it had one. */
-export function productUsageLaunch(type: string, id: unknown, emit: (signal: ProductUsageLaunchSignal) => void, engine?: unknown) {
+ * [engine] is the request's `engine`; the reply's [agent] is its agent frame, or whether it had one.
+ * [agentStarted]: the create says an agent started it (`startedBy: 'agent'`). */
+export function productUsageLaunch(type: string, id: unknown, emit: (signal: ProductUsageLaunchSignal) => void, engine?: unknown, agentStarted = false) {
const known = ['agent_create', 'agent_create_status', 'agent_create_cancel'].includes(type)
&& typeof id === 'string' && /^[a-zA-Z0-9_-]{16,96}$/.test(id)
if (!known) return unmeasured
const send = (signal: Omit<ProductUsageLaunchSignal, 'id'>) => {
if (known) { try { emit({ id: id as string, ...signal }) } catch { /* Optional measurement. */ } }
}
- if (type === 'agent_create') send({ phase: 'start', engine: launchEngine(engine) })
+ if (type === 'agent_create') send({ phase: 'start', engine: launchEngine(engine), ...(agentStarted ? { agentStarted: true } : {}) })
return (error: unknown, state: unknown, agent: unknown, held: unknown) => {
- if (error != null || state === 'failed') {
+ if (typeof error === 'string' && LAUNCH_REFUSALS.has(error)) send({ phase: 'refused', code: launchErrorCode(error) })
+ else if (error != null || state === 'failed') {
const failure = failureKind(error)
send({ phase: 'failed', failure, ...(failure === 'other' || failure === 'setup' ? { code: launchErrorCode(error) } : {}) })
}
@@ -143,12 +152,17 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet
count('requests'); detail('started')
if (userAction && (PRODUCT_USAGE_USER_OPENED_ACTIONS as readonly string[]).includes(action)) count('user_requests')
// [failure]: the kind of a refusal its caller already knows (a message's, [messageReceipt]), not read off a code.
- return (error: unknown, state: unknown, hasAgent: boolean, ok?: unknown, failure?: typeof HEALTH_FAILURES[number]) => {
+ // [preparation]: the reply's `reason` — for a resume whose history could not be prepared, which check refused it.
+ return (error: unknown, state: unknown, hasAgent: boolean, ok?: unknown, failure?: typeof HEALTH_FAILURES[number], preparation?: unknown) => {
if (!action || answered) return
answered = true
if (action === 'resume' && (error != null || ok === false || ['failed', 'cancelled', 'unconfirmed', 'unavailable'].some(value => state === value))) {
const reason = typeof error === 'string' ? resumeReasons.get(error) : undefined
detail(`reason_${reason ?? (state === 'unconfirmed' ? 'unconfirmed' : 'other')}`)
+ // Only a name from the fixed list leaves here: a kind this build does not know is `other`.
+ if (reason === 'preparation_failed' && preparation !== undefined) {
+ detail(`preparation_${(RESUME_PREPARATION_KINDS as readonly unknown[]).includes(preparation) ? preparation : 'other'}`)
+ }
}
// A runtime we cannot verify is unknown; a harness changed during the request is cancelled.
// Neither proves a launch failure. Older clients classified these two codes as failures.
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index e5f12d2ae..c1da51aeb 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -8,6 +8,7 @@ import { registry, type RegisteredSession } from './registry.js'
import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'
import { materializeResumeTranscript } from '../engines/resumeTranscript.js'
import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
+import { ResumePreparationError } from '../engines/kit/resumeRepair.js'
import { env } from '../config/env.js'
import { StoppedAgentStore } from './stoppedAgents.js'
import { AgentRestartCoordinator } from './restartAgent.js'
@@ -552,6 +553,49 @@ describe('production resume handler', () => {
expect(deps.stoppedAgents.beginResume(saved.agentId) === null).toBe(reason !== 'tmux is unavailable')
expect(registry.byAgent(saved.agentId)).toBeUndefined()
})
+ // On 2026-10-26, 10 of 17 failed resumes were a preparation failure, and nothing said which check refused.
+ it('reports why preparation failed, in the reply and the daemon log', async () => {
+ const warned = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(deps.prepareSessionResume).mockImplementationOnce(() => {
+ throw new ResumePreparationError('changed_during', 'Codex rollout changed during resume preparation; retry after its writer stops')
+ })
+ expect(await start()).toEqual({ ok: false, error: 'RESUME_PREPARATION_FAILED', reason: 'changed_during',
+ detail: 'Codex is still writing this conversation. Try again once it stops.' })
+ expect(warned.mock.calls.map(call => call.join(' '))).toContainEqual(expect.stringContaining(
+ 'resume preparation failed: changed_during: Codex rollout changed during resume preparation; retry after its writer stops'))
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('names a preparation failure of no known kind as other, with the usual words', async () => {
+ const warned = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(deps.prepareSessionResume).mockImplementationOnce(() => { throw new Error('EACCES: permission denied') })
+ expect(await start()).toEqual({ ok: false, error: 'RESUME_PREPARATION_FAILED', reason: 'other',
+ detail: 'Could not prepare the saved conversation. Its history has been retained.' })
+ expect(warned.mock.calls.map(call => call.join(' '))).toContainEqual(expect.stringContaining('resume preparation failed: other: Error'))
+ })
+
+ // An error of no known kind can carry anything: a profile path, a token, a line of the conversation.
+ it('logs a preparation failure of no known kind by its class only, never its message', async () => {
+ const warned = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const printed = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const secret = 'SECRET-SENTINEL /Users/someone/.codex/sessions/rollout.jsonl user said: my password is hunter2'
+ vi.mocked(deps.prepareSessionResume).mockImplementationOnce(() => { throw new TypeError(secret) })
+ expect(await start()).toMatchObject({ ok: false, error: 'RESUME_PREPARATION_FAILED', reason: 'other' })
+ const logged = [...warned.mock.calls, ...printed.mock.calls].map(call => call.join(' ')).join('\n')
+ expect(logged).toContain('resume preparation failed: other: TypeError')
+ expect(logged).not.toContain('SECRET-SENTINEL')
+ expect(logged).not.toContain('hunter2')
+ })
+
+ it('logs a non-Error throw as its type only', async () => {
+ const warned = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(deps.prepareSessionResume).mockImplementationOnce(() => { throw 'SECRET-SENTINEL thrown as a string' })
+ expect(await start()).toMatchObject({ ok: false, error: 'RESUME_PREPARATION_FAILED', reason: 'other' })
+ const logged = warned.mock.calls.map(call => call.join(' ')).join('\n')
+ expect(logged).toContain('resume preparation failed: other: string')
+ expect(logged).not.toContain('SECRET-SENTINEL')
+ })
+
it('retains a typed native hold from synchronous history repair and releases its reservation', async () => {
vi.mocked(deps.prepareSessionResume).mockImplementationOnce(() => { throw new IdentityReadUnavailable('the native store is incomplete') })
expect(await start()).toMatchObject({ ok: false, error: 'IDENTITY_UNAVAILABLE' })
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index 2f52d2480..cdba5c3c7 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -7,6 +7,7 @@ import { engineKeepsTranscriptFile, registry as liveRegistry, type RegisteredSes
import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'
import { materializeResumeTranscript } from '../engines/resumeTranscript.js'
import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
+import { ResumePreparationError } from '../engines/kit/resumeRepair.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
import { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed, RESUME_READINESS_BUDGET_MS } from './resumeStoppedAgent.js'
import { checkPidRuntime } from './deleteAgentFallback.js'
@@ -55,6 +56,19 @@ export interface ResumeAgentServiceDeps {
relaunchMarks?: Pick<RelaunchMarks, 'note'>
}
+/** A history that could not be prepared, and which check refused it: on 2026-10-26, 10 of 17 failed resumes were
+ * this and nothing said why. The kind goes in the reply for its counter; the message of a typed failure (an engine's
+ * file label and a line number, never conversation text) only to this daemon's log. Any other error is logged by
+ * its class alone: its message can carry a profile path, a token or a line of the conversation (review of #1777). */
+function preparationFailed(agent: string, error: unknown) {
+ const reason = error instanceof ResumePreparationError ? error.kind : 'other'
+ const said = error instanceof ResumePreparationError ? error.message : error instanceof Error ? error.name : typeof error
+ console.warn(`[resume] ${agent} · resume preparation failed: ${reason}: ${said}`)
+ return { ok: false as const, error: 'RESUME_PREPARATION_FAILED', reason,
+ detail: reason === 'changed_during' ? 'Codex is still writing this conversation. Try again once it stops.'
+ : 'Could not prepare the saved conversation. Its history has been retained.' }
+}
+
export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
const { registry, stoppedAgents, createBackend, noBackendCode = 'TMUX_UNAVAILABLE', backendFor, restartJobs, stopJobs, pinnedControls,
retainExitedSession, announceSession, relaunchOverrides, prepareSessionResume, adoptSwarmSkill,
@@ -275,7 +289,7 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
if (resumeSessionId) {
try { prepareSessionResume(saved) } catch (error) {
if (error instanceof IdentityReadUnavailable) throw error
- return { ok: false, error: 'RESUME_PREPARATION_FAILED', detail: 'Could not prepare the saved conversation. Its history has been retained.' }
+ return preparationFailed(sid(saved.agentId), error)
}
// The confirmed synchronous repair may atomically replace this file.
// Earn a new proof of the same conversation before the next await.
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 27a6942e1..f182f06b9 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -330,6 +330,15 @@ class AgentCreationAttempt {
bool _codexHomeTrusted = false;
bool get awaitingConfirmation => _awaitingConfirmation;
+
+ /// What the machine answered a create, for a test's fake `createAgent`: the harness it made, or that the
+ /// start is still being confirmed.
+ @visibleForTesting
+ void answeredForTest({String? agentId, bool awaitingConfirmation = false}) {
+ _agentId = agentId;
+ _awaitingConfirmation = awaitingConfirmation;
+ }
+
bool get canCancelPending => _awaitingConfirmation && _holdReason != null;
bool get canFollowPending =>
_awaitingConfirmation && (_starting || _holdReason != null);
diff --git a/desktop/lib/state/first_arrival.dart b/desktop/lib/state/first_arrival.dart
index 8896b6373..f34f4cd57 100644
--- a/desktop/lib/state/first_arrival.dart
+++ b/desktop/lib/state/first_arrival.dart
@@ -157,6 +157,12 @@ class FirstArrival {
final generation = app.accountGeneration;
var opened = false;
String? tab;
+ // The last create made its harness and only its pane was missing: look for that pane again. Creating again
+ // resumed the same session and was refused as already a harness (SESSION_IN_HARNESS, the Oct 26 report).
+ final made = _attempt?.awaitingConfirmation == true
+ ? null
+ : _attempt?.agentId;
+ bool otherPanes() => app.allPanes.any((p) => p.agentId != made);
bool current() =>
_state != 'done' &&
app.signedIn &&
@@ -170,8 +176,36 @@ class FirstArrival {
return false;
}
+ /// Focuses the harness this run made, with the starter draft its plan asks for.
+ bool open(String machineId, FirstArrivalPlan plan) {
+ final panes = app.swarms.where((s) => s.id == tab).firstOrNull?.panes;
+ final createdId = _attempt?.agentId;
+ final pane = panes
+ ?.where(
+ (p) =>
+ p.machineId == machineId &&
+ (createdId == null
+ ? panes.length == 1
+ : p.agentId == createdId),
+ )
+ .firstOrNull;
+ if (pane == null) {
+ return fail('The harness has not opened yet. Try again to check it.');
+ }
+ if (plan.typesStarterTask) {
+ // An editable Flutter draft, not keystrokes sent to a terminal that may still be signing in.
+ pane.firstTask = starterTask;
+ pane.composerVisible = true;
+ }
+ app.focusPane(pane.id, reveal: true);
+ app.productMeasurement.firstRunReady(machineId, pane.agentId);
+ opened = true;
+ dismiss();
+ return true;
+ }
+
try {
- if (!current() || app.allPanes.isNotEmpty) {
+ if (!current() || otherPanes()) {
dismiss();
return false;
}
@@ -192,6 +226,10 @@ class FirstArrival {
'The computer changed. Choose a harness on the computer you want to use.',
);
}
+ if (made != null && _plan != null) {
+ tab = app.activeSwarmId;
+ return open(machineId, _plan!);
+ }
final (sessions, _) = await (
recentSessions(app, machineId, budget: indexWait),
app.probeEngines(machineId),
@@ -273,30 +311,7 @@ class FirstArrival {
return false;
}
if (failure != null) return fail(failure);
- final panes = app.swarms.where((s) => s.id == tab).firstOrNull?.panes;
- final createdId = _attempt?.agentId;
- final pane = panes
- ?.where(
- (p) =>
- p.machineId == machineId &&
- (createdId == null
- ? panes.length == 1
- : p.agentId == createdId),
- )
- .firstOrNull;
- if (pane == null) {
- return fail('The harness has not opened yet. Try again to check it.');
- }
- if (plan.typesStarterTask) {
- // An editable Flutter draft, not keystrokes sent to a terminal that may still be signing in.
- pane.firstTask = starterTask;
- pane.composerVisible = true;
- }
- app.focusPane(pane.id, reveal: true);
- app.productMeasurement.firstRunReady(machineId, pane.agentId);
- opened = true;
- dismiss();
- return true;
+ return open(machineId, plan);
} catch (_) {
if (!current()) {
dismiss();
diff --git a/desktop/test/first_arrival_test.dart b/desktop/test/first_arrival_test.dart
index 5776e8700..59aee2531 100644
--- a/desktop/test/first_arrival_test.dart
+++ b/desktop/test/first_arrival_test.dart
@@ -126,6 +126,42 @@ class _OpeningApp extends _PreparingApp {
}
}
+/// A create the machine answered: made (its harness's id) with no pane yet, or still being confirmed.
+class _AnsweredApp extends _OpeningApp {
+ _AnsweredApp({this.awaiting = false});
+ final bool awaiting;
+ final attempts = <AgentCreationAttempt?>[];
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ ProjectFolderRequest? projectFolder,
+ bool bypassPermission = true,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ GridModel? model,
+ String? prompt,
+ String? name,
+ String? agent,
+ String? swarmId,
+ String? swarmRole,
+ String? swarmSkillMode,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ starts.add((engine: engine, folder: folder, prompt: prompt));
+ attempts.add(attempt);
+ attempt!.answeredForTest(
+ agentId: awaiting ? null : 'first',
+ awaitingConfirmation: awaiting,
+ );
+ return awaiting ? 'Still starting. Check again in a moment.' : null;
+ }
+}
+
final _base = DateTime(2026, 10, 8, 12);
/// A conversation last active [minutesAgo] minutes before noon.
@@ -332,6 +368,51 @@ void main() {
]);
});
+ // A second create resumed the same session and was refused as already a harness (Oct 26 report).
+ test('retry after the harness was made but not shown waits for that harness, and creates nothing', () async {
+ final app = _AnsweredApp();
+ addTearDown(app.dispose);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
+ await arrival.restore();
+ arrival.index.complete([]);
+ expect(await arrival.run(app), isFalse);
+ expect(
+ arrival.error,
+ 'The harness has not opened yet. Try again to check it.',
+ );
+ // Still not shown: the same answer again, and still no second create.
+ expect(await arrival.retry(app), isFalse);
+ expect(
+ arrival.error,
+ 'The harness has not opened yet. Try again to check it.',
+ );
+ app.activeSwarm.panes.add(
+ TerminalPane(id: 1, machineId: 'local', agentId: 'first'),
+ );
+ expect(await arrival.retry(app), isTrue);
+ expect(app.starts, hasLength(1));
+ expect(app.allPanes.single.firstTask, FirstArrival.starterTask);
+ expect(arrival.needsRecovery, isFalse);
+ });
+
+ test(
+ 'retry while a start is being confirmed asks about the same start again',
+ () async {
+ final app = _AnsweredApp(awaiting: true);
+ addTearDown(app.dispose);
+ final arrival = _PreparingArrival(_MemoryStore())
+ ..begin(downloads: false);
+ await arrival.restore();
+ arrival.index.complete([]);
+ expect(await arrival.run(app), isFalse);
+ expect(arrival.checkingStatus, isTrue);
+ expect(await arrival.retry(app), isFalse);
+ expect(app.attempts, hasLength(2));
+ expect(app.attempts.last, same(app.attempts.first));
+ },
+ );
+
test('the index and engine check start together and both finish before planning', () async {
final app = _PreparingApp();
addTearDown(app.dispose);
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 6b57b0f14..9d25fb66c 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -9,7 +9,7 @@ automatically proven improvement. Changes still need review, tests and a deliber
| Question | Signal | Interpretation |
| --- | --- | --- |
| Does first measured use lead to work? | First-launch installation cohorts; work and first text response within 24 hours; the first launch's engine (`first_launch_engine_opencode`, `_claude`, `_codex`, `_other`) and, for Claude Code and Codex, whether that engine had a credential here (`first_launch_<engine>_signed_in`, `_signed_out`, `_unknown`) | Same participating installation, not signup conversion, same-task success or unique people. Existing users enter when updated; mature only after the full follow-up day ends. The credential is one presence check per installation, in the gateway (`cli/src/lib/engineAccount.ts`: a file stat'ed or parsed for a token, a Keychain item looked up without its secret); it reads the gateway's own environment and starts no login shell, so a key only a shell profile exports reads as signed out on a daemon launchd or systemd started. `unknown` is a Codex that keeps its tokens in the OS keyring, or a check that failed. An answer lost to a stop or a choice change leaves the engine count without one. |
-| Where does a launch stall or fail? | Pending install/model/native waits; observed launch created/failed/cancelled/unconfirmed; fixed failure categories and duration buckets; an `other` failure's code (`launch_failed_code_<code>`); a created launch whose engine then did not start (`launch_late_failed`, by code in `launch_late_failed_code_<code>`) | Polls are not attempts. Missing outcomes, daemon restarts and the 15-minute observation bound reduce coverage. Inspect unknowns alongside failures. Codes are the daemon's own fixed names, lower-cased (`LAUNCH_ERROR_CODES`); `unlisted` is a code not in the list and `none` a failure that named none, so the codes add up to `launch_failed_other`. A late failure (the new-pane watcher's ENGINE_DID_NOT_START, ENGINE_NOT_INSTALLED or START_TIMEOUT, set after the reply said created) is one of the `launch_created`, never a `launch_failed`; the gateway reads it from the agent's own announcement for 15 minutes after the launch was created, and earlier CLI releases counted these only as created (compare releases separately). |
+| Where does a launch stall or fail? | Pending install/model/native waits; observed launch created/failed/cancelled/unconfirmed; fixed failure categories and duration buckets; an `other` failure's code (`launch_failed_code_<code>`); a created launch whose engine then did not start (`launch_late_failed`, by code in `launch_late_failed_code_<code>`) | Polls are not attempts. Missing outcomes, daemon restarts and the 15-minute observation bound reduce coverage. Inspect unknowns alongside failures. Codes are the daemon's own fixed names, lower-cased (`LAUNCH_ERROR_CODES`); `unlisted` is a code not in the list and `none` a failure that named none, so the codes add up to `launch_failed_other`. A late failure (the new-pane watcher's ENGINE_DID_NOT_START, ENGINE_NOT_INSTALLED or START_TIMEOUT, set after the reply said created) is one of the `launch_created`, never a `launch_failed`; the gateway reads it from the agent's own announcement for 15 minutes after the launch was created, and earlier CLI releases counted these only as created (compare releases separately). A create correctly turned down is `launch_refused`, by code in `launch_refused_code_<code>`, and never a `launch_failed`: the refusal set is exactly SESSION_IN_HARNESS, SESSION_OPEN_ELSEWHERE, SESSION_OPEN_IN_TERMINAL, SESSION_BUSY_IN_TERMINAL and INVALID_REQUEST (opening a conversation that is already a harness or is open elsewhere, a cloud agent with no task or repository); earlier releases counted them as `launch_failed_other`. `launch_agent_started`, `_created`, `_failed` and `_refused` count again the launches whose create carried a `startedBy` (an agent or a Swarm started it); the totals keep counting every launch, so a person's own launches are the total less the agent twin. |
| Which actions break? | Create, resume, restart, model-change, history, fork, close, delete, search, history paging, Store list/install/update/remove, model list/download/start/stop and browser-open requests, fixed outcomes/errors and latency buckets; the code of an `other` create or resume refusal (`create_error_code_<code>`, `resume_error_code_<code>`), and of every delete or restart refusal (`delete_error_code_<code>`, `restart_error_code_<code>`; the phone's again apart, `phone_delete_error_code_<code>`, `phone_restart_error_code_<code>`) | Request acceptance is not task success. Pending/unknown requests are separate from completed replies. A person's message (`request_<source>_message_*`), which nothing answers, is `ok` once its engine took it (its turn began, or it left the composer), `failed` by what the person was told (`not_found`, `unavailable`, `conflict` for a pane busy with a dialog or a full queue, `timeout`, `invalid`, `other`), `unknown` when typed and never confirmed, `cancelled` when stopped; from the CLI release that carries it (an older one counts only `started`), and not yet for cloud agents. Requests are also counted by source: `app`, `tool`, `automatic` (fixed polls, whichever app makes them), `unknown` and `phone` — the phone marks the requests the daemon measures (`usageSurface: 'phone'`, inside the E2EE payload); older phones still count as `app`. Each code family adds up to its `create_error_other` or `resume_error_other`; the delete and restart families add up to `delete_failed` and `restart_failed`, whatever the kind (the phone's 2026-10-19 refusals were `other` and `setup`). |
| Does work get a response promptly? | First text response buckets; over-one-minute waits; error events; matched ends without text; interruptions | Includes automation. Tool-only turns, interruptions and missing lifecycle events can explain missing text. No message is inspected. |
| Do installations return to work? | D1/D7/D28 working-day cohorts, consecutive complete-week and calendar-month returns, return after a seven-day gap | Any working day can be a cohort; not new-signup retention. Local date flags produce unlinked totals. Opt-outs, reinstallations, resets and missing uploads affect results. |
@@ -343,6 +343,12 @@ launch failed, invalid and other. These come only from known error codes, never
An engine of a resumed harness that did not start (ENGINE_DID_NOT_START, ENGINE_NOT_INSTALLED,
START_TIMEOUT) is a launch failure, a resume while the harness is being deleted is busy, and a request
that named no harness is invalid; earlier releases counted these as `other`.
+A preparation failure also names which check refused the saved history, by request source:
+`request_<source>_resume_preparation_<kind>`, where the kind is `invalid_json` (a record that is not JSON),
+`foreign_session` (a first record missing or another session's), `not_owned_file` (outside the session
+folders, a link, or not this user's), `changed_during` (the engine was still writing it) or `other`. Each
+counts once per resume reply, beside `resume_reason_preparation_failed`. A half-written last line, which an
+interrupted Codex leaves behind, no longer refuses a resume: it is kept as it is and only logged.
From CLI 0.4.3, an unconfirmed runtime counts as unknown and a concurrently changed harness as
cancelled (legacy aggregate: unknown), rather than failed. Compare releases separately across this
definition change; a lower failure rate alone is not proof the product improved.
diff --git a/docs/superpowers/plans/2026-10-27-launch-resume-failure-accuracy.md b/docs/superpowers/plans/2026-10-27-launch-resume-failure-accuracy.md
new file mode 100644
index 000000000..c679e016d
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-launch-resume-failure-accuracy.md
@@ -0,0 +1,175 @@
+# Launch and Resume Failure Accuracy Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Launch counters stop counting correct refusals as failures and say who started a launch; a failed resume preparation keeps its reason; a half-written Codex history line no longer refuses a resume; Desktop's first-arrival Retry and `harness new <cloud>` stop producing refusals of their own.
+
+**Architecture:** Fixed counter names are added to the two mirrored contract files (CLI and backend copies must stay byte-identical). The daemon classifies refusals in `productUsageSignals.ts` and counts them in `gateway/productUsage.ts`. Resume repair throws a typed error whose kind travels in the resume reply. The cloud request checks move into one helper both the cloud service and `harness new` call.
+
+**Tech Stack:** TypeScript (CLI and backend: vitest), Dart/Flutter (Desktop).
+
+**Spec:** `docs/superpowers/specs/2026-10-27-launch-resume-failure-accuracy-design.md`
+
+## Global Constraints
+
+- `cli/src/lib/productUsageContract.ts` ≡ `backend/src/types/productUsage.ts` and `cli/src/lib/productHealthContract.ts` ≡ `backend/src/types/productHealthContract.ts`, byte for byte (tests: `backend/src/lib/productUsage.test.ts` "keeps the client and server vocabulary identical", `backend/src/analytics/productHealth.test.ts`).
+- Only fixed names leave the daemon: no message text, path, session id or conversation text in a counter. Log lines may carry the repair error's message (file name + line number only) — never conversation text.
+- Refusal set (spec §3), exactly: `SESSION_IN_HARNESS`, `SESSION_OPEN_ELSEWHERE`, `SESSION_OPEN_IN_TERMINAL`, `SESSION_BUSY_IN_TERMINAL`, `INVALID_REQUEST`.
+- Preparation kinds (spec §1), exactly: `invalid_json`, `foreign_session`, `not_owned_file`, `changed_during`, `other`.
+- Existing totals keep counting what they count today except that refusals leave `launch_failed`; nothing is renamed or removed.
+- Rollout: backend before CLI (spec "Rollout"). Plan produces both; release order is the releaser's.
+
+## Review Focus
+
+1. A resume whose history ends in a complete line with no trailing newline (valid JSON) — must resume exactly as before, bytes unchanged. Test in Task 2.
+2. A half-written last line *followed by nothing* in a history that also needs repair elsewhere — the repaired lines change, the tail stays byte-identical. Test in Task 2.
+3. A create refused with a refusal code from an agent (`startedBy: 'agent'`) — counts `launch_refused`, `launch_agent_started`, `launch_agent_refused`, never `launch_failed` or `launch_agent_failed`. Test in Task 4.
+4. A first-arrival Retry while the first create is still `awaitingConfirmation` — keeps today's behaviour (re-checks the same attempt). Test in Task 6.
+5. `harness new devin-cloud -- task` with no `--repo` — Devin's repository is optional, so it must NOT be refused locally. Test in Task 5.
+
+## Ruling against the spec
+
+Spec §2 says the passed-through tail is "counted as `resume_preparation_partial_tail`". The repair runs in `core/agents/launch.ts`, which has no counter path, and a resume that succeeds has no failure to attach it to. Ruling: log it (`resume history ended in a partial line; kept as is`) and do not add a counter. Task 2 edits the spec line to match.
+
+Spec §1 puts the `changed_during` wording in Desktop. Desktop has no case for `RESUME_PREPARATION_FAILED` and shows the daemon's `detail`, so the daemon's detail carries it instead (Task 3) and every app, the phone included, shows the same words. Task 3 edits the spec line to match.
+
+---
+
+### Task 1: Counter vocabulary
+
+**Files:**
+- Modify: `cli/src/lib/productUsageContract.ts` (launch names ~line 175–205), then copy to `backend/src/types/productUsage.ts`
+- Modify: `cli/src/lib/productHealthContract.ts` (~line 44–52), then copy to `backend/src/types/productHealthContract.ts`
+- Modify: `docs/product-measurement.md`
+- Test: `backend/src/lib/productUsage.test.ts`, `backend/src/analytics/productHealth.test.ts`
+
+**Interfaces:**
+- Produces: metrics `launch_refused`, `launch_agent_started`, `launch_agent_created`, `launch_agent_failed`, `launch_agent_refused`; family `launch_refused_code` in `LAUNCH_ERROR_FAMILIES` (so `launch_refused_code_<code>` exists for every `LAUNCH_ERROR_CODES` entry); `export const RESUME_PREPARATION_KINDS = ['invalid_json', 'foreign_session', 'not_owned_file', 'changed_during', 'other'] as const` and `type ResumePreparationKind` in `productHealthContract.ts`; metrics `request_<source>_resume_preparation_<kind>` for every `HEALTH_SOURCES` × kind in `PRODUCT_HEALTH_METRICS`.
+
+- [ ] **Step 1: Write the failing test** in `backend/src/lib/productUsage.test.ts`:
+
+```ts
+it('names launch refusals and agent-started launches', () => {
+ const metrics = new Set<string>(PRODUCT_USAGE_METRICS)
+ for (const m of ['launch_refused', 'launch_agent_started', 'launch_agent_created', 'launch_agent_failed', 'launch_agent_refused',
+ 'launch_refused_code_session_in_harness', 'launch_refused_code_invalid_request']) expect(metrics.has(m), m).toBe(true)
+})
+```
+and in `backend/src/analytics/productHealth.test.ts`:
+```ts
+it('names each resume preparation kind per source', () => {
+ for (const kind of ['invalid_json', 'foreign_session', 'not_owned_file', 'changed_during', 'other'])
+ expect((PRODUCT_HEALTH_METRICS as readonly string[]).includes(`request_app_resume_preparation_${kind}`), kind).toBe(true)
+})
+```
+
+- [ ] **Step 2: Run** `cd backend && npx vitest run src/lib/productUsage.test.ts src/analytics/productHealth.test.ts` — Expected: the two new tests FAIL.
+- [ ] **Step 3: Add the names** to the two CLI contract files, then `cp` each over its backend copy.
+- [ ] **Step 4: Run** the same command — Expected: PASS, parity tests included. Also `cd cli && npx tsc --noEmit -p .` — Expected: no errors.
+- [ ] **Step 5: Document** in `docs/product-measurement.md` beside the launch counters: `launch_refused` (+ code family) with the refusal set; `launch_agent_*` (a create carrying `startedBy`; person-started = total − agent); `request_<source>_resume_preparation_<kind>`.
+- [ ] **Step 6: Commit** `feat(usage): names for launch refusals, agent launches and resume preparation kinds`.
+
+### Task 2: Typed resume preparation errors; keep a half-written tail
+
+**Files:**
+- Modify: `cli/src/engines/kit/resumeRepair.ts` (`historyRepair` ~55–92, `scanHistory` ~111+, `repairHistory` ~168–220)
+- Modify: spec line in §2 (see Ruling)
+- Test: `cli/src/engines/kit/resumeRepair.spec.ts`
+
+**Interfaces:**
+- Consumes: `ResumePreparationKind` (Task 1).
+- Produces: `export class ResumePreparationError extends Error { constructor(readonly kind: ResumePreparationKind, message: string) }` from `resumeRepair.ts`. Every throw in that file becomes one: invalid JSON / non-object record → `invalid_json`; wrong or missing first record (`does not belong`, `has no session metadata`) → `foreign_session`; outside the session profile / not an owned regular file → `not_owned_file`; `changedDuring` → `changed_during`; write failure and non-ENOENT stat errors → `other`. Messages unchanged.
+
+- [ ] **Step 1: Write failing tests** in `resumeRepair.spec.ts`, reusing the file's existing history fixtures:
+ - `classifies each refusal`: invalid JSON mid-file → `kind === 'invalid_json'`; first record of another session → `foreign_session`; no `session_meta` → `foreign_session`; a symlinked history → `not_owned_file`.
+ - `keeps a half-written last line`: history = valid `session_meta` line + one repairable item line + `'{"type":"respo'` (no trailing `\n`) → `repairHistory` returns without throwing; the file's last bytes equal `'{"type":"respo'`; the repairable line is repaired.
+ - `still refuses a broken line that ends in a newline`: same tail followed by `\n` → throws `invalid_json`.
+ - `leaves a complete unterminated last line alone`: last line valid JSON without `\n` → bytes unchanged, no throw (Review Focus 1).
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/engines/kit/resumeRepair.spec.ts` — Expected: new tests FAIL (no `ResumePreparationError`; tail throws).
+- [ ] **Step 3: Implement.** `historyRepair.line(line, last: boolean)`: when `last` and `JSON.parse` fails, return the line unchanged and set a `partialTail` flag instead of throwing; `scanHistory` passes `last = true` only for the final fragment that had no newline; `repairHistoryText` passes `last` for the final element only when the input does not end in `\n`. `repairHistory` logs `resume history ended in a partial line; kept as is` (the file's existing logger) when the flag is set.
+- [ ] **Step 4: Run** the spec file and `resumeRepair.real.spec.ts` — Expected: PASS.
+- [ ] **Step 5: Edit spec §2**: replace "and counted as `resume_preparation_partial_tail`" with "and logged; no counter (a resume that succeeds has no failure to attach it to)".
+- [ ] **Step 6: Commit** `fix(resume): typed preparation errors; a half-written last history line no longer refuses`.
+
+### Task 3: The resume reply and counters carry the kind
+
+**Files:**
+- Modify: `cli/src/lib/resumeAgentService.ts:276-278`
+- Modify: `cli/src/lib/productUsageSignals.ts` (`productUsageRequest`'s returned function), `cli/src/backendSocket.ts:~949` (the `measured(...)` call)
+- Test: `cli/src/lib/resumeAgentService.spec.ts`, `cli/src/lib/productUsageSignals.spec.ts`
+
+**Interfaces:**
+- Consumes: `ResumePreparationError` (Task 2), `RESUME_PREPARATION_KINDS` (Task 1).
+- Produces: reply `{ ok: false, error: 'RESUME_PREPARATION_FAILED', reason: ResumePreparationKind, detail }`; the measured callback becomes `(error, state, hasAgent, ok?, failure?, preparation?: unknown)`, and `backendSocket` passes `p.reason`.
+
+- [ ] **Step 1: Write failing tests.**
+ - `resumeAgentService.spec.ts` `reports why preparation failed`: stub `prepareSessionResume` to throw `new ResumePreparationError('changed_during', 'rollout changed…')` → reply `reason === 'changed_during'`, `detail === 'Codex is still writing this conversation. Try again once it stops.'`; a plain `Error` → `reason === 'other'`, detail unchanged (`'Could not prepare the saved conversation. Its history has been retained.'`); the daemon log receives `resume preparation failed: changed_during: rollout changed…`.
+ - `productUsageSignals.spec.ts` `counts a preparation kind once`: a resume answered `('RESUME_PREPARATION_FAILED', undefined, false, false, undefined, 'invalid_json')` from source `app` emits `request_app_resume_preparation_invalid_json` and `request_app_resume_reason_preparation_failed`; an unknown string → `..._preparation_other`; no `preparation` → no preparation counter.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/resumeAgentService.spec.ts src/lib/productUsageSignals.spec.ts` — Expected: new tests FAIL.
+- [ ] **Step 3: Implement** in the three files; the kind is emitted through `detail('preparation_<kind>')`, normalised against `RESUME_PREPARATION_KINDS`.
+- [ ] **Step 4: Run** — Expected: PASS.
+- [ ] **Step 5: Edit spec §1**: "Desktop's text for the refusal names the cause" → "The reply's detail names the cause" (same sentence otherwise).
+- [ ] **Step 6: Commit** `feat(resume): the reply and counters say why preparation failed`.
+
+### Task 4: Launch refusals and agent-started launches
+
+**Files:**
+- Modify: `cli/src/lib/productUsageSignals.ts` (`ProductUsageLaunchSignal`, `productUsageLaunch` ~88–107)
+- Modify: `cli/src/backendSocket.ts:939-940`
+- Modify: `cli/src/gateway/productUsage.ts` (`launch()` ~425–475)
+- Test: `cli/src/lib/productUsageSignals.spec.ts`, `cli/src/gateway/productUsage.spec.ts`
+
+**Interfaces:**
+- Consumes: Task 1 names.
+- Produces: `export const LAUNCH_REFUSALS = new Set(['SESSION_IN_HARNESS', 'SESSION_OPEN_ELSEWHERE', 'SESSION_OPEN_IN_TERMINAL', 'SESSION_BUSY_IN_TERMINAL', 'INVALID_REQUEST'])`; signal `phase` gains `'refused'`; signal gains `agentStarted?: true` on `start`; `productUsageLaunch(type, id, emit, engine?, agentStarted = false)`. `backendSocket` passes `(frame.payload as { startedBy?: unknown })?.startedBy === 'agent'`.
+
+- [ ] **Step 1: Write failing tests.**
+ - `productUsageSignals.spec.ts` `a correct refusal is not a launch failure`: for each code in the refusal set, `productUsageLaunch('agent_create', ID, emit)` then the reply `(code, 'failed')` emits `{ phase: 'refused', code: <lower-cased listed code> }` and no `phase: 'failed'`; `'SPAWN_FAILED'` still emits `phase: 'failed'`.
+ - `productUsageSignals.spec.ts` `marks an agent's launch`: `productUsageLaunch('agent_create', ID, emit, 'claude', true)` emits `{ phase: 'start', engine: 'claude', agentStarted: true }`.
+ - `gateway/productUsage.spec.ts` `counts refusals and agent launches apart`: start(agentStarted) + refused(`session_in_harness`) → counters `launch_started`, `launch_agent_started`, `launch_refused`, `launch_refused_code_session_in_harness`, `launch_agent_refused`; and none of `launch_failed`, `launch_agent_failed` (Review Focus 3). A person's start + failed → `launch_failed` only, no `launch_agent_*`. An agent's start + created → `launch_created` and `launch_agent_created`.
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/productUsageSignals.spec.ts src/gateway/productUsage.spec.ts` — Expected: new tests FAIL.
+- [ ] **Step 3: Implement.** The gateway stores `agent: boolean` on the launch record at `start`, adds `launch_refused` / `launch_refused_code_<listed>` on `refused`, and the `launch_agent_<phase>` twin for `started`, `created`, `failed`, `refused`. `refused` marks the launch done like the other final phases.
+- [ ] **Step 4: Run** — Expected: PASS.
+- [ ] **Step 5: Commit** `feat(usage): correct refusals and agent launches counted apart`.
+
+### Task 5: One cloud request check for the service and `harness new`
+
+**Files:**
+- Modify: `cli/src/lib/cloudAgents.ts` (new export), `cli/src/cloud/service.ts:246-252`, `cli/src/lib/newCommand.ts` (`parseNewArgs`, after the `--repo` check ~171)
+- Test: `cli/src/lib/newCommand.spec.ts`, existing `cli/src/cloud/service.spec.ts` (must stay green)
+
+**Interfaces:**
+- Produces: `export function cloudRequestRefusal(agent: CloudAgentId, task: string, repository: string | null | undefined): string | null` in `cloudAgents.ts` — returns the exact `detail` strings `service.ts` uses today (no task; not a GitHub repository; a coding agent without `repositoryOptional` and no repository), else `null`. `repositoryOf` moves with it if `service.ts` is its only home.
+
+- [ ] **Step 1: Write failing tests** in `newCommand.spec.ts`:
+ - `refuses a cloud task locally`: `parseNewArgs(['cursor-cloud'])` (no task) throws `NewUsageError` with `'Tell Cursor Cloud what to do.'`; `['cursor-cloud', '--repo', 'gitlab.com/a/b', '--', 'x']` throws with `'That is not a GitHub repository: give owner/name or https://github.com/owner/name.'`; `['cursor-cloud', '--', 'x']` throws `'Choose a GitHub repository for Cursor Cloud.'`.
+ - `lets Devin Cloud start without a repository`: `['devin-cloud', '--', 'x']` parses (Review Focus 5).
+ (Use the names from `CLOUD_AGENTS`; if `cursor-cloud` is not a coding agent there, use the first `kind: 'coding'` entry without `repositoryOptional`.)
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/lib/newCommand.spec.ts` — Expected: FAIL.
+- [ ] **Step 3: Implement** the helper; `service.ts` returns `{ ok: false, error: 'INVALID_REQUEST', detail }` from it; `parseNewArgs` throws `NewUsageError(detail)` from it.
+- [ ] **Step 4: Run** `newCommand.spec.ts` and `src/cloud/*.spec.ts` — Expected: PASS.
+- [ ] **Step 5: Commit** `fix(cli): harness new checks a cloud task before sending it`.
+
+### Task 6: First-arrival Retry does not create twice
+
+**Files:**
+- Modify: `desktop/lib/state/first_arrival.dart` (`run` ~220–290)
+- Test: `desktop/test/first_arrival_test.dart`
+
+**Interfaces:**
+- Consumes: nothing new. `AgentCreationAttempt.agentId` and `.awaitingConfirmation` exist.
+
+- [ ] **Step 1: Write failing tests** in `first_arrival_test.dart`, using the file's fake `createAgent` (line ~100) with a call counter:
+ - `retry after the pane was missing waits for the same harness`: first run's create returns an id but no pane appears → error `'The harness has not opened yet. Try again to check it.'`; add the pane with that `agentId`; `retry` → succeeds, and `createAgent` was called **once**.
+ - `retry after a failed create creates again`: first create fails → `retry` calls `createAgent` a second time.
+ - `retry while confirming keeps the same attempt` (Review Focus 4): an attempt with `awaitingConfirmation == true` → `retry` re-checks it, no second create.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/first_arrival_test.dart` — Expected: the first test FAILS (two creates).
+- [ ] **Step 3: Implement.** In `run`, when `_attempt?.agentId != null` and the previous failure was the missing pane, skip the create and go straight to the pane lookup (waiting as the first run does); keep `_attempt` instead of replacing it.
+- [ ] **Step 4: Run** the test file, then the New Harness coverage gate: `flutter test --coverage --branch-coverage && node tool/check_new_harness_coverage.mjs coverage/lcov.info` — Expected: PASS; gate prints `100%` (or the same pre-existing gap as `main` — record it, do not widen it).
+- [ ] **Step 5: Commit** `fix(desktop): first-arrival Retry waits for the harness it already made`.
+
+### Task 7: Whole-change checks
+
+- [ ] **Step 1: Run** `cd cli && npm test` and `npx tsc --noEmit -p .`; `cd backend && npm test`; record pass counts.
+- [ ] **Step 2: Run** the CLI coverage gates the touched areas fall under (AGENTS.md): `npm run test:core` and `npm run test:resume`. Expected: PASS.
+- [ ] **Step 3:** No commit unless a fix was needed; record results in the PR body.
diff --git a/docs/superpowers/specs/2026-10-27-launch-resume-failure-accuracy-design.md b/docs/superpowers/specs/2026-10-27-launch-resume-failure-accuracy-design.md
new file mode 100644
index 000000000..884383830
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-27-launch-resume-failure-accuracy-design.md
@@ -0,0 +1,103 @@
+# Launch and resume failures: count them right, keep the reason
+
+Status: spec · 2026-10-27 · from the Oct 26 usage report (items 2 and 3)
+
+## Why
+
+The Oct 26 usage report showed agent start failures at 8–16% a day since Oct 21 (3–5% before) and
+17 of 38 resumes failing on Oct 26, 10 of them `resume_preparation_failed`. Reading the code:
+
+- Some "failures" are correct refusals. `SESSION_IN_HARNESS` (opening an outside conversation that
+ is already a harness here, `cli/src/core/agents/adopt.ts`) and `INVALID_REQUEST` (a cloud agent
+ with no task or no GitHub repository, `cli/src/cloud/service.ts:248-253`) are both counted as
+ `launch_failed` with failure `other` (`cli/src/lib/productUsageSignals.ts:96-99`).
+- Desktop's first-arrival Retry sends the create again after the first one succeeded but its pane
+ was not found yet (`desktop/lib/state/first_arrival.dart:226-288`). The second create resumes the
+ same session and gets `SESSION_IN_HARNESS`.
+- `harness new <cloud>` sends a cloud request without checking the task or repository first
+ (`cli/src/lib/newCommand.ts`), so a typo becomes a counted failure.
+- The launch counters do not say whether a person or an agent started the launch, so Swarm and
+ agent-started launches (much more of them since Oct 21) move a rate people read as user pain.
+- `RESUME_PREPARATION_FAILED` discards the error (`cli/src/lib/resumeAgentService.ts:276-278`). In
+ practice it comes from Codex history repair (`cli/src/engines/kit/resumeRepair.ts`), and nobody can
+ tell which check failed. One of them, invalid JSON, refuses a whole conversation because its last
+ line is half written, which is what an interrupted Codex leaves behind.
+
+Out of scope: sign-up (item 1, the sign-in service is outside this repo), rejected usage reports
+(item 4, needs a database query, not code), `dsh_runtime_failed` (needs a Windows reproduction
+first), the phone relay spike (back to normal).
+
+## What changes
+
+### 1. Resume preparation keeps its reason
+
+- `repairHistory` throws a typed `ResumePreparationError` with `kind` ∈ `invalid_json`,
+ `foreign_session` (first record missing or another session's), `not_owned_file` (outside the
+ session folders, a symlink, not owned), `changed_during` (still being written), `other`. The
+ message stays as today: file name and line number, never conversation text.
+- `resumeAgentService` returns `RESUME_PREPARATION_FAILED` with that kind in the reply
+ (`reason: <kind>`; the core's resume reply and its receipt carry it on, `failure.reason` in a receipt's status) and logs `resume preparation failed: <kind>: <message>` to the daemon log.
+- New counters `request_<source>_resume_preparation_<kind>` (one per kind), counted once per
+ resume reply, beside the existing `resume_reason_preparation_failed`.
+- The reply's detail names the cause for `changed_during` ("Codex is still writing this
+ conversation. Try again once it stops.") and keeps today's text otherwise.
+
+### 2. A half-written last line does not refuse the resume
+
+In `historyRepair`, a final line with no trailing newline that is not valid JSON is passed through
+unchanged (not repaired, not refused) and logged; no counter (a resume that succeeds has no failure to attach it to). Every other
+check stays as strict as now: invalid JSON anywhere else, a foreign or missing first record, a file
+outside the session folders, and a file that changes during preparation still refuse. Those are
+integrity and safety checks, not damage.
+
+### 3. Launch counters separate refusals and who started
+
+- New `launch_refused` (with `launch_refused_code_<code>`): a create refused because the request was
+ correctly turned down, not because Harness failed. The set is fixed: `SESSION_IN_HARNESS`,
+ `SESSION_OPEN_ELSEWHERE`, `SESSION_OPEN_IN_TERMINAL`, `SESSION_BUSY_IN_TERMINAL`,
+ `INVALID_REQUEST`. These stop counting as `launch_failed`.
+- Every launch counter gets an agent-started twin: `launch_agent_started`, `launch_agent_created`,
+ `launch_agent_failed`, `launch_agent_refused`, counted when the create request carries a
+ `startedBy` (the field `core/agents/create.ts` already records for agent and Swarm starts). The
+ measurement at `backendSocket.ts:939` reads it from the same payload. The existing totals keep counting everything, so
+ history stays comparable; person-started = total − agent.
+
+### 4. First-arrival Retry checks before it creates again
+
+When the last attempt already has an `agentId` (the create succeeded and only the pane was missing),
+Retry waits for that agent's pane again and does not send a new create. It creates again only when
+the previous attempt failed or never got an id.
+
+### 5. `harness new <cloud>` checks before sending
+
+Before sending, `harness new` refuses locally, exit 2, with the same wording the cloud service uses:
+no task; `--repo` not a GitHub repository; a coding cloud agent with no `--repo`.
+
+## Rollout
+
+- The counter names live in two mirrored files, `cli/src/lib/productUsageContract.ts` /
+ `productHealthContract.ts` and `backend/src/types/`. The backend drops unknown names one by one
+ (`withoutUnknownCounters`), so the backend ships first, then the CLI. A CLI that ships first only
+ loses the new counters until the backend catches up.
+- `docs/product-measurement.md` documents the new counters and the refusal set.
+- Desktop changes (sections 1's copy and 4) ship in the next Desktop release; nothing depends on
+ the order between Desktop and CLI.
+
+## Testing
+
+- `resumeRepair`: one test per kind; a half-written last line resumes and keeps its bytes; invalid
+ JSON in the middle still refuses; a half-written line followed by a newline still refuses.
+- `resumeAgentService`: the reply carries `reason`, and the log line has kind and message.
+- `productUsageSignals`: each refusal code counts `launch_refused` and its code, not `launch_failed`;
+ an agent-started create counts both the total and the `launch_agent_*` twin; a person-started one
+ only the total.
+- Contract parity test (CLI vs backend files) stays green.
+- `newCommand`: the three local refusals, exit 2, and nothing sent.
+- Desktop `first_arrival`: Retry after "has not opened yet" sends no second create and opens the
+ pane when it appears; Retry after a failed create creates again. The New Harness coverage gate
+ stays at 100%.
+
+## Success
+
+After a week on the new CLI: `launch_failed` (person-started) back near the pre-Oct-21 3–5% unless
+real failures remain, and every `resume_preparation_failed` attributed to a kind.