The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(measurement): reduce upload contention and clarify resume outcomes (#1334)
Dee3864b5bc67ad
diff --git a/.github/workflows/production-be-build.yaml b/.github/workflows/production-be-build.yamlindex fe5e7d6a6..8e9e3819a 100644--- a/.github/workflows/production-be-build.yaml+++ b/.github/workflows/production-be-build.yaml@@ -126,3 +126,4 @@ jobs:build-args: |BUILD_ENV=${{ env.BUILD_ENV }}BUILD_TAG=${{ env.IMAGE_TAG }}+ BUILD_SHA=${{ github.sha }}diff --git a/backend/Dockerfile.k8s b/backend/Dockerfile.k8sindex f91ae886a..defea1630 100644--- a/backend/Dockerfile.k8s+++ b/backend/Dockerfile.k8s@@ -58,6 +58,11 @@ COPY --from=builder /app/node_modules/@prisma ./node_modules/@prismaCOPY --from=builder /app/dist ./distENV NODE_ENV=production+# Public tag/SHA only; /api/health uses these to verify the image actually serving traffic.+ARG BUILD_TAG+ARG BUILD_SHA+ENV BUILD_TAG=${BUILD_TAG}+ENV BUILD_SHA=${BUILD_SHA}# Role selector. Override to `job` on the worker Deployment (replicas: 1).ENV APP=api# Each pod is one node process (no pm2 cluster here), so cap V8's old space explicitly: without it V8diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.tsindex ad4b63a7e..2c7a6b924 100644--- a/backend/src/lib/productUsage.test.ts+++ b/backend/src/lib/productUsage.test.ts@@ -26,8 +26,8 @@ it('commits release and platform margins under the same unlinked receipt and disconst context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' } as constexpect(await ingestProductUsage('PRIVATE_ACCOUNT', { ...report, context }, now)).toEqual({ accepted: true })expect(db.$transaction).toHaveBeenCalledOnce()- expect(db.productUsageTotal.upsert).toHaveBeenCalledTimes(6)- const stored = JSON.stringify([db.productUsageReceipt.create.mock.calls, db.productUsageTotal.upsert.mock.calls])+ expect(db.$runCommandRaw.mock.calls[0][0].updates).toHaveLength(6)+ const stored = JSON.stringify([db.productUsageReceipt.create.mock.calls, db.$runCommandRaw.mock.calls])expect(stored).not.toContain('PRIVATE_ACCOUNT')expect(stored).not.toContain('1.2.73:macos')expect(stored).toContain('breakdown:release:desktop:1.2.73:turns_started')@@ -40,6 +40,7 @@ const report: ProductUsageReport = { schemaVersion: 1, revision: 0, id: 'cf1c5a0const now = new Date('2026-10-13T12:00:00Z')beforeEach(() => {vi.resetAllMocks()+ db.$runCommandRaw.mockImplementation(async command => ({ ok: 1, n: command.updates?.length ?? 0 }))db.$transaction.mockImplementation((fn: (tx: typeof db) => unknown) => fn(db))db.productUsagePreference.findUnique.mockResolvedValue(null)db.analyticsMachineState.findFirst.mockResolvedValue(null)@@ -72,12 +73,14 @@ describe('aggregate ingestion', () => {it('stores only totals and an unlinked receipt, in one transaction', async () => {expect(await ingestProductUsage('private-account', report, now)).toEqual({ accepted: true })expect(db.$transaction).toHaveBeenCalledOnce()- expect(db.productUsageTotal.upsert).toHaveBeenCalledTimes(2)- expect(db.productUsageTotal.upsert.mock.calls[0][0]).toEqual({- where: { dayUtc_metric: { dayUtc: new Date('2026-10-13'), metric: 'turns_started' } },- create: { dayUtc: new Date('2026-10-13'), metric: 'turns_started', value: 4 }, update: { value: { increment: 4 } },+ expect(db.$runCommandRaw).toHaveBeenCalledOnce()+ expect(db.$runCommandRaw.mock.calls[0][0]).toEqual({+ update: 'product_usage_totals', ordered: true, updates: [+ { q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'turns_started' }, u: { $inc: { value: 4 } }, upsert: true },+ { q: { dayUtc: { $date: '2026-10-13T00:00:00.000Z' }, metric: 'turns_ended' }, u: { $inc: { value: 3 } }, upsert: true },+ ],})- const stored = JSON.stringify([db.productUsageTotal.upsert.mock.calls, db.productUsageReceipt.create.mock.calls])+ const stored = JSON.stringify([db.$runCommandRaw.mock.calls, db.productUsageReceipt.create.mock.calls])for (const forbidden of ['private-account', 'userId', 'machineId', 'agentId', 'revision', 'counters', 'receivedAt']) expect(stored).not.toContain(forbidden)})it('rejects opted-out and stale queued uploads without receipts or counters', async () => {@@ -86,7 +89,7 @@ describe('aggregate ingestion', () => {db.productUsagePreference.findUnique.mockResolvedValue({ enabled: true, revision: 2 })expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })expect(db.productUsageReceipt.create).not.toHaveBeenCalled()- expect(db.productUsageTotal.upsert).not.toHaveBeenCalled()+ expect(db.$runCommandRaw).not.toHaveBeenCalled()})it.each(['2026-09-08', '2026-10-14', '2026-02-30', 'bad'])('refuses expired/future/invalid day %s', async day => {expect(await ingestProductUsage('a', { ...report, day }, now)).toEqual({ accepted: false, reason: 'EXPIRED' })@@ -96,17 +99,17 @@ describe('aggregate ingestion', () => {db.productUsageReceipt.create.mockRejectedValue({ code: 'P2002' })db.productUsageReceipt.findUnique.mockResolvedValue({ id: report.id })expect(await ingestProductUsage('a', report, now)).toEqual({ accepted: true })- expect(db.productUsageTotal.upsert).not.toHaveBeenCalled()+ expect(db.$runCommandRaw).not.toHaveBeenCalled()})it('does not mistake a rolled-back aggregate creation race for a received report', async () => {- db.productUsageTotal.upsert.mockRejectedValue({ code: 'P2002' })+ db.$runCommandRaw.mockRejectedValue({ code: 'P2002' })db.productUsageReceipt.findUnique.mockResolvedValue(null)await expect(ingestProductUsage('a', report, now)).rejects.toMatchObject({ code: 'P2002' })expect(db.$transaction).toHaveBeenCalledTimes(4)expect(delay).toHaveBeenCalledTimes(3)})it.each(['P2034', 'P2002'])('retries a fast %s conflict with the same receipt and a fresh permission check', async code => {- db.productUsageTotal.upsert.mockRejectedValueOnce({ code })+ db.$runCommandRaw.mockRejectedValueOnce({ code })expect(await ingestProductUsage('private-account', report, now)).toEqual({ accepted: true })expect(db.$transaction).toHaveBeenCalledTimes(2)expect(db.productUsagePreference.findUnique).toHaveBeenCalledTimes(2)@@ -116,7 +119,7 @@ describe('aggregate ingestion', () => {expect(vi.mocked(delay).mock.calls[0][0]).toBeLessThan(75)})it('rechecks a sharing-off choice before retrying the transaction', async () => {- db.productUsageTotal.upsert.mockRejectedValueOnce({ code: 'P2034' })+ db.$runCommandRaw.mockRejectedValueOnce({ code: 'P2034' })db.productUsagePreference.findUnique.mockResolvedValueOnce({ enabled: true, revision: 0 }).mockResolvedValueOnce({ enabled: false, revision: 1 })expect(await ingestProductUsage('a', report, now)).toMatchObject({ accepted: false, reason: 'CHOICE_CHANGED' })diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.tsindex 9363868fd..a19857c63 100644--- a/backend/src/lib/productUsage.ts+++ b/backend/src/lib/productUsage.ts@@ -7,6 +7,7 @@ import { env } from '../config/env.js'import { prisma } from './prisma.js'import { PRODUCT_USAGE_DAYS, type ProductUsageChoice, type ProductUsageReport } from '../types/productUsage.js'import { ACTIVITY_DAYS, type ActivitySurface } from '../types/productUsageActivity.js'+import { incrementUsageTotals, type UsageIncrement } from './productUsageWrite.js'const DAY = 86_400_000type Db = Pick<Prisma.TransactionClient, 'productUsagePreference' | 'analyticsMachineState'>@@ -52,6 +53,17 @@ export async function ingestSetupUsage(report: SetupUsageReport, now = new Date(async function ingestCounters(report: SetupUsageReport & { revision?: number; context?: ProductUsageContext }, userId?: string, now = new Date()) {if (report.context?.channel === 'development') return { accepted: true, reason: 'DEVELOPMENT' }+ const increments: UsageIncrement[] = []+ for (const [metric, value] of Object.entries(report.counters)) {+ if (!value) continue+ for (const name of [metric, ...healthBreakdowns(report.context, metric)]) {+ increments.push({ dayUtc: new Date(report.day), metric: name, value })+ }+ }+ if (report.context && report.day < now.toISOString().slice(0, 10)) {+ increments.push({ dayUtc: new Date(Math.floor(now.getTime() / DAY) * DAY),+ metric: `health_${report.context.surface}_report_late`, value: 1 })+ }// October's delivery audit found aggregate write conflicts. Retry the entire transaction,// including permission, without extending a slow request or waiting a full client interval.// At most four attempts; only fast conflicts may start another within the first second.@@ -67,21 +79,7 @@ async function ingestCounters(report: SetupUsageReport & { revision?: number; coawait tx.productUsageReceipt.create({ data: {id: report.id, expiresAt: new Date(Date.parse(report.day) + (PRODUCT_USAGE_DAYS + 1) * DAY),} })- for (const [metric, value] of Object.entries(report.counters)) {- if (!value) continue- for (const name of [metric, ...healthBreakdowns(report.context, metric)]) {- await tx.productUsageTotal.upsert({- where: { dayUtc_metric: { dayUtc: new Date(report.day), metric: name } },- create: { dayUtc: new Date(report.day), metric: name, value }, update: { value: { increment: value } },- })- }- }- if (report.context && report.day < now.toISOString().slice(0, 10)) {- const dayUtc = new Date(Math.floor(now.getTime() / DAY) * DAY)- const metric = `health_${report.context.surface}_report_late`- await tx.productUsageTotal.upsert({ where: { dayUtc_metric: { dayUtc, metric } },- create: { dayUtc, metric, value: 1 }, update: { value: { increment: 1 } } })- }+ await incrementUsageTotals(tx, increments)return { accepted: true }})} catch (error) {diff --git a/backend/src/lib/productUsageWrite.test.ts b/backend/src/lib/productUsageWrite.test.tsnew file mode 100644index 000000000..5914dc547--- /dev/null+++ b/backend/src/lib/productUsageWrite.test.ts@@ -0,0 +1,20 @@+import { expect, it, vi } from 'vitest'+import { incrementUsageTotals } from './productUsageWrite.js'++const increments = [{ dayUtc: new Date('2026-10-14'), metric: 'turns_started', value: 2 }]+it.each([+ [{ ok: 1, n: 0, writeErrors: [{ code: 112, errmsg: 'PRIVATE_CANARY' }] }, 'P2034'],+ [{ ok: 1, n: 0, writeErrors: [{ code: 11000, errmsg: 'PRIVATE_CANARY' }] }, 'P2002'],+ [{ ok: 1, n: 0, writeErrors: [{ code: 14, errmsg: 'PRIVATE_CANARY' }] }, 'USAGE_WRITE_FAILED'],+ [{ ok: 1, n: 0 }, 'USAGE_WRITE_FAILED'],+ [{ ok: 0, n: 1 }, 'USAGE_WRITE_FAILED'],+ [{ ok: 1, n: 1, writeConcernError: { errmsg: 'PRIVATE_CANARY' } }, 'USAGE_WRITE_FAILED'],+])('aborts partial or uncertain writes without reflecting database text', async (result, code) => {+ const tx = { $runCommandRaw: vi.fn().mockResolvedValue(result) }+ await expect(incrementUsageTotals(tx, increments)).rejects.toMatchObject({ code, message: 'Product usage write unavailable' })+})+it('avoids an invalid empty update command', async () => {+ const tx = { $runCommandRaw: vi.fn() }+ await incrementUsageTotals(tx, [])+ expect(tx.$runCommandRaw).not.toHaveBeenCalled()+})diff --git a/backend/src/lib/productUsageWrite.ts b/backend/src/lib/productUsageWrite.tsnew file mode 100644index 000000000..af98cd7b9--- /dev/null+++ b/backend/src/lib/productUsageWrite.ts@@ -0,0 +1,26 @@+import type { Prisma } from '@prisma/client'++export interface UsageIncrement { dayUtc: Date; metric: string; value: number }++/** One database round trip for a report's counters and separate margins. Called only inside the+ * receipt transaction: October's sequential upserts held shared daily totals long enough for+ * overlapping uploads to exhaust retries. No report body or identity becomes a stored document. */+export async function incrementUsageTotals(tx: Pick<Prisma.TransactionClient, '$runCommandRaw'>, increments: UsageIncrement[]): Promise<void> {+ if (!increments.length) return+ const result = await tx.$runCommandRaw({+ update: 'product_usage_totals', ordered: true,+ updates: increments.map(({ dayUtc, metric, value }) => ({+ q: { dayUtc: { $date: dayUtc.toISOString() }, metric },+ u: { $inc: { value } }, upsert: true,+ })),+ })+ // A command can return ok:1 with writeErrors. Never commit its receipt after a partial write.+ const errors = result.writeErrors+ if (result.ok !== 1 || result.n !== increments.length || result.writeConcernError+ || (Array.isArray(errors) && errors.length)) {+ const first = Array.isArray(errors) ? errors[0] as { code?: number } | undefined : undefined+ throw Object.assign(new Error('Product usage write unavailable'), {+ code: first?.code === 112 ? 'P2034' : first?.code === 11000 ? 'P2002' : 'USAGE_WRITE_FAILED',+ })+ }+}diff --git a/backend/src/routes/health.test.ts b/backend/src/routes/health.test.tsnew file mode 100644index 000000000..7ea4d72b1--- /dev/null+++ b/backend/src/routes/health.test.ts@@ -0,0 +1,21 @@+import Fastify from 'fastify'+import { afterEach, expect, it, vi } from 'vitest'+import { healthRoutes } from './health.js'++afterEach(() => vi.unstubAllEnvs())+it.each([+ ['v1.2.72_backend', 'a'.repeat(40), { version: 'v1.2.72_backend', sha: 'a'.repeat(40) }],+ ['', '', null],+ ['PRIVATE_CANARY', 'a'.repeat(40), null],+ ['v1.2.72_backend', 'PRIVATE_CANARY', null],+])('exposes only validated public build coordinates', async (tag, sha, build) => {+ vi.stubEnv('BUILD_TAG', tag); vi.stubEnv('BUILD_SHA', sha)+ const app = Fastify({ logger: false })+ try {+ await app.register(healthRoutes)+ const response = await app.inject('/api/health')+ expect(response.statusCode).toBe(200)+ expect(response.json()).toEqual({ success: true, data: { status: 'ok', build } })+ expect(response.body).not.toContain('PRIVATE_CANARY')+ } finally { await app.close() }+})diff --git a/backend/src/routes/health.ts b/backend/src/routes/health.tsindex 60ef325fa..c2d64f90d 100644--- a/backend/src/routes/health.ts+++ b/backend/src/routes/health.ts@@ -1,8 +1,13 @@import type { FastifyInstance } from 'fastify'export async function healthRoutes(app: FastifyInstance): Promise<void> {+ // Public release coordinates only. Deployment verification must not rely on an image build+ // succeeding while the live API still runs an older image, or expose arbitrary environment text.+ const version = process.env.BUILD_TAG ?? '', sha = process.env.BUILD_SHA ?? ''+ const build = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(_backend)?$/.test(version)+ && /^[a-f0-9]{40}$/.test(sha) ? { version, sha } : nullapp.get('/api/health', async () => ({success: true,- data: { status: 'ok' },+ data: { status: 'ok', build },}))}diff --git a/backend/src/types/productHealthContract.ts b/backend/src/types/productHealthContract.tsindex 6317d2431..1e3a7dca0 100644--- a/backend/src/types/productHealthContract.ts+++ b/backend/src/types/productHealthContract.ts@@ -28,8 +28,13 @@ export const HEALTH_MEASURES = [export const CLI_REPORT_FAILURES = ['invalid', 'too_large', 'auth', 'rate_limited', 'timeout', 'unreachable','write_conflict', 'transaction', 'server', 'other'] as constexport type CliReportFailure = typeof CLI_REPORT_FAILURES[number]+// Fixed resume conditions, separate from raw errors and from whether a request actually failed.+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]export const PRODUCT_HEALTH_METRICS = [...CLI_REPORT_FAILURES.map(reason => `health_cli_report_failure_${reason}` as const),+ ...HEALTH_SOURCES.flatMap(source => RESUME_REASONS.map(reason => `request_${source}_resume_reason_${reason}` as const)),...(['cli', 'desktop'] as const).flatMap(surface => HEALTH_MEASURES.map(m => `health_${surface}_${m}` as const)),...HEALTH_SOURCES.flatMap(source => HEALTH_ACTIONS.flatMap(action => [...HEALTH_RESULTS.map(result => `request_${source}_${action}_${result}` as const),diff --git a/cli/e2e/productUsage.e2e.ts b/cli/e2e/productUsage.e2e.tsindex 7ca9bbb22..36dc75dd7 100644--- a/cli/e2e/productUsage.e2e.ts+++ b/cli/e2e/productUsage.e2e.ts@@ -47,6 +47,8 @@ it('reports only local counters from a real turn, and the account switch stops treturn rows.agents.some((a: Record<string, unknown>) => a.id === agentId && a.sessionId) || null}, 45000)await client.request('session_search', { query: 'PRIVATE_SEARCH_CANARY' })+ const missing = await client.request('agent_resume', { agentId: 'PRIVATE_MISSING_AGENT_CANARY' })+ expect(missing.error).toBe('AGENT_NOT_FOUND')// The same Desktop-format fixture must pass both the local proxy and the backend route tests.const appReport = { ...JSON.parse(readFileSync(new URL('../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8')), day: new Date().toISOString().slice(0, 10) }const forwarded = await fetch(`http://127.0.0.1:${d.port}/api/product-usage/report`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: JSON.stringify(appReport) })@@ -65,6 +67,8 @@ it('reports only local counters from a real turn, and the account switch stops texpect(sum('health_cli_interactive_work_days')).toBe(1)expect(sum('health_cli_first_interactive_work')).toBe(1)expect(sum('request_app_message_started')).toBeGreaterThan(0)+ expect(sum('request_app_resume_failed')).toBe(1)+ expect(sum('request_app_resume_reason_saved_state_missing')).toBe(1)const wire = JSON.stringify(backend.productUsage.reports)for (const privateValue of ['PRIVATE_', creationId, machine.machineId, machine.computerId, machine.token, agentId, cwd, 'userMessage', 'payload']) expect(wire).not.toContain(privateValue)expect((await fetch(settings, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"enabled":false}' })).status).toBe(200)diff --git a/cli/src/lib/productHealthContract.ts b/cli/src/lib/productHealthContract.tsindex 6317d2431..1e3a7dca0 100644--- a/cli/src/lib/productHealthContract.ts+++ b/cli/src/lib/productHealthContract.ts@@ -28,8 +28,13 @@ export const HEALTH_MEASURES = [export const CLI_REPORT_FAILURES = ['invalid', 'too_large', 'auth', 'rate_limited', 'timeout', 'unreachable','write_conflict', 'transaction', 'server', 'other'] as constexport type CliReportFailure = typeof CLI_REPORT_FAILURES[number]+// Fixed resume conditions, separate from raw errors and from whether a request actually failed.+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]export const PRODUCT_HEALTH_METRICS = [...CLI_REPORT_FAILURES.map(reason => `health_cli_report_failure_${reason}` as const),+ ...HEALTH_SOURCES.flatMap(source => RESUME_REASONS.map(reason => `request_${source}_resume_reason_${reason}` as const)),...(['cli', 'desktop'] as const).flatMap(surface => HEALTH_MEASURES.map(m => `health_${surface}_${m}` as const)),...HEALTH_SOURCES.flatMap(source => HEALTH_ACTIONS.flatMap(action => [...HEALTH_RESULTS.map(result => `request_${source}_${action}_${result}` as const),diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.tsindex f99b23bba..b0431aa1c 100644--- a/cli/src/lib/productUsageSignals.spec.ts+++ b/cli/src/lib/productUsageSignals.spec.ts@@ -1,5 +1,6 @@import { expect, it, vi } from 'vitest'import { productUsageIntent, productUsageLaunch, productUsageRequest } from './productUsageSignals.js'+import { PRODUCT_USAGE_METRICS } from './productUsageContract.js'it('separates automated polling, tool and app RPCs without inspecting error objects or content', () => {const emit = vi.fn()@@ -78,3 +79,39 @@ it('marks a Store or model list a person opened, and only those', () => {productUsageRequest('session_tail', emit, Date.now, 'app', true)(undefined, undefined, false)expect(emit.mock.calls.flat().filter(m => String(m).includes('_user_'))).toEqual([])})++it.each([+ ['TMUX_UNAVAILABLE', 'runtime_unavailable'], ['NATIVE_LAUNCH_HELD', 'runtime_unavailable'],+ ['AGENT_NOT_FOUND', 'saved_state_missing'], ['RESUME_UNAVAILABLE', 'saved_state_missing'],+ ['CWD_NOT_FOUND', 'project_missing'], ['INVALID_DSH', 'harness_missing'],+ ['GRID_CREDENTIAL_REQUIRED', 'credentials_missing'], ['AGENT_BUSY', 'busy'],+ ['RESUME_PREPARATION_FAILED', 'preparation_failed'], ['RESUME_FAILED', 'launch_failed'],+ ['INVALID_PERMISSION_MODE', 'invalid'], ['PRIVATE_ERROR_WITH_PATH', 'other'], ['__proto__', 'other'],+])('reduces resume condition %s to an approved counter without retaining it', (error, reason) => {+ const emit = vi.fn(), done = productUsageRequest('agent_resume', emit, () => 0, 'app')+ done(error, 'failed', false); done(error, 'failed', false)+ const names = emit.mock.calls.flat()+ expect(names.filter(name => name.startsWith('request_app_resume_reason_'))).toEqual([`request_app_resume_reason_${reason}`])+ expect(names).toContain('request_app_resume_failed')+ for (const name of names) expect(PRODUCT_USAGE_METRICS).toContain(name)+ expect(JSON.stringify(names)).not.toContain(error)+})+it.each([+ ['RESUME_UNCONFIRMED', undefined, 'unconfirmed', 'unknown'],+ [undefined, 'unconfirmed', 'unconfirmed', 'unknown'],+ ['AGENT_CHANGED', 'failed', 'changed', 'cancelled'],+])('does not call an unverified or superseded resume a failure', (error, state, reason, result) => {+ const emit = vi.fn()+ productUsageRequest('agent_resume', emit, () => 0, 'tool')(error, state, false)+ expect(emit.mock.calls.flat()).toEqual(['resume_requests', 'request_tool_resume_started',+ `request_tool_resume_reason_${reason}`, 'resume_unknown', `request_tool_resume_${result}`, 'resume_under_1s'])+})+it('never coerces private reply values and leaves successful resumes without a diagnostic', () => {+ const emit = vi.fn(), privateValue = { toString() { throw Error('PRIVATE') } }+ expect(() => productUsageRequest('agent_resume', emit, () => 0, 'unknown')(privateValue, privateValue, false)).not.toThrow()+ expect(emit.mock.calls.flat()).toContain('request_unknown_resume_reason_other')+ emit.mockClear()+ productUsageRequest('agent_resume', emit, () => 0, 'app')(undefined, 'created', true)+ expect(emit.mock.calls.flat()).toContain('request_app_resume_ok')+ expect(emit.mock.calls.flat().some(name => name.includes('_reason_'))).toBe(false)+})diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.tsindex 389025045..19d3d7316 100644--- a/cli/src/lib/productUsageSignals.ts+++ b/cli/src/lib/productUsageSignals.ts@@ -1,4 +1,4 @@-import type { HealthSource } from './productHealthContract.js'+import type { HealthSource, ResumeReason } from './productHealthContract.js'import { PRODUCT_USAGE_USER_OPENED_ACTIONS, type ProductUsageMetric } from './productUsageContract.js'const actions = { agent_create: 'create', agent_resume: 'resume', agent_restart: 'restart',@@ -18,6 +18,17 @@ const unavailable = new Set(['SERVICE_UNAVAILABLE', 'SERVICE_FAILED', 'GRID_UNAV'UNSUPPORTED', 'UNSUPPORTED_ON_REMOTE', 'TIMEOUT', 'NATIVE_UNAVAILABLE'])const invalid = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'CWD_NOT_FOUND', 'INVALID_GRID', 'INVALID_DSH','INVALID_MODEL', 'INVALID_PERMISSION_MODE', 'INVALID_CREATION_ID', 'INVALID_PROJECT_SOURCE', 'WORKTREE_BUSY'])+const resumeReasons = new Map<string, ResumeReason>([+ ['TMUX_UNAVAILABLE', 'runtime_unavailable'], ['NATIVE_LAUNCH_HELD', 'runtime_unavailable'],+ ['ENGINE_UNAVAILABLE', 'runtime_unavailable'],+ ['AGENT_NOT_FOUND', 'saved_state_missing'], ['RESUME_UNAVAILABLE', 'saved_state_missing'],+ ['CWD_NOT_FOUND', 'project_missing'], ['INVALID_DSH', 'harness_missing'],+ ['GRID_CREDENTIAL_REQUIRED', 'credentials_missing'], ['AUTH_REQUIRED', 'credentials_missing'],+ ['AGENT_BUSY', 'busy'], ['WORKTREE_BUSY', 'busy'], ['PERMISSION_CHANGE_REQUIRES_STOP', 'busy'],+ ['AGENT_CHANGED', 'changed'], ['RESUME_UNCONFIRMED', 'unconfirmed'],+ ['RESUME_PREPARATION_FAILED', 'preparation_failed'], ['RESUME_FAILED', 'launch_failed'],+ ['INVALID_PERMISSION_MODE', 'invalid'], ['INVALID_CREATION_ID', 'invalid'],+])type Failure = 'setup' | 'auth' | 'unavailable' | 'invalid' | 'other'function failureKind(error: unknown): Failure {@@ -72,7 +83,15 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMetreturn (error: unknown, state: unknown, hasAgent: boolean, ok?: unknown) => {if (!action || answered) returnanswered = true- if (error != null || state === 'failed' || ok === false) {+ 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')}`)+ }+ // 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.+ if (action === 'resume' && (state === 'unconfirmed' || error === 'RESUME_UNCONFIRMED' || error === 'AGENT_CHANGED')) {+ count('unknown'); detail(error === 'AGENT_CHANGED' ? 'cancelled' : 'unknown')+ } else if (error != null || state === 'failed' || ok === false) {count('failed'); detail('failed')count(`error_${failureKind(error)}`)detail(`error_${error === 'TIMEOUT' ? 'timeout' : typeof error === 'string' && ['AGENT_NOT_FOUND', 'SESSION_NOT_FOUND', 'NOT_FOUND'].includes(error) ? 'not_found' : typeof error === 'string' && ['DELETE_IN_PROGRESS', 'WORKTREE_BUSY', 'BUSY'].includes(error) ? 'conflict' : failureKind(error)}`)diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex 6233a26ac..0f864adb1 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -119,6 +119,18 @@ Fast database write conflicts retry that complete transaction up to three timesrechecking the sharing choice each time. No retry starts after the first second; existing transactiondeadlines still apply to each attempt. Slow or exhausted conflicts return to the client's normalimmutable-report retry. Receipts prevent both immediate and later retries from counting twice.+Reports update their counters and separate margins in one Mongo update command inside+that transaction. A partial write aborts the receipt and all counts; no per-report body is stored.+This shortens shared-row contention without adding a daemon timer or delaying product actions.+The public `/api/health` response includes validated release tag/SHA coordinates so a successful+image build can be distinguished from the version actually serving requests.++Resume diagnostics add fixed conditions by request source: runtime unavailable, saved state missing,+project missing, harness missing, credentials missing, busy, changed, unconfirmed, preparation failed,+launch failed, invalid and other. These come only from known error codes, never error text or paths.+From CLI 0.4.2, 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.Receipts expire within 36 days and totals within 396 days through the existing Mongo TTL indexes.No account deduplication markers or stable hashes enter these totals. People-based daily counts andD1/D2/D3/D7 returns come from one mark per sharing person per day under an HMAC pseudonym (no time,